diff --git a/apps/desktop/src/session/events/mod.rs b/apps/desktop/src/session/events/mod.rs index 00777e6d2..f124a87c0 100644 --- a/apps/desktop/src/session/events/mod.rs +++ b/apps/desktop/src/session/events/mod.rs @@ -641,6 +641,13 @@ impl App { let active_server = crate::servers::runtime::active(self).clone(); crate::surfaces::browser::rpc::on_session_lifecycle(self, &active_server, ty, &sid); } + #[cfg(not(target_arch = "wasm32"))] + if ty == "location.shutdown" + && let Some(dir) = data["eventLocation"]["directory"].as_str().filter(|d| !d.is_empty()) + { + let active_server = crate::servers::runtime::active(self).clone(); + crate::surfaces::browser::rpc::on_location_shutdown(self, &active_server, dir); + } changed |= self.invalidate_catalogs_on_event(ty, data, tx); changed |= crate::session::meta::flags::on_sse_event(self, ty, data); if done.project { self.list_unlisted_worktrees(); } diff --git a/apps/desktop/src/surfaces/automations/source.rs b/apps/desktop/src/surfaces/automations/source.rs index a084bb15b..9a640f40e 100644 --- a/apps/desktop/src/surfaces/automations/source.rs +++ b/apps/desktop/src/surfaces/automations/source.rs @@ -226,23 +226,61 @@ pub fn is_failed(s: &App) -> bool { }) } +fn return_tab_dir(s: &App, server: &ServerKey) -> Option { + let uid = s.gestures.home_return_tab.as_deref()?; + let tab = s.tab(uid).filter(|t| t.server == *server)?; + let dir = s + .session(&tab.id) + .map(|i| i.directory.as_str()) + .filter(|d| !d.is_empty()) + .unwrap_or(tab.directory.as_str()); + (!dir.is_empty()).then(|| dir.to_owned()) +} + +fn default_draft_dir(s: &App, server: &ServerKey) -> Option { + if let Some(dir) = return_tab_dir(s, server) { + return Some(dir); + } + if server == crate::servers::runtime::active(s) { + if let Some(dir) = s.last_used_project().map(|p| p.directory.as_str()).filter(|d| !d.is_empty()) { + return Some(dir.to_owned()); + } + if let Some(dir) = crate::start_location::server_directory(s).filter(|d| !d.is_empty()) { + return Some(dir.to_owned()); + } + return (!s.default_dir.is_empty()).then(|| (*s.default_dir).clone()); + } + s.tabs + .iter() + .find(|t| t.server == *server && !t.directory.is_empty()) + .map(|t| t.directory.clone()) +} + pub fn draft_target(s: &App, selected: Option<&Entry>) -> Option<(ServerKey, String)> { let st = s.kernel.slots.get(&AUTOMATIONS); if let Some(entry) = selected { let srv = st.servers.get(&entry.server)?; - if srv.commands.get(&entry.row.directory) == Some(&CmdOffer::Offered) { + if srv.commands.get(&entry.row.directory) == Some(&CmdOffer::Offered) + || srv.commands.get("") == Some(&CmdOffer::Offered) + { return Some((entry.server.clone(), entry.row.directory.clone())); } return None; } let active = crate::servers::runtime::active(s); - let pick = |srv: &ServerState| -> Option { - srv.commands.iter().find(|(_, c)| **c == CmdOffer::Offered).map(|(d, _)| d.clone()) + let pick = |key: &ServerKey, srv: &ServerState| -> Option { + if let Some((d, _)) = srv.commands.iter().find(|(d, c)| !d.is_empty() && **c == CmdOffer::Offered) { + return Some(d.clone()); + } + if srv.commands.get("") == Some(&CmdOffer::Offered) { + return default_draft_dir(s, key); + } + None }; - if let Some(dir) = st.servers.get(active).and_then(pick) { + if let Some(dir) = st.servers.get(active).and_then(|srv| pick(active, srv)) { return Some((active.clone(), dir)); } - st.servers.iter().find_map(|(k, srv)| pick(srv).map(|d| (k.clone(), d))) + st.servers.iter().find_map(|(k, srv)| pick(k, srv).map(|d| (k.clone(), d))) } pub fn mutate(s: &mut App, entry: &Entry, op: Operation, tx: &mut Tx) { @@ -422,21 +460,26 @@ pub fn poll(s: &mut App, now: f64, tx: &mut Tx) -> bool { Route::Draft(_) => Some(s.draft_dir().to_owned()), Route::Home | Route::Automations => None, }; - let tab_dirs: Vec<(ServerKey, String)> = if open { - s.tabs - .iter() - .filter(|t| !t.directory.is_empty()) - .map(|t| (t.server.clone(), t.directory.clone())) - .collect() - } else { - Vec::new() - }; - let proj_dirs: Vec = if open { - s.used_projects().iter().map(|p| p.directory.clone()).collect() + let active_srv = crate::servers::runtime::active(s).clone(); + // Probe at most one already-warm location per server when Automations opens (return tab or + // server default `""`), plus the single currently selected automation's directory — never + // every `used_projects()`, tab, or row directory, which would boot every cold project + // location (and its stdio MCP servers) in parallel. + let warm_active_dir = open.then(|| return_tab_dir(s, &active_srv)).flatten(); + let selected_dir: Option<(ServerKey, String)> = if open { + let st = s.kernel.slots.untracked(&AUTOMATIONS); + st.selected.as_deref().and_then(|sel_key| { + st.servers.iter().find_map(|(k, srv)| { + srv.rows + .iter() + .find(|r| entry_key(k, &r.id) == sel_key) + .filter(|r| !r.directory.is_empty()) + .map(|r| (k.clone(), r.directory.clone())) + }) + }) } else { - Vec::new() + None }; - let active_srv = crate::servers::runtime::active(s).clone(); let is_due = |srv: &ServerState| -> bool { let offered = srv.commands.values().any(|c| *c == CmdOffer::Offered); @@ -448,6 +491,36 @@ pub fn poll(s: &mut App, now: f64, tx: &mut Tx) -> bool { } }; + let probe_dir_for = |key: &ServerKey, srv: &ServerState| -> Option { + if *key == active_srv + && let Some(d) = active_dir.as_deref().filter(|d| !d.is_empty()) + && !srv.commands.contains_key(d) + { + return Some(d.to_owned()); + } + if !open { + return None; + } + if let Some((sk, sd)) = &selected_dir + && sk == key + && !srv.commands.contains_key(sd) + && srv.commands.get("") != Some(&CmdOffer::Offered) + { + return Some(sd.clone()); + } + if !srv.commands.values().any(|c| matches!(c, CmdOffer::Offered | CmdOffer::Pending)) { + let fallback = if *key == active_srv { + warm_active_dir.as_deref().unwrap_or("") + } else { + "" + }; + if !srv.commands.contains_key(fallback) { + return Some(fallback.to_owned()); + } + } + None + }; + // Inspect untracked first so idle polls never bump the Tracked slot or allocate collections. let needs_mut = { let st = s.kernel.slots.untracked(&AUTOMATIONS); @@ -463,27 +536,7 @@ pub fn poll(s: &mut App, now: f64, tx: &mut Tx) -> bool { { return true; } - if is_due(srv) { - return true; - } - if item.key == active_srv { - if let Some(d) = &active_dir - && !d.is_empty() - && !srv.commands.contains_key(d) - { - return true; - } - if proj_dirs.iter().any(|d| !d.is_empty() && !srv.commands.contains_key(d)) { - return true; - } - } - if open - && (tab_dirs.iter().any(|(tk, td)| *tk == item.key && !td.is_empty() && !srv.commands.contains_key(td)) - || srv.rows.iter().any(|r| !r.directory.is_empty() && !srv.commands.contains_key(&r.directory))) - { - return true; - } - false + is_due(srv) || probe_dir_for(&item.key, srv).is_some() }) }; @@ -506,30 +559,9 @@ pub fn poll(s: &mut App, now: f64, tx: &mut Tx) -> bool { to_fetch.push((item.key.clone(), item.server.clone())); } - let mut dirs = Vec::new(); - if item.key == active_srv { - if let Some(d) = &active_dir { - dirs.push(d.clone()); - } - dirs.extend(proj_dirs.iter().cloned()); - } - if open { - for (tk, td) in &tab_dirs { - if *tk == item.key { - dirs.push(td.clone()); - } - } - for row in &srv.rows { - if !row.directory.is_empty() { - dirs.push(row.directory.clone()); - } - } - } - for d in dirs { - if !d.is_empty() && !srv.commands.contains_key(&d) { - srv.commands.insert(d.clone(), CmdOffer::Pending); - to_check_cmd.push((item.key.clone(), item.server.clone(), d)); - } + if let Some(d) = probe_dir_for(&item.key, srv) { + srv.commands.insert(d.clone(), CmdOffer::Pending); + to_check_cmd.push((item.key.clone(), item.server.clone(), d)); } } } diff --git a/apps/desktop/src/surfaces/browser/rpc/comes_back.rs b/apps/desktop/src/surfaces/browser/rpc/comes_back.rs index cab3d3c70..93a780f61 100644 --- a/apps/desktop/src/surfaces/browser/rpc/comes_back.rs +++ b/apps/desktop/src/surfaces/browser/rpc/comes_back.rs @@ -93,3 +93,56 @@ pub fn person_came(app: &mut App, session_id: &str) { apply_batch_effects(app, batch, None); } } + +/// The server evicted `directory` (`location.shutdown`): drop idle, off-screen attachments in +/// that folder so their backoff timers do not immediately re-boot the evicted location. Returning +/// to the tab or waking it in the background re-attaches via `reconcile_sessions`. +pub fn on_location_shutdown(app: &mut App, server_key: &ServerKey, directory: &str) { + if directory.is_empty() { + return; + } + let dir_key = opencode_servers::home::same_directory_key(directory); + let routed = match &*app.route { + crate::Route::Session { server, id } if server == server_key => Some(id.as_str()), + _ => None, + }; + let active_on_server = crate::servers::runtime::active(app) == server_key; + let drop_keys: Vec = app + .kernel + .slots + .untracked(&BROWSER_RPC) + .sessions + .iter() + .filter(|((k, sid), att)| { + k == server_key + && opencode_servers::home::same_directory_key(&att.location.directory) == dir_key + && routed != Some(sid.as_str()) + && !(active_on_server && app.family_busy(sid)) + && att.active_commands.is_empty() + }) + .map(|(k, _)| k.clone()) + .collect(); + if drop_keys.is_empty() { + return; + } + let now = Instant::now(); + let mut disposed = Vec::new(); + { + let st = app.kernel.slots.get_mut(&BROWSER_RPC); + for key in drop_keys { + st.routed_sessions.remove(&key); + if let Some(mut old) = st.sessions.remove(&key) { + let _ = old.attach.step(AttachEvent::Dispose, now); + disposed.push(old); + } + } + } + if disposed.is_empty() { + return; + } + for mut old in disposed { + old.dispose_cleanup(app); + } + super::suppression::sync_mcp_suppression(app); + super::tunnel::sync_remote_tunnels(app); +} diff --git a/apps/desktop/src/surfaces/browser/rpc/mod.rs b/apps/desktop/src/surfaces/browser/rpc/mod.rs index 121589218..b9fb934ab 100644 --- a/apps/desktop/src/surfaces/browser/rpc/mod.rs +++ b/apps/desktop/src/surfaces/browser/rpc/mod.rs @@ -29,7 +29,7 @@ use opencode_kit::servers::ServerKey; use rune::{Tx, Waker, time::Instant}; use serde_json::Value; -pub use self::comes_back::person_came; +pub use self::comes_back::{on_location_shutdown, person_came}; pub use self::exec::wake::{is_tab_or_session_busy, on_tab_hibernated}; use self::session::SessionAttachment; pub use self::tunnel::grant_remote_navigation; diff --git a/apps/desktop/src/surfaces/browser/rpc/suppression.rs b/apps/desktop/src/surfaces/browser/rpc/suppression.rs index 6ad237558..c47d36d0b 100644 --- a/apps/desktop/src/surfaces/browser/rpc/suppression.rs +++ b/apps/desktop/src/surfaces/browser/rpc/suppression.rs @@ -79,11 +79,14 @@ pub(super) fn maybe_start_capability_probe(app: &mut App) { if !(active_server.is_sidecar() && server.is_local()) { return; } - let probe_dir = app - .projects - .first() - .map(|p| p.directory.as_str()) + // Probe the server's already-booted default directory (or active draft directory), never + // `app.projects.first()`, so a server-wide capability check never boots an unopened project. + let draft = matches!(*app.route, crate::Route::Draft(_)) + .then(|| app.draft_dir()) + .filter(|d| !d.is_empty()); + let probe_dir = crate::start_location::server_directory(app) .filter(|d| !d.is_empty()) + .or(draft) .unwrap_or(&app.default_dir) .to_owned(); let (worker_tx, waker, generation) = { diff --git a/apps/desktop/src/workspace/lifecycle/rune_mcp.rs b/apps/desktop/src/workspace/lifecycle/rune_mcp.rs index f198e8b9d..31a551fd2 100644 --- a/apps/desktop/src/workspace/lifecycle/rune_mcp.rs +++ b/apps/desktop/src/workspace/lifecycle/rune_mcp.rs @@ -66,10 +66,12 @@ impl RuneMcpHost for App { } fn tab_at(&self, index: usize) -> Option> { + let active = crate::servers::runtime::active(self); self.tabs.get(index).map(|t| McpTab { id: t.id.as_str(), directory: t.directory.as_str(), server: &t.server, + busy: !t.is_draft() && t.server == *active && self.family_busy(&t.id), }) } diff --git a/crates/opencode-kit/src/client/automations.rs b/crates/opencode-kit/src/client/automations.rs index 886950f6a..b9aca3207 100644 --- a/crates/opencode-kit/src/client/automations.rs +++ b/crates/opencode-kit/src/client/automations.rs @@ -47,10 +47,14 @@ impl Server { self.write("DELETE", &path, None).map(|_| ()) } - /// Whether `GET /api/command?location[directory]=…` lists a command named `name` - /// (used by Automations to check whether `/automation` is enabled in `directory`). + /// Whether `GET /api/command` (scoped to `directory` when non-empty) lists a command named + /// `name` (used by Automations to check whether `/automation` is enabled without booting cold + /// project locations when `directory` is empty). pub fn has_slash_command(&self, directory: &str, name: &str) -> Result { - let path = format!("/api/command?location%5Bdirectory%5D={}", encode_component(directory)); + let path = format!( + "/api/command{}", + crate::integration::location_query((!directory.is_empty()).then_some(directory)) + ); let v = self.get(&path)?; let items = v.get("data").and_then(serde_json::Value::as_array).or_else(|| v.as_array()); Ok(items.is_some_and(|arr| { diff --git a/features/files/src/watch.rs b/features/files/src/watch.rs index 2cd239743..8b416b2d7 100644 --- a/features/files/src/watch.rs +++ b/features/files/src/watch.rs @@ -69,11 +69,18 @@ pub fn forget_session(host: &mut dyn FilesHost, sid: &str) { } } -/// The stream connected or came back: re-arm open file watches, retry/refresh the visible +/// The stream connected or came back: re-arm open file watches for the active session only (so +/// inactive restored sessions never boot cold server locations at launch or on reconnect; off- +/// screen sessions re-arm their watches in `shown` when revisited), retry/refresh the visible /// workspace tree immediately, and mark off-screen sessions stale so they refresh when shown. pub fn connected(host: &mut dyn FilesHost) { - for (sid, path) in open_tabs(host) { - watch(host, &sid, &path); + host.files_mut().watches.clear(); + if let Some(active_sid) = host.active_session_id().map(str::to_owned) { + for (sid, path) in open_tabs(host) { + if sid == active_sid { + watch(host, &sid, &path); + } + } } let primary = host .files_tree_shown_session() @@ -260,9 +267,28 @@ pub fn reload(host: &mut dyn FilesHost, sid: &str, path: &str) { crate::ops::read_file(host, sid, path, true); } -/// Session `sid` came on screen: its files that changed while it was off read again, silently, -/// the shown tab first, and a stale visible workspace tree refreshes. +/// Session `sid` came on screen: re-arm any open file watches deferred while it was off screen, +/// read files that changed while it was off silently (the shown tab first), and refresh a stale +/// visible workspace tree. pub fn shown(host: &mut dyn FilesHost, sid: &str) { + let need_watch: Vec = host + .all_open_file_tabs() + .into_iter() + .filter(|(s, path)| { + s == sid + && directory(host, sid, path).is_some_and(|dir| { + !host + .files() + .watches + .get(&(dir, path.clone())) + .is_some_and(|holders| holders.contains(sid)) + }) + }) + .map(|(_, path)| path) + .collect(); + for path in need_watch { + watch(host, sid, &path); + } if host.files_tree_shown_session().as_deref() == Some(sid) && host .files() diff --git a/features/workspace-tools/src/rune_mcp/mod.rs b/features/workspace-tools/src/rune_mcp/mod.rs index 929e357b5..bc7058024 100644 --- a/features/workspace-tools/src/rune_mcp/mod.rs +++ b/features/workspace-tools/src/rune_mcp/mod.rs @@ -1,9 +1,10 @@ //! Per-folder `rune` client MCP lifecycle, multi-window connection sharing, and session routing. //! -//! OpenCode (Rune) attaches one WebSocket per folder that has an open tab, active session, or -//! active draft on the connected server (`name=rune`). Unopened sidebar projects are intentionally -//! excluded because opening a client MCP WebSocket for a directory boots its server location -//! (plugins, file watchers, and configured stdio MCP servers). Multiple windows open on the same +//! OpenCode (Rune) attaches one WebSocket per folder that has the active routed session/draft or +//! an actively busy open tab on the connected server (`name=rune`). Unopened sidebar projects and +//! idle background tabs are intentionally excluded because holding a client MCP WebSocket for a +//! directory boots its server location (plugins, file watchers, and configured stdio MCP servers) +//! and its reconnect loop re-boots evicted idle locations. Multiple windows open on the same //! folder share one [`ClientMcp`] connection through [`RuneMcpHub`], and every incoming //! `tools/call` is routed by `_meta["ai.opencode/sessionID"]` (and its parent chain) to the //! window and session tab showing it. @@ -98,6 +99,8 @@ pub struct McpTab<'a> { pub id: &'a str, pub directory: &'a str, pub server: &'a ServerKey, + /// True while this tab's session family is actively running, queued, or awaiting permission. + pub busy: bool, } /// Object-safe host boundary for per-window `rune` client MCP registration, polling, and tool dispatch. @@ -675,6 +678,7 @@ fn sync_stamp(host: &dyn RuneMcpHost, server: &Server) -> u64 { t.id.hash(&mut h); t.directory.hash(&mut h); t.server.hash(&mut h); + t.busy.hash(&mut h); } } host.sessions_version().hash(&mut h); @@ -713,9 +717,14 @@ fn sync_window(host: &mut dyn RuneMcpHost) { McpRoute::Session { .. } | McpRoute::Home => {} } let tab_count = host.tab_count(); + // Attach only to actively busy background tabs (in addition to the routed session/draft + // above): idle background tabs do not invoke MCP tools, and holding a persistent WebSocket + // per idle tab boots every restored tab's server location (and its stdio MCP servers) at + // launch and re-boots evicted locations on reconnect. for i in 0..tab_count { if let Some(t) = host.tab_at(i) && t.server == &active + && t.busy { add(host.session(t.id).map_or(t.directory, |info| info.directory.as_str())); }