Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion apps/desktop/src/plugin_host/bridge/commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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());
}
Expand Down
4 changes: 1 addition & 3 deletions apps/desktop/src/plugin_host/native/browser.rs
Original file line number Diff line number Diff line change
Expand Up @@ -319,9 +319,7 @@ pub fn build(ctx: &mut HostCtx<'_>, vmx: &Rc<Vmx>, 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",
Expand Down
4 changes: 1 addition & 3 deletions apps/desktop/src/plugin_host/native/browser/history.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
21 changes: 6 additions & 15 deletions apps/desktop/src/plugin_host/native/browser/tab.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,21 +54,12 @@ fn tab_asyncs(ctx: &mut HostCtx<'_>) -> JsResult<BrowserTabAsyncs> {
if let Some(existing) = ctx.get_user_data::<BrowserTabAsyncs>() {
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",
Expand Down
82 changes: 32 additions & 50 deletions apps/desktop/src/plugin_host/runtime/dormant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,19 +25,25 @@
//! 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;

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.<id>.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)]
Expand All @@ -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<String, Vec<(String, String, serde_json::Value)>>,
/// Wake requests queued by views of this window since the last poll.
asked: std::cell::RefCell<Vec<(String, Wait)>>,
asked: RefCell<Vec<(String, Wait)>>,
/// Count of settings-open retries for bundled settings plugins killed by a startup watchdog.
watchdog_retries: BTreeMap<String, u8>,
/// Periodic active-window dormancy cadence and per-plugin warmth table.
pub(super) active: ActiveSleep,
}

impl Dormant {
Expand Down Expand Up @@ -88,7 +96,7 @@ fn panel_rows(record: &Record) -> impl Iterator<Item = &opencode_plugin_runtime:
/// plugin with no entry there needn't, nor one whose entries are all in its record: of fifteen
/// built-ins a side panel restored on New tab started before its first frame, four have such an
/// entry (strobe `rec_7ecdd3`, `rec_5a45c9`, `rec_2fd572`: 18.5 ms of plugin starts).
fn is_new_tab_slot(e: &opencode_plugin_runtime::dormant::Entry) -> 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"))
}

Expand Down Expand Up @@ -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 });
}
Expand Down Expand Up @@ -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| {
Expand All @@ -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<Vec<(String, Contribs)>> = const { std::cell::RefCell::new(Vec::new()) };
static APP_HALVES: RefCell<Vec<(String, Contribs)>> = const { RefCell::new(Vec::new()) };
/// Interned `plugin.<id>.woke` perf-mark labels (at most one allocation per plugin id).
static WAKE_MARKS: RefCell<BTreeMap<String, &'static str>> = 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
Expand Down Expand Up @@ -298,14 +279,15 @@ 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
}

/// 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();
Expand Down
Loading
Loading