Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(agent): lower the bash output caps and ring a doorbell for background shells (#9033)
Akarshan Biswas422c04c84798
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 ead6ab6ba..8f7a28ef6 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@@ -26,10 +26,11 @@ const MAX_LINES: usize = 2000;/// text file whose name ends in an image extension) cannot flood the model/// context as a base64 blob.const MAX_IMAGE_BYTES: usize = 20 * 1024 * 1024;-/// bash output caps: generous enough that typical command output reaches the-/// model intact on a large-context run, spilling to a temp file only past this.-const BASH_MAX_BYTES: usize = 256 * 1024;-const BASH_MAX_LINES: usize = 10_000;+/// bash output caps, matching the `read` tool. Overflow is not lost: it spills+/// to a temp file the `read` tool can page through, so the cap is tuned for+/// context economy (~16k tokens worst case) rather than for fitting everything.+const BASH_MAX_BYTES: usize = MAX_BYTES;+const BASH_MAX_LINES: usize = MAX_LINES;const GREP_MAX_LINE: usize = 500;const LS_DEFAULT_LIMIT: usize = 500;const FIND_DEFAULT_LIMIT: usize = 1000;@@ -896,6 +897,9 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {// The child's pid stays registered until the task ends so a shutdown can// reap its whole process tree if it is still running.let (tx, mut rx) = oneshot::channel();+ // Taken before the race so a backgrounded command's reported runtime covers+ // its whole life, not just the part after the timeout.+ let started = std::time::Instant::now();let spill_scratch = ctx.scratch_root.map(Path::to_path_buf);// Owned for the detached task, which unregisters from the same session// bucket the child was registered under.@@ -945,53 +949,136 @@ async fn bash(args: &serde_json::Value, ctx: &ToolContext<'_>) -> String {if let Some(pid) = pid {proc::mark_backgrounded(ctx.thread_id, pid);}- match new_temp_path(ctx.scratch_root) {- Some(path) => {- let display =- crate::tools::sandbox::scratch_display_path(ctx.scratch_root, &path);+ // Rung by the detached task once the command really ends, so the+ // caller can ping the model rather than leaving it to poll the file.+ let done_sink = ctx.shell_done_sink.clone();+ let command_owned = command.to_string();+ let id = next_background_id();+ let temp = new_temp_path(ctx.scratch_root);+ let display = temp+ .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.+ 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(),+ },+ ));+ }+ match (temp, display) {+ (Some(path), Some(display)) => {+ let done_display = display.clone();tokio::spawn(async move {let out = rx.await.unwrap_or_else(|_| {"ERROR: background command ended without producing output".to_string()});- write_background_output(&path, &out);+ // The file is published before the doorbell rings, so a+ // model reacting to the ping always finds the output+ // already there -- and if publishing failed the ping+ // says nothing was captured rather than naming a file+ // that is absent or stale.+ let published = write_background_output(&path, &out);+ if let Some(sink) = done_sink {+ sink(crate::tools::ShellEvent::Finished(crate::tools::ShellDone {+ id,+ command: command_owned,+ elapsed_secs: started.elapsed().as_secs(),+ output_path: published.then_some(done_display),+ failed: bash_result_failed(&out),+ }));+ }});+ 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. \+ 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)+ )+ } else {+ String::new()+ };format!("Command exceeded {timeout_secs}s and is still running in the \background. Its result will be written to {display} once it \finishes; read that file to collect it (if the output was large \- that file keeps a tail and points to the full log)."+ that file keeps a tail and points to the full log).{ping}"+ )+ }+ _ => {+ // No file, but the completion is still worth reporting: the+ // model otherwise has no way to learn the command ended.+ tokio::spawn(async move {+ let out = rx.await.unwrap_or_default();+ if let Some(sink) = done_sink {+ sink(crate::tools::ShellEvent::Finished(crate::tools::ShellDone {+ id,+ command: command_owned,+ elapsed_secs: started.elapsed().as_secs(),+ output_path: None,+ failed: bash_result_failed(&out),+ }));+ }+ });+ format!(+ "Command exceeded {timeout_secs}s and is still running in the \+ background, but a file to capture its output could not be created, \+ so the output will not be collected.")}- None => format!(- "Command exceeded {timeout_secs}s and is still running in the \- background, but a file to capture its output could not be created, \- so the output will not be collected."- ),}}}}+/// Serial number for one backgrounded command, so a completion can be paired+/// with the hand-off that created it.+fn next_background_id() -> u64 {+ static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);+ NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)+}+/// Atomically publish a backgrounded command's formatted output at `path`: write/// a sibling `.part` file, then rename it into place, so an agent polling for/// `path` never observes a half-written file (existence means complete). Uses/// [`open_spill_file`] so the write never follows a symlink; leaves nothing/// behind on failure.-fn write_background_output(path: &Path, content: &str) {+///+/// Returns whether `path` now holds this command's output. The caller reports+/// the path to the model only on `true`: on ENOSPC, or a leftover `.part` from+/// an earlier crash, the promise "its output is in {path}" would otherwise name+/// a file that is absent or stale.+#[must_use]+fn write_background_output(path: &Path, content: &str) -> bool {use std::io::Write;let part = path.with_extension("part");let Ok(mut file) = open_spill_file(&part) else {- return;+ return false;};if file.write_all(content.as_bytes()).is_err() || file.flush().is_err() {drop(file);remove_spill_file(&part);- return;+ return false;}drop(file);if std::fs::rename(&part, path).is_err() {remove_spill_file(&part);+ return false;}+ true}/// Drain a running child's stdout+stderr into a bounded rolling buffer (so a@@ -3014,6 +3101,89 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The doorbell: a backgrounded command must announce itself the moment it+ /// is detached (so the caller knows a result is owed and does not end the+ /// run under it) and report again when it really finishes, naming the file+ /// the output was published to. The order matters -- the file is written+ /// before the ping, so reacting to the ping always finds it there.+ #[tokio::test]+ async fn a_backgrounded_command_rings_the_doorbell_when_it_finishes() {+ let root = unique_root();+ let store = crate::workspace::project_store(&root);+ let events = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let seen = events.clone();+ let ctx = ToolContext::new(&root, &store, &[]).with_shell_done_sink(std::sync::Arc::new(+ move |e: crate::tools::ShellEvent| seen.lock().unwrap().push(e),+ ));+ let out = super::execute_builtin(+ lookup("bash").unwrap(),+ &json!({"command": "sleep 0.3; echo done; exit 3", "timeout": 0}),+ &ctx,+ )+ .await+ .0;+ assert!(out.contains("still running in the background"), "{out}");+ assert!(+ out.contains("pinged automatically") || out.contains("notified automatically"),+ "a sink-backed run must tell the model not to poll: {out}"+ );+ // Owed immediately, before the command has ended.+ let handoff = {+ let got = events.lock().unwrap();+ let [crate::tools::ShellEvent::Backgrounded(handoff)] = got.as_slice() else {+ panic!("must announce the hand-off synchronously: {got:?}");+ };+ handoff.clone()+ };+ assert_eq!(+ 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 {+ panic!("no completion event: {got:?}");+ };+ assert_eq!(+ done.id, handoff.id,+ "the completion closes its own hand-off"+ );+ assert!(done.failed, "exit 3 must be reported as a failure");+ assert!(done.command.contains("echo done"), "names the command");+ let path = done.output_path.clone().expect("an output file");+ let collected =+ super::execute_builtin(lookup("read").unwrap(), &json!({"path": path}), &ctx)+ .await+ .0;+ assert!(+ collected.contains("done"),+ "the output must already be readable when the ping lands: {collected}"+ );+ let _ = std::fs::remove_dir_all(&root);+ }++ /// Without a sink the tool must not promise a ping that will never come.+ #[tokio::test]+ async fn backgrounding_without_a_doorbell_still_tells_the_model_to_read_the_file() {+ let root = unique_root();+ let out = execute_builtin(+ lookup("bash").unwrap(),+ &json!({"command": "sleep 2", "timeout": 0}),+ &root,+ )+ .await;+ assert!(out.contains("result will be written to"), "{out}");+ assert!(+ !out.contains("notified automatically"),+ "no sink, no promise of a ping: {out}"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn bash_exceeding_timeout_backgrounds_instead_of_erroring() {let root = unique_root();@@ -3134,23 +3304,53 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// Typical command output (well under the caps) must reach the model whole:+ /// lowering the caps for context economy must not start truncating the+ /// everyday `cargo check` / `git status` sized result.#[tokio::test]- async fn bash_output_past_old_64kb_cap_survives_intact() {+ async fn bash_output_under_the_cap_survives_intact() {let root = unique_root();- // ~128KB of output: over the shared 64KB cap, under the bash cap.+ // ~32KB over 500 lines: half the byte cap, a quarter of the line cap.let out = execute_builtin(lookup("bash").unwrap(),- &json!({"command": "for i in $(seq 1 2000); do printf '%064d\\n' \"$i\"; done"}),+ &json!({"command": "for i in $(seq 1 500); do printf '%064d\\n' \"$i\"; done"}),&root,).await;assert!(!out.starts_with("ERROR"), "unexpected: {out}");assert!(- !out.contains("[truncated"),+ !out.contains("output truncated"),"should not truncate: len={}",out.len());- assert!(out.len() > 64 * 1024, "expected >64KB, got {}", out.len());+ assert!(out.contains("000500"), "last line lost: end of {out}");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// The counterpart: past the cap the notice appears. Pinned just above+ /// 64KB so the test fails if the cap drifts back up to the old 256KB.+ #[tokio::test]+ async fn bash_output_past_the_byte_cap_is_truncated() {+ let root = unique_root();+ // ~128KB over 2000 lines of 64 chars: over the byte cap, at the line cap.+ let out = execute_builtin(+ lookup("bash").unwrap(),+ &json!({"command": "for i in $(seq 1 2000); do printf '%064d\\n' \"$i\"; done"}),+ &root,+ )+ .await;+ assert!(+ out.contains("output truncated at"),+ "should truncate: end of {out}"+ );+ // Pinned just above BASH_MAX_BYTES (not at some loose multiple of it):+ // the notice alone already fails at the old 256KB cap, so only a tight+ // bound actually pins the byte cap itself.+ assert!(+ out.len() < BASH_MAX_BYTES + 6 * 1024,+ "cap not honoured: len={}",+ out.len()+ );let _ = std::fs::remove_dir_all(&root);}@@ -3317,9 +3517,8 @@ mod tests {#[tokio::test]async fn bash_line_overflow_keeps_the_tail_not_the_head() {let root = unique_root();- // 12000 short lines: over the 10000-line cap but under the byte cap.- // Tail truncation must keep the LAST lines (final result/errors) and- // drop the earliest ones.+ // 12000 short lines: well over the line cap. Tail truncation must keep+ // the LAST lines (final result/errors) and drop the earliest ones.let out = execute_builtin(lookup("bash").unwrap(),&json!({"command": "for i in $(seq 1 12000); do echo \"L$i\"; done"}),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 acb2ad196..882b10952 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@@ -174,6 +174,11 @@ pub struct ToolContext<'a> {/// Where a hook's `context` answer and failure notices go. `None` drops/// them, which is what a caller with nowhere to show them wants.pub hook_sink: Option<HookSink>,+ /// Rung when a `bash` call that outran its timeout finally finishes, so the+ /// caller can ping the model instead of leaving it to poll the output file.+ /// `None` keeps the pull-only behaviour, which is right for a surface with+ /// no conversation to deliver into.+ pub shell_done_sink: Option<ShellDoneSink>,}impl std::fmt::Debug for ToolContext<'_> {@@ -202,6 +207,7 @@ impl std::fmt::Debug for ToolContext<'_> {.field("hooks", &self.hooks.map(|h| h.len()).unwrap_or(0)).field("plan_mode", &self.plan_mode).field("hook_sink", &self.hook_sink.is_some())+ .field("shell_done_sink", &self.shell_done_sink.is_some()).finish()}}@@ -215,6 +221,85 @@ pub type OutputSink = std::sync::Arc<dyn Fn(String) + Send + Sync>;/// [`OutputSink`] is one -- the toolset hands it to code that outlives the call.pub type HookSink = std::sync::Arc<dyn Fn(crate::tools::hooks::HookReport) + Send + Sync>;+/// A `bash` command that outran its timeout and is now running detached: what+/// the caller needs to know that a result is owed, and for how long to hold the+/// run open waiting for it.+#[derive(Debug, Clone)]+pub struct ShellBackgrounded {+ /// Pairs this hand-off with the [`ShellDone`] that ends it. A caller+ /// 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+/// tell the model where its output landed.+#[derive(Debug, Clone)]+pub struct ShellDone {+ /// The id of the [`ShellBackgrounded`] this closes.+ pub id: u64,+ /// The command line, for the ping the user and model read.+ pub command: String,+ /// How long the command ran in total, wall clock.+ pub elapsed_secs: u64,+ /// The path the output was published at, in the spelling that resolves from+ /// both the `read` tool and the sandboxed shell. `None` when no file could+ /// be created *or the write failed*, so there is nothing to collect: a ping+ /// must never name a file that is absent or stale.+ pub output_path: Option<String>,+ /// Whether the command reported a nonzero exit or a signal.+ pub failed: bool,+}++/// The life of a backgrounded `bash` command, as the caller sees it.+///+/// Two events rather than one because the caller has to know a result is owed+/// *before* the `bash` call returns: a run that learned of the command only+/// when it ended could end first, with nowhere to deliver the answer.+#[derive(Debug, Clone)]+pub enum ShellEvent {+ /// The command outran its timeout and is now running detached. Raised+ /// synchronously, before `bash` returns.+ Backgrounded(ShellBackgrounded),+ /// It finally ended. Raised from the detached task, after the output file+ /// (if any) has been published.+ Finished(ShellDone),+}++/// Where a backgrounded shell reports. `Arc` for the same reason [`OutputSink`]+/// is one: the toolset hands it to a detached task that outlives the `bash`+/// call which created it.+pub type ShellDoneSink = std::sync::Arc<dyn Fn(ShellEvent) + Send + Sync>;++/// How long a caller should hold a run open waiting for one backgrounded+/// command, in seconds.+///+/// A backgrounded command has no deadline of its own -- `npm run dev`,+/// `tail -f` or a hung build never ends -- so, unlike a monitor, waiting on it+/// 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.+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.+ const MAX_PARK_SECS: u64 = 1800;+ timeout_secs+ .saturating_mul(4)+ .clamp(MIN_PARK_SECS, MAX_PARK_SECS)+}+/// Renders a local HTML/SVG file (path, width, height, scale) to PNG bytes.////// Injected by the desktop so `screenshot` can capture through the app's own@@ -257,9 +342,17 @@ impl<'a> ToolContext<'a> {hooks: None,plan_mode: false,hook_sink: None,+ shell_done_sink: None,}}+ /// Report finished background shells to `sink`. See+ /// [`Self::shell_done_sink`].+ pub fn with_shell_done_sink(mut self, sink: ShellDoneSink) -> Self {+ self.shell_done_sink = Some(sink);+ self+ }+/// Attach the run's lifecycle hooks, the plan-mode flag they honor, and/// where their non-blocking output goes. See [`Self::hooks`].pub fn with_hooks(diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex b0b9014e4..4d4519215 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -98,7 +98,7 @@ pub fn builtin_tool_schemas() -> Vec<Value> {"type": "function","function": {"name": "bash",- "description": "Run a shell command in the project root. Returns combined stdout and stderr, followed by a final `[exit N]` line (or `[terminated by signal]`). Judge success by that exit code, not by whether there is text on stderr: many commands (e.g. `git push`) write normal status to stderr on success, so `[exit 0]` means it worked. The output is COMPLETE and verbatim: trust it and do not re-run a command to double-check. It is truncated only when it exceeds 10000 lines or 256KB, and only then is an explicit `[output truncated ...]` notice appended with a temp-file path holding the full output; when truncated the LAST lines are kept (so the final result and errors stay visible). Absent that notice, you have the full output. If the command doesn't finish within `timeout` seconds (default 30), it keeps running in the background instead of erroring or being killed, and this call returns the path to a file where its full output will be written once it finishes; read that file (with the read tool) to collect the result. The file appears only when the command is done, so its presence means the output is complete.",+ "description": "Run a shell command in the project root. Returns combined stdout and stderr, followed by a final `[exit N]` line (or `[terminated by signal]`). Judge success by that exit code, not by whether there is text on stderr: many commands (e.g. `git push`) write normal status to stderr on success, so `[exit 0]` means it worked. The output is COMPLETE and verbatim: trust it and do not re-run a command to double-check. It is truncated only when it exceeds 2000 lines or 64KB, and only then is an explicit `[output truncated ...]` notice appended with a temp-file path holding the full output; when truncated the LAST lines are kept (so the final result and errors stay visible). Absent that notice, you have the full output. If the command doesn't finish within `timeout` seconds (default 30), it keeps running in the background instead of erroring or being killed, and this call returns the path to a file where its full output will be written once it finishes; read that file (with the read tool) to collect the result. The file appears only when the command is done, so its presence means the output is complete.","parameters": {"type": "object","properties": {diff --git a/src-tauri/src/core/agent/bg_shell.rs b/src-tauri/src/core/agent/bg_shell.rsnew file mode 100644index 000000000..a58ffa511--- /dev/null+++ b/src-tauri/src/core/agent/bg_shell.rs@@ -0,0 +1,457 @@+//! Completion doorbell for backgrounded `bash` commands.+//!+//! A `bash` call that outruns its timeout keeps running and publishes its output+//! to a file, but nothing used to tell the model when that happened: the model+//! had to guess when to read the path back, and a run with nothing else to do+//! would end while the command was still going. This registry closes that gap+//! the way [`crate::core::agent::subagent::BackgroundSubagents`] and+//! `MonitorSet` do -- queue the ping, wake anyone parked, and hold the run open+//! while a command is still owed -- so a finished shell reaches the model as a+//! `<SYSTEM>` reminder at the top of the next turn.+//!+//! 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.++use std::sync::Mutex;++use tauri_plugin_agent_tools::tools::{shell_park_budget_secs, ShellBackgrounded, ShellDone};++/// One finished background command, ready for delivery.+pub(crate) struct ShellNotice {+ /// Shown to the user at delivery, since nothing else reports the fact.+ pub headline: String,+ /// What reaches the model.+ pub text: String,+}++/// 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,+}++/// Everything one run is still owed from background shells: the commands not+/// yet reported, and the pings for those that have. Both live under one lock on+/// purpose -- the count and the queue are read together by+/// [`BackgroundShells::has_pending_work`], so a command cannot be observed as+/// "no longer running" in the window before its ping is queued, and a parked+/// run cannot see "nothing running, nothing queued" and end under an answer+/// about to land.+#[derive(Default)]+struct State {+ pending: Vec<Pending>,+ notices: Vec<ShellNotice>,+}++/// The background commands one run is still owed a result from, plus the pings+/// for those that have finished.+#[derive(Default)]+pub(crate) struct BackgroundShells {+ state: Mutex<State>,+ wake: tokio::sync::Notify,+}++impl BackgroundShells {+ /// A command has been backgrounded and its completion is now owed to the+ /// model -- until it finishes, or until its park budget runs out.+ pub(crate) fn start(&self, handoff: ShellBackgrounded) {+ let deadline = tokio::time::Instant::now()+ + 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,+ });+ }++ /// A backgrounded command ended: queue its ping and release the run.+ pub(crate) fn finish(&self, done: ShellDone) {+ let mut state = self.state.lock().unwrap();+ // Removed by id rather than by count: a command whose budget already+ // expired was dropped from `pending` when it was abandoned, and+ // decrementing a count here would underflow and park the run forever.+ // Its late ping is still queued -- it is real news, and it is queued at+ // most once per command.+ state.pending.retain(|p| p.id != done.id);+ state.notices.push(ShellNotice {+ headline: headline(&done),+ text: text(&done),+ });+ drop(state);+ self.wake.notify_waiters();+ }++ /// Take every queued ping, oldest first.+ pub(crate) fn take_notices(&self) -> Vec<ShellNotice> {+ std::mem::take(&mut self.state.lock().unwrap().notices)+ }++ /// Whether anything is still owed: a command running within its budget, or+ /// a ping queued and not yet delivered. Safe to park on -- every pending+ /// command either ends or is abandoned at its deadline.+ pub(crate) fn has_pending_work(&self) -> bool {+ let state = self.state.lock().unwrap();+ !state.notices.is_empty() || !state.pending.is_empty()+ }++ /// Whether a ping is queued and not yet taken. Unlike+ /// [`Self::has_pending_work`] this says nothing about commands still+ /// running: a set that outlives its run consults it to decide whether the+ /// model has something to react to *now*, since a command finishing later+ /// starts a turn of its own rather than holding this one open.+ pub(crate) fn has_queued_notices(&self) -> bool {+ !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+ /// 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.+ self.abandon_expired();+ let next = {+ let state = self.state.lock().unwrap();+ if !state.notices.is_empty() || state.pending.is_empty() {+ return;+ }+ state.pending.iter().map(|p| p.deadline).min()+ };+ match next {+ Some(deadline) => {+ tokio::select! {+ _ = waiter => {}+ _ = tokio::time::sleep_until(deadline) => {}+ }+ }+ None => waiter.await,+ }+ }+ }++ /// 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.+ 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: format!(+ "Background command still running: {}",+ short_command(&p.command)+ ),+ text: abandoned_text(&p),+ });+ }+ }+}++/// The command line, flattened and capped, for a one-line ping.+fn short_command(command: &str) -> String {+ const MAX: usize = 60;+ let flat = command.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= MAX {+ return flat;+ }+ let head: String = flat.chars().take(MAX - 3).collect();+ format!("{head}...")+}++fn headline(done: &ShellDone) -> String {+ let verb = if done.failed { "failed" } else { "finished" };+ format!(+ "Background command {verb} after {}s: {}",+ done.elapsed_secs,+ short_command(&done.command)+ )+}++fn text(done: &ShellDone) -> String {+ let verb = if done.failed {+ "finished with a nonzero exit"+ } else {+ "finished"+ };+ match &done.output_path {+ // Hedged the way the `bash` result itself is: the published file holds+ // the already-capped output, so past the cap it is a tail plus a+ // pointer to the full log, not the whole thing. A `<SYSTEM>` notice+ // reads as authoritative, so it must not overclaim.+ Some(path) => format!(+ "Background command `{}` {verb} after {}s. Its output is in {path} -- read \+ that file when you need it (if the output was large that file keeps a tail \+ and points to the full log).",+ short_command(&done.command),+ done.elapsed_secs+ ),+ None => format!(+ "Background command `{}` {verb} after {}s. Its output was not captured, \+ so there is nothing to read back.",+ short_command(&done.command),+ done.elapsed_secs+ ),+ }+}++/// 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()),+ }+ }++ fn done(failed: bool, path: Option<&str>) -> ShellDone {+ ShellDone {+ id: 1,+ command: "cargo build --release".to_string(),+ elapsed_secs: 42,+ output_path: path.map(str::to_string),+ failed,+ }+ }++ #[test]+ fn a_finished_command_queues_one_ping_naming_its_output_file() {+ let shells = BackgroundShells::default();+ shells.start(handoff(1, 30));+ assert!(shells.has_pending_work(), "a running command is owed");+ shells.finish(done(false, Some("/tmp/jan-bash/out.txt")));+ let notices = shells.take_notices();+ assert_eq!(notices.len(), 1);+ assert!(+ notices[0].text.contains("/tmp/jan-bash/out.txt"),+ "must point at the output: {}",+ notices[0].text+ );+ assert!(+ notices[0].text.contains("cargo build --release"),+ "must name the command: {}",+ notices[0].text+ );+ assert!(+ notices[0].headline.contains("finished"),+ "user-facing line: {}",+ notices[0].headline+ );+ // Drained: nothing is owed any more.+ assert!(!shells.has_pending_work());+ }++ /// The published file holds the already-capped result, so the ping must+ /// hedge exactly as the `bash` call's own wording does rather than promise+ /// the complete output.+ #[test]+ fn the_ping_does_not_promise_more_than_the_file_holds() {+ let shells = BackgroundShells::default();+ shells.start(handoff(1, 30));+ shells.finish(done(false, Some("/tmp/jan-bash/out.txt")));+ let notices = shells.take_notices();+ assert!(+ !notices[0].text.contains("full output is in"),+ "must not claim completeness: {}",+ notices[0].text+ );+ assert!(+ notices[0].text.contains("keeps a tail"),+ "must carry the same hedge the tool result does: {}",+ notices[0].text+ );+ }++ #[test]+ fn a_failing_command_says_so_in_both_registers() {+ let shells = BackgroundShells::default();+ shells.start(handoff(1, 30));+ shells.finish(done(true, Some("/tmp/jan-bash/out.txt")));+ let notices = shells.take_notices();+ assert!(notices[0].headline.contains("failed"));+ assert!(notices[0].text.contains("nonzero exit"));+ }++ #[test]+ fn a_command_with_no_output_file_still_reports_that_it_ended() {+ let shells = BackgroundShells::default();+ shells.start(handoff(1, 30));+ shells.finish(done(false, None));+ let notices = shells.take_notices();+ assert!(+ notices[0].text.contains("not captured"),+ "unexpected: {}",+ notices[0].text+ );+ }++ /// The ping must be queued before the command stops counting as owed, or a+ /// parked run could observe "nothing running, nothing queued" and end under+ /// a command whose answer was about to land. One lock over both makes the+ /// window impossible.+ #[test]+ fn a_queued_ping_keeps_the_run_owed_even_after_the_command_ended() {+ let shells = BackgroundShells::default();+ shells.start(handoff(1, 30));+ shells.finish(done(false, Some("/tmp/x")));+ assert!(+ shells.has_pending_work(),+ "an undelivered ping is still owed"+ );+ let _ = shells.take_notices();+ assert!(!shells.has_pending_work());+ }++ /// A `Finished` for a command that is not pending (a duplicate, or one+ /// already abandoned at its deadline) must not corrupt the count: with a+ /// bare decrement it would wrap and park the run forever.+ #[test]+ fn an_unpaired_completion_cannot_wedge_the_registry() {+ let shells = BackgroundShells::default();+ shells.finish(done(false, Some("/tmp/x")));+ shells.finish(done(false, Some("/tmp/x")));+ assert_eq!(shells.take_notices().len(), 2);+ assert!(+ !shells.has_pending_work(),+ "nothing is owed once the pings are delivered"+ );+ }++ #[tokio::test]+ async fn parking_wakes_when_a_command_finishes() {+ let shells = std::sync::Arc::new(BackgroundShells::default());+ shells.start(handoff(1, 30));+ let waiter = shells.clone();+ let parked = tokio::spawn(async move { waiter.wait_for_notice().await });+ tokio::task::yield_now().await;+ shells.finish(done(false, Some("/tmp/x")));+ tokio::time::timeout(std::time::Duration::from_secs(5), parked)+ .await+ .expect("park must wake on a completion")+ .unwrap();+ assert_eq!(shells.take_notices().len(), 1);+ }++ /// The park also returns when nothing is left to wait for, so a run whose+ /// shells were all reaped cannot hang.+ #[tokio::test]+ async fn parking_returns_immediately_when_nothing_is_owed() {+ let shells = BackgroundShells::default();+ tokio::time::timeout(std::time::Duration::from_secs(5), shells.wait_for_notice())+ .await+ .expect("must not park with nothing in flight");+ }++ /// 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.+ #[tokio::test(start_paused = true)]+ async fn a_command_that_never_ends_stops_holding_the_run_open() {+ 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+ );+ assert!(+ !shells.has_pending_work(),+ "the obligation is discharged, so the run is free to end"+ );+ }++ /// The park is sized per command: a short-timeout command must not be+ /// abandoned while a long-running sibling still has budget left.+ #[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 floor+ shells.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");+ assert!(shells.has_pending_work(), "the long one is still owed");+ }++ /// A command that comes back after it was abandoned still reports: it is+ /// real news, delivered once, and the stale entry must not double-count.+ #[tokio::test(start_paused = true)]+ async fn a_late_completion_after_abandonment_still_pings_exactly_once() {+ let shells = BackgroundShells::default();+ shells.start(handoff(7, 0));+ shells.wait_for_notice().await;+ let _ = shells.take_notices();+ shells.finish(ShellDone {+ id: 7,+ ..done(false, Some("/tmp/x"))+ });+ let notices = shells.take_notices();+ assert_eq!(notices.len(), 1);+ assert!(notices[0].headline.contains("finished"));+ assert!(!shells.has_pending_work());+ }++ #[test]+ fn a_long_command_line_is_flattened_and_capped() {+ let short = short_command(" echo hello \n world ");+ assert_eq!(short, "echo hello world");+ let long = short_command(&"x".repeat(200));+ assert_eq!(long.chars().count(), 60);+ assert!(long.ends_with("..."));+ }+}diff --git a/src-tauri/src/core/agent/context.rs b/src-tauri/src/core/agent/context.rsindex 8770eb0d1..e9cbcdda5 100644--- a/src-tauri/src/core/agent/context.rs+++ b/src-tauri/src/core/agent/context.rs@@ -26,7 +26,12 @@ const GUIDELINES: &str =- Tool output is complete and verbatim. Trust it. Do not re-run a command to check for hidden or \missing output: when output is cut it always carries an explicit `[output truncated ...]` notice, so \its absence means you have everything. A command's `[exit N]` line is the authoritative result -- \-`[exit 0]` is success even if there is text on stderr (many tools write normal status there).";+`[exit 0]` is success even if there is text on stderr (many tools write normal status there).\n\+- You may end your turn while background work is still running -- a backgrounded shell command, a \+dispatched subagent, a monitor. You are notified automatically when each one finishes, and the \+notice reaches you as a `<SYSTEM>` note that resumes the conversation, so nothing is lost by \+stopping. Do not idle, poll a file in a loop, or narrate waiting: say what you started, then either \+get on with unrelated work or finish the turn.";/// The one instructions file Jan reads, discovered by walking from the project/// root up to the filesystem root. Another agent's file (`AGENTS.md`,@@ -558,6 +563,28 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The permission to stop while background work runs is unconditional: it+ /// applies to a backgrounded shell and a monitor, which exist on runs with+ /// subagents disabled, so it must not live in the gated subagent block.+ #[test]+ fn guidelines_permit_ending_a_turn_while_background_work_runs() {+ let root = scratch_project("bgturn");+ let without_subagents = default_prompt(None, &root, None, false).expect("prompt");+ assert!(+ without_subagents.contains("You may end your turn while background work is still running"),+ "missing the permission: {without_subagents}"+ );+ assert!(+ without_subagents.contains("notified automatically"),+ "must say the notice arrives on its own"+ );+ assert!(+ !without_subagents.contains("dispatch_subagent"),+ "the subagent block must still be gated off"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+#[test]fn context_files_ingested_nearest_last() {let root = scratch_project("ctxfiles");diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 06862b617..c050383e2 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -117,6 +117,20 @@ pub(crate) struct OrchestrationArgs {/// child) scopes monitors to the run, which then parks on them. Never/// inherited by a child run, which gets its own per-run set.pub monitors: Option<std::sync::Arc<tauri_plugin_agent_tools::tools::monitor::MonitorSet>>,+ /// A backgrounded-shell registry owned by the session rather than by this+ /// run. When set, a command still running does not park the run: the+ /// model's turn ends and the owner starts a new turn when the command+ /// finishes. `None` (a headless run, a child) scopes shells to the run,+ /// which then parks on them. Never inherited by a child run.+ pub bg_shells: Option<std::sync::Arc<crate::core::agent::bg_shell::BackgroundShells>>,+ /// A background-subagent registry owned by the session rather than by this+ /// run, on the same terms as `monitors` and `bg_shells`: a child still+ /// running does not park the run, and its completion starts a turn of its+ /// own. A session set is also exempt from the run-scoped `AbortOnDrop`+ /// teardown -- the owner decides when children die (the TUI kills them on+ /// cancel and on session reset). Never inherited by a child run, which+ /// cannot dispatch grandchildren anyway.+ pub subagent_bg: Option<std::sync::Arc<crate::core::agent::subagent::BackgroundSubagents>>,/// When this run compacts ahead of dispatching: the route's context window,/// the share of it a prompt may fill, and any explicitly configured reserve.///@@ -393,6 +407,22 @@ struct CompositeToolInvoker {/// the tool-event hooks fire inside the toolset and report through a sink/// that outlives the call (see [`CompositeToolInvoker::hook_sink`]).hook_notices_queue: std::sync::Arc<std::sync::Mutex<Vec<BackgroundNotice>>>,+ /// Backgrounded `bash` commands this run is still owed a result from, and+ /// the pings for those that have finished. `Arc` because the doorbell is+ /// rung from the detached task inside the toolset, which outlives the call+ /// (see [`CompositeToolInvoker::shell_done_sink`]). Parking on it is+ /// bounded like a monitor, but by the registry rather than the command: a+ /// backgrounded shell may never end, so one past its park budget is+ /// abandoned with a notice telling the model where to collect it later.+ bg_shells: std::sync::Arc<crate::core::agent::bg_shell::BackgroundShells>,+ /// Whether `bg_shells` outlives this run. A session-owned registry never+ /// parks the run on a command that has not finished: the owner delivers a+ /// later completion as a fresh turn, so the user can keep talking meanwhile.+ bg_shells_outlive_run: bool,+ /// Whether the subagent registry in `subagents` outlives this run, on the+ /// same terms as `bg_shells_outlive_run`. A session-owned set is also left+ /// out of the run's `AbortOnDrop` teardown and its end-of-run `join_all`.+ subagent_bg_outlive_run: bool,}/// Default for the sandboxed shell's network namespace, used when@@ -656,6 +686,31 @@ impl CompositeToolInvoker {}}+ /// Whether the backgrounded shells owe the model something the run must+ /// stay alive for, on the same terms as [`Self::monitors_owed`]: a queued+ /// ping always, plus a command still running when the registry dies with+ /// the run (nothing else could deliver its output).+ fn shells_owed(&self) -> bool {+ if self.bg_shells_outlive_run {+ self.bg_shells.has_queued_notices()+ } else {+ self.bg_shells.has_pending_work()+ }+ }++ /// 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 {+ let Some(ctx) = self.subagents.as_ref() else {+ return false;+ };+ if self.subagent_bg_outlive_run {+ ctx.bg.has_queued_notices()+ } else {+ ctx.bg.has_pending_work()+ }+ }+fn tool_context(&self) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {tauri_plugin_agent_tools::tools::ToolContext::new(&self.project_root,@@ -673,6 +728,24 @@ impl CompositeToolInvoker {self.run_mode == crate::core::agent::plan::RunMode::Plan,Some(self.hook_sink()),)+ .with_shell_done_sink(self.shell_done_sink())+ }++ /// Where a backgrounded `bash` command reports when it finally ends: the+ /// run's shell registry, drained into a `<SYSTEM>` reminder at the top of+ /// the next turn the way a finished subagent is.+ fn shell_done_sink(&self) -> tauri_plugin_agent_tools::tools::ShellDoneSink {+ // Shared rather than borrowed because the sink outlives the call that+ // created it, the way the hook and output sinks do.+ let shells = self.bg_shells.clone();+ std::sync::Arc::new(+ move |event: tauri_plugin_agent_tools::tools::ShellEvent| match event {+ tauri_plugin_agent_tools::tools::ShellEvent::Backgrounded(handoff) => {+ shells.start(handoff)+ }+ tauri_plugin_agent_tools::tools::ShellEvent::Finished(done) => shells.finish(done),+ },+ )}/// Where the `PreToolUse`/`PostToolUse` hooks fired inside@@ -1237,17 +1310,35 @@ impl ToolInvoker for CompositeToolInvoker {out.extend(std::mem::take(&mut *self.hook_notices_queue.lock().unwrap(),));+ // A backgrounded shell that finished rides the same channel. It carries+ // a headline, like a monitor match and unlike a subagent: no other row+ // reports that the command ended.+ out.extend(+ self.bg_shells+ .take_notices()+ .into_iter()+ .map(|n| BackgroundNotice {+ headline: Some(n.headline),+ text: n.text,+ }),+ );out}fn background_pending(&self) -> bool {- self.subagents- .as_ref()- .is_some_and(|ctx| ctx.bg.has_pending_work())+ self.subagents_owed()|| self.monitors_owed()// A queued hook answer is owed to the model the same way a monitor// match is: the turn that would end must deliver it first.|| !self.hook_notices_queue.lock().unwrap().is_empty()+ // Likewise a backgrounded command: ending the run here would drop+ // the output of a build the model is still waiting on. Bounded+ // too, though the bound is the park's rather than the command's --+ // a shell has no deadline of its own, so `BackgroundShells`+ // abandons one past its budget with a notice saying so. A+ // session-owned registry never parks on a command still running:+ // its owner starts a turn when the output lands.+ || self.shells_owed()}fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {@@ -1267,24 +1358,32 @@ impl ToolInvoker for CompositeToolInvoker {// Each wait returns on a notice OR when its own side has nothing left,// so an exhausted side must not be selected over: it would win// instantly every time and starve the side actually being waited on.- // The re-check between iterations is what `run_turn_cycle` does anyway.- // A session-owned set is still selected while a subagent is awaited: a- // match landing then should wake the park like a finished child does.- let sub_pending = self+ // Hence only the pending sides are collected here. The re-check between+ // iterations is what `run_turn_cycle` does anyway, and a session-owned+ // monitor set is still selected while a subagent is awaited: a match+ // landing then should wake the park like a finished child does.+ //+ // A list of futures rather than a match over every combination of+ // (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()- .is_some_and(|ctx| ctx.bg.has_pending_work());- let mon_pending = self.monitors.has_pending_work();- match (self.subagents.as_ref(), sub_pending, mon_pending) {- (Some(ctx), true, true) => {- tokio::select! {- _ = ctx.bg.wait_for_notice() => {}- _ = self.monitors.wait_for_notice() => {}- }- }- (Some(ctx), true, false) => ctx.bg.wait_for_notice().await,- (_, _, true) => self.monitors.wait_for_notice().await,- _ => {}+ .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() {+ let _ = futures::future::select_all(waits).await;}}@@ -1797,6 +1896,10 @@ pub(crate) async fn run_server_side_openai_orchestration(session_id: None,sandbox: None,monitors: None,+ // Run-owned: the proxy has no conversation to deliver a later ping+ // into, so background work must be settled before the run returns.+ bg_shells: None,+ subagent_bg: None,// Server-side runs take whatever window the proxy's route reports// through its own path, so the loop has none to size against here.compaction: None,@@ -2293,6 +2396,8 @@ async fn orchestrate_inner(run_mode,session_id,monitors: session_monitors,+ bg_shells: session_bg_shells,+ subagent_bg: session_subagent_bg,sandbox,compaction,} = args;@@ -2569,13 +2674,23 @@ async fn orchestrate_inner(let index_memory = system_prompt_override.is_none();if let Some(root) = project_root {- // Background subagents are scoped to this run: `_bg_guard` aborts any- // still-running child when `orchestrate_inner` returns or is cancelled.- // The cap (`max_parallel_subagents`) is snapshotted here, at run start.- let bg = std::sync::Arc::new(- crate::core::agent::subagent::BackgroundSubagents::new(*max_parallel_subagents),- );- let _bg_guard = crate::core::agent::subagent::AbortOnDrop(bg.clone());+ // Background subagents are scoped to this run unless the session owns+ // them: `_bg_guard` aborts any still-running child when+ // `orchestrate_inner` returns or is cancelled. The cap+ // (`max_parallel_subagents`) is snapshotted here, at run start.+ let bg = session_subagent_bg.clone().unwrap_or_else(|| {+ std::sync::Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(+ *max_parallel_subagents,+ ))+ });+ // A session set outlives the run by design, so the run-scoped teardown+ // must not arm for it: the owner decides when its children die (the+ // TUI aborts them on cancel and on session reset). Arming it here would+ // kill on the first turn's return exactly the children this change+ // exists to keep running.+ let _bg_guard = session_subagent_bg+ .is_none()+ .then(|| crate::core::agent::subagent::AbortOnDrop(bg.clone()));let subagents = args.subagents_enabled.then(|| SubagentContext {parent_args: args.clone(),model_id: model_id.clone(),@@ -2620,6 +2735,8 @@ async fn orchestrate_inner(subagents,monitors: session_monitors.clone().unwrap_or_default(),monitors_outlive_run: session_monitors.is_some(),+ bg_shells_outlive_run: session_bg_shells.is_some(),+ subagent_bg_outlive_run: session_subagent_bg.is_some(),auto_approve: *auto_approve,run_mode,// Resolved once per run, like every other config-derived field: a@@ -2628,6 +2745,7 @@ async fn orchestrate_inner(hooks: crate::core::agent::hooks_config::resolve_hooks(root),plugin_tools: crate::core::agent::hooks_config::resolve_plugin_tools(root),hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),+ bg_shells: session_bg_shells.clone().unwrap_or_default(),};// Entries dropped while loading the hook files are reported once here,// before anything fires: a user whose matcher is a bad glob otherwise@@ -2722,8 +2840,11 @@ async fn orchestrate_inner(.await;// On a clean exit, wait for any subagents the model dispatched but never// explicitly awaited, so their in-flight work isn't aborted and lost by- // `_bg_guard`. On an error, teardown still aborts them.- if result.is_ok() {+ // `_bg_guard`. On an error, teardown still aborts them. A session-owned+ // set is skipped: nothing is about to abort those children, and waiting+ // here would hold the run open for precisely the work the session set+ // exists to outlive it.+ if result.is_ok() && session_subagent_bg.is_none() {bg.join_all().await;}// Fired on failure too: a SessionEnd hook that only ran on the happy@@ -6562,11 +6683,16 @@ mod tests {tauri_plugin_agent_tools::tools::monitor::MonitorSet::new(),),monitors_outlive_run: false,+ bg_shells_outlive_run: false,+ subagent_bg_outlive_run: false,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,hooks: tauri_plugin_agent_tools::tools::hooks::HookSet::new(),plugin_tools: tauri_plugin_agent_tools::tools::plugin_tools::PluginToolSet::new(),hook_notices_queue: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),+ bg_shells: std::sync::Arc::new(+ crate::core::agent::bg_shell::BackgroundShells::default(),+ ),}}@@ -8095,6 +8221,77 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// The shell counterpart of+ /// `a_session_owned_monitor_does_not_park_the_run_until_it_fires`: a+ /// command still running must not hold the run open when the session owns+ /// the registry, so the model's turn can end and the user can type into an+ /// idle agent. A queued completion is still owed, since it has to reach+ /// the model somewhere.+ #[tokio::test]+ async fn a_session_owned_background_shell_does_not_park_the_run_until_it_finishes() {+ use tauri_plugin_agent_tools::tools::{ShellBackgrounded, ShellDone};++ let root = unique_project_root();+ let (tx, _rx) = mpsc::unbounded_channel();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let mut invoker = build_prompting_invoker(root.clone(), tx, registry);+ invoker.bg_shells_outlive_run = true;++ 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(),+ "a command still running must not park a session-owned run"+ );++ invoker.bg_shells.finish(ShellDone {+ id: 1,+ command: "sleep 600".to_string(),+ elapsed_secs: 1,+ output_path: Some("/tmp/out.log".to_string()),+ failed: false,+ });+ assert!(+ invoker.background_pending(),+ "a queued completion is owed to the model"+ );+ let notices = invoker.background_notices();+ assert_eq!(notices.len(), 1);+ assert!(notices[0].headline.is_some(), "a shell reports its own end");+ assert!(!invoker.background_pending(), "taken, so nothing is owed");+ let _ = std::fs::remove_dir_all(&root);+ }++ /// A run-owned registry keeps the old contract: nothing else could deliver+ /// the output, so the run parks until the command reports back. This is+ /// the headless and child-run path.+ #[tokio::test]+ async fn a_run_owned_background_shell_still_parks_the_run() {+ use tauri_plugin_agent_tools::tools::ShellBackgrounded;++ let root = unique_project_root();+ let (tx, _rx) = mpsc::unbounded_channel();+ let registry: PermissionRegistry = Arc::new(Mutex::new(HashMap::new()));+ let invoker = build_prompting_invoker(root.clone(), tx, registry);+ assert!(!invoker.bg_shells_outlive_run, "run-owned by default");++ invoker.bg_shells.start(ShellBackgrounded {+ id: 1,+ command: "sleep 600".to_string(),+ timeout_secs: 30,+ output_path: None,+ });+ assert!(+ invoker.background_pending(),+ "nothing else could deliver this output, so the run waits"+ );+ let _ = std::fs::remove_dir_all(&root);+ }+#[tokio::test]async fn auto_approve_writes_without_prompting() {let root = unique_project_root();diff --git a/src-tauri/src/core/agent/mod.rs b/src-tauri/src/core/agent/mod.rsindex d51cbd546..fb02ec51c 100644--- a/src-tauri/src/core/agent/mod.rs+++ b/src-tauri/src/core/agent/mod.rs@@ -6,6 +6,8 @@//! builds with or without Tauri so the desktop app and the headless CLI share//! one implementation. This module owns orchestration only.+/// Completion pings for backgrounded `bash` commands.+pub mod bg_shell;// Tauri IPC surface for the desktop agent; the CLI drives the loop directly.#[cfg(not(feature = "cli"))]pub mod commands;diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 2363281b0..f724862ee 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -693,6 +693,18 @@ pub(crate) struct BackgroundSubagents {/// whole life, so the parent stays parked across the gap where one phase has/// finished (`running == 0`) but the driver has not yet spawned the next.plans_pending: std::sync::atomic::AtomicUsize,+ /// Where a child's events go when the registry outlives any one run.+ ///+ /// A child dispatched by run N but still working after it ends would+ /// otherwise stream `ToolCall`/`SubagentEnd` into run N's channel, which+ /// its consumer stopped reading the moment the run finished: the panel+ /// freezes and the closing bracket is lost. So a session installs one+ /// durable channel here and every child reports into that instead. `None`+ /// for a run-owned registry, where the dispatching run's sender is correct+ /// precisely because no child outlives it.+ session_events: std::sync::Mutex<+ Option<tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>>,+ >,}/// Default cap on concurrently *running* subagents per parent run when@@ -718,9 +730,36 @@ impl BackgroundSubagents {wake: Arc::new(tokio::sync::Notify::new()),running: std::sync::atomic::AtomicUsize::new(0),plans_pending: std::sync::atomic::AtomicUsize::new(0),+ session_events: std::sync::Mutex::new(None),}}+ /// Install the durable channel a session's children report into. Called+ /// once at session start; see [`Self::session_events`].+ ///+ /// Only a session owns a registry that outlives its runs, and only the TUI+ /// has one, so this does not exist in the desktop build.+ #[cfg(feature = "cli")]+ pub(crate) fn install_session_events(+ &self,+ tx: tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) {+ *self.session_events.lock().unwrap() = Some(tx);+ }++ /// The channel a child dispatched now should report into: the session's+ /// durable one when this registry outlives runs, else the dispatching run's.+ fn child_events(+ &self,+ run_events: &tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent>,+ ) -> tokio::sync::mpsc::UnboundedSender<crate::core::agent::events::StreamEvent> {+ self.session_events+ .lock()+ .unwrap()+ .clone()+ .unwrap_or_else(|| run_events.clone())+ }+/// Mark a multi-phase plan as driving, keeping the parent parked until the/// driver calls [`end_plan`]. Balanced 1:1 with `end_plan`.fn begin_plan(&self) {@@ -752,6 +791,15 @@ impl BackgroundSubagents {|| self.plans_pending.load(std::sync::atomic::Ordering::SeqCst) > 0}+ /// Whether a ping is queued and not yet taken. Unlike+ /// [`Self::has_pending_work`] this says nothing about children still+ /// running: a set that outlives its run consults it to decide whether the+ /// model has something to react to *now*, since a child finishing later+ /// starts a turn of its own rather than holding this one open.+ pub(crate) fn has_queued_notices(&self) -> bool {+ !self.notices.lock().unwrap().is_empty()+ }+/// Park until a ping is available, or until nothing is left to wait for.////// The waiter is registered *before* the state is re-read (`enable`), so a@@ -838,6 +886,21 @@ impl BackgroundSubagents {self.notices.lock().unwrap().clear();}+ /// The run ids of children still registered, i.e. dispatched and not yet+ /// finished or aborted. A session-owned registry is the authority on which+ /// live panels survive a run end: what the run streamed says only what it+ /// last saw, not what is still running.+ #[cfg(feature = "cli")]+ pub(crate) fn live_run_ids(&self) -> std::collections::HashSet<String> {+ self.inner+ .lock()+ .unwrap()+ .values()+ .filter(|entry| !entry.finished.load(std::sync::atomic::Ordering::SeqCst))+ .map(|entry| entry.run_id.clone())+ .collect()+ }+/// Wait for every still-registered child to finish on its own, rather than/// aborting it. Called on a clean parent exit so dispatched work that the/// model never explicitly awaited is not silently discarded mid-flight.@@ -936,6 +999,14 @@ async fn run_subagent(// A child's monitors are its own and die with it; nothing would pick up a// match left in the session set once the child has returned.child_args.monitors = None;+ // Likewise its backgrounded shells: a child's run is the only thing that+ // could deliver their output, so they stay run-owned and it parks on them+ // rather than handing the session a command nobody is reading for.+ child_args.bg_shells = None;+ // A child cannot dispatch subagents at all (`subagents_enabled = false`+ // above), so it has no registry to share; clearing this keeps it from+ // inheriting the parent session's by accident.+ child_args.subagent_bg = None;let body = child_body(&resolved, &description, &parent);@@ -1057,8 +1128,10 @@ pub(crate) fn spawn_subagent(}let parent_args = parent_args.clone();- let task_events = events.clone();- let entry_events = events.clone();+ // A session-owned registry routes the child to its durable channel, so a+ // child outliving this run keeps reporting somewhere that is still read.+ let task_events = bg.child_events(events);+ let entry_events = bg.child_events(events);let inherited = parent.clone();let description = req.description.clone();let run_id_task = run_id.clone();@@ -2597,6 +2670,8 @@ mod tests {max_parallel_subagents: 1,auto_approve: false,monitors: None,+ bg_shells: None,+ subagent_bg: None,run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 513cfec95..c8099fbfd 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1093,6 +1093,10 @@ fn build_cli_orchestration_args(// Run-owned here, so a headless run parks on its watchers: nobody is// there to talk to meanwhile. The TUI installs its session set itself.monitors: None,+ // Run-owned for the same reason: a headless run has no one to start a+ // later turn, so it must park until the command reports back.+ bg_shells: None,+ subagent_bg: None,// `--sandbox` only when passed; unset falls through to the project's// `[tools].sandbox` and then the user's global `sandbox`.sandbox,diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rsindex 9c36b5633..b559fcf72 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -2106,6 +2106,17 @@ struct App {/// runs; a match landing between runs starts a turn of its own/// (`submit_monitor_notices`).monitor_set: Arc<MonitorSet>,+ /// The session-owned backgrounded-shell registry, shared with every run+ /// through `OrchestrationArgs::bg_shells`. A command outlives the turn that+ /// started it, so the model can answer and the user can keep talking while+ /// it runs; output landing between runs starts a turn of its own+ /// (`submit_background_notices`). Distinct from `bg_shells`, which is the+ /// process-wide display snapshot behind the footer chip and `/shells`.+ shell_set: Arc<crate::core::agent::bg_shell::BackgroundShells>,+ /// The session-owned background-subagent registry, on the same terms as+ /// `shell_set`. Children outlive the run that dispatched them, so their+ /// panels survive a run end and a completion between runs starts a turn.+ subagent_set: Arc<crate::core::agent::subagent::BackgroundSubagents>,/// Committed finished-subagent summary rows, expandable to their full/// tool-call list via Ctrl-O (parallel to `groups`/`reasoning_blocks`).subagent_blocks: Vec<SubagentBlock>,@@ -2623,6 +2634,10 @@ impl App {subagents: Vec::new(),monitors: Vec::new(),monitor_set: Arc::new(MonitorSet::new()),+ shell_set: Arc::new(crate::core::agent::bg_shell::BackgroundShells::default()),+ subagent_set: Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(+ crate::core::agent::subagent::DEFAULT_MAX_PARALLEL_SUBAGENTS,+ )),subagent_blocks: Vec::new(),awaiting: Vec::new(),starting: Vec::new(),@@ -2730,8 +2745,13 @@ impl App {self.reasoning_blocks.clear();self.expanded_traces.clear();self.subagent_blocks.clear();+ // Aborts the children themselves, not just their panels: the+ // conversation they would report into is going away.+ self.stop_subagents();self.subagents.clear();self.stop_monitors();+ // Pings for work whose conversation is gone have no turn to join.+ self.shell_set.take_notices();self.expanded.clear();self.reveal = None;self.assistant_buf.clear();@@ -3208,7 +3228,18 @@ impl App {/// so publishing here would emit an extra intermediate state. A new caller/// that does not follow that pattern owns the `publish_agent_status()`.fn close_live_background(&mut self) {- for panel in std::mem::take(&mut self.subagents) {+ // Children are session-owned: one still running outlives the run that+ // dispatched it, so its panel stays docked exactly as a still-watching+ // monitor does. Only children this run will never hear from again are+ // summarized as interrupted. `subagent_set` is the authority on what is+ // still alive -- a panel whose run id it no longer knows is finished or+ // aborted, whatever the panel last rendered.+ let live = self.subagent_set.live_run_ids();+ let panels = std::mem::take(&mut self.subagents);+ let (still_running, finished): (Vec<_>, Vec<_>) = panels+ .into_iter()+ .partition(|panel| live.contains(&panel.run_id));+ for panel in finished {// A later-phase subagent that never started has no run to summarize;// drop it rather than report a phantom "interrupted (0 calls)".if panel.pending {@@ -3216,6 +3247,7 @@ impl App {}self.push_subagent_summary(&panel.name, panel.calls, SubagentOutcome::Interrupted);}+ self.subagents = still_running;self.awaiting.clear();// Session monitors outlive the run, so the dock keeps whatever is// still watching; a run that ended is no longer parked on anything.@@ -3232,6 +3264,22 @@ impl App {self.monitors.clear();}+ /// Abort every background child and undock its panel. Cancelling stops the+ /// whole session's background work, not just the turn in flight: children+ /// used to die with the run through `AbortOnDrop`, and a session-owned+ /// registry must not quietly turn Esc into "keep working". Also called when+ /// the conversation goes away (reset, thread switch), where a later+ /// completion would have no turn to join.+ fn stop_subagents(&mut self) {+ self.subagent_set.abort_all();+ for panel in std::mem::take(&mut self.subagents) {+ if panel.pending {+ continue;+ }+ self.push_subagent_summary(&panel.name, panel.calls, SubagentOutcome::Interrupted);+ }+ }+/// Deliver monitor pings that landed while no run was active. Each headline/// is noted where the user is looking and each text joins the history as/// the same `<SYSTEM>` reminder the loop attaches mid-run, then one turn@@ -3259,6 +3307,37 @@ impl App {self.persist();}+ /// Deliver backgrounded-shell and subagent pings that landed while no run+ /// was active, on exactly the terms `submit_monitor_notices` delivers a+ /// monitor match: headline where the user is looking, text as the same+ /// `<SYSTEM>` reminder the loop attaches mid-run, then one turn so the+ /// model reacts. A shell carries a headline (nothing else reports that the+ /// command ended); a finished subagent does not, since its `SubagentEnd`+ /// row already did.+ fn submit_background_notices(&mut self) {+ let shells = self.shell_set.take_notices();+ let subagents = self.subagent_set.take_notices();+ if shells.is_empty() && subagents.is_empty() {+ return;+ }+ for notice in &shells {+ self.note(¬ice.headline);+ }+ if self.model.is_empty() {+ self.note("background update dropped: not signed in, run /login first");+ return;+ }+ for notice in &shells {+ crate::core::agent::reminder::attach(&mut self.history, ¬ice.text);+ }+ for text in &subagents {+ crate::core::agent::reminder::attach(&mut self.history, text);+ }+ self.begin_turn();+ self.want_start = true;+ self.persist();+ }+/// The live terminal box for `group`'s newest unresolved *command*, streamed/// from the moment the command starts -- before any output -- so it reads as/// a terminal opening rather than a spinner that later becomes one. No rows@@ -6040,6 +6119,10 @@ impl App {// snapshot readiness); otherwise the loop starts it once ready and the// cancel is silently undone.self.want_start = false;+ // Esc/Ctrl-C stops the session's background work too, not just the+ // turn: children died with the run before they were session-owned, and+ // cancel must not quietly become "keep working in the background".+ self.stop_subagents();self.close_live_background();self.publish_agent_status();self.detail = "cancelled".to_string();@@ -8436,6 +8519,31 @@ async fn await_monitor_ping(set: &Arc<MonitorSet>, idle: bool) {set.wait_for_notice().await}+/// Await a backgrounded-shell ping the TUI must deliver itself, on the same+/// terms as [`await_monitor_ping`]: only between runs, since a running loop+/// drains the same registry at the top of each turn.+async fn await_shell_ping(+ set: &Arc<crate::core::agent::bg_shell::BackgroundShells>,+ idle: bool,+) {+ if !idle || !set.has_pending_work() {+ return pending().await;+ }+ set.wait_for_notice().await+}++/// Await a background-subagent ping the TUI must deliver itself, on the same+/// terms as [`await_monitor_ping`].+async fn await_subagent_ping(+ set: &Arc<crate::core::agent::subagent::BackgroundSubagents>,+ idle: bool,+) {+ if !idle || !set.has_pending_work() {+ return pending().await;+ }+ set.wait_for_notice().await+}+/// Await the next event of the active run, or park forever when idle.async fn next_event(current: &mut Option<CurrentRun>) -> RunEvent {match current {@@ -8842,6 +8950,17 @@ pub async fn run(// model's answer ends the run instead of parking on it.let monitor_set = Arc::new(MonitorSet::new());args.monitors = Some(monitor_set.clone());+ // Background shells and subagents are session-owned for the same reason:+ // the model finishing its turn must end the run even with work still+ // running, so a typed message starts an ordinary turn instead of queueing+ // behind work that may take minutes. Their completions are delivered as a+ // fresh turn by `submit_background_notices`.+ let shell_set = Arc::new(crate::core::agent::bg_shell::BackgroundShells::default());+ args.bg_shells = Some(shell_set.clone());+ let subagent_set = Arc::new(crate::core::agent::subagent::BackgroundSubagents::new(+ args.max_parallel_subagents,+ ));+ args.subagent_bg = Some(subagent_set.clone());let session_scratch = args.session_id.clone();let args = Arc::new(args);@@ -8900,6 +9019,8 @@ pub async fn run(app.stream_reasoning = stream_reasoning;app.send_reasoning = send_reasoning;app.monitor_set = monitor_set;+ app.shell_set = shell_set;+ app.subagent_set = subagent_set;app.args = Some(args.clone());// Adopt the session's startup run mode (e.g. `--plan`) so the header badge// shows immediately; a resumed thread overrides this via restore_run_mode.@@ -9131,6 +9252,13 @@ async fn chat_loop<B: Backend>(// Cloned out of `app` so the select arm below can await it while other// arms borrow `app` mutably.let monitor_set = app.monitor_set.clone();+ let shell_set = app.shell_set.clone();+ let subagent_set = app.subagent_set.clone();+ // The durable channel session-owned children report into, read for the+ // whole session rather than for one run: a child outliving the run that+ // dispatched it must still reach its panel and emit its closing bracket.+ let (session_events_tx, mut session_events) = mpsc::unbounded_channel::<StreamEvent>();+ subagent_set.install_session_events(session_events_tx);// Active MCP servers connect in the background; gate the first run on them// so the model's tools (collected once per run) are ready.let mut mcp_ready = mcp_task.is_none();@@ -9517,6 +9645,12 @@ async fn chat_loop<B: Backend>(_ = await_monitor_ping(&monitor_set, current.is_none() && !app.want_start) => {app.submit_monitor_notices();}+ _ = await_shell_ping(&shell_set, current.is_none() && !app.want_start) => {+ app.submit_background_notices();+ }+ _ = await_subagent_ping(&subagent_set, current.is_none() && !app.want_start) => {+ app.submit_background_notices();+ }branch = await_branch_poll(&mut branch_task) => {app.git_branch = branch;}@@ -9642,6 +9776,13 @@ async fn chat_loop<B: Backend>(}drain_stream_events(app, &mut current).await;}+ // Children stream here whether or not a run is open. Applied with+ // the same handler, so a panel updates and closes identically+ // between runs; `current` is untouched, since a child's events say+ // nothing about the run that dispatched it.+ Some(ev) = session_events.recv() => {+ apply_stream_event(app, Some(ev), &mut current).await;+ }}}@@ -15824,7 +15965,10 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value, verb: &str) {app.reasoning_blocks.clear();app.expanded_traces.clear();app.subagent_blocks.clear();+ // The conversation these would report into is being replaced.+ app.stop_subagents();app.stop_monitors();+ app.shell_set.take_notices();app.expanded.clear();app.reveal = None;app.assistant_buf.clear();@@ -19061,7 +19205,8 @@ mod tests {use super::{age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,apply_repaint, apply_resume, apply_stream_event, assistant_is_awaiting_user_answer,- assistant_runs, autoscroll_selection, await_branch_poll, await_monitor_ping, brand,+ assistant_runs, autoscroll_selection, await_branch_poll, await_monitor_ping,+ await_shell_ping, brand,build_user_message, clipboard_path, compact_tokens, context_lines, diff_lines,drain_stream_events, estimate_token_count, finish_account_login, finish_compaction,finish_context_report, finish_login, finish_plugin_install, finish_tokamak_login,@@ -24525,6 +24670,8 @@ mod tests {session_id: None,sandbox: None,monitors: Some(app.monitor_set.clone()),+ bg_shells: Some(app.shell_set.clone()),+ subagent_bg: Some(app.subagent_set.clone()),compaction: None,})}@@ -34234,6 +34381,119 @@ mod tests {);}+ /// The point of making the registries session-owned: when the model has+ /// finished and only background work is left, the run is over, so a typed+ /// message starts an ordinary turn instead of queueing behind a command+ /// that may run for minutes.+ #[test]+ fn input_with_background_work_running_starts_a_turn_instead_of_queueing() {+ use tauri_plugin_agent_tools::tools::ShellBackgrounded;++ let mut app = test_app();+ 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.+ app.on_done("stop".into(), None);+ assert_eq!(app.status, Status::Idle, "the run ends under live work");+ assert!(!app.run_is_live());++ app.want_start = false;+ app.submit_user("while that runs, what does the readme say?".into());++ assert!(+ app.message_queue.is_empty(),+ "an idle agent takes the message directly: {:?}",+ app.message_queue.len()+ );+ assert!(app.want_start, "a normal turn starts");+ assert_eq!(app.status, Status::Running);+ assert!(+ app.shell_set.has_pending_work(),+ "the command keeps running across the new turn"+ );+ }++ /// A backgrounded command finishing between runs delivers like a monitor+ /// match: headline on screen, text as a `<SYSTEM>` reminder, one new turn.+ #[test]+ fn a_background_shell_ping_between_runs_starts_a_turn() {+ use tauri_plugin_agent_tools::tools::{ShellBackgrounded, ShellDone};++ let mut app = test_app();+ app.history+ .push(serde_json::json!({ "role": "user", "content": "build it" }));+ app.history+ .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,+ command: "cargo build".to_string(),+ elapsed_secs: 12,+ output_path: Some("/tmp/build.log".to_string()),+ failed: false,+ });++ app.submit_background_notices();++ assert!(app.want_start, "a ping arms one turn");+ assert_eq!(app.status, Status::Running);+ let last = app.history.last().unwrap();+ assert_eq!(last["role"], "user");+ assert!(crate::core::agent::reminder::is_reminder_only(+ &last["content"]+ ));+ assert!(last["content"].as_str().unwrap().contains("cargo build"));+ assert!(+ transcript_text(&app).contains("cargo build"),+ "the headline reports the command ended: {}",+ transcript_text(&app)+ );+ }++ /// The loop drains the registry itself while a run is up, so the TUI's+ /// wait must stay parked then rather than racing it for the same ping.+ #[tokio::test]+ async fn await_shell_ping_only_fires_between_runs() {+ use tauri_plugin_agent_tools::tools::{ShellBackgrounded, ShellDone};++ let set = Arc::new(crate::core::agent::bg_shell::BackgroundShells::default());+ let parked = tokio::time::timeout(Duration::from_millis(20), await_shell_ping(&set, true));+ assert!(parked.await.is_err(), "nothing could fire, so it parks");++ set.start(ShellBackgrounded {+ id: 1,+ command: "cargo build".to_string(),+ timeout_secs: 30,+ output_path: None,+ });+ set.finish(ShellDone {+ id: 1,+ command: "cargo build".to_string(),+ elapsed_secs: 1,+ output_path: None,+ failed: false,+ });+ tokio::time::timeout(Duration::from_secs(5), await_shell_ping(&set, true))+ .await+ .expect("idle: the ping is ours to deliver");+ let busy = tokio::time::timeout(Duration::from_millis(20), await_shell_ping(&set, false));+ assert!(+ busy.await.is_err(),+ "a run is active, so the loop drains it"+ );+ }+/// A child's panel normally closes on its own `SubagentEnd`. A run that/// ends without one -- an upstream error mid-fan-out, a `Done` that beats/// the child's own event -- used to strand the block: it kept spinning in