Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): drop the "background command still running" notice (#9271)
Akarshan Biswas7515cae7b54e
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rsindex 919866779..6f2b1e681 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/handlers.rs@@ -997,17 +997,10 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {.as_ref().map(|p| crate::tools::sandbox::scratch_display_path(ctx.scratch_root, p));// Raised before this call returns, so the caller is already owed a- // result by the time the turn that made the call can end. It- // carries the path too, so a caller that stops waiting can still- // say where the output will land.+ // result by the time the turn that made the call can end.if let Some(sink) = &done_sink {sink(crate::tools::ShellEvent::Backgrounded(- crate::tools::ShellBackgrounded {- id,- command: command_owned.clone(),- timeout_secs,- output_path: display.clone(),- },+ crate::tools::ShellBackgrounded { id, timeout_secs },));}match (temp, display) {@@ -1034,21 +1027,11 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {}});let ping = if ctx.shell_done_sink.is_some() {- // The bound is quoted alongside the promise: the model- // needs to know both when it will be told and when the- // run stops holding itself open for a command that may- // never end.- format!(- " You do not have to wait or poll for it: you are notified \- automatically when it finishes, so carry on with other work \- or end your turn. \- If it is still running after about {}s you are told that \- instead, and the run is free to end -- the file still appears \- when the command eventually finishes.",- crate::tools::shell_park_budget_secs(timeout_secs)- )+ " You do not have to wait or poll for it: you are notified \+ automatically when it finishes, so carry on with other work \+ or end your turn."} else {- String::new()+ ""};format!("Command exceeded {timeout_secs}s and is still running in the \@@ -3302,10 +3285,6 @@ mod tests {handoff.timeout_secs, 0,"the park budget is sized from this");- assert!(- handoff.output_path.is_some(),- "the hand-off names the file, so a caller that gives up can still say where"- );tokio::time::sleep(std::time::Duration::from_millis(1200)).await;let got = events.lock().unwrap().clone();let Some(crate::tools::ShellEvent::Finished(done)) = got.get(1) else {diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rsindex f5881b091..77d3fabf9 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/mod.rs@@ -276,16 +276,10 @@ pub struct ShellBackgrounded {/// tracking several commands needs the pairing to be exact: matching on the/// command line would confuse two runs of the same build.pub id: u64,- /// The command line, for the ping the user and model read.- pub command: String,/// The timeout the call was given, which is what the caller sizes its park/// budget from (see [`shell_park_budget_secs`]): a command handed 600s is/// expected to be slow, one handed 5s is not.pub timeout_secs: u64,- /// Where the output will be published, if a file could be created. Known- /// here as well as in [`ShellDone`] so a caller that gives up waiting can- /// still tell the model where to collect the result later.- pub output_path: Option<String>,}/// A backgrounded `bash` command that has finished: what the caller needs to@@ -335,8 +329,9 @@ pub type ShellDoneSink = std::sync::Arc<dyn Fn(ShellEvent) + Send + Sync>;/// unbounded would park the run forever. The budget is sized from the call's/// own timeout (a command given a long one is expected to be slow) and clamped/// at both ends: never less than a minute, never more than the ceiling a-/// monitor gets. Quoted to the model by `bash` and enforced by the caller, so-/// both describe the same bound.+/// monitor gets. Enforced by the caller, which stops waiting silently: the+/// model already knows the command runs in the background, and a late+/// completion still reaches it.pub fn shell_park_budget_secs(timeout_secs: u64) -> u64 {const MIN_PARK_SECS: u64 = 60;/// The same ceiling `monitor::DEFAULT_TIMEOUT_SECS` gives a watcher.diff --git a/src-tauri/src/core/agent/bg_shell.rs b/src-tauri/src/core/agent/bg_shell.rsindex 058f7d87a..bca0ad87f 100644--- a/src-tauri/src/core/agent/bg_shell.rs+++ b/src-tauri/src/core/agent/bg_shell.rs@@ -12,12 +12,12 @@//! Unlike a monitor, a backgrounded command carries no deadline of its own://! `npm run dev`, `tail -f` and a hung build never end. So the *park* is what//! is bounded here (see [`tauri_plugin_agent_tools::tools::shell_park_budget_secs`]):-//! once a command outlives its budget the registry discharges the obligation-//! with a notice of its own -- "still running after Ns, read {path} when it-//! finishes" -- which both lets the turn end and leaves the model something to-//! act on. Expiring without a notice would be worse than not bounding it: the-//! run loop re-checks `has_pending_work` after the park and would spin a fresh-//! turn with nothing to deliver, once per deadline, forever.+//! once a command outlives its budget the registry silently stops waiting on+//! it. No notice is queued for that: the model already knows the command is+//! running (the `bash` result said so) and gains nothing actionable from being+//! told again, while the late completion still pings when it eventually lands.+//! The run loop re-checks `background_pending` after the park, so a park that+//! ends with nothing queued ends the run rather than spinning an empty turn.use std::sync::Mutex;@@ -34,10 +34,6 @@ pub(crate) struct ShellNotice {/// A command that was backgrounded and has not reported back yet.struct Pending {id: u64,- command: String,- /// Where its output will land, so an expiry notice can still say where to- /// collect a result this run has stopped waiting for.- output_path: Option<String>,/// When the run stops holding itself open for this command.deadline: tokio::time::Instant,}@@ -71,8 +67,6 @@ impl BackgroundShells {+ std::time::Duration::from_secs(shell_park_budget_secs(handoff.timeout_secs));self.state.lock().unwrap().pending.push(Pending {id: handoff.id,- command: handoff.command,- output_path: handoff.output_path,deadline,});}@@ -116,17 +110,16 @@ impl BackgroundShells {!self.state.lock().unwrap().notices.is_empty()}- /// Park until a ping is queued, a command's budget expires, or nothing is- /// left to wait for. The waiter registers before the state re-read, so a+ /// Park until a ping is queued or nothing is left to wait for (every+ /// remaining command finished or outlived its budget). The waiter registers before the state re-read, so a/// command finishing in between wakes this call rather than being missed.pub(crate) async fn wait_for_notice(&self) {loop {let waiter = self.wake.notified();tokio::pin!(waiter);waiter.as_mut().enable();- // Discharged before the state is read, so an already-expired- // command returns from the park with its notice queued rather than- // as a bare "nothing to deliver" wakeup.+ // Discharged before the state is read, so a park whose last+ // command has expired returns instead of sleeping on it again.self.abandon_expired();let next = {let state = self.state.lock().unwrap();@@ -147,22 +140,12 @@ impl BackgroundShells {}}- /// Stop waiting on every command past its budget, leaving a ping that says- /// so. Taking that ping is what lets the run end: the obligation is- /// discharged, not merely timed out.+ /// Stop waiting on every command past its budget. Silent on purpose: the+ /// model was told the command runs in the background when `bash` returned,+ /// and its completion still pings if it ever lands.fn abandon_expired(&self) {let now = tokio::time::Instant::now();- let mut state = self.state.lock().unwrap();- let (expired, live): (Vec<_>, Vec<_>) = std::mem::take(&mut state.pending)- .into_iter()- .partition(|p| p.deadline <= now);- state.pending = live;- for p in expired {- state.notices.push(ShellNotice {- headline: still_running_headline(&p.command),- text: abandoned_text(&p),- });- }+ self.state.lock().unwrap().pending.retain(|p| p.deadline > now);}}@@ -197,11 +180,6 @@ pub(crate) fn headline(done: &ShellDone) -> String {)}-/// The headline of a command the run stopped waiting on.-pub(crate) fn still_running_headline(command: &str) -> String {- format!("Background command still running: {}", short_command(command))-}-fn text(done: &ShellDone) -> String {let verb = if done.failed {"finished with a nonzero exit"@@ -229,37 +207,12 @@ fn text(done: &ShellDone) -> String {}}-/// What the model is told when a command outlives the run's patience: the run-/// is no longer held open for it, but it is still running and its output will-/// still appear.-fn abandoned_text(p: &Pending) -> String {- match &p.output_path {- Some(path) => format!(- "Background command `{}` is still running. This run is no longer waiting on \- it, so you are free to finish your turn: its output appears in {path} when \- it eventually ends, and you can read that file then (if the output was large \- that file keeps a tail and points to the full log).",- short_command(&p.command)- ),- None => format!(- "Background command `{}` is still running, and this run is no longer waiting \- on it. Its output is not being captured, so there is nothing to read back.",- short_command(&p.command)- ),- }-}-#[cfg(test)]mod tests {use super::*;fn handoff(id: u64, timeout_secs: u64) -> ShellBackgrounded {- ShellBackgrounded {- id,- command: "cargo build --release".to_string(),- timeout_secs,- output_path: Some("/tmp/jan-bash/out.txt".to_string()),- }+ ShellBackgrounded { id, timeout_secs }}fn done(failed: bool, path: Option<&str>) -> ShellDone {@@ -401,27 +354,19 @@ mod tests {}/// The bound: a command that never ends (`npm run dev`, `tail -f`) must not- /// park the run for its whole life. The park ends at the budget with a- /// notice, and once that notice is delivered nothing is owed, so the turn- /// can finish.+ /// park the run for its whole life. The park ends at the budget with+ /// nothing queued -- the model was already told the command runs in the+ /// background, so a "still running" reminder would only cost it a turn --+ /// and nothing is owed afterwards, so the turn can finish.#[tokio::test(start_paused = true)]- async fn a_command_that_never_ends_stops_holding_the_run_open() {+ async fn a_command_that_never_ends_stops_holding_the_run_open_silently() {let shells = BackgroundShells::default();shells.start(handoff(1, 30));// Never signalled: the park can only end on the budget.shells.wait_for_notice().await;- let notices = shells.take_notices();- assert_eq!(notices.len(), 1, "expiry must leave something to deliver");assert!(- notices[0].text.contains("still running")- && notices[0].text.contains("no longer waiting"),- "must say the run stopped waiting: {}",- notices[0].text- );- assert!(- notices[0].text.contains("/tmp/jan-bash/out.txt"),- "must still say where the output will land: {}",- notices[0].text+ shells.take_notices().is_empty(),+ "expiry must not ping the model about a command it knows is running");assert!(!shells.has_pending_work(),@@ -430,15 +375,24 @@ mod tests {}/// The park is sized per command: a short-timeout command must not be- /// abandoned while a long-running sibling still has budget left.+ /// abandoned while a long-running sibling still has budget left, and+ /// abandoning the short one must not wake the park with nothing to say.#[tokio::test(start_paused = true)]async fn each_command_is_abandoned_at_its_own_deadline() {let shells = BackgroundShells::default();shells.start(handoff(1, 0)); // clamped to the 60s floorshells.start(handoff(2, 600)); // clamped to the 1800s ceiling- shells.wait_for_notice().await;- assert_eq!(shells.take_notices().len(), 1, "only the first expires");+ let parked = tokio::time::timeout(+ std::time::Duration::from_secs(120),+ shells.wait_for_notice(),+ )+ .await;+ assert!(parked.is_err(), "the long one keeps the park open");+ assert!(shells.take_notices().is_empty());assert!(shells.has_pending_work(), "the long one is still owed");+ shells.wait_for_notice().await;+ assert!(shells.take_notices().is_empty());+ assert!(!shells.has_pending_work());}/// A command that comes back after it was abandoned still reports: it is@@ -448,7 +402,7 @@ mod tests {let shells = BackgroundShells::default();shells.start(handoff(7, 0));shells.wait_for_notice().await;- let _ = shells.take_notices();+ assert!(shells.take_notices().is_empty(), "abandoning is silent");shells.finish(ShellDone {id: 7,..done(false, Some("/tmp/x"))diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 8affff1da..a7cbf2558 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -1135,6 +1135,17 @@ impl CompositeToolInvoker {}}+ /// Whether any background source has a notice ready to deliver now, as+ /// opposed to work that is merely still running.+ fn has_queued_background(&self) -> bool {+ self.subagents+ .as_ref()+ .is_some_and(|ctx| ctx.bg.has_queued_notices())+ || self.monitors.has_queued_notices()+ || self.bg_shells.has_queued_notices()+ || !self.hook_notices_queue.lock().unwrap().is_empty()+ }+/// Whether the background subagents owe the model something the run must/// stay alive for, on the same terms as [`Self::monitors_owed`].fn subagents_owed(&self) -> bool {@@ -2121,23 +2132,37 @@ impl ToolInvoker for CompositeToolInvoker {// (subagent, monitor, shell): with three sources the arms would be// eight, and a fourth would double them again. `select_all` keeps the// same guarantee with one rule.- let mut waits: Vec<std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>>> =- Vec::new();- if let Some(ctx) = self- .subagents- .as_ref()- .filter(|ctx| ctx.bg.has_pending_work())- {- waits.push(Box::pin(ctx.bg.wait_for_notice()));- }- if self.monitors.has_pending_work() {- waits.push(Box::pin(self.monitors.wait_for_notice()));- }- if self.bg_shells.has_pending_work() {- waits.push(Box::pin(self.bg_shells.wait_for_notice()));- }- if !waits.is_empty() {+ //+ // Looped because a side can wake with nothing to deliver: a shell+ // abandoned at its park budget, a child aborted, a plan between phases.+ // Returning then while another side still holds the run open would+ // resume it and spend a model turn reacting to nothing. A woken side+ // either queued something (we return) or has nothing left (it drops out+ // of the next round), so this cannot spin.+ loop {+ let mut waits: Vec<+ std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send + '_>>,+ > = Vec::new();+ if let Some(ctx) = self+ .subagents+ .as_ref()+ .filter(|ctx| ctx.bg.has_pending_work())+ {+ waits.push(Box::pin(ctx.bg.wait_for_notice()));+ }+ if self.monitors.has_pending_work() {+ waits.push(Box::pin(self.monitors.wait_for_notice()));+ }+ if self.bg_shells.has_pending_work() {+ waits.push(Box::pin(self.bg_shells.wait_for_notice()));+ }+ if waits.is_empty() {+ return;+ }let _ = futures::future::select_all(waits).await;+ if self.has_queued_background() || !self.background_pending() {+ return;+ }}}@@ -11018,9 +11043,7 @@ mod tests {invoker.bg_shells.start(ShellBackgrounded {id: 1,- command: "sleep 600".to_string(),timeout_secs: 30,- output_path: Some("/tmp/out.log".to_string()),});assert!(!invoker.background_pending(),@@ -11060,9 +11083,7 @@ mod tests {invoker.bg_shells.start(ShellBackgrounded {id: 1,- command: "sleep 600".to_string(),timeout_secs: 30,- output_path: None,});assert!(invoker.background_pending(),@@ -11748,6 +11769,36 @@ mod tests {invoker}+ /// A shell abandoned at its park budget wakes its own wait with nothing to+ /// deliver. While a subagent still holds the run open, that empty wake must+ /// not end the park: the run would resume and spend a model turn reacting+ /// to nothing.+ #[cfg(feature = "cli")]+ #[tokio::test(start_paused = true)]+ async fn a_silently_abandoned_shell_does_not_end_the_park_while_a_child_runs() {+ use tauri_plugin_agent_tools::tools::ShellBackgrounded;++ let root = unique_project_root();+ let bg = Arc::new(crate::core::agent::subagent::BackgroundSubagents::default());+ crate::core::agent::subagent::tests::hold_running(&bg);+ let invoker = invoker_with_registry(root.clone(), bg);+ // Clamped to the 60s floor.+ invoker.bg_shells.start(ShellBackgrounded {+ id: 1,+ timeout_secs: 0,+ });++ let parked = tokio::time::timeout(+ std::time::Duration::from_secs(120),+ invoker.await_background(),+ )+ .await;+ assert!(parked.is_err(), "the empty shell wake must not end the park");+ assert!(!invoker.bg_shells.has_pending_work(), "the shell was abandoned");+ assert!(invoker.background_notices().is_empty(), "and said nothing");+ let _ = std::fs::remove_dir_all(&root);+ }+/// The whole model-facing path: `stop_subagent {name}` reaches the registry/// entry the dispatch created and stops it, and `message_subagent {name}`/// reaches its inbox.diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex a006abad3..7ac20b94b 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -4566,6 +4566,13 @@ pub(crate) mod tests {inbox}+ /// Count a child as running without spawning one, so a test can hold the+ /// registry's park open for as long as it needs.+ #[cfg(feature = "cli")]+ pub(crate) fn hold_running(bg: &Arc<BackgroundSubagents>) {+ bg.running.fetch_add(1, std::sync::atomic::Ordering::SeqCst);+ }+#[cfg(feature = "cli")]pub(crate) fn child_is_finished(bg: &Arc<BackgroundSubagents>, run_id: &str) -> bool {bg.inner.lock().unwrap()[run_id]diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex db39f700a..eaafb9840 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -515,7 +515,7 @@ enum NoticeKind {MonitorTimedOut,ShellFinished,ShellFailed,- /// Anything else (a hook notice, a still-running shell): a plain note.+ /// Anything else (a hook notice): a plain note.Other,}@@ -25457,7 +25457,7 @@ mod tests {/// quietly turning a failure back into a dim note.#[test]fn notice_kinds_classify_the_real_headlines() {- use crate::core::agent::bg_shell::{headline, still_running_headline};+ use crate::core::agent::bg_shell::headline;use tauri_plugin_agent_tools::tools::monitor::headline as monitor_headline;use tauri_plugin_agent_tools::tools::ShellDone;let done = |failed| ShellDone {@@ -25477,7 +25477,6 @@ mod tests {),(headline(&done(false)), NoticeKind::ShellFinished),(headline(&done(true)), NoticeKind::ShellFailed),- (still_running_headline("npm run dev"), NoticeKind::Other),("hook 'fmt' failed: exit 2".to_string(), NoticeKind::Other),];for (text, kind) in cases {@@ -43245,9 +43244,7 @@ mod tests {app.submit_user("start the build".into());app.shell_set.start(ShellBackgrounded {id: 1,- command: "cargo build".to_string(),timeout_secs: 30,- output_path: None,});// The model answered and the run ended: background work no longer// holds it open, so the session is idle.@@ -43284,9 +43281,7 @@ mod tests {.push(serde_json::json!({ "role": "assistant", "content": "building" }));app.shell_set.start(ShellBackgrounded {id: 1,- command: "cargo build".to_string(),timeout_secs: 30,- output_path: Some("/tmp/build.log".to_string()),});app.shell_set.finish(ShellDone {id: 1,@@ -43325,9 +43320,7 @@ mod tests {set.start(ShellBackgrounded {id: 1,- command: "cargo build".to_string(),timeout_secs: 30,- output_path: None,});set.finish(ShellDone {id: 1,