From e1dfb47681e8d9a0603c4f0359852f032f69a7fb Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Sun, 6 Dec 2026 15:30:18 +1000 Subject: [PATCH] perf(plugins,restore): sleep unused plugins while active and debounce restore.persist --- .../src/plugin_host/runtime/dormant.rs | 228 +++++++++++++++--- .../src/workspace/lifecycle/restore.rs | 4 +- features/restore/src/copies.rs | 6 +- features/restore/src/draft_doc.rs | 18 +- features/restore/src/lib.rs | 10 +- features/restore/src/parked.rs | 30 ++- features/restore/src/persist.rs | 42 +++- features/restore/src/preview.rs | 3 + features/restore/src/state.rs | 76 ++++++ features/restore/src/undo.rs | 3 +- 10 files changed, 369 insertions(+), 51 deletions(-) diff --git a/apps/desktop/src/plugin_host/runtime/dormant.rs b/apps/desktop/src/plugin_host/runtime/dormant.rs index e23c1407b..5133f781d 100644 --- a/apps/desktop/src/plugin_host/runtime/dormant.rs +++ b/apps/desktop/src/plugin_host/runtime/dormant.rs @@ -25,6 +25,7 @@ //! whose record doesn't match (an update that changed it, another language, a first launch) starts //! after the first frame as before, and records itself. +use std::cell::{Cell, RefCell}; use std::collections::BTreeMap; use std::time::Duration; @@ -38,6 +39,47 @@ use crate::plugin_host::{Life, LifeEvent, Overlay, PluginHost, Tier, bump, drive /// Server events kept for one dormant plugin; the oldest go first past it. const KEPT_EVENTS: usize = 256; +/// Active-window dormancy cadence (60 s), cold grace window (120 s), and anti-ping-pong backoff. +const ACTIVE_SWEEP_SECS: f64 = 60.0; +const COLD_AFTER_SECS: f64 = 120.0; +const PING_PONG_SECS: f64 = 15.0; +const MAX_COOLDOWN_SECS: f64 = 960.0; + +/// Explicit cadence state machine for active-window dormancy checks (piggybacks on existing polls). +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum SweepPhase { #[default] Idle, Armed { due: f64 } } +enum SweepEvent { Poll(f64), Reset } +enum SweepEffect { None, Check } + +fn step_sweep(state: &mut SweepPhase, event: SweepEvent) -> SweepEffect { + match (*state, event) { + (SweepPhase::Idle, SweepEvent::Poll(now)) => { *state = SweepPhase::Armed { due: now + ACTIVE_SWEEP_SECS }; SweepEffect::None } + (SweepPhase::Armed { due }, SweepEvent::Poll(now)) if now + 1e-6 >= due => { *state = SweepPhase::Armed { due: now + ACTIVE_SWEEP_SECS }; SweepEffect::Check } + (SweepPhase::Armed { .. }, SweepEvent::Poll(_)) => SweepEffect::None, + (_, SweepEvent::Reset) => { *state = SweepPhase::Idle; SweepEffect::None } + } +} + +/// Explicit per-plugin idle warmth state machine for active-window dormancy. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Warmth { Warm { since: f64, cooldown: f64 }, Slept { at: f64, cooldown: f64 } } +enum WarmthEvent { Started(f64), InUse(f64), IdleCheck(f64), Slept(f64) } +enum WarmthEffect { Keep, Eligible(f64) } + +fn step_warmth(state: Option, event: WarmthEvent) -> (Warmth, WarmthEffect) { + let cd = |w: Option| match w { Some(Warmth::Warm { cooldown, .. } | Warmth::Slept { cooldown, .. }) => cooldown, None => COLD_AFTER_SECS }; + match (state, event) { + (Some(Warmth::Slept { at, cooldown }), WarmthEvent::Started(now)) if now >= at && now - at < PING_PONG_SECS => + (Warmth::Warm { since: now, cooldown: (cooldown * 2.0).min(MAX_COOLDOWN_SECS) }, WarmthEffect::Keep), + (_, WarmthEvent::Started(now)) => (Warmth::Warm { since: now, cooldown: COLD_AFTER_SECS }, WarmthEffect::Keep), + (Some(Warmth::Warm { cooldown, .. }), WarmthEvent::InUse(now)) => (Warmth::Warm { since: now, cooldown }, WarmthEffect::Keep), + (_, WarmthEvent::InUse(now)) => (Warmth::Warm { since: now, cooldown: COLD_AFTER_SECS }, WarmthEffect::Keep), + (Some(Warmth::Warm { since, cooldown }), WarmthEvent::IdleCheck(now)) if now >= since => + (Warmth::Warm { since, cooldown }, if now - since + 1e-6 >= cooldown { WarmthEffect::Eligible(since) } else { WarmthEffect::Keep }), + (_, WarmthEvent::IdleCheck(now)) => (Warmth::Warm { since: now, cooldown: COLD_AFTER_SECS }, WarmthEffect::Keep), + (prev, WarmthEvent::Slept(now)) => (Warmth::Slept { at: now, cooldown: cd(prev) }, WarmthEffect::Keep), + } +} /// The window's dormant plugins and the records file as this window read it. #[derive(Default)] @@ -48,9 +90,13 @@ pub struct Dormant { /// Events kept for a plugin that started, handed to it at the next poll: `(server_id, ty, data)`. pub catch_up: BTreeMap>, /// Wake requests queued by views of this window since the last poll. - asked: std::cell::RefCell>, + asked: RefCell>, /// Count of settings-open retries for bundled settings plugins killed by a startup watchdog. watchdog_retries: BTreeMap, + /// Periodic active-window sweep cadence (`Cell` so checks never dirty `Tracked`). + sweep: Cell, + /// Per-plugin idle warmth map (`RefCell` so observations never dirty `Tracked`). + warmth: RefCell>, } impl Dormant { @@ -142,7 +188,11 @@ pub fn note_started(app: &mut App, i: usize) { events: p.half.events.borrow().iter().map(|(_, prefix, _, _)| prefix.clone()).collect(), signals, }; + let now = *app.clock; let d = &mut app.plugins.dormant; + let prev = d.warmth.borrow().get(&id).copied(); + let (next, _) = step_warmth(prev, WarmthEvent::Started(now)); + d.warmth.borrow_mut().insert(id.clone(), next); d.ensure_read(); d.records.step(RecordsEvent::Note { id, record }); } @@ -177,49 +227,147 @@ pub fn doze(app: &mut App, i: usize, record: Record, background: bool) { APP_HALVES.with_borrow_mut(|a| a.push((id, app_half))); } -/// A window at rest showing no session (`App::rest`): each built-in a use started goes back to -/// sleep with the record that start wrote, as it is at launch, so its commands, keys and menus stay -/// listed and its next use starts it again. Not one with work of its own (`background`), nor one -/// busy now: a process or run of it, power or a prompt it holds, its dialog or popover open. Not -/// with another window open either, which may show it and shares its app half. +fn sleep_one(app: &mut App, i: usize, id: &str, record: Record, now: f64, reason: &str) { + drive(app, i, LifeEvent::Sleep); + super::app_half::stop(id); + doze(app, i, record, false); + let prev = app.plugins.dormant.warmth.borrow().get(id).copied(); + let (next, _) = step_warmth(prev, WarmthEvent::Slept(now)); + app.plugins.dormant.warmth.borrow_mut().insert(id.to_owned(), next); + eprintln!("plugins: {id} sleeps again ({reason})"); +} + +/// A window at rest showing no session (`App::rest`): sleeps every non-busy, non-background +/// bundled plugin using its recorded contributions so commands, keys, and menus stay listed. pub fn sleep_unused(app: &mut App) { - if app.other_windows() || app.settings_open() { - return; - } + let mut sweep = rune::Tracked::untracked(&app.plugins).dormant.sweep.get(); + let _ = step_sweep(&mut sweep, SweepEvent::Reset); + rune::Tracked::untracked(&app.plugins).dormant.sweep.set(sweep); + if app.other_windows() || app.settings_open() { return; } + let now = *app.clock; let running: Vec<(usize, String)> = app.plugins.list.iter().enumerate() .filter(|(_, p)| p.tier == Tier::Bundled && matches!(p.life, Life::Running(_)) && !super::boot::background(&p.manifest.id)) - .map(|(i, p)| (i, p.manifest.id.clone())) - .collect(); + .map(|(i, p)| (i, p.manifest.id.clone())).collect(); for (i, id) in running { - if busy(app, i, &id) { - continue; - } + if busy(app, i, &id) { continue; } let p = &app.plugins.list[i]; let Some(hash) = super::sources::files_hash(&id, &p.origin, p.tier) else { continue }; let Some(record) = app.plugins.dormant.record(&id, &hash) else { continue }; - drive(app, i, LifeEvent::Sleep); - super::app_half::stop(&id); - doze(app, i, record, false); - eprintln!("plugins: {id} sleeps again (nothing shows it)"); + sleep_one(app, i, &id, record, now, "nothing shows it"); + } +} + +/// At most once per [`ACTIVE_SWEEP_SECS`] during active polls (zero idle wakes), sleeps at most +/// one unused, non-busy, cold (`>= COLD_AFTER_SECS`) bundled plugin VM. +fn poll_active_sleep(app: &mut App) -> bool { + let now = *app.clock; + let plugins = rune::Tracked::untracked(&app.plugins); + let mut sweep = plugins.dormant.sweep.get(); + let effect = step_sweep(&mut sweep, SweepEvent::Poll(now)); + plugins.dormant.sweep.set(sweep); + if !matches!(effect, SweepEffect::Check) || crate::headless() || app.other_windows() || app.settings_open() || !plugins.boot.later().is_empty() { + return false; + } + let mut warmth = plugins.dormant.warmth.borrow_mut(); + warmth.retain(|id, _| plugins.list.iter().any(|p| p.manifest.id == *id)); + let mut coldest: Option<(usize, String, f64)> = None; + for (i, p) in plugins.list.iter().enumerate() { + if p.tier != Tier::Bundled || !matches!(p.life, Life::Running(_)) || super::boot::background(&p.manifest.id) { continue; } + let id = p.manifest.id.as_str(); + let Some(hash) = super::sources::files_hash(id, &p.origin, p.tier) else { continue }; + let Some(record) = plugins.dormant.kept(id, &hash) else { continue }; + let ev = if busy(app, i, id) || shown_in_window(app, i, id, record) { WarmthEvent::InUse(now) } else { WarmthEvent::IdleCheck(now) }; + let (next, eff) = step_warmth(warmth.get(id).copied(), ev); + warmth.insert(id.to_owned(), next); + if let WarmthEffect::Eligible(since) = eff && coldest.as_ref().is_none_or(|(_, _, b)| since < *b) { + coldest = Some((i, id.to_owned(), since)); + } + } + drop(warmth); + let Some((i, id, _)) = coldest else { return false }; + let p = &app.plugins.list[i]; + let Some(hash) = super::sources::files_hash(&id, &p.origin, p.tier) else { return false }; + let Some(record) = app.plugins.dormant.record(&id, &hash) else { return false }; + sleep_one(app, i, &id, record, now, "cold while active"); + #[cfg(not(target_arch = "wasm32"))] + crate::purge_free_pages_soft(); + true +} + +/// Whether plugin `id` is drawn on the active route right now. +fn shown_in_window(app: &App, i: usize, id: &str, record: &Record) -> bool { + if !rune::Tracked::untracked(&app.plugins).list[i].half.contribs.borrow().titlebar_items.is_empty() + || (id == "debug" && super::first_screen::debug_bar_shown()) + || app.layout.narrow.more.drawn_view().and_then(crate::panels::tabs::split_panel_key).is_some_and(|(o, _)| o == id) + { return true; } + let slots = record.window.get("slots").map(Vec::as_slice).unwrap_or(&[]); + fn at_is(e: &opencode_plugin_runtime::dormant::Entry) -> Option<&str> { e.spec.get("at").and_then(serde_json::Value::as_str) } + let own_slot = id != "perf" && id != "debug"; + if own_slot && slots.iter().any(|e| matches!(at_is(e), Some("window.bottom" | "window.right" | "window.overlay" | "sidebar.section" | "sidebar.header"))) { + return true; + } + match rune::Tracked::untracked(&app.route) { + crate::Route::Home | crate::Route::Automations => slots.iter().any(|e| at_is(e) == Some("home.main")), + crate::Route::Draft(_) => slots.iter().any(|e| at_is(e) == Some("new-session.composer.after")), + crate::Route::Session { id: session, .. } => { + if (own_slot && slots.iter().any(|e| !is_new_tab_slot(e))) + || record.window.get("composer_pills").is_some_and(|es| !es.is_empty()) + || (shows_launchers(app, session) && launcher_needs(record)) + { return true; } + let side_state = app.kernel.slots.untracked(&crate::panels::SIDE); + let Some(side) = side_state.sessions.get(app.panel_root(session)) else { return false }; + let side_open = if app.settings.shared_side_panel { side_state.shared_open.unwrap_or(false) } else { side.visibility.open() }; + let tabs = &side.tab_state.tabs; + let mut has_file = false; + for key in &tabs.all { + let vis = match tabs.panes.get(key).copied().unwrap_or(crate::panels::SessionPane::Side) { + crate::panels::SessionPane::Bottom => side.bottom_open, + _ => side_open, + }; + if vis && let Some((owner, _)) = crate::panels::tabs::split_panel_key(key) { + if owner == id { return true; } + has_file |= owner == "file"; + } + } + has_file && record.window.get("file_viewers").is_some_and(|es| !es.is_empty()) + } } } /// Whether plugin i is doing something a stop would end. fn busy(app: &App, i: usize, id: &str) -> bool { - let half = &app.plugins.list[i].half; - let overlay = match &app.plugins.overlay { - Overlay::Popover { plugin, .. } | Overlay::PillMenu { plugin, .. } => &**plugin == id, - Overlay::Closed => false, + let plugins = rune::Tracked::untracked(&app.plugins); + let half = &plugins.list[i].half; + let overlay = matches!(&plugins.overlay, Overlay::Popover { plugin, .. } | Overlay::PillMenu { plugin, .. } if &**plugin == id); + let aux_open = app.kernel.slots.try_untracked(&crate::plugin_host::aux_windows::AUX_MANAGER) + .is_some_and(|m| m.entries.iter().any(|((p, _), e)| &**p == id && e.phase.is_open())); + let inspector_open = app.kernel.slots.try_untracked(&crate::plugin_host::ui::inspector::PLUGIN_INSPECTOR) + .is_some_and(|s| matches!(&s.state, crate::plugin_host::ui::inspector::InspectorState::Open(sess) if sess.plugin_id == id)); + let app_any = |f: &dyn Fn(&Contribs) -> bool| super::app_half::each(|a| (&*a.half.id == id).then(|| f(&a.half.contribs.borrow()))).into_iter().any(|b| b); + let calls = plugins.mcp_calls.borrow(); + let mcp_busy = !calls.is_empty() && { + let owns = |c: &Contribs| calls.values().any(|(call, _)| c.mcp_tools.iter().any(|t| t.spec.name == call.name)); + owns(&half.contribs.borrow()) || app_any(&owns) }; + drop(calls); + let has_source = !half.contribs.borrow().server_sources.is_empty() || app_any(&|c| !c.server_sources.is_empty()); + let source_busy = has_source && (crate::plugin_host::server_sources::remembers(id) + || crate::plugin_host::server_sources::all().iter().any(|(p, _, _)| p == id) + || crate::plugin_host::server_sources::pending_sources().iter().any(|(p, _)| p == id)); half.procs.is_busy() || half.sockets.is_busy() || half.watchers.is_busy() || !half.held.borrow().is_empty() - || app.plugins.shared.audio.borrow().is_busy_for(id) + || plugins.shared.audio.borrow().is_busy_for(id) || (id == "perf" && crate::shell::perf::is_slot_open(app)) - || app.plugins.dialog.as_ref().is_some_and(|d| &*d.plugin == id) || overlay - || super::app_half::each(|a| { - (&*a.half.id == id).then(|| { - a.half.procs.is_busy() || a.half.sockets.is_busy() || a.half.watchers.is_busy() || !a.half.held.borrow().is_empty() - }) - }).into_iter().any(|b| b) + || plugins.dialog.as_ref().is_some_and(|d| &*d.plugin == id) + || overlay || aux_open || inspector_open || mcp_busy || source_busy + || crate::plugin_host::native::embeds::has_any(app, id) + || crate::plugin_host::ui::prompt_dialog::is_open(app) + || plugins.pending_requests.borrow().iter().any(|(p, _)| &**p == id) + || plugins.model_badges.get(id).is_some_and(|(_, m)| !m.is_empty()) + || plugins.go_usage.contains_key(id) + || app.settings.theme.strip_prefix(id).is_some_and(|r| r.starts_with(':')) + || super::app_half::each(|a| (&*a.half.id == id).then(|| + a.half.procs.is_busy() || a.half.sockets.is_busy() || a.half.watchers.is_busy() || !a.half.held.borrow().is_empty() + )).into_iter().any(|b| b) } /// One window's dormant app half `id` is gone (it started, was turned off, or its window closed). @@ -241,7 +389,20 @@ pub fn close(host: &PluginHost) { thread_local! { /// The app halves of dormant plugins, as their records list them: their app menu rows and MCP /// tools, which the app lists without a window (`commands::menubar_items`). - static APP_HALVES: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; + static APP_HALVES: RefCell> = const { RefCell::new(Vec::new()) }; + /// Interned `plugin..woke` perf-mark labels (at most one allocation per plugin id). + static WAKE_MARKS: RefCell> = const { RefCell::new(BTreeMap::new()) }; +} + +fn wake_mark(id: &str) -> &'static str { + WAKE_MARKS.with_borrow_mut(|m| { + if let Some(&s) = m.get(id) { + return s; + } + let s: &'static str = Box::leak(format!("plugin.{id}.woke").into_boxed_str()); + m.insert(id.to_owned(), s); + s + }) } /// Runs `f` on each dormant app half's recorded contributions, once per plugin, but for those whose @@ -298,7 +459,7 @@ pub fn wake(app: &mut App, id: &str, why: Why) -> bool { let running = app.plugins.list[i].running(); let when = match why { Why::Use => "first use", Why::Near => "next turn (a session near, or a surface showing it)", Why::Idle => "idle time" }; eprintln!("plugins: started {id} at its {when} in {} us; {caught} server events kept while it slept go to it", started.elapsed().as_micros()); - rune::marks::mark(Box::leak(format!("plugin.{id}.woke").into_boxed_str())); + rune::marks::mark(wake_mark(id)); bump(); running } @@ -306,6 +467,7 @@ pub fn wake(app: &mut App, id: &str, why: Why) -> bool { /// Plugin `id` was turned off or replaced while dormant: its recorded contributions go with it. pub fn forget(app: &mut App, id: &str) { app.plugins.dormant.catch_up.remove(id); + app.plugins.dormant.warmth.borrow_mut().remove(id); if app.plugins.dormant.asleep.remove(id).is_some() { if let Some(half) = app.plugins.half(id) { *half.contribs.borrow_mut() = Contribs::default(); @@ -602,11 +764,11 @@ pub fn poll(app: &mut App, tx: &mut Tx) -> bool { } return true; } - let Some(id) = due(Wait::Idle) else { return false }; + let Some(id) = due(Wait::Idle) else { return poll_active_sleep(app) }; let quiet = crate::idle::quiet_for(); if quiet < crate::idle::AFTER { tx.wake_after(crate::idle::AFTER - quiet); - return false; + return poll_active_sleep(app); } // In pieces, one a turn: its app half first, then the rest (`wake`), so a key that comes // meanwhile waits for one piece, not the whole start. diff --git a/apps/desktop/src/workspace/lifecycle/restore.rs b/apps/desktop/src/workspace/lifecycle/restore.rs index c2686178c..809e7da89 100644 --- a/apps/desktop/src/workspace/lifecycle/restore.rs +++ b/apps/desktop/src/workspace/lifecycle/restore.rs @@ -777,7 +777,7 @@ impl Feature for RestoreFeature { builder .schedule(stage::REACT_SHELL, "restore.show_draft", |s, _, _| s.show_draft()) .after("narrow.poll"); - builder.schedule(stage::PERSIST_FLUSH, "restore.persist", |s, _, tx| { + builder.schedule(stage::PERSIST_FLUSH, "restore.persist", |s, now, tx| { if !s.persists() { return false; } @@ -785,7 +785,7 @@ impl Feature for RestoreFeature { changed |= s.tell_storage_notice(); changed |= s.hydrate_restore(); changed |= crate::crash_notice::poll(s); - s.poll_restore(); + if !s.window.is_settings() { poll_restore_debounced(s, now, tx); } s.poll_preview(false); changed |= s.poll_copies(tx); changed diff --git a/features/restore/src/copies.rs b/features/restore/src/copies.rs index 74d230cc5..cf525cbb1 100644 --- a/features/restore/src/copies.rs +++ b/features/restore/src/copies.rs @@ -105,7 +105,8 @@ pub fn poll_copies(host: &mut dyn RestoreHost, tx: &mut Tx) -> bool { { ask_copy(host, &server, &id); } - if !host.restore().copies.has_arrived.swap(false, Ordering::AcqRel) { + let has_arrived = &host.restore().copies.has_arrived; + if !has_arrived.load(Ordering::Acquire) || !has_arrived.swap(false, Ordering::AcqRel) { return false; } let arrived = std::mem::take(&mut *host.restore().copies.arrived.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); @@ -165,7 +166,8 @@ pub(crate) fn queue_encode( /// Hands any background-encoded copies that are still current to storage. pub(crate) fn flush_encoded(host: &mut dyn RestoreHost) { - if !host.restore().copies.has_encoded.swap(false, Ordering::AcqRel) { + let has_encoded = &host.restore().copies.has_encoded; + if !has_encoded.load(Ordering::Acquire) || !has_encoded.swap(false, Ordering::AcqRel) { return; } let ready = std::mem::take( diff --git a/features/restore/src/draft_doc.rs b/features/restore/src/draft_doc.rs index 9a663b969..6cca02efb 100644 --- a/features/restore/src/draft_doc.rs +++ b/features/restore/src/draft_doc.rs @@ -61,6 +61,18 @@ impl Blobs { pub fn pending_keys(&self) -> impl Iterator + '_ { self.pending.keys() } + + /// Lock-free check whether storage answers are queued (avoids atomic writes on idle frames). + pub(crate) fn has_arrived(&self) -> bool { + self.has_arrived.load(Ordering::Acquire) + } + + fn insert_id(&mut self, at: usize, weak: Weak<[u8]>, id: String) { + if self.ids.len() >= 64 { + self.ids.retain(|_, (w, _)| w.strong_count() > 0); + } + self.ids.insert(at, (weak, id)); + } } /// A draft's pieces besides its words, borrowed where they live (the composer's own for the @@ -265,7 +277,7 @@ pub fn poll_draft_files(host: &mut dyn RestoreHost) -> bool { })); } } - if !host.restore().blobs.has_arrived.swap(false, Ordering::AcqRel) { + if !host.restore().blobs.has_arrived() || !host.restore().blobs.has_arrived.swap(false, Ordering::AcqRel) { return false; } let arrived = std::mem::take(&mut *host.restore().blobs.arrived.lock().unwrap_or_else(std::sync::PoisonError::into_inner)); @@ -279,7 +291,7 @@ pub fn poll_draft_files(host: &mut dyn RestoreHost) -> bool { Arrival::Stored { at, bytes, id } => { let blobs = &mut host.restore_mut().blobs; blobs.asked.remove(&at); - blobs.ids.insert(at, (bytes, id)); + blobs.insert_id(at, bytes, id); } Arrival::Read { draft, entry, file } => { { @@ -293,7 +305,7 @@ pub fn poll_draft_files(host: &mut dyn RestoreHost) -> bool { } let Some(file) = file else { continue }; let id = entry["blob"]["id"].as_str().unwrap_or_default().to_owned(); - host.restore_mut().blobs.ids.insert(address(&file.bytes), (Arc::downgrade(&file.bytes), id)); + host.restore_mut().blobs.insert_id(address(&file.bytes), Arc::downgrade(&file.bytes), id); if crate::parked::composer_holds(host, &draft) { host.push_attach_file(file); shown = true; diff --git a/features/restore/src/lib.rs b/features/restore/src/lib.rs index 8069acb60..8448f483e 100644 --- a/features/restore/src/lib.rs +++ b/features/restore/src/lib.rs @@ -43,7 +43,7 @@ pub use parked::{ ContextFile, Parked, composer_holds, composer_parked, draft_has_content, draft_parked, drop_shown_draft, land_upload, park_draft, park_shown_draft, }; -pub use persist::{draft_document_of, draft_documents, draft_tab_key, poll_restore}; +pub use persist::{draft_document_of, draft_documents, draft_tab_key, poll_restore, poll_restore_debounced}; pub use places::{Kept as KeptPlaces, land_place, poll_places, restore_places}; pub use preview::{Previews, encode as encode_preview, poll_preview, preview_place, stamp as preview_stamp}; pub use state::{ @@ -414,13 +414,13 @@ pub fn show_draft(host: &mut dyn RestoreHost) -> bool { host.leave_queue_edits(); let old_shown = host.restore().shown.clone(); host.swap_composer_mode_draft(old_shown.as_deref(), key.as_deref()); - // The field itself (its undo history) waits for the draft to show again. - let edit = host.composer().clone(); + // The field itself (its undo history) waits for the draft to show again when non-empty. + let edit = parked::snapshot_edit(host.composer()); let (text, parked) = parked::take_composer_draft(host); let old = host.restore_mut().shown.take(); if let Some(old) = old { - host.restore_mut().edits.insert(old.clone(), edit); - parked::park_draft(host, old, text, parked); + parked::park_draft(host, old.clone(), text, parked); + parked::keep_edit(host.restore_mut(), old, edit); } // Another draft replaces this one: no list or recalled prompt applies to it (`history.reset`). host.suggest_drop(); diff --git a/features/restore/src/parked.rs b/features/restore/src/parked.rs index 38d805785..8bd43765b 100644 --- a/features/restore/src/parked.rs +++ b/features/restore/src/parked.rs @@ -156,6 +156,30 @@ pub fn park_draft(host: &mut dyn RestoreHost, key: String, text: String, parked: } } +/// Soft cap on in-memory undo-only editors (`Restore::edits`); active unsent drafts are kept, +/// and closed/empty drafts already persist their undo history to storage (`undo.rs`). +const MAX_KEPT_EDITS: usize = 32; + +/// Clones `composer` only when it holds text or undo history worth preserving across switches. +pub(crate) fn snapshot_edit(composer: &TextEdit) -> Option { + (!composer.text.is_empty() || composer.history_len() != (0, 0)).then(|| composer.clone()) +} + +/// Stores or removes a parked editor and prunes stale undo-only entries past [`MAX_KEPT_EDITS`]. +pub(crate) fn keep_edit(r: &mut crate::Restore, key: String, edit: Option) { + match edit { + Some(e) => { + r.edits.insert(key.clone(), e); + if r.edits.len() > MAX_KEPT_EDITS { + r.edits.retain(|k, _| k == &key || r.drafts.contains_key(k)); + } + } + None => { + r.edits.remove(&key); + } + } +} + /// Takes the shown draft out of the composer: its words and the rest. pub(crate) fn take_composer_draft(host: &mut dyn RestoreHost) -> (String, Parked) { let (pills, caret) = { @@ -219,10 +243,10 @@ pub fn park_shown_draft(host: &mut dyn RestoreHost) { } let Some(key) = host.restore_mut().shown.take() else { return }; host.swap_composer_mode_draft(Some(key.as_str()), None); - let edit = host.composer().clone(); + let edit = snapshot_edit(host.composer()); let (text, parked) = take_composer_draft(host); - host.restore_mut().edits.insert(key.clone(), edit); - park_draft(host, key, text, parked); + park_draft(host, key.clone(), text, parked); + keep_edit(host.restore_mut(), key, edit); let composer = host.composer_mut(); let focused = composer.focused; *composer = TextEdit::new(""); diff --git a/features/restore/src/persist.rs b/features/restore/src/persist.rs index 517db3034..3086a0f88 100644 --- a/features/restore/src/persist.rs +++ b/features/restore/src/persist.rs @@ -17,7 +17,7 @@ use opencode_runtime::composer_mode::Mode; use opencode_servers::tabs::ClosedTab; use serde_json::{Value, json}; -use crate::state::organize_expanded_sorted; +use crate::state::{PersistDebounceEffect, PersistDebounceEvent, organize_expanded_sorted}; use crate::{ContextFile, GLOBAL, Parked, RestoreHost, RestoreRoute, RestoreTab, RestoreVersions, doc, draft_doc, hydrated, parked, undo}; /// The page as Desktop's last active URL keeps it (`route-storage.ts`): Settings, while open, is @@ -589,9 +589,10 @@ fn poll_restore_versioned(host: &mut dyn RestoreHost, v: RestoreVersions) { if prev == Some(v) { return; } - if prev.is_none_or(|p| p.route != v.route) { + if host.restore().exit_route_ver.get() != Some(v.route) { let active = host.active_session_id().map(str::to_owned); host.set_active_exit_session(active.as_deref()); + host.restore().exit_route_ver.set(Some(v.route)); } if !host.persists() { host.restore().versions.set(Some(v)); @@ -705,7 +706,44 @@ fn poll_restore_versioned(host: &mut dyn RestoreHost, v: RestoreVersions) { /// database behind). Callers outside the scheduled tick (`save_on_close`, `save_on_quit`, /// visibility hide) run `show_draft` and `hydrate_restore` first; the per-frame schedule already /// runs them before `poll_restore`. +/// Scheduled per-frame persistence tick: debounces rapid version churn (side/sidebar resize drags, +/// continuous typing, active session streaming) via `PersistDebounce` (1 s settle, 2 s max wait) +/// while keeping crash-recovery route tracking and draft blob uploads immediate. Hide/close/quit +/// paths call [`poll_restore`] directly to flush synchronously with zero data loss. +pub fn poll_restore_debounced(host: &mut dyn RestoreHost, now: f64, tx: &mut rune::Tx) { + if host.persists() && host.restore().blobs.has_arrived() { + draft_doc::poll_draft_files(host); + } + let Some(mut v) = host.restore_versions() else { + poll_restore(host); + return; + }; + let persisted = host.restore().versions.get(); + if host.persists() && persisted.is_none_or(|p| p.attach != v.attach || p.restore != v.restore) { + draft_doc::poll_draft_files(host); + if let Some(next_v) = host.restore_versions() { + v = next_v; + } + } + if host.restore().exit_route_ver.get() != Some(v.route) { + let active = host.active_session_id().map(str::to_owned); + host.set_active_exit_session(active.as_deref()); + host.restore().exit_route_ver.set(Some(v.route)); + } + let mut debounce = host.restore().debounce.get(); + let effect = debounce.step(PersistDebounceEvent::Poll { current: v, persisted, now }); + host.restore().debounce.set(debounce); + match effect { + PersistDebounceEffect::Skip => {} + PersistDebounceEffect::WakeAt(at) => tx.wake_at(at), + PersistDebounceEffect::FlushNow => poll_restore_versioned(host, v), + } +} + pub fn poll_restore(host: &mut dyn RestoreHost) { + let mut debounce = host.restore().debounce.get(); + let _ = debounce.step(PersistDebounceEvent::Flushed); + host.restore().debounce.set(debounce); if host.persists() { draft_doc::poll_draft_files(host); } diff --git a/features/restore/src/preview.rs b/features/restore/src/preview.rs index b8073681d..9f5a4908e 100644 --- a/features/restore/src/preview.rs +++ b/features/restore/src/preview.rs @@ -122,6 +122,9 @@ fn write_preview(host: &mut dyn RestoreHost, server: &str, id: &str, msg_stamp: host.restore_mut().previews.0.insert(id.to_owned(), (msg_stamp, turn)); // Kept for the sessions that have a tab: a closed one's preview goes with it. let tabs = host.session_tab_ids(); + if host.restore().previews.0.len() > 64 { + host.restore_mut().previews.0.retain(|session, _| session == id || tabs.contains(session)); + } host.storage_update_json(crate::GLOBAL, OLDER, &mut |map| { map.retain(|session, _| session == id || tabs.contains(session)); if older { diff --git a/features/restore/src/state.rs b/features/restore/src/state.rs index 48a064dd4..5a7c34b36 100644 --- a/features/restore/src/state.rs +++ b/features/restore/src/state.rs @@ -203,6 +203,76 @@ pub fn parse_inbox_server_cutoffs(v: &Value) -> Option> { Some(map) } +/// Trailing quiet delay before live `restore.persist` serializes and diffs dirty state. +pub(crate) const PERSIST_SETTLE_SECS: f64 = 1.0; +/// Maximum delay from the first unpersisted change during continuous drag, typing, or streaming. +pub(crate) const PERSIST_MAX_WAIT_SECS: f64 = 2.0; + +/// Explicit debounce state machine for scheduled `restore.persist` version changes. +/// Stored in a `Cell` on [`Restore`] so tracking dirty windows never bumps the tracked slot. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub(crate) enum PersistDebounce { + #[default] + Clean, + Pending { seen: RestoreVersions, first_dirty: f64, due: f64, wake_armed: f64 }, +} + +pub(crate) enum PersistDebounceEvent { + Poll { current: RestoreVersions, persisted: Option, now: f64 }, + Flushed, +} + +pub(crate) enum PersistDebounceEffect { + Skip, + WakeAt(f64), + FlushNow, +} + +impl PersistDebounce { + pub(crate) fn step(&mut self, event: PersistDebounceEvent) -> PersistDebounceEffect { + match (*self, event) { + (_, PersistDebounceEvent::Flushed) => { + *self = Self::Clean; + PersistDebounceEffect::Skip + } + (_, PersistDebounceEvent::Poll { current, persisted: Some(prev), .. }) if current == prev => { + *self = Self::Clean; + PersistDebounceEffect::Skip + } + // Initial poll and hydration transitions flush immediately so boot split settles at once. + (_, PersistDebounceEvent::Poll { current, persisted, .. }) + if persisted.is_none_or(|p| p.hydrated != current.hydrated) => + { + *self = Self::Clean; + PersistDebounceEffect::FlushNow + } + (Self::Clean, PersistDebounceEvent::Poll { current, now, .. }) => { + let due = now + PERSIST_SETTLE_SECS; + *self = Self::Pending { seen: current, first_dirty: now, due, wake_armed: due }; + PersistDebounceEffect::WakeAt(due) + } + (Self::Pending { seen, first_dirty, due, wake_armed }, PersistDebounceEvent::Poll { current, now, .. }) => { + let origin = first_dirty.min(now); + let next_due = if current == seen && now >= first_dirty { + due + } else { + (now + PERSIST_SETTLE_SECS).min(origin + PERSIST_MAX_WAIT_SECS) + }; + if now + 1e-6 >= next_due { + *self = Self::Clean; + PersistDebounceEffect::FlushNow + } else if wake_armed > now + 1e-6 && wake_armed <= next_due + 1e-6 { + *self = Self::Pending { seen: current, first_dirty: origin, due: next_due, wake_armed }; + PersistDebounceEffect::Skip + } else { + *self = Self::Pending { seen: current, first_dirty: origin, due: next_due, wake_armed: next_due }; + PersistDebounceEffect::WakeAt(next_due) + } + } + } + } +} + /// Cheap monotonic version tuple read per poll so [`crate::poll_restore`] skips hashing and /// sorting on idle frames and rebuilds only the dirty persistence groups when something changes. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -272,6 +342,10 @@ pub struct Restore { /// Last seen monotonic version tuple from `RestoreHost::restore_versions` (`Cell` so recording /// post-write versions never bumps the `RESTORE` tracked slot). pub(crate) versions: Cell>, + /// Debounce phase for per-frame scheduled `restore.persist` ticks (`Cell`: zero slot bumps). + pub(crate) debounce: Cell, + /// Last `route` version forwarded to `set_active_exit_session` immediately on route switch. + pub(crate) exit_route_ver: Cell>, /// Order-independent hash of the last open-tab + routed-session ID set used for `side`/`side.rest`. pub(crate) hot_side_hash: Cell>, /// Last verified 128-bit stamp of `side.rest`'s persisted non-hot sessions + `shared_open` @@ -312,6 +386,8 @@ impl Restore { /// rebuild and value diff (used on forced flush / shutdown without bumping `RESTORE`). pub fn invalidate_cached_stamps(&self) { self.versions.set(None); + self.debounce.set(PersistDebounce::Clean); + self.exit_route_ver.set(None); self.hot_side_hash.set(None); self.side_rest_stamp.set(None); self.drafts_stamp.set(None); diff --git a/features/restore/src/undo.rs b/features/restore/src/undo.rs index b6bb2426c..79f33305d 100644 --- a/features/restore/src/undo.rs +++ b/features/restore/src/undo.rs @@ -182,7 +182,8 @@ pub fn poll_undo(host: &mut dyn RestoreHost, now: f64, tx: &mut Tx) { /// Stores the histories workers finished, each unless its draft was dropped or written again /// since it was sent. fn store_done_histories(host: &mut dyn RestoreHost) { - if !host.restore().undo.has_done.swap(false, Ordering::AcqRel) { + let has_done = &host.restore().undo.has_done; + if !has_done.load(Ordering::Acquire) || !has_done.swap(false, Ordering::AcqRel) { return; } let done = std::mem::take(&mut *host.restore().undo.done.lock().unwrap_or_else(std::sync::PoisonError::into_inner));