diff --git a/apps/desktop/src/plugin_host/bridge/commands.rs b/apps/desktop/src/plugin_host/bridge/commands.rs index 3dfa12f91..6a14d89f0 100644 --- a/apps/desktop/src/plugin_host/bridge/commands.rs +++ b/apps/desktop/src/plugin_host/bridge/commands.rs @@ -22,7 +22,9 @@ use crate::plugin_host::{app_half, dormant, panels, plugin}; /// Runs `f(...args)` of plugin `i` as a task, then carries out what it asked for. pub fn spawn(app: &mut App, i: usize, f: &JsFn, args: &[Data], tx: &mut Tx) { - let Some(script) = app.plugins.list.get(i).and_then(|p| p.adopted_script()) else { return }; + let Some(p) = app.plugins.list.get(i) else { return }; + dormant::note_in_use(app, &p.manifest.id); + let Some(script) = p.adopted_script() else { return }; cx::enter(app, || script.spawn_fn(f, args, Some(&mut *tx)).ok()); super::requests::carry_out(app, tx); } @@ -132,6 +134,7 @@ pub fn run(app: &mut App, id: &str, input: Option<&str>, tx: &mut Tx) -> bool { let Some((i, f)) = app.plugins.running().find_map(|(i, p)| Some((i, p.half.contribs.borrow().commands.iter().find(|c| c.key == id)?.f("run")?.clone()))) else { return false; }; + dormant::note_in_use(app, &app.plugins.list[i].manifest.id); let Some(script) = app.plugins.list[i].adopted_script() else { return false }; let Some(Ok(wrap)) = script.with_ctx(command_wrapper) else { return false }; struct RestoreDeclined(bool); @@ -580,6 +583,7 @@ pub fn mcp_call(app: &mut App, call: McpCall, session: &str, directory: &str, tx dormant::wake_owners(app, |c| c.mcp_tools.iter().any(|t| t.spec.name == call.name)); let found = app.plugins.running().find_map(|(i, p)| Some((i, p.half.contribs.borrow().mcp_tools.iter().find(|c| c.spec.name == call.name)?.f("call")?.clone()))); let Some((i, f)) = found else { return Some(call) }; + dormant::note_in_use(app, &app.plugins.list[i].manifest.id); let Some(script) = app.plugins.list[i].adopted_script() else { return Some(call) }; let wrap = match script.with_ctx(tool_wrapper) { Some(Ok(w)) => w, @@ -722,6 +726,7 @@ pub fn run_menubar(app: &mut App, key: &str, tx: &mut Tx) -> bool { .into_iter() .next(); let Some((plugin_id, f)) = found else { return false }; + dormant::note_in_use(app, &plugin_id); if let Some(target) = app_half::find(&plugin_id) { cx::enter(app, || target.script.spawn_fn(&f, &[], Some(&mut *tx)).ok()); } diff --git a/apps/desktop/src/plugin_host/native/browser.rs b/apps/desktop/src/plugin_host/native/browser.rs index 6ddb103d7..8ad1b675f 100644 --- a/apps/desktop/src/plugin_host/native/browser.rs +++ b/apps/desktop/src/plugin_host/native/browser.rs @@ -319,9 +319,7 @@ pub fn build(ctx: &mut HostCtx<'_>, vmx: &Rc, obj: Val) -> JsResult<()> { cookies::service_methods(ctx, obj)?; extensions::service_methods(ctx, obj)?; - let raw_open = ctx.async_fn("Browser.OpenAsync", |ctx, args, done| { - open(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); + let raw_open = opencode_plugin_runtime::js::tracked_async_fn(ctx, "Browser.OpenAsync", open)?; let open_wrapped = opencode_plugin_runtime::chunk::eval_call( ctx, "=Browser.OpenAsync", diff --git a/apps/desktop/src/plugin_host/native/browser/history.rs b/apps/desktop/src/plugin_host/native/browser/history.rs index c61e02629..cfa0cb7f1 100644 --- a/apps/desktop/src/plugin_host/native/browser/history.rs +++ b/apps/desktop/src/plugin_host/native/browser/history.rs @@ -310,9 +310,7 @@ pub(super) fn service_methods(ctx: &mut HostCtx<'_>, obj: Val) -> JsResult<()> { Ok(data_to_val(ctx, &out)) }); - let raw_import = ctx.async_fn("Browser.HistoryImportProfileAsync", |ctx, args, done| { - import_profile_async(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); + let raw_import = opencode_plugin_runtime::js::tracked_async_fn(ctx, "Browser.HistoryImportProfileAsync", import_profile_async)?; let wrapped = opencode_plugin_runtime::chunk::eval_call( ctx, "=Browser.HistoryImportProfileAsync", diff --git a/apps/desktop/src/plugin_host/native/browser/tab.rs b/apps/desktop/src/plugin_host/native/browser/tab.rs index 5a55db1a5..5429b6f89 100644 --- a/apps/desktop/src/plugin_host/native/browser/tab.rs +++ b/apps/desktop/src/plugin_host/native/browser/tab.rs @@ -54,21 +54,12 @@ fn tab_asyncs(ctx: &mut HostCtx<'_>) -> JsResult { if let Some(existing) = ctx.get_user_data::() { return Ok(existing); } - let raw_devtools = ctx.async_fn("BrowserTab.DevtoolsAsync", |ctx, args, done| { - devtools::devtools(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); - let raw_site_cookies = ctx.async_fn("BrowserTab.SiteCookiesAsync", |ctx, args, done| { - devtools::site_cookies(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); - let raw_clear_site = ctx.async_fn("BrowserTab.ClearSiteAsync", |ctx, args, done| { - devtools::clear_site(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); - let raw_clear_cache = ctx.async_fn("BrowserTab.ClearCacheAsync", |ctx, args, done| { - chrome::clear_cache(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); - let raw_read_file = ctx.async_fn("BrowserTab.ReadFileAsync", |ctx, args, done| { - chrome::read_file(ctx, args, done).map_err(|e| e.to_val(ctx)) - }); + use opencode_plugin_runtime::js::tracked_async_fn; + let raw_devtools = tracked_async_fn(ctx, "BrowserTab.DevtoolsAsync", devtools::devtools)?; + let raw_site_cookies = tracked_async_fn(ctx, "BrowserTab.SiteCookiesAsync", devtools::site_cookies)?; + let raw_clear_site = tracked_async_fn(ctx, "BrowserTab.ClearSiteAsync", devtools::clear_site)?; + let raw_clear_cache = tracked_async_fn(ctx, "BrowserTab.ClearCacheAsync", chrome::clear_cache)?; + let raw_read_file = tracked_async_fn(ctx, "BrowserTab.ReadFileAsync", chrome::read_file)?; let wrapped = opencode_plugin_runtime::chunk::eval_call( ctx, "=BrowserTab.asyncs", diff --git a/apps/desktop/src/plugin_host/runtime/dormant.rs b/apps/desktop/src/plugin_host/runtime/dormant.rs index e23c1407b..ba9fcbe1f 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::RefCell; use std::collections::BTreeMap; use std::time::Duration; @@ -32,12 +33,17 @@ pub use opencode_plugin_runtime::dormant::{Asleep, Record, Wait, Why}; use opencode_plugin_runtime::dormant::{Records, RecordsEffect, RecordsEvent, contribs_of, parse_records, record_kinds}; use rune::Tx; +pub(crate) use super::dormant_sweep::poll_active_sleep; +pub use super::dormant_sweep::{note_in_use, sleep_unused}; +use super::dormant_sweep::ActiveSleep; use super::plugin::Contribs; use crate::App; -use crate::plugin_host::{Life, LifeEvent, Overlay, PluginHost, Tier, bump, drive, tasks}; +use crate::plugin_host::{Life, LifeEvent, PluginHost, Tier, bump, drive, tasks}; /// Server events kept for one dormant plugin; the oldest go first past it. const KEPT_EVENTS: usize = 256; +/// Defensive cap on interned `plugin..woke` perf-mark labels. +const MAX_WAKE_MARKS: usize = 128; /// The window's dormant plugins and the records file as this window read it. #[derive(Default)] @@ -48,9 +54,11 @@ 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 dormancy cadence and per-plugin warmth table. + pub(super) active: ActiveSleep, } impl Dormant { @@ -88,7 +96,7 @@ fn panel_rows(record: &Record) -> impl Iterator bool { +pub(super) fn is_new_tab_slot(e: &opencode_plugin_runtime::dormant::Entry) -> bool { matches!(e.spec.get("at").and_then(|v| v.as_str()), Some("session.panel.new" | "session.panel.new.list")) } @@ -142,7 +150,9 @@ 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; + d.active.note_started(&id, now); d.ensure_read(); d.records.step(RecordsEvent::Note { id, record }); } @@ -177,51 +187,6 @@ 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. -pub fn sleep_unused(app: &mut App) { - if app.other_windows() || app.settings_open() { - return; - } - 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(); - for (i, id) in running { - 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)"); - } -} - -/// 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, - }; - 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) - || (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) -} - /// One window's dormant app half `id` is gone (it started, was turned off, or its window closed). fn release_app_half(id: &str) { APP_HALVES.with_borrow_mut(|a| { @@ -241,7 +206,23 @@ 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; + } + if m.len() >= MAX_WAKE_MARKS { + return "plugin.woke"; + } + 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 +279,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 +287,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.active.forget(id); if app.plugins.dormant.asleep.remove(id).is_some() { if let Some(half) = app.plugins.half(id) { *half.contribs.borrow_mut() = Contribs::default(); diff --git a/apps/desktop/src/plugin_host/runtime/dormant_sweep.rs b/apps/desktop/src/plugin_host/runtime/dormant_sweep.rs new file mode 100644 index 000000000..9907be1db --- /dev/null +++ b/apps/desktop/src/plugin_host/runtime/dormant_sweep.rs @@ -0,0 +1,435 @@ +//! Periodic active-window dormancy sweep and busy/visibility guards for bundled plugins. +//! +//! Runs both from `App::on_rest` ([`sleep_unused`], sleeping all non-busy bundled plugins on Home) +//! and once per [`ACTIVE_SWEEP_SECS`] inside `lifecycle::poll` ([`poll_active_sleep`], putting at +//! most one unused, non-busy, cold bundled plugin VM to sleep after [`COLD_AFTER_SECS`], with zero +//! idle wake timers so `App::on_rest` remains undisturbed). + +use std::cell::{Cell, RefCell}; +use std::collections::BTreeMap; + +use opencode_plugin_runtime::dormant::{Entry, Record}; +use rune::Tx; + +use super::dormant::{doze, is_new_tab_slot, launcher_needs, shows_launchers}; +use super::plugin::Contribs; +use crate::App; +use crate::plugin_host::{Life, LifeEvent, Overlay, Tier, drive}; + +/// Active-window dormancy check cadence (seconds). Piggybacks on existing polls with zero idle wakes. +const ACTIVE_SWEEP_SECS: f64 = 60.0; +/// Grace window (seconds) a running bundled plugin stays completely unused before sleeping. +const COLD_AFTER_SECS: f64 = 120.0; +/// Re-waking within this window after active sleep doubles that plugin's cooldown to prevent ping-pong. +const PING_PONG_SECS: f64 = 15.0; +/// Upper bound (seconds) on active-sleep backoff cooldown. +const MAX_COOLDOWN_SECS: f64 = 960.0; + +/// Explicit cadence state machine for periodic active-window dormancy checks. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +enum SweepPhase { + #[default] + Idle, + Armed { armed_at: f64, 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 { armed_at: now, due: now + ACTIVE_SWEEP_SECS }; + SweepEffect::None + } + // Clock moved backwards (e.g. story reset): re-arm cleanly instead of stalling. + (SweepPhase::Armed { armed_at, .. }, SweepEvent::Poll(now)) if now < armed_at => { + *state = SweepPhase::Armed { armed_at: now, due: now + ACTIVE_SWEEP_SECS }; + SweepEffect::None + } + (SweepPhase::Armed { due, .. }, SweepEvent::Poll(now)) if now + 1e-6 >= due => { + *state = SweepPhase::Armed { armed_at: now, 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 prev_cd = match state { + 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 => { + let eff = if now - since + 1e-6 >= cooldown { + WarmthEffect::Eligible(since) + } else { + WarmthEffect::Keep + }; + (Warmth::Warm { since, cooldown }, eff) + } + (_, WarmthEvent::IdleCheck(now)) => { + (Warmth::Warm { since: now, cooldown: COLD_AFTER_SECS }, WarmthEffect::Keep) + } + (_, WarmthEvent::Slept(now)) => { + (Warmth::Slept { at: now, cooldown: prev_cd }, WarmthEffect::Keep) + } + } +} + +/// Interior-mutable sweep cadence and per-plugin warmth table embedded in [`super::dormant::Dormant`] +/// so periodic reads and observations never dirty `Tracked`. +#[derive(Default)] +pub(super) struct ActiveSleep { + sweep: Cell, + warmth: RefCell>, +} + +impl ActiveSleep { + pub(super) fn note_started(&self, id: &str, now: f64) { + let mut map = self.warmth.borrow_mut(); + let (next, _) = step_warmth(map.get(id).copied(), WarmthEvent::Started(now)); + map.insert(id.to_owned(), next); + } + + pub(super) fn note_in_use(&self, id: &str, now: f64) { + let mut map = self.warmth.borrow_mut(); + let (next, _) = step_warmth(map.get(id).copied(), WarmthEvent::InUse(now)); + map.insert(id.to_owned(), next); + } + + pub(super) fn note_slept(&self, id: &str, now: f64) { + let mut map = self.warmth.borrow_mut(); + let (next, _) = step_warmth(map.get(id).copied(), WarmthEvent::Slept(now)); + map.insert(id.to_owned(), next); + } + + pub(super) fn forget(&self, id: &str) { + self.warmth.borrow_mut().remove(id); + } + + fn reset_sweep(&self) { + let mut phase = self.sweep.get(); + let _ = step_sweep(&mut phase, SweepEvent::Reset); + self.sweep.set(phase); + } +} + +/// Marks plugin `id` as actively used right now (e.g. command, action, or MCP tool dispatch) +/// without dirtying `Tracked`. +pub fn note_in_use(app: &App, id: &str) { + let now = *rune::Tracked::untracked(&app.clock); + rune::Tracked::untracked(&app.plugins).dormant.active.note_in_use(id, now); +} + +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); + rune::Tracked::untracked(&app.plugins).dormant.active.note_slept(id, now); + 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. +/// Skips whenever any other live window exists (main, popped-out Settings, or torn) because all +/// windows share `app_half`. +pub fn sleep_unused(app: &mut App) { + rune::Tracked::untracked(&app.plugins).dormant.active.reset_sweep(); + if app.any_other_live_window() || 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(); + for (i, id) in running { + 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 }; + sleep_one(app, i, &id, record, now, "nothing shows it"); + } +} + +/// Runs at the end of `lifecycle::poll` (after server event delivery and `requests::carry_out`): +/// at most once per [`ACTIVE_SWEEP_SECS`] with zero idle wakes, puts at most one unused, non-busy, +/// cold (`>= COLD_AFTER_SECS`) bundled plugin VM back to sleep. +pub(crate) fn poll_active_sleep(app: &mut App, tx: &Tx) -> bool { + if tx.input_waiting() || crate::launch::trace::held().is_some() { + return false; + } + let now = *app.clock; + let plugins = rune::Tracked::untracked(&app.plugins); + let mut phase = plugins.dormant.active.sweep.get(); + let effect = step_sweep(&mut phase, SweepEvent::Poll(now)); + plugins.dormant.active.sweep.set(phase); + if !matches!(effect, SweepEffect::Check) + || crate::headless() + || app.any_other_live_window() + || app.settings_open() + || !plugins.boot.later().is_empty() + || !plugins.events.borrow().is_empty() + { + return false; + } + let mut warmth = plugins.dormant.active.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(|(_, _, best)| since < *best) + { + 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 +} + +fn slot_at(e: &Entry) -> Option<&str> { + e.spec.get("at").and_then(serde_json::Value::as_str) +} + +fn has_non_empty(record: &Record, kind: &str) -> bool { + record.window.get(kind).is_some_and(|es| !es.is_empty()) +} + +fn has_mobile_panel(record: &Record) -> bool { + record + .window + .get("panels") + .is_some_and(|es| es.iter().any(|e| e.spec.get("mobile").is_some_and(|v| !v.is_null()))) +} + +fn has_native_browser_tabs(app: &App, id: &str) -> bool { + #[cfg(not(target_arch = "wasm32"))] + { + id == crate::surfaces::browser::PLUGIN + && !rune::Tracked::untracked(&app.workspace_panes.browser).host.tabs().is_empty() + } + #[cfg(target_arch = "wasm32")] + { + let _ = (app, id); + false + } +} + +/// Whether plugin `id` is shown on or backing 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() { + return true; + } + if id == "debug" + && (super::first_screen::debug_bar_shown() || crate::plugin_host::services::diag::memory_log_active()) + { + return true; + } + let more_owner = app + .layout + .narrow + .more + .drawn_view() + .and_then(crate::panels::tabs::split_panel_key) + .map(|(owner, _)| owner); + if more_owner == Some(id) { + return true; + } + let slots = record.window.get("slots").map(Vec::as_slice).unwrap_or(&[]); + let own_slot = id != "perf" && id != "debug"; + if own_slot + && slots.iter().any(|e| { + matches!( + slot_at(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| slot_at(e) == Some("home.main")), + crate::Route::Draft(_) => slots.iter().any(|e| slot_at(e) == Some("new-session.composer.after")), + crate::Route::Session { id: session, .. } => { + if (own_slot && slots.iter().any(|e| !is_new_tab_slot(e))) + || has_non_empty(record, "composer_pills") + || has_non_empty(record, "code_blocks") + || has_non_empty(record, "code_block_actions") + || (shows_launchers(app, session) && launcher_needs(record)) + { + return true; + } + let mut has_file = more_owner == Some("file"); + if app.narrow() { + if has_mobile_panel(record) { + return true; + } + if let Some((owner, _)) = crate::panels::tabs::split_panel_key(app.narrow_view()) { + if owner == id { + return true; + } + has_file |= owner == "file"; + } + } + // Match `dormant::for_session`: protect every plugin in `tabs.all` even when collapsed + // so `features/panels/src/keys.rs` never prunes collapsed `transient: true` tabs. + let side_state = app.kernel.slots.untracked(&crate::panels::SIDE); + if let Some(side) = side_state.sessions.get(app.panel_root(session)) { + for key in &side.tab_state.tabs.all { + if let Some((owner, _)) = crate::panels::tabs::split_panel_key(key) { + if owner == id { + return true; + } + has_file |= owner == "file"; + } + } + } + // `plugins/file` consumes `Contracts.Use("review.changes")` provided by `plugins/review` + // for git status badges (`M`/`A`/`D`), alongside `file_viewers` (e.g. `microsoft-office`). + has_file && (id == "review" || has_non_empty(record, "file_viewers")) + } + } +} + +/// Whether plugin `i` is doing something a stop would end. +fn busy(app: &App, i: usize, id: &str) -> bool { + 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)); + let app_half_busy = 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() + || a.half.has_in_flight_async() + }) + }) + .into_iter() + .any(|b| b); + half.procs.is_busy() + || half.sockets.is_busy() + || half.watchers.is_busy() + || !half.held.borrow().is_empty() + || half.has_in_flight_async() + || app_half_busy + || plugins.shared.audio.borrow().is_busy_for(id) + || (id == "perf" && crate::shell::perf::is_slot_open(app)) + || (id == "debug" && crate::plugin_host::services::diag::memory_log_active()) + || has_native_browser_tabs(app, id) + || 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(':')) +} \ No newline at end of file diff --git a/apps/desktop/src/plugin_host/runtime/lifecycle.rs b/apps/desktop/src/plugin_host/runtime/lifecycle.rs index b19de6ac7..5d259b799 100644 --- a/apps/desktop/src/plugin_host/runtime/lifecycle.rs +++ b/apps/desktop/src/plugin_host/runtime/lifecycle.rs @@ -276,6 +276,7 @@ fn stop(app: &mut App, i: usize, script: Script) { fire_disposing(app, &half, &script, opencode_plugin_spec::DisposeReason::Disable); drop(script); half.adopted_vm.set(None); + half.in_flight_async.borrow_mut().clear(); *half.contribs.borrow_mut() = plugin::Contribs::default(); crate::plugin_host::contrib::bump(); services::reap(&half, None); @@ -453,7 +454,8 @@ pub fn poll(app: &mut App, fresh: bool, transcript_fresh: bool, tx: &mut Tx) -> app.plugins.titlebar_focus = focused_pill.map(str::to_owned); changed = true; } - changed |= dormant::poll(app, tx); + let dormant_woke = dormant::poll(app, tx); + changed |= dormant_woke; changed |= poll_restarts(app, tx); if app.plugins.boot.later().is_empty() { dormant::save(app); @@ -640,9 +642,10 @@ pub fn poll(app: &mut App, fresh: bool, transcript_fresh: bool, tx: &mut Tx) -> perf_spans.as_ref(), crate::shell::perf::spans::POLL_PLUGINS_MEDIA_REQ, None, || crate::plugin_host::aux_windows::sync_renders(app, tx), ); + let slept = !dormant_woke && dormant::poll_active_sleep(app, tx); let exit_store_gen = services::store::generation(); let store_changed = app.plugins.last_store_gen.replace(exit_store_gen) != exit_store_gen; - let tail_changed = sync_changed || entry_epoch != epoch() || store_changed; + let tail_changed = slept || sync_changed || entry_epoch != epoch() || store_changed; changed |= tail_changed; let only_perf_self_img = perf_img_candidate && !non_perf_changed && !tail_changed && !asked; if only_perf_self_img { diff --git a/apps/desktop/src/plugin_host/runtime/mod.rs b/apps/desktop/src/plugin_host/runtime/mod.rs index dc75fc69b..dabea6731 100644 --- a/apps/desktop/src/plugin_host/runtime/mod.rs +++ b/apps/desktop/src/plugin_host/runtime/mod.rs @@ -3,6 +3,7 @@ pub mod app_half; pub(crate) mod boot; pub(crate) mod dormant; +mod dormant_sweep; mod first_screen; pub(crate) mod hot; pub(crate) mod lifecycle; diff --git a/apps/desktop/src/plugin_host/runtime/plugin.rs b/apps/desktop/src/plugin_host/runtime/plugin.rs index 6f3aa593e..9d4fc5d5e 100644 --- a/apps/desktop/src/plugin_host/runtime/plugin.rs +++ b/apps/desktop/src/plugin_host/runtime/plugin.rs @@ -5,6 +5,8 @@ use std::cell::{Cell, RefCell}; use std::collections::{BTreeMap, HashMap}; use std::rc::Rc; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; use rune_psychoscript::{JsFn, JsVal}; @@ -35,6 +37,8 @@ pub struct Half { pub events: RefCell, JsVal)>>, /// Fires a script signal, by VM: `(signal, ...args) => signal.Fire(...args)`. pub fire: RefCell>, + /// Per-VM count of unsettled host async Promises (`async_method` / `tracked_async_fn`). + pub in_flight_async: RefCell>>, /// Optional `ctx.BindHotState` save hook for the active VM. pub hot_save: RefCell>, /// Optional `ctx.BindHotState` load hook for the active VM. @@ -136,6 +140,7 @@ impl Half { signal_mask: Cell::new(0), events: RefCell::default(), fire: RefCell::default(), + in_flight_async: RefCell::default(), hot_save: RefCell::default(), hot_load: RefCell::default(), editors_made: Cell::new(0), @@ -159,6 +164,12 @@ impl Half { }) } + /// Whether the currently adopted VM has any unsettled host async Promises in flight. + pub fn has_in_flight_async(&self) -> bool { + let Some(vm) = self.adopted_vm.get() else { return false }; + self.in_flight_async.borrow().get(&vm).is_some_and(|c| c.load(Ordering::Relaxed) > 0) + } + /// Whether this half belongs to the genuinely bundled built-in plugin `id` (`Tier::Bundled`, /// never a user, override, or dev plugin replacing that id). pub fn is_builtin(&self, id: &str) -> bool { @@ -177,6 +188,7 @@ impl Half { self.recompute_signal_mask(Some(vm)); self.events.borrow_mut().retain(|(v, _, _, _)| *v == vm); self.fire.borrow_mut().retain(|v, _| *v == vm); + self.in_flight_async.borrow_mut().retain(|v, _| *v == vm); self.hot_save.borrow_mut().take_if(|f| f.vm_id() != vm); self.hot_load.borrow_mut().take_if(|f| f.vm_id() != vm); self.resources.borrow_mut().retain(|_, r| { diff --git a/apps/desktop/src/plugin_host/runtime/vm.rs b/apps/desktop/src/plugin_host/runtime/vm.rs index 358fca7b3..3b603a26b 100644 --- a/apps/desktop/src/plugin_host/runtime/vm.rs +++ b/apps/desktop/src/plugin_host/runtime/vm.rs @@ -136,6 +136,9 @@ fn start(ctx: &mut HostCtx<'_>, module: Val, vm: u64, kind: Kind) -> JsResult<() let fire = JsFn::pin(ctx, fire_val) .ok_or_else(|| JsError::runtime("failed to pin signal fire helper"))?; vmx.half.fire.borrow_mut().insert(vm, fire); + let async_count = std::sync::Arc::new(std::sync::atomic::AtomicU32::new(0)); + vmx.half.in_flight_async.borrow_mut().insert(vm, async_count.clone()); + opencode_plugin_runtime::js::install_async_tracker(ctx, async_count)?; *vmx.half.made.borrow_mut() = Some((vm, Contribs::default())); vmx.half.editors_made.set(0); let plugin_ctx = bridge::ctx::build(ctx, &vmx, &vmx.hot)?; diff --git a/apps/desktop/src/plugin_host/services/audio.rs b/apps/desktop/src/plugin_host/services/audio.rs index 62cce8735..a4be64b34 100644 --- a/apps/desktop/src/plugin_host/services/audio.rs +++ b/apps/desktop/src/plugin_host/services/audio.rs @@ -102,13 +102,13 @@ pub fn build(ctx: &mut HostCtx<'_>, vmx: &Rc, obj: Val) -> JsResult<()> { // Reuse one StartCapture and StopCapture async fn per VM so repeated StartCaptureAsync calls // allocate zero new Rust closures and zero evals. let v_cap = vmx.clone(); - let raw_start = ctx.async_fn("Audio.StartCaptureAsync", move |ctx, args, done| { - start_capture(ctx, args, done, &v_cap).map_err(|e| e.to_val(ctx)) - }); + let raw_start = opencode_plugin_runtime::js::tracked_async_fn(ctx, "Audio.StartCaptureAsync", move |ctx, args, done| { + start_capture(ctx, args, done, &v_cap) + })?; let v_stop = vmx.clone(); - let raw_stop = ctx.async_fn("AudioCaptureHandle.StopAsync", move |ctx, args, done| { - stop_capture(ctx, args, done, &v_stop).map_err(|e| e.to_val(ctx)) - }); + let raw_stop = opencode_plugin_runtime::js::tracked_async_fn(ctx, "AudioCaptureHandle.StopAsync", move |ctx, args, done| { + stop_capture(ctx, args, done, &v_stop) + })?; let plugin_take = vmx.half.id.clone(); let take_buf = ctx.new_local_fn("take_capture_buf", move |ctx, args| { diff --git a/apps/desktop/src/plugin_host/services/diag.rs b/apps/desktop/src/plugin_host/services/diag.rs index d571b75c5..f4744b7e4 100644 --- a/apps/desktop/src/plugin_host/services/diag.rs +++ b/apps/desktop/src/plugin_host/services/diag.rs @@ -260,6 +260,11 @@ thread_local! { static LOG: RefCell = const { RefCell::new(MemoryLog::Off) }; } +/// Whether continuous memory diagnostics logging is currently active (`"on"` or `"env"`). +pub(crate) fn memory_log_active() -> bool { + debug_build() && LOG.with_borrow(|l| matches!(l, MemoryLog::On { .. })) +} + /// `OPENCODE_DESKTOP_MEMORY_LOG=`, read once: invalid values disable diagnostics rather /// than turning a bad interval into a hot timer. fn env_interval() -> Option { diff --git a/apps/desktop/src/plugin_host/services/net.rs b/apps/desktop/src/plugin_host/services/net.rs index 6dc2cc28e..9d8f46fbf 100644 --- a/apps/desktop/src/plugin_host/services/net.rs +++ b/apps/desktop/src/plugin_host/services/net.rs @@ -38,9 +38,9 @@ pub fn build(ctx: &mut HostCtx<'_>, vmx: &Rc, name: &str, obj: Val) -> JsRe "Http" => { let stash = vmx.half.bytes_stash.clone(); let v_vm = vmx.clone(); - let raw_fetch = ctx.async_fn("Http.FetchAsync", move |ctx, args, done| { - fetch(ctx, args, done, &stash, v_vm.vm.get()).map_err(|e| e.to_val(ctx)) - }); + let raw_fetch = opencode_plugin_runtime::js::tracked_async_fn(ctx, "Http.FetchAsync", move |ctx, args, done| { + fetch(ctx, args, done, &stash, v_vm.vm.get()) + })?; let stash = vmx.half.bytes_stash.clone(); let take = ctx.new_local_fn("take_http_bytes", move |ctx, args| { diff --git a/apps/desktop/src/plugin_host/services/workspace_fs.rs b/apps/desktop/src/plugin_host/services/workspace_fs.rs index 536f6a413..e720a30ce 100644 --- a/apps/desktop/src/plugin_host/services/workspace_fs.rs +++ b/apps/desktop/src/plugin_host/services/workspace_fs.rs @@ -48,9 +48,9 @@ pub fn build(ctx: &mut HostCtx<'_>, vmx: &Rc, obj: Val) -> JsResult<()> { // Wrap Workspace.ReadBytesAsync so the stashed Vec returns as a native JS `Uint8Array`. let stash = vmx.half.bytes_stash.clone(); let v_vm = vmx.clone(); - let raw_read = ctx.async_fn("Workspace.ReadBytesAsync", move |ctx, args, done| { - read_bytes(ctx, args, done, &stash, v_vm.vm.get()).map_err(|e| e.to_val(ctx)) - }); + let raw_read = opencode_plugin_runtime::js::tracked_async_fn(ctx, "Workspace.ReadBytesAsync", move |ctx, args, done| { + read_bytes(ctx, args, done, &stash, v_vm.vm.get()) + })?; let stash = vmx.half.bytes_stash.clone(); let take = ctx.new_local_fn("take_ws_bytes", move |ctx, args| { diff --git a/apps/desktop/src/workspace/lifecycle/restore.rs b/apps/desktop/src/workspace/lifecycle/restore.rs index ef2f9a6b6..7eaa7e970 100644 --- a/apps/desktop/src/workspace/lifecycle/restore.rs +++ b/apps/desktop/src/workspace/lifecycle/restore.rs @@ -779,7 +779,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; } @@ -787,7 +787,7 @@ impl Feature for RestoreFeature { changed |= s.tell_storage_notice(); changed |= s.hydrate_restore(); changed |= crate::crash_notice::poll(s); - s.poll_restore(false); + if !s.window.is_settings() { poll_restore_debounced(s, now, tx); } s.poll_preview(false); changed |= s.poll_copies(tx); changed diff --git a/apps/desktop/src/workspace/windows/close.rs b/apps/desktop/src/workspace/windows/close.rs index f18eb8380..ea1b25233 100644 --- a/apps/desktop/src/workspace/windows/close.rs +++ b/apps/desktop/src/workspace/windows/close.rs @@ -47,6 +47,24 @@ impl App { OPEN.with(|o| o.borrow().iter().any(|w| w.id != *id && w.life.saved())) } + /// Whether any other live window (main, popped-out Settings, torn, or closing) exists beside + /// this one, sharing process-wide plugin `app_half` instances. + pub(crate) fn any_other_live_window(&self) -> bool { + let id = &rune::Tracked::untracked(&self.window).id; + OPEN.with(|o| { + o.borrow().iter().any(|w| { + w.id != *id + && matches!( + w.life, + super::life::Life::Open + | super::life::Life::Torn + | super::life::Life::Settings + | super::life::Life::Closing + ) + }) + }) + } + /// ⌘W and File › Close Tab. pub(crate) fn close_tab_key(&mut self, tx: &mut Tx) { // Popped-out Settings window: ⌘W closes the window (`shell.tsx` `settings.window.close`, `opencode#67759`). diff --git a/crates/opencode-plugin-runtime/src/js.rs b/crates/opencode-plugin-runtime/src/js.rs index b04801af3..16f43ea88 100644 --- a/crates/opencode-plugin-runtime/src/js.rs +++ b/crates/opencode-plugin-runtime/src/js.rs @@ -5,6 +5,8 @@ use std::collections::HashMap; use std::hash::{Hash, Hasher}; +use std::sync::Arc; +use std::sync::atomic::{AtomicU32, Ordering}; pub use rune_psychoscript::bridge::{DirectArgs, FnHandle, HostCtx, Key, Session, Val, ValHandle}; pub use rune_psychoscript::{Completer, Data, Host, JsError, JsFn, JsObj, JsResult, JsVal, Record}; @@ -64,6 +66,83 @@ pub fn method( ctx.obj_set_str(obj, name, func); } +const ASYNC_TRACK_JS: &str = r#" +return (function(inner, begin, end) { + return function() { + begin(); + let settled = false; + function finish() { + if (!settled) { settled = true; end(); } + } + try { + const p = inner.apply(this, arguments); + if (p && typeof p.then === "function") { + p.then(finish, finish); + } else { + finish(); + } + return p; + } catch (e) { + finish(); + throw e; + } + }; +}); +"#; + +#[derive(Clone)] +struct AsyncTracker { + wrap: JsFn, + begin: JsFn, + end: JsFn, +} + +/// Installs a per-VM counter tracking in-flight host async Promises created via +/// [`tracked_async_fn`] / [`async_method`] until they settle. +pub fn install_async_tracker(ctx: &mut HostCtx<'_>, count: Arc) -> JsResult<()> { + let wrap_val = crate::chunk::eval(ctx, "=opencode.async_track", ASYNC_TRACK_JS)?; + let wrap = JsFn::pin(ctx, wrap_val) + .ok_or_else(|| JsError::runtime("failed to pin async tracker wrapper"))?; + let inc = count.clone(); + let begin_val = ctx.new_local_fn("async_track.begin", move |_, _| { + inc.fetch_add(1, Ordering::Relaxed); + Ok(Val::UNDEFINED) + }); + let begin = JsFn::pin(ctx, begin_val) + .ok_or_else(|| JsError::runtime("failed to pin async tracker begin"))?; + let end_val = ctx.new_local_fn("async_track.end", move |_, _| { + let mut cur = count.load(Ordering::Relaxed); + while cur > 0 { + match count.compare_exchange_weak(cur, cur - 1, Ordering::Relaxed, Ordering::Relaxed) { + Ok(_) => break, + Err(next) => cur = next, + } + } + Ok(Val::UNDEFINED) + }); + let end = JsFn::pin(ctx, end_val) + .ok_or_else(|| JsError::runtime("failed to pin async tracker end"))?; + ctx.set_user_data(AsyncTracker { wrap, begin, end }); + Ok(()) +} + +/// Creates a host async function wrapped with the VM's in-flight Promise tracker when installed. +pub fn tracked_async_fn( + ctx: &mut HostCtx<'_>, + name: &str, + f: impl Fn(&mut HostCtx<'_>, DirectArgs<'_>, Completer) -> JsResult<()> + 'static, +) -> JsResult { + let raw = ctx.async_fn(name, move |ctx, args, done| f(ctx, args, done).map_err(|e| e.to_val(ctx))); + if !ctx.is_fn(raw) { + return Err(JsError::runtime("failed to wrap async host function")); + } + let Some(tracker) = ctx.get_user_data::() else { + return Ok(raw); + }; + let args = [raw, tracker.begin.val(ctx), tracker.end.val(ctx)]; + call_fn_val(ctx, tracker.wrap.val(ctx), Val::UNDEFINED, &args) +} + /// Attaches an async Promise-returning host method `name` directly onto JS object `obj`. pub fn async_method( ctx: &mut HostCtx<'_>, @@ -71,10 +150,7 @@ pub fn async_method( name: &str, f: impl Fn(&mut HostCtx<'_>, DirectArgs<'_>, Completer) -> JsResult<()> + 'static, ) -> JsResult<()> { - let func = ctx.async_fn(name, move |ctx, args, done| f(ctx, args, done).map_err(|e| e.to_val(ctx))); - if !ctx.is_fn(func) { - return Err(JsError::runtime("failed to wrap async host function")); - } + let func = tracked_async_fn(ctx, name, f)?; ctx.obj_set_str(obj, name, func); Ok(()) } 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/draft_stamp.rs b/features/restore/src/draft_stamp.rs new file mode 100644 index 000000000..1b66f4603 --- /dev/null +++ b/features/restore/src/draft_stamp.rs @@ -0,0 +1,280 @@ +//! Canonical 128-bit draft stamp over active and parked composer drafts, matching +//! `draft_doc::encode` so route switches and unrelated `RESTORE` bumps skip `sync_all_drafts`. + +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::ops::Range; + +use opencode_kit::client::PathAttachment; +use opencode_kit::model::{Attachment, PromptComment}; +use opencode_kit::servers::{ServerKey, TabKey}; +use opencode_runtime::composer_mode::Mode; +use serde_json::Value; + +use crate::{ContextFile, Parked, RestoreHost, RestoreRoute, draft_doc}; + +struct HashWriter<'a, H>(&'a mut H); + +impl std::io::Write for HashWriter<'_, H> { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.write(buf); + Ok(buf.len()) + } + + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +fn hash_json(v: &T, h: &mut impl Hasher) -> Option<()> { + 0u8.hash(h); + serde_json::to_writer(HashWriter(h), v).ok() +} + +fn hash_draft_tab_key( + host: &dyn RestoreHost, + key: &str, + route: &mut Option, + server: &mut Option, + h: &mut impl Hasher, +) { + if let Some(tab_key) = host.tab_key_by_id(key) { + match &tab_key { + TabKey::Draft(id) => (0u8, id).hash(h), + TabKey::Session { server: s, session_id } => (1u8, s, session_id).hash(h), + } + return; + } + if key.starts_with("draft_") { + (0u8, key).hash(h); + return; + } + let r = route.get_or_insert_with(|| host.route()); + let srv = match r { + RestoreRoute::Session { server: s, id } if id == key => s, + _ => server.get_or_insert_with(|| host.current_server()), + }; + (1u8, srv, key).hash(h); +} + +struct DraftEntry<'a, P, Q> { + key: &'a str, + text: &'a str, + shell: bool, + has_rich: bool, + caret: Option, + pills: P, + files: &'a [Attachment], + paths: &'a [PathAttachment], + context: &'a [ContextFile], + quotes: Q, + blobs: &'a draft_doc::Blobs, + pending: Option<&'a Vec>, +} + +struct DraftStampAcc { + count: usize, + sum_a: u64, + sum_b: u64, + xor_a: u64, + xor_b: u64, + route: Option, + server: Option, +} + +impl DraftStampAcc { + fn new() -> Self { + Self { count: 0, sum_a: 0, sum_b: 0, xor_a: 0, xor_b: 0, route: None, server: None } + } + + /// Feeds one canonical draft entry matching `draft_doc::encode` identically whether live in + /// the composer (`shown`) or parked. Returns `None` on a `serde_json` write error to force a + /// full `sync_all_drafts` fallback. + fn push<'a, 'p, 'q, P, Q>(&mut self, host: &dyn RestoreHost, entry: DraftEntry<'a, P, Q>) -> Option<()> + where + P: Iterator, &'p str)>, + Q: Iterator, + { + let pending_slice = entry.pending.map_or(&[][..], Vec::as_slice); + let has_pending = !pending_slice.is_empty(); + if !entry.has_rich && !has_pending && !entry.shell && entry.text.trim().is_empty() { + return Some(()); + } + let mut eh = DefaultHasher::new(); + hash_draft_tab_key(host, entry.key, &mut self.route, &mut self.server, &mut eh); + entry.text.hash(&mut eh); + entry.shell.hash(&mut eh); + let rich_or_pending = entry.has_rich || has_pending; + rich_or_pending.hash(&mut eh); + if rich_or_pending { + if entry.has_rich { + entry.caret.filter(|&c| c != entry.text.len()).hash(&mut eh); + let mut pill_count = 0usize; + for (r, id) in entry.pills { + pill_count += 1; + (r.start, r.end, id).hash(&mut eh); + } + pill_count.hash(&mut eh); + entry.paths.len().hash(&mut eh); + for p in entry.paths { + hash_json(p, &mut eh)?; + } + entry.context.len().hash(&mut eh); + for c in entry.context { + let ContextFile { path, start, end } = c; + (path, start, end).hash(&mut eh); + } + let mut quote_count = 0usize; + for q in entry.quotes { + quote_count += 1; + hash_json(q, &mut eh)?; + } + quote_count.hash(&mut eh); + let mut file_count = 0usize; + for f in entry.files { + let Attachment { mime, name, bytes, media } = f; + match (media, entry.blobs.id(bytes)) { + (Some(media), _) => { + file_count += 1; + (1u8, name, mime, media).hash(&mut eh); + } + (None, Some(id)) => { + file_count += 1; + (2u8, name, mime, bytes.len(), id).hash(&mut eh); + } + (None, None) => {} + } + } + file_count.hash(&mut eh); + } else { + // Matches `draft_doc::encode`'s `rich.unwrap_or_default()` when only pending blobs exist. + (Option::::None, 0usize, 0usize, 0usize, 0usize, 0usize).hash(&mut eh); + } + pending_slice.len().hash(&mut eh); + for v in pending_slice { + hash_json(v, &mut eh)?; + } + } + let a = eh.finish(); + 1u8.hash(&mut eh); + let b = eh.finish(); + self.count += 1; + self.sum_a = self.sum_a.wrapping_add(a); + self.sum_b = self.sum_b.wrapping_add(b); + self.xor_a ^= a; + self.xor_b ^= b; + Some(()) + } + + fn finish(self) -> (u64, u64) { + let mut out = DefaultHasher::new(); + (self.count, self.sum_a, self.sum_b, self.xor_a, self.xor_b).hash(&mut out); + let lo = out.finish(); + 1u8.hash(&mut out); + let hi = out.finish(); + (lo, hi) + } +} + +/// Deterministic 128-bit stamp over every input to [`drafts_now`] (`r.drafts`, `r.parked`, +/// `r.blobs` pending + resolved ids, `parked_composer_modes`, active composer/`shown`, and each +/// non-empty draft's resolved [`draft_tab_key`]). Canonical across park/unpark swaps so route +/// switches and unrelated `RESTORE` bumps skip `sync_all_drafts` without missing any change. +pub(crate) fn drafts_stamp(host: &dyn RestoreHost) -> Option<(u64, u64)> { + let r = host.restore(); + let shown = r.shown.as_deref(); + let parked_modes = host.parked_composer_modes(); + let is_parked_shell = |k: &str| { + parked_modes.iter().rev().find(|(mk, _)| mk.as_str() == k).is_some_and(|(_, m)| *m == Mode::Shell) + }; + let mut acc = DraftStampAcc::new(); + let mut push_parked = |k: &str, text: &str| -> Option<()> { + let (has_rich, caret, pills, files, paths, context, quotes) = match r.parked.get(k) { + Some(Parked { pills, caret, files, paths, context, quotes }) => { + let rich = !files.is_empty() + || !paths.is_empty() + || !context.is_empty() + || !quotes.is_empty() + || (!text.trim().is_empty() + && (!pills.is_empty() || caret.is_some_and(|c| c != text.len()))); + (rich, *caret, pills.as_slice(), files.as_slice(), paths.as_slice(), context.as_slice(), quotes.as_slice()) + } + None => (false, None, &[][..], &[][..], &[][..], &[][..], &[][..]), + }; + acc.push( + host, + DraftEntry { + key: k, + text, + shell: is_parked_shell(k), + has_rich, + caret, + pills: pills.iter().map(|(range, id)| (range.clone(), id.as_str())), + files, + paths, + context, + quotes: quotes.iter(), + blobs: &r.blobs, + pending: r.blobs.pending_for(k), + }, + ) + }; + for (k, text) in &r.drafts { + if shown != Some(k.as_str()) { + push_parked(k, text)?; + } + } + for k in r.parked.keys() { + if shown != Some(k.as_str()) && !r.drafts.contains_key(k) { + push_parked(k, "")?; + } + } + for k in r.blobs_pending() { + if shown != Some(k.as_str()) && !r.drafts.contains_key(k) && !r.parked.contains_key(k) { + push_parked(k, "")?; + } + } + for (i, (k, _)) in parked_modes.iter().enumerate() { + if shown != Some(k.as_str()) + && !r.drafts.contains_key(k) + && !r.parked.contains_key(k) + && r.blobs.pending_for(k).is_none() + && !parked_modes[..i].iter().any(|(pk, _)| pk == k) + { + push_parked(k, "")?; + } + } + if let Some(k) = shown { + let composer = host.composer(); + let text = composer.text.as_str(); + let shell = host.composer_mode() == Mode::Shell; + let caret = composer.range().1.min(text.len()); + let files = host.attach_files(); + let paths = host.attach_paths(); + let context = host.attach_context(); + let has_quotes = host.quote_any(); + let has_rich = !files.is_empty() + || !paths.is_empty() + || !context.is_empty() + || has_quotes + || (!text.trim().is_empty() && (composer.pills().next().is_some() || caret != text.len())); + let quotes = if has_quotes { host.quote_comments() } else { Vec::new() }; + acc.push( + host, + DraftEntry { + key: k, + text, + shell, + has_rich, + caret: Some(caret), + pills: composer.pills(), + files, + paths, + context, + quotes: quotes.into_iter(), + blobs: &r.blobs, + pending: r.blobs.pending_for(k), + }, + )?; + } + Some(acc.finish()) +} diff --git a/features/restore/src/lib.rs b/features/restore/src/lib.rs index 7335b36d3..83ffbe0cc 100644 --- a/features/restore/src/lib.rs +++ b/features/restore/src/lib.rs @@ -14,6 +14,7 @@ pub mod copies; pub mod doc; pub mod draft_doc; +mod draft_stamp; pub mod host; pub mod parked; pub mod persist; @@ -43,7 +44,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, poll_restore_now}; +pub use persist::{draft_document_of, draft_documents, draft_tab_key, poll_restore, poll_restore_debounced, poll_restore_now}; 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 +415,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, 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..e730aab79 100644 --- a/features/restore/src/parked.rs +++ b/features/restore/src/parked.rs @@ -156,6 +156,38 @@ pub fn park_draft(host: &mut dyn RestoreHost, key: String, text: String, parked: } } +/// Soft cap on in-memory parked editors (`Restore::edits`); entries for the just-parked key, +/// active unsent drafts, and currently open tabs (session or draft) are always retained, while +/// undo-only editors for closed empty tabs are pruned past this threshold. +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 closed empty-draft undo entries past [`MAX_KEPT_EDITS`]. +pub(crate) fn keep_edit(host: &mut dyn RestoreHost, key: String, edit: Option) { + match edit { + Some(e) => { + let over = { + let r = host.restore_mut(); + r.edits.insert(key.clone(), e); + r.edits.len() > MAX_KEPT_EDITS + }; + if over { + let open: std::collections::HashSet = + host.tabs().into_iter().map(|t| t.id).collect(); + let r = host.restore_mut(); + r.edits.retain(|k, _| k == &key || r.drafts.contains_key(k) || open.contains(k)); + } + } + None => { + host.restore_mut().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 +251,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, 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 4447deeb0..49347ef91 100644 --- a/features/restore/src/persist.rs +++ b/features/restore/src/persist.rs @@ -7,18 +7,16 @@ use std::collections::HashMap; use std::hash::{DefaultHasher, Hash, Hasher}; -use std::ops::Range; -use opencode_kit::client::PathAttachment; -use opencode_kit::model::{Attachment, PromptComment}; +use opencode_kit::servers::TabKey; use opencode_kit::servers::key::Route as Page; -use opencode_kit::servers::{ServerKey, TabKey}; use opencode_runtime::composer_mode::Mode; use opencode_servers::tabs::ClosedTab; use serde_json::{Value, json}; -use crate::state::organize_expanded_sorted; -use crate::{ContextFile, GLOBAL, Parked, RestoreHost, RestoreRoute, RestoreTab, RestoreVersions, doc, draft_doc, hydrated, parked, undo}; +use crate::draft_stamp::drafts_stamp; +use crate::state::{PersistDebounceEffect, PersistDebounceEvent, organize_expanded_sorted}; +use crate::{GLOBAL, 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 /// the page (`/settings?tab=`), whatever it was opened over. @@ -160,273 +158,6 @@ pub(crate) fn note_written(host: &mut dyn RestoreHost) { r.drafts_stamp.set(None); } -struct HashWriter<'a, H>(&'a mut H); - -impl std::io::Write for HashWriter<'_, H> { - fn write(&mut self, buf: &[u8]) -> std::io::Result { - self.0.write(buf); - Ok(buf.len()) - } - - fn flush(&mut self) -> std::io::Result<()> { - Ok(()) - } -} - -fn hash_json(v: &T, h: &mut impl Hasher) -> Option<()> { - 0u8.hash(h); - serde_json::to_writer(HashWriter(h), v).ok() -} - -fn hash_draft_tab_key( - host: &dyn RestoreHost, - key: &str, - route: &mut Option, - server: &mut Option, - h: &mut impl Hasher, -) { - if let Some(tab_key) = host.tab_key_by_id(key) { - match &tab_key { - TabKey::Draft(id) => (0u8, id).hash(h), - TabKey::Session { server: s, session_id } => (1u8, s, session_id).hash(h), - } - return; - } - if key.starts_with("draft_") { - (0u8, key).hash(h); - return; - } - let r = route.get_or_insert_with(|| host.route()); - let srv = match r { - RestoreRoute::Session { server: s, id } if id == key => s, - _ => server.get_or_insert_with(|| host.current_server()), - }; - (1u8, srv, key).hash(h); -} - -struct DraftEntry<'a, P, Q> { - key: &'a str, - text: &'a str, - shell: bool, - has_rich: bool, - caret: Option, - pills: P, - files: &'a [Attachment], - paths: &'a [PathAttachment], - context: &'a [ContextFile], - quotes: Q, - blobs: &'a draft_doc::Blobs, - pending: Option<&'a Vec>, -} - -struct DraftStampAcc { - count: usize, - sum_a: u64, - sum_b: u64, - xor_a: u64, - xor_b: u64, - route: Option, - server: Option, -} - -impl DraftStampAcc { - fn new() -> Self { - Self { count: 0, sum_a: 0, sum_b: 0, xor_a: 0, xor_b: 0, route: None, server: None } - } - - /// Feeds one canonical draft entry matching `draft_doc::encode` identically whether live in - /// the composer (`shown`) or parked. Returns `None` on a `serde_json` write error to force a - /// full `sync_all_drafts` fallback. - fn push<'a, 'p, 'q, P, Q>(&mut self, host: &dyn RestoreHost, entry: DraftEntry<'a, P, Q>) -> Option<()> - where - P: Iterator, &'p str)>, - Q: Iterator, - { - let pending_slice = entry.pending.map_or(&[][..], Vec::as_slice); - let has_pending = !pending_slice.is_empty(); - if !entry.has_rich && !has_pending && !entry.shell && entry.text.trim().is_empty() { - return Some(()); - } - let mut eh = DefaultHasher::new(); - hash_draft_tab_key(host, entry.key, &mut self.route, &mut self.server, &mut eh); - entry.text.hash(&mut eh); - entry.shell.hash(&mut eh); - let rich_or_pending = entry.has_rich || has_pending; - rich_or_pending.hash(&mut eh); - if rich_or_pending { - if entry.has_rich { - entry.caret.filter(|&c| c != entry.text.len()).hash(&mut eh); - let mut pill_count = 0usize; - for (r, id) in entry.pills { - pill_count += 1; - (r.start, r.end, id).hash(&mut eh); - } - pill_count.hash(&mut eh); - entry.paths.len().hash(&mut eh); - for p in entry.paths { - hash_json(p, &mut eh)?; - } - entry.context.len().hash(&mut eh); - for c in entry.context { - let ContextFile { path, start, end } = c; - (path, start, end).hash(&mut eh); - } - let mut quote_count = 0usize; - for q in entry.quotes { - quote_count += 1; - hash_json(q, &mut eh)?; - } - quote_count.hash(&mut eh); - let mut file_count = 0usize; - for f in entry.files { - let Attachment { mime, name, bytes, media } = f; - match (media, entry.blobs.id(bytes)) { - (Some(media), _) => { - file_count += 1; - (1u8, name, mime, media).hash(&mut eh); - } - (None, Some(id)) => { - file_count += 1; - (2u8, name, mime, bytes.len(), id).hash(&mut eh); - } - (None, None) => {} - } - } - file_count.hash(&mut eh); - } else { - // Matches `draft_doc::encode`'s `rich.unwrap_or_default()` when only pending blobs exist. - (Option::::None, 0usize, 0usize, 0usize, 0usize, 0usize).hash(&mut eh); - } - pending_slice.len().hash(&mut eh); - for v in pending_slice { - hash_json(v, &mut eh)?; - } - } - let a = eh.finish(); - 1u8.hash(&mut eh); - let b = eh.finish(); - self.count += 1; - self.sum_a = self.sum_a.wrapping_add(a); - self.sum_b = self.sum_b.wrapping_add(b); - self.xor_a ^= a; - self.xor_b ^= b; - Some(()) - } - - fn finish(self) -> (u64, u64) { - let mut out = DefaultHasher::new(); - (self.count, self.sum_a, self.sum_b, self.xor_a, self.xor_b).hash(&mut out); - let lo = out.finish(); - 1u8.hash(&mut out); - let hi = out.finish(); - (lo, hi) - } -} - -/// Deterministic 128-bit stamp over every input to [`drafts_now`] (`r.drafts`, `r.parked`, -/// `r.blobs` pending + resolved ids, `parked_composer_modes`, active composer/`shown`, and each -/// non-empty draft's resolved [`draft_tab_key`]). Canonical across park/unpark swaps so route -/// switches and unrelated `RESTORE` bumps skip `sync_all_drafts` without missing any change. -fn drafts_stamp(host: &dyn RestoreHost) -> Option<(u64, u64)> { - let r = host.restore(); - let shown = r.shown.as_deref(); - let parked_modes = host.parked_composer_modes(); - let is_parked_shell = |k: &str| { - parked_modes.iter().rev().find(|(mk, _)| mk.as_str() == k).is_some_and(|(_, m)| *m == Mode::Shell) - }; - let mut acc = DraftStampAcc::new(); - let mut push_parked = |k: &str, text: &str| -> Option<()> { - let (has_rich, caret, pills, files, paths, context, quotes) = match r.parked.get(k) { - Some(Parked { pills, caret, files, paths, context, quotes }) => { - let rich = !files.is_empty() - || !paths.is_empty() - || !context.is_empty() - || !quotes.is_empty() - || (!text.trim().is_empty() - && (!pills.is_empty() || caret.is_some_and(|c| c != text.len()))); - (rich, *caret, pills.as_slice(), files.as_slice(), paths.as_slice(), context.as_slice(), quotes.as_slice()) - } - None => (false, None, &[][..], &[][..], &[][..], &[][..], &[][..]), - }; - acc.push( - host, - DraftEntry { - key: k, - text, - shell: is_parked_shell(k), - has_rich, - caret, - pills: pills.iter().map(|(range, id)| (range.clone(), id.as_str())), - files, - paths, - context, - quotes: quotes.iter(), - blobs: &r.blobs, - pending: r.blobs.pending_for(k), - }, - ) - }; - for (k, text) in &r.drafts { - if shown != Some(k.as_str()) { - push_parked(k, text)?; - } - } - for k in r.parked.keys() { - if shown != Some(k.as_str()) && !r.drafts.contains_key(k) { - push_parked(k, "")?; - } - } - for k in r.blobs_pending() { - if shown != Some(k.as_str()) && !r.drafts.contains_key(k) && !r.parked.contains_key(k) { - push_parked(k, "")?; - } - } - for (i, (k, _)) in parked_modes.iter().enumerate() { - if shown != Some(k.as_str()) - && !r.drafts.contains_key(k) - && !r.parked.contains_key(k) - && r.blobs.pending_for(k).is_none() - && !parked_modes[..i].iter().any(|(pk, _)| pk == k) - { - push_parked(k, "")?; - } - } - if let Some(k) = shown { - let composer = host.composer(); - let text = composer.text.as_str(); - let shell = host.composer_mode() == Mode::Shell; - let caret = composer.range().1.min(text.len()); - let files = host.attach_files(); - let paths = host.attach_paths(); - let context = host.attach_context(); - let has_quotes = host.quote_any(); - let has_rich = !files.is_empty() - || !paths.is_empty() - || !context.is_empty() - || has_quotes - || (!text.trim().is_empty() && (composer.pills().next().is_some() || caret != text.len())); - let quotes = if has_quotes { host.quote_comments() } else { Vec::new() }; - acc.push( - host, - DraftEntry { - key: k, - text, - shell, - has_rich, - caret: Some(caret), - pills: composer.pills(), - files, - paths, - context, - quotes: quotes.into_iter(), - blobs: &r.blobs, - pending: r.blobs.pending_for(k), - }, - )?; - } - Some(acc.finish()) -} - /// The document draft `key`'s words are kept in (none in a window without an id, which keeps /// no drafts): the outbox clears it in the same transaction as the prompt's first row. pub fn draft_document_of(host: &dyn RestoreHost, key: &str) -> Option { @@ -592,9 +323,10 @@ fn poll_restore_versioned(host: &mut dyn RestoreHost, v: RestoreVersions, now: b if prev == Some(v) && (!deferred || (!now && host.side_resizing())) { 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)); @@ -726,13 +458,111 @@ fn poll_restore_versioned(host: &mut dyn RestoreHost, v: RestoreVersions, now: b } // Re-read after our own `written` writes so recording the stamp via `Cell` settles next poll. let after = host.restore_versions(); - host.restore().versions.set(after); + let r = host.restore(); + r.versions.set(after); + r.full_drafts_ver.set(after.map(|a| (a.restore, a.tabs, a.route, a.checkout, a.hydrated))); +} + +/// Journals typed composer draft edits and deletions immediately while layout/tab/side rows wait +/// for [`PersistDebounce`], so a process kill never loses typed words or resurrects deleted text. +fn flush_drafts_immediate( + host: &mut dyn RestoreHost, + v: &mut RestoreVersions, + persisted: &mut Option, +) { + let Some(mut prev) = *persisted else { return }; + if prev.hydrated != v.hydrated { + return; + } + let full_key = (v.restore, v.tabs, v.route, v.checkout, v.hydrated); + let full_dirty = (prev.restore != v.restore + || prev.tabs != v.tabs + || prev.route != v.route + || prev.checkout != v.checkout) + && host.restore().full_drafts_ver.get() != Some(full_key); + let active_dirty = prev.composer != v.composer + || prev.attach != v.attach + || prev.quote != v.quote + || prev.add_menu != v.add_menu; + if !full_dirty && !active_dirty { + return; + } + let restore_was_clean = prev.restore == v.restore; + if full_dirty { + let stamp = drafts_stamp(host); + if stamp.is_none() || host.restore().drafts_stamp.get() != stamp { + sync_all_drafts(host); + host.restore().drafts_stamp.set(stamp); + } + } else { + sync_active_draft(host); + } + if let Some(after) = host.restore_versions() { + *v = after; + } + prev.composer = v.composer; + prev.attach = v.attach; + prev.quote = v.quote; + prev.add_menu = v.add_menu; + if restore_was_clean { + prev.restore = v.restore; + } + let r = host.restore(); + r.full_drafts_ver.set(Some((v.restore, v.tabs, v.route, v.checkout, v.hydrated))); + r.versions.set(Some(prev)); + *persisted = Some(prev); +} + +/// Scheduled per-frame persistence tick: debounces expensive layout/tab/`side`/`side.rest` +/// serialization via `PersistDebounce` (1 s settle, 2 s max wait) while journaling typed composer +/// draft edits and deletions, crash-recovery route tracking, and draft blob uploads immediately. +/// Window hide, close (`save_on_close`), and quit (`save_on_quit`) call [`poll_restore_now`]. +pub fn poll_restore_debounced(host: &mut dyn RestoreHost, now: f64, tx: &mut rune::Tx) { + let persists = host.persists(); + let mut polled_blobs = false; + if persists && host.restore().blobs.has_arrived() { + draft_doc::poll_draft_files(host); + polled_blobs = true; + } + let Some(mut v) = host.restore_versions() else { + poll_restore(host); + return; + }; + 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 !persists { + let r = host.restore(); + r.versions.set(Some(v)); + let mut debounce = r.debounce.get(); + let _ = debounce.step(PersistDebounceEvent::Flushed); + r.debounce.set(debounce); + return; + } + let mut persisted = host.restore().versions.get(); + if !polled_blobs && 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; + } + } + flush_drafts_immediate(host, &mut v, &mut persisted); + let deferred_ready = host.restore().side_deferred.get() && !host.side_resizing(); + let mut debounce = host.restore().debounce.get(); + let effect = debounce.step(PersistDebounceEvent::Poll { current: v, persisted, deferred_ready, now }); + host.restore().debounce.set(debounce); + match effect { + PersistDebounceEffect::Skip => {} + PersistDebounceEffect::WakeAt(at) => tx.wake_at(at), + PersistDebounceEffect::FlushNow => poll_restore_versioned(host, v, false), + } } -/// Called every poll: on any change, hands only the dirty rows to storage (memory now, the -/// 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`. +/// Immediate persistence check respecting active panel resize drags. Callers outside the +/// scheduled tick (`save_on_close`, `save_on_quit`, visibility hide) use [`poll_restore_now`] +/// after running `show_draft` and `hydrate_restore`. pub fn poll_restore(host: &mut dyn RestoreHost) { poll_restore_mode(host, false); } @@ -744,6 +574,9 @@ pub fn poll_restore_now(host: &mut dyn RestoreHost) { } fn poll_restore_mode(host: &mut dyn RestoreHost, now: bool) { + 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 1975296df..8929643e9 100644 --- a/features/restore/src/state.rs +++ b/features/restore/src/state.rs @@ -203,6 +203,78 @@ 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, deferred_ready: bool, 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), deferred_ready: false, .. }) + if current == prev => + { + *self = Self::Clean; + PersistDebounceEffect::Skip + } + // Initial poll, hydration transitions, and post-drag deferred side flush run immediately. + (_, PersistDebounceEvent::Poll { current, persisted, deferred_ready, .. }) + if deferred_ready || 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 +344,12 @@ 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>, + /// Last `(restore, tabs, route, checkout, hydrated)` tuple checked by immediate draft journaling. + pub(crate) full_drafts_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` @@ -317,6 +395,9 @@ 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.full_drafts_ver.set(None); self.hot_side_hash.set(None); self.side_rest_stamp.set(None); self.side_rest_ver.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));