Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(agent): monitors outlive the turn and poll one script
Akarshan Biswas768e32cd5e7a
diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.tsindex 440d01a43..3f515ca6c 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts+++ b/src-tauri/plugins/tauri-plugin-agent-tools/guest-js/types.ts@@ -59,14 +59,13 @@ export type ToolOutputChunk = {/*** One monitor notice, in the two registers a background ping needs: `headline`* for the transcript row, `text` for the `<SYSTEM>` reminder the model gets.- * `done` marks the update that also ends the monitor (all met, or timeout).+ * Every update is terminal (the script matched, or the monitor timed out), so+ * it also closes the monitor; `matched` tells the two apart.*/export type MonitorUpdate = {monitorId: string+ name: stringheadline: stringtext: string- done: boolean- /** Condition names met so far, and those still outstanding, at this update. */- met: string[]- unmet: string[]+ matched: boolean}diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rsindex d370f4d9b..418d2a6a3 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/commands.rs@@ -490,10 +490,10 @@ fn session_monitors(SETS.get_or_init(|| std::sync::Mutex::new(std::collections::HashMap::new()))}-/// Start a file monitor for a Cowork session; updates stream over `on_update`.+/// Start a monitor for a Cowork session; updates stream over `on_update`.////// Returns the model-facing result string from `MonitorSet::start`. Like-/// `bash` on this surface, condition scripts run only under an enforcing OS+/// `bash` on this surface, the polled script runs only under an enforcing OS/// sandbox -- there is no one to prompt, so unconfined execution is refused/// rather than allowed.#[tauri::command]diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rsindex c3940ee54..d4ed4963b 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/monitor.rs@@ -1,14 +1,13 @@-//! The `monitor` tool: watch a file a long-running job streams into and-//! evaluate custom condition scripts against it, reporting each match to the-//! agent as an out-of-band notice.+//! The `monitor` tool: poll one shell script on an interval until it matches,+//! then report its output to the agent as an out-of-band notice.//!-//! A condition is an arbitrary shell script run from the project root under the-//! same confinement `bash` gets (`handlers::confined_shell`). Exit 0 means the-//! condition matched, and its stdout is the matched content. Conditions are-//! evaluated once at start and again whenever the watched file changes; a met-//! condition is never re-evaluated. The monitor stops itself when every-//! condition has matched, when it is stopped explicitly, or at its deadline ---//! the bound that makes it safe for a run to park on an active monitor.+//! The script is arbitrary shell run from the project root under the same+//! confinement `bash` gets (`handlers::confined_shell`). Exit 0 means matched,+//! and its stdout is the matched content; anything else means "not yet" and+//! the poll repeats. A monitor is one-shot: the first match ends it, as does an+//! explicit stop or its deadline -- the bound that makes it safe for a+//! run-owned set to park a run on an active monitor. One script per monitor+//! keeps the call shape small enough for local models to emit reliably.//!//! Delivery is the caller's: a [`MonitorSet`] either queues [`MonitorUpdate`]s//! for the agent loop to drain into `<SYSTEM>` reminders (the CLI/desktop run@@ -20,40 +19,36 @@ use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};use std::sync::{Arc, Mutex};use std::time::Duration;-use crate::tools::{sandbox, ToolContext};+use crate::tools::ToolContext;pub const MONITOR_TOOL_NAME: &str = "monitor";-/// Active monitors per set. A run fanning out more watchers than this is-/// polling, not monitoring, and each one holds a background task.+/// Active monitors per set. Each one holds a background task, and a run+/// fanning out more than this is doing the job's work itself.pub const MAX_MONITORS: usize = 8;-/// Conditions per monitor.-pub const MAX_CONDITIONS: usize = 16;pub const DEFAULT_TIMEOUT_SECS: u64 = 1800;pub const MAX_TIMEOUT_SECS: u64 = 7200;const MIN_TIMEOUT_SECS: u64 = 10;-/// How often the watched file is re-checked for changes.-const POLL_INTERVAL: Duration = Duration::from_secs(2);-/// A condition script that runs longer than this is killed and treated as-/// unmet; a matcher is a check, not a job of its own.+pub const DEFAULT_INTERVAL_SECS: u64 = 5;+const MIN_INTERVAL_SECS: u64 = 1;+const MAX_INTERVAL_SECS: u64 = 300;+/// A script that runs longer than this is killed and treated as unmatched; a+/// poll is a check, not a job of its own.const EVAL_TIMEOUT: Duration = Duration::from_secs(60);+/// Cap on the label derived from a script when no `name` is given.+const DEFAULT_NAME_CHARS: usize = 60;/// Cap on the matched content a notice carries into the conversation.const MATCH_MAX_BYTES: usize = 4096;#[derive(Debug, Clone, PartialEq)]-pub struct MonitorCondition {+pub struct MonitorSpec {+ /// Short label quoted back in every notice; the script itself when the+ /// model gave none.pub name: String,+ /// Run from the project root on every poll; exit 0 = matched.pub script: String,-}--#[derive(Debug, Clone, PartialEq)]-pub struct MonitorSpec {- /// The watched path as the model wrote it; resolved against the project- /// root and scratch at start.- pub file: String,- pub conditions: Vec<MonitorCondition>,pub timeout_secs: u64,- /// Poll cadence. Not model-settable; tests shorten it.+ /// Poll cadence, model-settable within [`MIN_INTERVAL_SECS`, `MAX_INTERVAL_SECS`].pub interval: Duration,}@@ -107,85 +102,73 @@ impl MonitorCtx {/// One notice, in the two registers every background ping needs: `headline`/// for the transcript row, `text` for the `<SYSTEM>` reminder the model gets.-/// `done` marks the update that also ends the monitor (all met, or timeout).-/// `met`/`unmet` snapshot the monitor's progress at the update, so a display-/// with no other view of the watcher (Cowork) can keep a live panel.+/// Every update is terminal (a match or the timeout), so it also closes the+/// monitor on any display that tracks it; `matched` tells the two apart.#[derive(Debug, Clone, PartialEq, serde::Serialize)]#[serde(rename_all = "camelCase")]pub struct MonitorUpdate {pub monitor_id: String,+ pub name: String,pub headline: String,pub text: String,- pub done: bool,- pub met: Vec<String>,- pub unmet: Vec<String>,+ pub matched: bool,}-/// Display-only view of one active monitor, for a status panel: what it-/// watches and how far along its conditions are.+/// Display-only view of one active monitor, for a status panel.#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]#[serde(rename_all = "camelCase")]pub struct MonitorSnapshot {pub monitor_id: String,- pub file: String,- pub met: Vec<String>,- pub unmet: Vec<String>,+ pub name: String,+ pub script: String,+ pub polls: u64,}/// Parse and validate a `monitor {op:"start"}` call.pub fn parse_start_args(args: &serde_json::Value) -> Result<MonitorSpec, String> {- let file = args- .get("file")+ let script = args+ .get("script").and_then(|v| v.as_str()).map(str::trim).filter(|s| !s.is_empty())- .ok_or("start requires 'file': the path the job streams its output to")?+ .ok_or("start requires 'script': a shell command that exits 0 once the thing you are waiting for has happened")?.to_string();- let raw = args- .get("conditions")- .and_then(|v| v.as_array())- .filter(|a| !a.is_empty())- .ok_or("start requires a non-empty 'conditions' array of {name, script}")?;- if raw.len() > MAX_CONDITIONS {- return Err(format!("at most {MAX_CONDITIONS} conditions per monitor"));- }- let mut conditions = Vec::with_capacity(raw.len());- for c in raw {- let name = c- .get("name")- .and_then(|v| v.as_str())- .map(str::trim)- .filter(|s| !s.is_empty())- .ok_or("every condition needs a non-empty 'name'")?;- let script = c- .get("script")- .and_then(|v| v.as_str())- .filter(|s| !s.trim().is_empty())- .ok_or("every condition needs a non-empty 'script'")?;- if conditions- .iter()- .any(|existing: &MonitorCondition| existing.name == name)- {- return Err(format!("duplicate condition name '{name}'"));- }- conditions.push(MonitorCondition {- name: name.to_string(),- script: script.to_string(),- });- }+ let name = args+ .get("name")+ .and_then(|v| v.as_str())+ .map(str::trim)+ .filter(|s| !s.is_empty())+ .map(str::to_string)+ .unwrap_or_else(|| default_name(&script));let timeout_secs = args.get("timeout").and_then(|v| v.as_u64()).unwrap_or(DEFAULT_TIMEOUT_SECS).clamp(MIN_TIMEOUT_SECS, MAX_TIMEOUT_SECS);+ let interval_secs = args+ .get("interval")+ .and_then(|v| v.as_u64())+ .unwrap_or(DEFAULT_INTERVAL_SECS)+ .clamp(MIN_INTERVAL_SECS, MAX_INTERVAL_SECS);Ok(MonitorSpec {- file,- conditions,+ name,+ script,timeout_secs,- interval: POLL_INTERVAL,+ interval: Duration::from_secs(interval_secs),})}+/// The script, flattened to one line and capped, as the label when the model+/// gave none.+fn default_name(script: &str) -> String {+ let flat: String = script.split_whitespace().collect::<Vec<_>>().join(" ");+ if flat.chars().count() <= DEFAULT_NAME_CHARS {+ return flat;+ }+ let head: String = flat.chars().take(DEFAULT_NAME_CHARS - 3).collect();+ format!("{head}...")+}+pub fn parse_stop_args(args: &serde_json::Value) -> Result<String, String> {args.get("monitor_id").and_then(|v| v.as_str())@@ -195,12 +178,13 @@ pub fn parse_stop_args(args: &serde_json::Value) -> Result<String, String> {.ok_or_else(|| "stop requires 'monitor_id'".to_string())}-/// Shared, mutable view of one monitor's progress, read by `list` and written-/// by the monitor's own task.+/// Shared view of one monitor, read by `list` and the snapshot and written by+/// the monitor's own task.struct MonitorStatus {- file: String,- met: Vec<String>,- unmet: Vec<String>,+ name: String,+ script: String,+ interval: Duration,+ polls: u64,}struct Entry {@@ -265,7 +249,15 @@ impl MonitorSet {/// queued update not yet delivered. Safe to park on -- every monitor/// terminates (all met, stopped, or its deadline).pub fn has_pending_work(&self) -> bool {- !self.notices.lock().unwrap().is_empty() || self.active.load(Ordering::SeqCst) > 0+ self.has_queued_notices() || self.active.load(Ordering::SeqCst) > 0+ }++ /// Whether an update is queued and not yet taken. Unlike+ /// [`Self::has_pending_work`] this says nothing about running monitors: a+ /// set that outlives its run consults it to decide whether the model has+ /// something to react to *now*.+ pub fn has_queued_notices(&self) -> bool {+ !self.notices.lock().unwrap().is_empty()}/// Park until an update is queued, or nothing is left to wait for. The@@ -293,44 +285,30 @@ impl MonitorSet {self.wake.notify_waiters();}- /// Start a monitor, returning the model-facing result string. The watched- /// path must sit where a read may reach (project, scratch, or an attached- /// read-only root); the file itself may not exist yet.+ /// Start a monitor, returning the model-facing result string.pub fn start(self: &Arc<Self>, spec: MonitorSpec, ctx: MonitorCtx) -> Result<String, String> {if self.inner.lock().unwrap().len() >= MAX_MONITORS {return Err(format!("at most {MAX_MONITORS} monitors may be active; stop one first"));}- let scratch = ctx.scratch_root.as_deref();- match sandbox::escapes_read_roots(&ctx.project_root, scratch, &ctx.read_roots, &spec.file) {- Ok(false) => {}- Ok(true) => {- return Err(format!(- "'{}' is outside the project; a monitor can only watch files the run can read",- spec.file- ))- }- Err(e) => return Err(format!("cannot resolve '{}': {e}", spec.file)),- }- let watch_path = sandbox::resolve_path(&ctx.project_root, scratch, &spec.file);let monitor_id = format!("mon-{}", self.seq.fetch_add(1, Ordering::Relaxed));-let status = Arc::new(Mutex::new(MonitorStatus {- file: spec.file.clone(),- met: Vec::new(),- unmet: spec.conditions.iter().map(|c| c.name.clone()).collect(),+ name: spec.name.clone(),+ script: spec.script.clone(),+ interval: spec.interval,+ polls: 0,}));- let condition_count = spec.conditions.len();+ let name = spec.name.clone();let timeout_secs = spec.timeout_secs;- let file = spec.file.clone();+ let interval_secs = spec.interval.as_secs();self.active.fetch_add(1, Ordering::SeqCst);let set = self.clone();let id_task = monitor_id.clone();let status_task = status.clone();let handle = tokio::spawn(async move {- run_monitor(&set, &id_task, spec, ctx, watch_path, status_task).await;+ run_monitor(&set, &id_task, spec, ctx, status_task).await;// The terminal update (queued inside run_monitor) precedes both the// entry removal and the count release.set.inner.lock().unwrap().remove(&id_task);@@ -344,13 +322,11 @@ impl MonitorSet {status,},);- let plural = if condition_count == 1 { "" } else { "s" };Ok(format!(- "Monitor started (monitor_id={monitor_id}) watching {file} with {condition_count} \- condition{plural}. Conditions are checked now and whenever the file changes; each \- match arrives as a <SYSTEM> note carrying the matched content. The monitor stops \- when every condition has matched, when you stop it, or after {timeout_secs}s. Keep \- working meanwhile."+ "Monitor started (monitor_id={monitor_id}): '{name}' runs every {interval_secs}s. \+ When it exits 0 you get a <SYSTEM> note with its output and the monitor stops; it \+ also stops if you stop it or after {timeout_secs}s without a match. Keep working \+ meanwhile."))}@@ -366,9 +342,9 @@ impl MonitorSet {self.wake.notify_waiters();let status = entry.status.lock().unwrap();format!(- "Monitor {monitor_id} stopped. Conditions met: {}; unmet: {}.",- name_list(&status.met),- name_list(&status.unmet)+ "Monitor {monitor_id} ('{}') stopped after {} without a match.",+ status.name,+ pluralize_polls(status.polls))}@@ -384,10 +360,11 @@ impl MonitorSet {for id in ids {let status = inner[id].status.lock().unwrap();out.push_str(&format!(- "{id}: watching {} (met: {}; unmet: {})\n",- status.file,- name_list(&status.met),- name_list(&status.unmet)+ "{id}: '{}' every {}s, {} so far ({})\n",+ status.name,+ status.interval.as_secs(),+ pluralize_polls(status.polls),+ status.script));}out.trim_end().to_string()@@ -404,9 +381,9 @@ impl MonitorSet {let status = inner[id].status.lock().unwrap();MonitorSnapshot {monitor_id: id.clone(),- file: status.file.clone(),- met: status.met.clone(),- unmet: status.unmet.clone(),+ name: status.name.clone(),+ script: status.script.clone(),+ polls: status.polls,}}).collect()@@ -435,89 +412,43 @@ impl Drop for MonitorSet {}}-fn name_list(names: &[String]) -> String {- if names.is_empty() {- "none".to_string()+fn pluralize_polls(n: u64) -> String {+ if n == 1 {+ "1 poll".to_string()} else {- names.join(", ")+ format!("{n} polls")}}-/// The change signature polling keys off. Length plus mtime rather than either-/// alone: an append changes the length, an in-place rewrite the mtime.-fn file_signature(meta: &std::fs::Metadata) -> (u64, Option<std::time::SystemTime>) {- (meta.len(), meta.modified().ok())-}-async fn run_monitor(set: &Arc<MonitorSet>,monitor_id: &str,spec: MonitorSpec,ctx: MonitorCtx,- watch_path: PathBuf,status: Arc<Mutex<MonitorStatus>>,) {let deadline = tokio::time::Instant::now() + Duration::from_secs(spec.timeout_secs);- let mut unmet = spec.conditions;- // `None` until the file exists; the first sighting triggers an evaluation,- // as does a start over a file that already has content.- let mut last_sig: Option<(u64, Option<std::time::SystemTime>)> = None;- let mut first_pass = true;loop {- let sig = tokio::fs::metadata(&watch_path)- .await- .ok()- .map(|m| file_signature(&m));- // The very first pass evaluates even with no file yet: a condition- // script need not read the watched file at all.- let changed = (sig.is_some() && sig != last_sig) || first_pass;- first_pass = false;- if changed {- last_sig = sig;- let mut still_unmet = Vec::with_capacity(unmet.len());- let mut met_now: Vec<(String, String)> = Vec::new();- for cond in unmet {- match eval_condition(&ctx, &cond.script).await {- Some(content) => met_now.push((cond.name, content)),- None => still_unmet.push(cond),- }- }- unmet = still_unmet;- let total = met_now.len();- for (i, (name, content)) in met_now.into_iter().enumerate() {- let (met, still_unmet) = {- let mut s = status.lock().unwrap();- s.unmet.retain(|n| n != &name);- s.met.push(name.clone());- (s.met.clone(), s.unmet.clone())- };- let last = unmet.is_empty() && i + 1 == total;- let mut update = match_update(monitor_id, &spec.file, &name, &content, last);- update.met = met;- update.unmet = still_unmet;- set.push_update(update);- }- if unmet.is_empty() {- return;- }+ status.lock().unwrap().polls += 1;+ if let Some(content) = eval_script(&ctx, &spec.script).await {+ set.push_update(match_update(monitor_id, &spec.name, &content));+ return;}let now = tokio::time::Instant::now();if now >= deadline {- let names: Vec<String> = unmet.iter().map(|c| c.name.clone()).collect();- let met = status.lock().unwrap().met.clone();+ let polls = status.lock().unwrap().polls;set.push_update(MonitorUpdate {monitor_id: monitor_id.to_string(),- headline: format!("Monitor {monitor_id}: timed out"),+ name: spec.name.clone(),+ headline: format!("Monitor {monitor_id}: '{}' timed out", spec.name),text: format!(- "Monitor '{monitor_id}' timed out after {}s watching {}. Unmet conditions: \- {}. It has stopped.",+ "Monitor '{monitor_id}' ('{}') timed out after {}s and {} without a match. \+ It has stopped.",+ spec.name,spec.timeout_secs,- spec.file,- name_list(&names)+ pluralize_polls(polls)),- done: true,- met,- unmet: names,+ matched: false,});return;}@@ -525,40 +456,26 @@ async fn run_monitor(}}-fn match_update(- monitor_id: &str,- file: &str,- name: &str,- content: &str,- last: bool,-) -> MonitorUpdate {+fn match_update(monitor_id: &str, name: &str, content: &str) -> MonitorUpdate {let body = if content.is_empty() {- "(the condition script matched with no output)".to_string()+ " (the script exited 0 with no output)".to_string()} else {format!(":\n{content}")};- let mut text = format!("Monitor '{monitor_id}' condition '{name}' matched on {file}{body}");- let headline = if last {- text.push_str("\n\nAll conditions for this monitor have now matched; it has stopped.");- format!("Monitor {monitor_id}: condition '{name}' matched; all conditions met")- } else {- format!("Monitor {monitor_id}: condition '{name}' matched")- };MonitorUpdate {monitor_id: monitor_id.to_string(),- headline,- text,- done: last,- met: Vec::new(),- unmet: Vec::new(),+ name: name.to_string(),+ headline: format!("Monitor {monitor_id}: '{name}' matched"),+ text: format!("Monitor '{monitor_id}' ('{name}') matched{body}\n\nIt has stopped."),+ matched: true,}}-/// Run one condition script under the same confinement `bash` gets.-/// `Some(content)` when it exits 0 (its stdout, bounded); `None` for a nonzero-/// exit, a spawn failure, or a script that outran [`EVAL_TIMEOUT`] -- all of-/// which read as "not matched yet" and are retried on the next change.-async fn eval_condition(ctx: &MonitorCtx, script: &str) -> Option<String> {+/// Run the script once under the same confinement `bash` gets. `Some(content)`+/// when it exits 0 (its stdout, bounded); `None` for a nonzero exit, a spawn+/// failure, or a script that outran [`EVAL_TIMEOUT`] -- all of which read as+/// "not yet" and are retried on the next poll.+async fn eval_script(ctx: &MonitorCtx, script: &str) -> Option<String> {let tool_ctx = ctx.as_tool_context();let (shell, sandbox_tmp, _policy) = crate::tools::handlers::confined_shell(&tool_ctx).ok()?;let mut child =@@ -625,25 +542,15 @@ pub fn monitor_tool_schema() -> serde_json::Value {"type": "function","function": {"name": MONITOR_TOOL_NAME,- "description": "Watch a file a long-running job streams output into (e.g. a backgrounded bash job redirecting to a log) and evaluate condition scripts against it. Each condition is a shell script run from the project root whenever the file changes; exit 0 means the condition matched and its stdout is the matched content. You get a <SYSTEM> note per match, so start the monitor and keep working. The monitor stops when every condition has matched, on stop, or at its timeout. A met condition is never re-checked.",+ "description": "Wait for something in the background: poll a shell script on an interval until it exits 0, then get its stdout as a <SYSTEM> note while you keep working. Use it to wait on a backgrounded job, e.g. script \"grep -m1 'BUILD FAILED' build.log\" or \"test -f done.flag\". The script runs from the project root on every poll; a nonzero exit means not yet. The first match ends the monitor, as does its timeout. Start one monitor per thing you are waiting for.","parameters": {"type": "object","properties": {"op": { "type": "string", "enum": ["start", "stop", "list"] },- "file": { "type": "string", "description": "For start: the file to watch, relative to the project root (or under /tmp). It may not exist yet." },- "conditions": {- "type": "array",- "description": "For start: the conditions to watch for. Scripts should be cheap checks (e.g. grep -m1 'BUILD FAILED' build.log), not jobs.",- "items": {- "type": "object",- "properties": {- "name": { "type": "string", "description": "Short unique label, quoted back to you when it matches." },- "script": { "type": "string", "description": "Shell script; exit 0 = matched, stdout = the matched content." }- },- "required": ["name", "script"]- }- },- "timeout": { "type": "integer", "description": "For start: seconds before the monitor gives up and reports its unmet conditions (default 1800, max 7200)." },+ "script": { "type": "string", "description": "For start: a cheap shell check that exits 0 once the thing has happened; its stdout is what you get back." },+ "name": { "type": "string", "description": "For start: optional short label quoted back to you when it matches (defaults to the script)." },+ "interval": { "type": "integer", "description": "For start: seconds between polls (default 5, min 1, max 300)." },+ "timeout": { "type": "integer", "description": "For start: seconds before the monitor gives up (default 1800, max 7200)." },"monitor_id": { "type": "string", "description": "For stop: the id returned by start." }},"required": ["op"]@@ -681,16 +588,10 @@ mod tests {}}- fn spec(file: &str, conditions: &[(&str, &str)], timeout_secs: u64) -> MonitorSpec {+ fn spec(name: &str, script: &str, timeout_secs: u64) -> MonitorSpec {MonitorSpec {- file: file.to_string(),- conditions: conditions- .iter()- .map(|(name, script)| MonitorCondition {- name: name.to_string(),- script: script.to_string(),- })- .collect(),+ name: name.to_string(),+ script: script.to_string(),timeout_secs,interval: Duration::from_millis(25),}@@ -707,201 +608,155 @@ mod tests {}#[test]- fn parse_rejects_a_call_with_no_conditions() {- assert!(parse_start_args(&serde_json::json!({"op": "start", "file": "a.log"})).is_err());- assert!(parse_start_args(- &serde_json::json!({"op": "start", "file": "a.log", "conditions": []})- )- .is_err());- assert!(parse_start_args(&serde_json::json!({- "op": "start", "conditions": [{"name": "x", "script": "true"}]+ fn parse_requires_a_script_and_labels_it_by_default() {+ assert!(parse_start_args(&serde_json::json!({"op": "start"})).is_err());+ assert!(parse_start_args(&serde_json::json!({"op": "start", "script": " "})).is_err());+ let spec = parse_start_args(&serde_json::json!({+ "op": "start", "script": "grep -m1 FAILED\n build.log"}))- .is_err());- assert!(parse_start_args(&serde_json::json!({- "op": "start", "file": "a.log",- "conditions": [{"name": "x", "script": "true"}, {"name": "x", "script": "false"}]+ .unwrap();+ assert_eq!(spec.name, "grep -m1 FAILED build.log", "flattened script");+ let named = parse_start_args(&serde_json::json!({+ "op": "start", "script": "true", "name": " build "}))- .is_err());+ .unwrap();+ assert_eq!(named.name, "build");+ let long = "x".repeat(200);+ let spec = parse_start_args(&serde_json::json!({ "op": "start", "script": long })).unwrap();+ assert_eq!(spec.name.chars().count(), DEFAULT_NAME_CHARS);+ assert!(spec.name.ends_with("..."));}#[test]- fn parse_clamps_the_timeout_and_defaults_it() {- let base = serde_json::json!({- "op": "start", "file": "a.log",- "conditions": [{"name": "x", "script": "true"}]- });- assert_eq!(- parse_start_args(&base).unwrap().timeout_secs,- DEFAULT_TIMEOUT_SECS- );+ fn parse_clamps_the_timeout_and_interval_and_defaults_them() {+ let base = serde_json::json!({ "op": "start", "script": "true" });+ let spec = parse_start_args(&base).unwrap();+ assert_eq!(spec.timeout_secs, DEFAULT_TIMEOUT_SECS);+ assert_eq!(spec.interval, Duration::from_secs(DEFAULT_INTERVAL_SECS));let mut low = base.clone();low["timeout"] = serde_json::json!(1);- assert_eq!(- parse_start_args(&low).unwrap().timeout_secs,- MIN_TIMEOUT_SECS- );+ low["interval"] = serde_json::json!(0);+ let spec = parse_start_args(&low).unwrap();+ assert_eq!(spec.timeout_secs, MIN_TIMEOUT_SECS);+ assert_eq!(spec.interval, Duration::from_secs(MIN_INTERVAL_SECS));let mut high = base;high["timeout"] = serde_json::json!(1_000_000);- assert_eq!(- parse_start_args(&high).unwrap().timeout_secs,- MAX_TIMEOUT_SECS- );+ high["interval"] = serde_json::json!(1_000_000);+ let spec = parse_start_args(&high).unwrap();+ assert_eq!(spec.timeout_secs, MAX_TIMEOUT_SECS);+ assert_eq!(spec.interval, Duration::from_secs(MAX_INTERVAL_SECS));}#[tokio::test]- async fn a_condition_matching_at_start_reports_its_content_and_stops() {+ async fn a_script_matching_at_start_reports_its_output_and_stops() {let dir = unique_root();std::fs::write(dir.join("build.log"), "warm up\nBUILD OK line\n").unwrap();let set = Arc::new(MonitorSet::new());let result = set- .start(- spec("build.log", &[("ok", "grep 'BUILD OK' build.log")], 30),- ctx_for(&dir),- )+ .start(spec("ok", "grep 'BUILD OK' build.log", 30), ctx_for(&dir)).unwrap();assert!(result.contains("monitor_id=mon-1"), "{result}");+ assert!(result.contains("'ok'"), "{result}");let update = next_notice(&set).await;- assert!(update.done, "single condition: the match ends the monitor");+ assert!(update.matched);+ assert_eq!(update.name, "ok");+ assert!(+ update.headline.contains("'ok' matched"),+ "{}",+ update.headline+ );assert!(update.text.contains("BUILD OK line"), "{}", update.text);- assert!(update.text.contains("all conditions") || update.text.contains("All conditions"));+ assert!(update.text.contains("It has stopped"));for _ in 0..100 {if !set.has_pending_work() {return;}tokio::time::sleep(Duration::from_millis(10)).await;}- panic!("the set still reports pending work after the final match");+ panic!("the set still reports pending work after the match");}#[tokio::test]- async fn a_later_append_meets_the_second_condition() {+ async fn a_later_change_is_caught_by_a_following_poll() {let dir = unique_root();let log = dir.join("job.log");std::fs::write(&log, "phase one done\n").unwrap();let set = Arc::new(MonitorSet::new());- set.start(- spec(- "job.log",- &[- ("one", "grep 'phase one' job.log"),- ("two", "grep 'phase two' job.log"),- ],- 30,- ),- ctx_for(&dir),- )- .unwrap();- let first = next_notice(&set).await;- assert!(first.text.contains("'one'"), "{}", first.text);- assert!(!first.done);- assert_eq!(first.met, vec!["one".to_string()]);- assert_eq!(first.unmet, vec!["two".to_string()]);- assert!(set.has_pending_work(), "condition 'two' is still owed");- assert!(- set.list().contains("met: one; unmet: two"),- "{}",- set.list()- );+ set.start(spec("two", "grep 'phase two' job.log", 30), ctx_for(&dir))+ .unwrap();+ tokio::time::sleep(Duration::from_millis(80)).await;+ assert!(set.take_notices().is_empty(), "nothing matched yet");+ assert!(set.has_pending_work());+ let listed = set.list();+ assert!(listed.contains("mon-1: 'two' every 0s"), "{listed}");+ assert!(listed.contains("grep 'phase two' job.log"), "{listed}");let mut content = std::fs::read_to_string(&log).unwrap();content.push_str("phase two done\n");std::fs::write(&log, content).unwrap();- let second = next_notice(&set).await;- assert!(second.text.contains("'two'"), "{}", second.text);- assert!(second.text.contains("phase two done"));- assert!(second.done);+ let update = next_notice(&set).await;+ assert!(update.matched);+ assert!(update.text.contains("phase two done"), "{}", update.text);}#[tokio::test]- async fn snapshot_lists_active_monitors_with_their_progress() {+ async fn snapshot_lists_active_monitors_with_their_poll_count() {let dir = unique_root();- std::fs::write(dir.join("job.log"), "phase one done\n").unwrap();let set = Arc::new(MonitorSet::new());- set.start(- spec(- "job.log",- &[- ("one", "grep 'phase one' job.log"),- ("two", "grep 'phase two' job.log"),- ],- 30,- ),- ctx_for(&dir),- )- .unwrap();- let _ = next_notice(&set).await;- assert_eq!(- set.snapshot(),- vec![MonitorSnapshot {- monitor_id: "mon-1".to_string(),- file: "job.log".to_string(),- met: vec!["one".to_string()],- unmet: vec!["two".to_string()],- }]- );+ set.start(spec("never", "false", 30), ctx_for(&dir))+ .unwrap();+ tokio::time::sleep(Duration::from_millis(80)).await;+ let snap = set.snapshot();+ assert_eq!(snap.len(), 1);+ assert_eq!(snap[0].monitor_id, "mon-1");+ assert_eq!(snap[0].name, "never");+ assert_eq!(snap[0].script, "false");+ assert!(snap[0].polls >= 2, "polled repeatedly: {}", snap[0].polls);set.stop("mon-1");assert!(set.snapshot().is_empty());}#[tokio::test]- async fn an_unmet_monitor_times_out_and_names_its_conditions() {+ async fn an_unmatched_monitor_times_out() {let dir = unique_root();let set = Arc::new(MonitorSet::new());// Timeout of zero: the deadline has passed by the first re-check, so// the test never waits out a real timeout.- set.start(- spec("never.log", &[("ghost", "grep ghost never.log")], 0),- ctx_for(&dir),- )- .unwrap();+ set.start(spec("ghost", "grep ghost never.log", 0), ctx_for(&dir))+ .unwrap();let update = next_notice(&set).await;- assert!(update.done);+ assert!(!update.matched);assert!(update.text.contains("timed out"), "{}", update.text);- assert!(update.text.contains("ghost"), "{}", update.text);- assert!(update.met.is_empty());- assert_eq!(update.unmet, vec!["ghost".to_string()]);+ assert!(update.text.contains("'ghost'"), "{}", update.text);+ assert!(update.text.contains("1 poll"), "{}", update.text);}#[tokio::test]- async fn stop_reports_progress_and_frees_the_slot() {+ async fn stop_reports_the_poll_count_and_frees_the_slot() {let dir = unique_root();let set = Arc::new(MonitorSet::new());let result = set- .start(- spec("never.log", &[("ghost", "false")], 3600),- ctx_for(&dir),- )+ .start(spec("ghost", "false", 3600), ctx_for(&dir)).unwrap();assert!(result.contains("mon-1"));assert!(set.has_pending_work());let stopped = set.stop("mon-1");- assert!(stopped.contains("unmet: ghost"), "{stopped}");+ assert!(stopped.contains("('ghost') stopped after"), "{stopped}");+ assert!(stopped.contains("without a match"), "{stopped}");assert!(!set.has_pending_work());assert!(set.stop("mon-1").starts_with("ERROR"));assert_eq!(set.list(), "No active monitors.");}- #[tokio::test]- async fn a_watched_path_outside_the_project_is_refused() {- let dir = unique_root();- let set = Arc::new(MonitorSet::new());- let err = set- .start(spec("/etc/passwd", &[("x", "true")], 30), ctx_for(&dir))- .unwrap_err();- assert!(err.contains("outside the project"), "{err}");- assert!(!set.has_pending_work());- }-#[tokio::test]async fn the_monitor_cap_is_enforced() {let dir = unique_root();let set = Arc::new(MonitorSet::new());for _ in 0..MAX_MONITORS {- set.start(spec("a.log", &[("x", "false")], 3600), ctx_for(&dir))- .unwrap();+ set.start(spec("x", "false", 3600), ctx_for(&dir)).unwrap();}let err = set- .start(spec("a.log", &[("x", "false")], 3600), ctx_for(&dir))+ .start(spec("x", "false", 3600), ctx_for(&dir)).unwrap_err();assert!(err.contains("at most"), "{err}");set.stop_all();@@ -913,11 +768,8 @@ mod tests {let dir = unique_root();let log = dir.join("late.log");let set = Arc::new(MonitorSet::new());- set.start(- spec("late.log", &[("hit", "grep hit late.log")], 30),- ctx_for(&dir),- )- .unwrap();+ set.start(spec("hit", "grep hit late.log", 30), ctx_for(&dir))+ .unwrap();let waiter = {let set = set.clone();tokio::spawn(async move {@@ -943,16 +795,13 @@ mod tests {let set = Arc::new(MonitorSet::subscribed(Arc::new(move |u| {let _ = tx.send(u);})));- set.start(- spec("s.log", &[("hit", "grep hit s.log")], 30),- ctx_for(&dir),- )- .unwrap();+ set.start(spec("hit", "grep hit s.log", 30), ctx_for(&dir))+ .unwrap();let update = tokio::time::timeout(Duration::from_secs(5), rx.recv()).await.expect("no subscriber update").unwrap();- assert!(update.done);+ assert!(update.matched);assert!(set.take_notices().is_empty(), "queue must stay empty");}}diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rsindex 3beab723e..4dbb73c40 100644--- a/src-tauri/src/core/agent/loop.rs+++ b/src-tauri/src/core/agent/loop.rs@@ -108,6 +108,12 @@ pub(crate) struct OrchestrationArgs {/// by dispatched subagents via the cloned parent args, so a child shell is/// confined exactly as its parent's was.pub sandbox: Option<bool>,+ /// A monitor set owned by the session rather than by this run. When set,+ /// a running monitor does not park the run: the model's turn ends and the+ /// owner starts a new turn when a match lands. `None` (a headless run, a+ /// 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>>,}#[async_trait]@@ -336,11 +342,16 @@ struct CompositeToolInvoker {todo_registry: Option<crate::core::agent::todo::TodoRegistry>,grants: std::sync::Mutex<tauri_plugin_agent_tools::tools::gate::SessionGrants>,subagents: Option<SubagentContext>,- /// This run's file monitors. Scoped to the run like `subagents`: dropping- /// the invoker aborts every watcher, and an active monitor keeps the run+ /// The file monitors this run may start. Run-owned unless+ /// `OrchestrationArgs::monitors` supplied a session set: dropping the last+ /// reference aborts every watcher, and an active monitor keeps the run/// parked via `background_pending` (bounded, since every monitor has a/// deadline).monitors: std::sync::Arc<tauri_plugin_agent_tools::tools::monitor::MonitorSet>,+ /// Whether `monitors` outlives this run. A session-owned set never parks+ /// the run on a watcher that has not fired: the owner delivers a later+ /// match as a fresh turn, so the user can keep talking meanwhile.+ monitors_outlive_run: bool,auto_approve: bool,run_mode: crate::core::agent::plan::RunMode,}@@ -495,6 +506,17 @@ fn output_sink(}impl CompositeToolInvoker {+ /// Whether the monitors owe the model something the run must stay alive+ /// for: any queued ping, plus a still-running watcher when the set dies+ /// with the run (nothing else could deliver its match).+ fn monitors_owed(&self) -> bool {+ if self.monitors_outlive_run {+ self.monitors.has_queued_notices()+ } else {+ self.monitors.has_pending_work()+ }+ }+fn tool_context(&self) -> tauri_plugin_agent_tools::tools::ToolContext<'_> {tauri_plugin_agent_tools::tools::ToolContext::new(&self.project_root,@@ -687,9 +709,9 @@ impl CompositeToolInvoker {}}- /// Prompt the user to approve starting a monitor: its condition scripts are- /// arbitrary shell commands the watcher will run repeatedly, so starting one- /// is an exec-class action even though each later evaluation is unattended.+ /// Prompt the user to approve starting a monitor: its script is an+ /// arbitrary shell command the watcher will run repeatedly, so starting one+ /// is an exec-class action even though each later poll is unattended.async fn prompt_monitor_start(&self,spec: &tauri_plugin_agent_tools::tools::monitor::MonitorSpec,@@ -700,23 +722,20 @@ impl CompositeToolInvoker {.lock().await.insert(request_id.clone(), tx);- // The prompt's detail shows `command` INSTEAD of `path`, so the watched- // file has to ride along here or the user approves scripts with no idea- // what triggers them. A shell comment keeps the `$ ` preview honest.- let scripts = std::iter::once(format!("# watches {}", spec.file))- .chain(- spec.conditions- .iter()- .map(|c| format!("{}: {}", c.name, c.script)),- )- .collect::<Vec<_>>()- .join("\n");+ // The cadence rides along as a shell comment, so the user approves a+ // script knowing how often it will run; the `$ ` preview stays honest.+ let command = format!(+ "# monitor '{}', every {}s\n{}",+ spec.name,+ spec.interval.as_secs(),+ spec.script+ );let _ = self.events.send(StreamEvent::PermissionRequest {request_id: request_id.clone(),tool_name: tauri_plugin_agent_tools::tools::monitor::MONITOR_TOOL_NAME.to_string(),capability: "run".to_string(),- path: Some(spec.file.clone()),- command: Some(scripts),+ path: None,+ command: Some(command),diff: None,prompt_kind: "monitor".to_string(),offers_always: false,@@ -998,7 +1017,7 @@ impl ToolInvoker for CompositeToolInvoker {self.subagents.as_ref().is_some_and(|ctx| ctx.bg.has_pending_work())- || self.monitors.has_pending_work()+ || self.monitors_owed()}fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {@@ -1010,6 +1029,8 @@ impl ToolInvoker for CompositeToolInvoker {// 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.subagents.as_ref()@@ -1393,6 +1414,7 @@ pub(crate) async fn run_server_side_openai_orchestration(run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,+ monitors: None,};let body = match json_body.get("max_turns") {Some(_) => std::borrow::Cow::Borrowed(json_body),@@ -1820,6 +1842,7 @@ async fn orchestrate_inner(auto_approve,run_mode,session_id,+ monitors: session_monitors,sandbox,} = args;@@ -2105,9 +2128,8 @@ async fn orchestrate_inner(tauri_plugin_agent_tools::tools::gate::SessionGrants::default(),),subagents,- monitors: std::sync::Arc::new(- tauri_plugin_agent_tools::tools::monitor::MonitorSet::new(),- ),+ monitors: session_monitors.clone().unwrap_or_default(),+ monitors_outlive_run: session_monitors.is_some(),auto_approve: *auto_approve,run_mode,};@@ -2597,9 +2619,11 @@ async fn run_turn_cycle(}}// The model has nothing left to do, but a subagent it dispatched is- // still running -- and its answer has nowhere to go once this cycle- // returns. So park here instead of ending: the ping drained at the- // top of the next turn is what resumes the conversation. The turn+ // still running (or a run-owned monitor is) -- and its answer has+ // nowhere to go once this cycle returns. So park here instead of+ // ending: the ping drained at the top of the next turn is what+ // resumes the conversation. A session-owned monitor never parks:+ // its owner starts a turn when it fires (`monitors_owed`). The turn// the model just took has to be recorded first, exactly as the// closeout nudge above records it, or the reminder would attach to// a conversation missing the answer it follows.@@ -4183,9 +4207,9 @@ mod tests {}vec![tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot {monitor_id: "mon-1".to_string(),- file: "build.log".to_string(),- met: Vec::new(),- unmet: vec!["ok".to_string()],+ name: "ok".to_string(),+ script: "grep OK build.log".to_string(),+ polls: 1,}]}}@@ -5083,6 +5107,7 @@ mod tests {monitors: std::sync::Arc::new(tauri_plugin_agent_tools::tools::monitor::MonitorSet::new(),),+ monitors_outlive_run: false,auto_approve: false,run_mode: crate::core::agent::plan::RunMode::Normal,}@@ -6017,9 +6042,8 @@ mod tests {"the prompt must show the scripts it approves: {command:?}");assert!(- shown.contains("# watches boot.log"),- "the prompt shows command INSTEAD of path, so the watched \- file must ride along: {command:?}"+ shown.contains("# monitor 'ready', every 5s"),+ "the prompt names the monitor and its cadence: {command:?}");let tx = registry.lock().await.remove(&request_id).unwrap();let _ = tx.send(PermissionDecision::Deny);@@ -6029,11 +6053,7 @@ mod tests {let out = invoker.invoke(&[monitor_call("m1",- json!({- "op": "start",- "file": "boot.log",- "conditions": [{ "name": "ready", "script": "grep READY boot.log" }]- }),+ json!({ "op": "start", "name": "ready", "script": "grep READY boot.log" }),)]).await.unwrap();@@ -6043,7 +6063,7 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}- /// End to end through the invoker: an auto-approved start whose condition+ /// End to end through the invoker: an auto-approved start whose script/// already holds delivers a merged background notice carrying a headline/// and the matched content, and the pending flag clears once all conditions/// are met.@@ -6061,11 +6081,7 @@ mod tests {let out = invoker.invoke(&[monitor_call("m1",- json!({- "op": "start",- "file": "boot.log",- "conditions": [{ "name": "ready", "script": "grep READY boot.log" }]- }),+ json!({ "op": "start", "name": "ready", "script": "grep READY boot.log" }),)]).await.unwrap();@@ -6108,6 +6124,57 @@ mod tests {let _ = std::fs::remove_dir_all(&root);}+ /// A session-owned set does not hold the run open: a watcher that has not+ /// fired leaves `background_pending` false (the turn ends and the user can+ /// keep talking), while a queued match still resumes the run, and taking+ /// it clears the flag again.+ #[tokio::test]+ async fn a_session_owned_monitor_does_not_park_the_run_until_it_fires() {+ let root = unique_project_root();+ std::fs::write(root.join("boot.log"), "starting\n").unwrap();+ 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.auto_approve = true;+ invoker.sandbox = false;+ invoker.monitors_outlive_run = true;++ let out = invoker+ .invoke(&[monitor_call(+ "m1",+ json!({ "op": "start", "name": "ready", "script": "grep READY boot.log" }),+ )])+ .await+ .unwrap();+ assert!(+ out[0].content.contains("monitor_id=mon-1"),+ "{}",+ out[0].content+ );+ assert_eq!(invoker.monitor_snapshot().len(), 1, "the watcher is up");+ assert!(+ !invoker.background_pending(),+ "an unfired session monitor must not park the run"+ );++ std::fs::write(root.join("boot.log"), "starting\nREADY on port 1337\n").unwrap();+ for _ in 0..300 {+ if invoker.background_pending() {+ break;+ }+ tokio::time::sleep(std::time::Duration::from_millis(10)).await;+ }+ assert!(+ invoker.background_pending(),+ "a queued match is owed to the model and resumes the run"+ );+ let notices = invoker.background_notices();+ assert_eq!(notices.len(), 1);+ assert!(notices[0].text.contains("READY on port 1337"));+ assert!(!invoker.background_pending(), "taken, so nothing is owed");+ 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/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 65f931bfa..8c0b9399a 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -855,6 +855,9 @@ async fn run_subagent(// Subagents cannot read or mutate the parent's todo list (isolated child// context, matching ask_requests above).child_args.todo_registry = None;+ // 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;let body = child_body(&resolved, &description, &parent);@@ -2048,6 +2051,7 @@ mod tests {subagents_enabled: true,max_parallel_subagents: 1,auto_approve: false,+ monitors: 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 76c5f5c12..96304f9ec 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -717,6 +717,9 @@ fn build_cli_orchestration_args(// reuses `args` across turns and wipes it when the interactive session// ends.session_id: Some(uuid::Uuid::new_v4().to_string()),+ // 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,// `--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 d96fb8342..add012ada 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -52,7 +52,7 @@ use crate::core::agent::r#loop::{};use serde_json::Value;use tauri_plugin_agent_tools::tools::gate::PermissionDecision;-use tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot;+use tauri_plugin_agent_tools::tools::monitor::{MonitorSet, MonitorSnapshot};use tauri_plugin_agent_tools::workspace;/// Mouse tracking, hand-rolled instead of crossterm's `EnableMouseCapture`,@@ -1952,10 +1952,17 @@ struct App {/// Live panels for background subagents currently streaming, one per run./// Several may be active at once; each renders its own rolling window.subagents: Vec<SubagentPanel>,- /// The run's active file monitors, replaced wholesale by each- /// `StreamEvent::Monitors`. Docked beside the fan-out; never a transcript- /// row, since a monitor describes now.+ /// The session's active file monitors, replaced wholesale by each+ /// `StreamEvent::Monitors` and re-read from `monitor_set` when a run ends.+ /// Docked beside the fan-out; never a transcript row, since a monitor+ /// describes now.monitors: Vec<MonitorSnapshot>,+ /// The session-owned monitor registry, shared with every run through+ /// `OrchestrationArgs::monitors`. A watcher outlives the turn that started+ /// it, so the model can answer and the user can keep talking while it+ /// runs; a match landing between runs starts a turn of its own+ /// (`submit_monitor_notices`).+ monitor_set: Arc<MonitorSet>,/// True from `StreamEvent::Parked` to the next `Step`: the model is done/// and the loop is waiting on background work, so the header says so/// instead of `[working]`.@@ -2411,6 +2418,7 @@ impl App {exit_armed: false,subagents: Vec::new(),monitors: Vec::new(),+ monitor_set: Arc::new(MonitorSet::new()),parked: false,subagent_blocks: Vec::new(),awaiting: Vec::new(),@@ -2497,6 +2505,7 @@ impl App {self.reasoning_blocks.clear();self.subagent_blocks.clear();self.subagents.clear();+ self.stop_monitors();self.expanded.clear();self.reveal = None;self.assistant_buf.clear();@@ -2843,12 +2852,46 @@ impl App {self.push_subagent_summary(&panel.name, panel.calls, SubagentOutcome::Interrupted);}self.awaiting.clear();- // Monitors die with the run's invoker, and a run that ended is no- // longer parked on anything.- self.monitors.clear();+ // Session monitors outlive the run, so the dock keeps whatever is+ // still watching; a run that ended is no longer parked on anything.+ self.monitors = self.monitor_set.snapshot();self.parked = false;}+ /// Stop every session monitor and undock it: the conversation they were+ /// started for is going away, so a later match would have no turn to join.+ fn stop_monitors(&mut self) {+ self.monitor_set.stop_all();+ self.monitors.clear();+ }++ /// 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+ /// starts so the model reacts. Nothing is submitted without a model to+ /// send to; the pings are dropped with a note rather than left to fire the+ /// moment `/login` completes on a conversation that has moved on.+ fn submit_monitor_notices(&mut self) {+ let notices = self.monitor_set.take_notices();+ self.monitors = self.monitor_set.snapshot();+ if notices.is_empty() {+ return;+ }+ for notice in ¬ices {+ self.note(¬ice.headline);+ }+ if self.model.is_empty() {+ self.note("monitor update dropped: not signed in, run /login first");+ return;+ }+ for notice in ¬ices {+ crate::core::agent::reminder::attach(&mut self.history, ¬ice.text);+ }+ self.begin_turn();+ self.want_start = true;+ self.persist();+ }+/// The live shell panel for `group`'s newest unresolved *command*, or no rows/// when nothing in the group is streaming yet.///@@ -6182,23 +6225,21 @@ fn tool_activity(name: &str, args: &serde_json::Value) -> String {/// Present/past-tense label for a `monitor` tool call, keyed on its `op`./// Without this the row falls through to the raw-JSON fallback, and a start's-/// condition scripts make that a paragraph, not a label.+/// script makes that a paragraph, not a label.fn monitor_activity(args: &serde_json::Value, past: bool) -> String {let s = |k: &str| args.get(k).and_then(|v| v.as_str()).unwrap_or("");match (s("op"), past) {("start", _) => {- let file = s("file");- let n = args- .get("conditions")- .and_then(|v| v.as_array())- .map(Vec::len)- .unwrap_or(0);let verb = if past { "Started" } else { "Starting" };- let conditions = format!("({n} condition{})", if n == 1 { "" } else { "s" });- if file.is_empty() {- format!("{verb} a monitor {conditions}")+ let label = match (s("name"), s("script")) {+ ("", "") => String::new(),+ ("", script) => script.to_string(),+ (name, _) => name.to_string(),+ };+ if label.is_empty() {+ format!("{verb} a monitor")} else {- format!("{verb} a monitor on {file} {conditions}")+ format!("{verb} a monitor: {label}")}}("stop", false) => format!("Stopping monitor {}", s("monitor_id")),@@ -7228,6 +7269,16 @@ fn spawn_run(args: &Arc<OrchestrationArgs>, body: serde_json::Value) -> CurrentR}}+/// Await a monitor ping the TUI must deliver itself: only between runs, since a+/// running loop drains the same set at the top of each turn. Parks forever when+/// a run is active or queued, or when no watcher could still fire.+async fn await_monitor_ping(set: &Arc<MonitorSet>, 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 {@@ -7602,6 +7653,10 @@ pub async fn run(args.ask_requests = Some(ask_requests.clone());let todo_registry = crate::core::agent::todo::new_registry();args.todo_registry = Some(todo_registry.clone());+ // Session-owned, so a watcher survives the turn that started it and the+ // model's answer ends the run instead of parking on it.+ let monitor_set = Arc::new(MonitorSet::new());+ args.monitors = Some(monitor_set.clone());let session_scratch = args.session_id.clone();let args = Arc::new(args);@@ -7643,6 +7698,7 @@ pub async fn run(app.smol_model = smol_model;app.stream_reasoning = stream_reasoning;app.send_reasoning = send_reasoning;+ app.monitor_set = monitor_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.@@ -7856,6 +7912,9 @@ async fn chat_loop<B: Backend>() -> Result<(), String> {let mut current: Option<CurrentRun> = None;let mut ticker = tokio::time::interval(Duration::from_millis(50));+ // 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();// 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();@@ -8214,6 +8273,9 @@ async fn chat_loop<B: Backend>(branch_task = Some(spawn_branch_poll(&app.project_root));}}+ _ = await_monitor_ping(&monitor_set, current.is_none() && !app.want_start) => {+ app.submit_monitor_notices();+ }branch = await_branch_poll(&mut branch_task) => {app.git_branch = branch;}@@ -13732,6 +13794,7 @@ async fn load_thread(app: &mut App, thread: &serde_json::Value) {app.pending_rows.clear();app.reasoning_blocks.clear();app.subagent_blocks.clear();+ app.stop_monitors();app.expanded.clear();app.reveal = None;app.assistant_buf.clear();@@ -16269,9 +16332,9 @@ fn activity_column(out}-/// The run's active monitors, as a column: one line per monitor (id, watched-/// file, conditions met so far), plus the still-unmet condition names when the-/// budget stretches to a second row each.+/// The session's active monitors, as a column: one line per monitor (id, name,+/// polls so far), plus its script when the budget stretches to a second row+/// each.fn monitors_column(monitors: &[MonitorSnapshot], width: u16, rows: usize) -> Vec<Line<'static>> {if monitors.is_empty() || rows == 0 {return Vec::new();@@ -16296,9 +16359,8 @@ fn monitors_column(monitors: &[MonitorSnapshot], width: u16, rows: usize) -> Vec};let detail = (body - shown).checked_div(shown).is_some_and(|n| n >= 1);for monitor in monitors.iter().take(shown) {- let total = monitor.met.len() + monitor.unmet.len();- let stats = format!(" {}/{total} met", monitor.met.len());- let label = format!("{} {}", monitor.monitor_id, monitor.file);+ let stats = format!(" {} polls", monitor.polls);+ let label = format!("{} {}", monitor.monitor_id, monitor.name);out.push(Line::from(vec![Span::styled("◔ ", Style::new().cyan()),Span::styled(@@ -16307,11 +16369,10 @@ fn monitors_column(monitors: &[MonitorSnapshot], width: u16, rows: usize) -> Vec),Span::styled(stats, dim),]));- if detail && !monitor.unmet.is_empty() {- let waiting = format!("waiting on {}", monitor.unmet.join(", "));+ if detail {out.push(Line::from(vec![Span::raw(" "),- Span::styled(truncate(&waiting, max.saturating_sub(3)), dim),+ Span::styled(truncate(&monitor.script, max.saturating_sub(3)), dim),]));}}@@ -16672,31 +16733,30 @@ mod tests {use tokio::sync::mpsc;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, backgrounded_job_id, brand,+ apply_repaint, apply_resume, apply_stream_event, assistant_is_awaiting_user_answer, assistant_runs,+ autoscroll_selection, await_branch_poll, await_monitor_ping, backgrounded_job_id, 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,- finish_update_install, format_tokens, group_detail_lines, group_summary,- handle_ask_key, handle_ask_mouse, handle_key, handle_mouse, header_spans, image_mime,- image_mime_of, input_content_lines, load_first_file_image, load_image_file,- message_text, note_update, open_config_screen, open_rewind_picker, pairs_to_str,- parse_command, partial_json_field, provider_label_for_model, rebuild_recall,- replay_display_log, restore_goal, restore_run_mode, restore_todos, resume_hint,- rewind_to, route_paste_event, row_width, run_command,- running_group_rows, selection_text, spans_width, spawn_branch_poll, split_reasoning,- starting_call_lines, startup_modes, strip_system_xml_tags, subagent_activity,- subagent_name_from_run_id, summarize_result, sync_output_for, thinking_open,- tilde_path, tokens_per_second, tool_activity, tool_finished, transcript_top_padding,- unescape_partial_json_string, user_content_parts, wave_sweep_line, with_wave_glyph,- without_think_tags, App, CompactKind, ContextReport, ContextSegment,- ContextView, CurrentRun, McpField, McpPrompt, Pending, PendingImage, PickerKind,- ProviderField, ReasoningSeg, ResumeTarget, Row, RowKind, Selection, SelectionMode,- SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE, ALT_SCROLL_SAVE_OFF, COPY_NOTICE,- DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS, DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS,- KITTY_KEYS_OFF, KITTY_KEYS_ON, MAX_IMAGE_BYTES, MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON,- PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER, SPINNER_ADVANCE_MS, THINKING_WORDS,- WORKING_WORDS,+ finish_update_install, format_tokens, group_detail_lines, group_summary, handle_ask_key,+ handle_ask_mouse, handle_key, handle_mouse, header_spans, image_mime, image_mime_of,+ input_content_lines, load_first_file_image, load_image_file, message_text, note_update,+ open_config_screen, open_rewind_picker, pairs_to_str, parse_command, partial_json_field,+ provider_label_for_model, rebuild_recall, replay_display_log, restore_goal,+ restore_run_mode, restore_todos, resume_hint, rewind_to, route_paste_event, row_width,+ run_command, running_group_rows, selection_text, spans_width, spawn_branch_poll,+ split_reasoning, starting_call_lines, startup_modes, strip_system_xml_tags,+ subagent_activity, subagent_name_from_run_id, summarize_result, sync_output_for,+ thinking_open, tilde_path, tokens_per_second, tool_activity, tool_finished,+ transcript_top_padding, unescape_partial_json_string, user_content_parts, wave_sweep_line,+ with_wave_glyph, without_think_tags, App, CompactKind, ContextReport, ContextSegment,+ ContextView, CurrentRun, McpField, McpPrompt, MonitorSet, Pending, PendingImage,+ PickerKind, ProviderField, ReasoningSeg, ResumeTarget, Row, RowKind, Selection,+ SelectionMode, SnapshotJob, Status, AGENT_SETTINGS, ALT_SCROLL_RESTORE,+ ALT_SCROLL_SAVE_OFF, COPY_NOTICE, DIFF_ADD_BG, DIFF_DEL_BG, DIFF_MAX_ROWS,+ DIFF_PREVIEW_MAX_ROWS, KEY_BINDINGS, KITTY_KEYS_OFF, KITTY_KEYS_ON, MAX_IMAGE_BYTES,+ MAX_OVERFLOW_RETRIES, MOUSE_TRACK_ON, PROVIDERS_SETTINGS_ROW, SLASH_COMMANDS, SPINNER,+ SPINNER_ADVANCE_MS, THINKING_WORDS, WORKING_WORDS,};use crate::core::agent::events::{StreamEvent, Usage};use crate::core::agent::r#loop::PermissionRegistry;@@ -19140,24 +19200,19 @@ mod tests {}/// A `monitor` call must never fall through to the raw-JSON fallback: a- /// start's condition scripts make that a paragraph, not a label.+ /// start's script makes that a paragraph, not a label.#[test]fn monitor_calls_get_readable_labels() {- let start = json!({- "op": "start",- "file": "build.log",- "conditions": [- { "name": "ok", "script": "grep OK build.log" },- { "name": "fail", "script": "grep FAILED build.log" }- ]- });+ let start = json!({ "op": "start", "name": "build", "script": "grep OK build.log" });assert_eq!(tool_activity("monitor", &start),- "Starting a monitor on build.log (2 conditions)"+ "Starting a monitor: build");+ assert_eq!(tool_finished("monitor", &start), "Started a monitor: build");+ let unnamed = json!({ "op": "start", "script": "test -f done.flag" });assert_eq!(- tool_finished("monitor", &start),- "Started a monitor on build.log (2 conditions)"+ tool_activity("monitor", &unnamed),+ "Starting a monitor: test -f done.flag");assert_eq!(tool_activity("monitor", &json!({ "op": "stop", "monitor_id": "mon-2" })),@@ -21659,6 +21714,7 @@ mod tests {run_mode: crate::core::agent::plan::RunMode::Normal,session_id: None,sandbox: None,+ monitors: Some(app.monitor_set.clone()),});app.args = Some(args.clone());@@ -29400,34 +29456,34 @@ mod tests {);}- fn monitor(id: &str, file: &str, met: &[&str], unmet: &[&str]) -> MonitorSnapshot {+ fn monitor(id: &str, name: &str, script: &str, polls: u64) -> MonitorSnapshot {MonitorSnapshot {monitor_id: id.to_string(),- file: file.to_string(),- met: met.iter().map(|s| s.to_string()).collect(),- unmet: unmet.iter().map(|s| s.to_string()).collect(),+ name: name.to_string(),+ script: script.to_string(),+ polls,}}/// Running monitors are live state like the fan-out, so they dock in the- /// status panel: one line each with the file and progress, the unmet- /// conditions beneath when the budget allows, beside any live agents.+ /// status panel: one line each with the name and poll count, the script+ /// beneath when the budget allows, beside any live agents.#[test]fn running_monitors_dock_in_the_status_panel() {let mut app = test_app();app.submit_user("go".into());app.apply(StreamEvent::Monitors {monitors: vec![- monitor("mon-1", "build.log", &["one"], &["two"]),- monitor("mon-2", "test.log", &[], &["green"]),+ monitor("mon-1", "build", "grep OK build.log", 3),+ monitor("mon-2", "tests", "grep green test.log", 1),],});let text = render_rows(&mut app, 100, 24).join("\n");assert!(text.contains("2 monitors"), "{text}");- assert!(text.contains("mon-1 build.log"), "{text}");- assert!(text.contains("1/2 met"), "{text}");- assert!(text.contains("waiting on two"), "{text}");- assert!(text.contains("mon-2 test.log"), "{text}");+ assert!(text.contains("mon-1 build"), "{text}");+ assert!(text.contains("3 polls"), "{text}");+ assert!(text.contains("grep OK build.log"), "{text}");+ assert!(text.contains("mon-2 tests"), "{text}");start_subagent(&mut app, "r0", "alpha");let text = render_rows(&mut app, 100, 24).join("\n");@@ -29454,7 +29510,7 @@ mod tests {assert!(header(&mut app).contains("[working]"));app.apply(StreamEvent::Monitors {- monitors: vec![monitor("mon-1", "build.log", &[], &["ok"])],+ monitors: vec![monitor("mon-1", "ok", "grep OK build.log", 1)],});app.apply(StreamEvent::Parked);let text = header(&mut app);@@ -29471,14 +29527,143 @@ mod tests {assert!(header(&mut app).contains("[waiting]"));app.apply(StreamEvent::Monitors {- monitors: vec![monitor("mon-2", "build.log", &[], &["ok"])],+ monitors: vec![monitor("mon-2", "ok", "grep OK build.log", 1)],});app.on_error("upstream".into(), "gone".into());- assert!(app.monitors.is_empty(), "monitors die with the run");+ assert!(+ app.monitors.is_empty(),+ "run end re-reads the session set, which has nothing running"+ );assert!(!app.parked);assert!(header(&mut app).contains("[ready]"));}+ fn session_monitor_spec(script: &str) -> tauri_plugin_agent_tools::tools::monitor::MonitorSpec {+ tauri_plugin_agent_tools::tools::monitor::MonitorSpec {+ name: "ready".to_string(),+ script: script.to_string(),+ timeout_secs: 60,+ interval: Duration::from_millis(20),+ }+ }++ fn session_monitor_ctx(+ root: &std::path::Path,+ ) -> tauri_plugin_agent_tools::tools::monitor::MonitorCtx {+ tauri_plugin_agent_tools::tools::monitor::MonitorCtx {+ project_root: root.to_path_buf(),+ scratch_root: None,+ mask_root: None,+ read_roots: Vec::new(),+ write_roots: Vec::new(),+ allow_network: false,+ home_readonly: false,+ // Bare shell: these exercise the TUI wiring, not the jail.+ sandbox: false,+ }+ }++ /// A session monitor outlives the run that started it: the run ends with+ /// the header back on `[ready]` while the watcher stays docked, and only a+ /// session reset (`/clear`, a thread switch) takes it down.+ #[tokio::test]+ async fn a_running_session_monitor_outlives_the_run_and_stays_docked() {+ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("boot.log"), "starting\n").unwrap();+ let mut app = test_app();+ app.monitor_set+ .start(+ session_monitor_spec("grep READY boot.log"),+ session_monitor_ctx(root.path()),+ )+ .unwrap();+ app.submit_user("go".into());+ let monitors = app.monitor_set.snapshot();+ app.apply(StreamEvent::Monitors { monitors });+ app.on_done("stop".into(), None);++ let header = render_rows(&mut app, 100, 24)[0].clone();+ assert!(header.contains("[ready]"), "{header}");+ assert_eq!(app.monitors.len(), 1, "the watcher is still docked");+ assert_eq!(app.status, Status::Idle);++ app.reset_session();+ assert!(app.monitors.is_empty());+ assert!(!app.monitor_set.has_pending_work());+ }++ /// A match landing between runs is delivered by the TUI itself: the+ /// headline is noted, the text joins the history as a `<SYSTEM>` reminder+ /// and one turn is armed, exactly as the loop would have done mid-run.+ #[tokio::test]+ async fn a_monitor_ping_between_runs_starts_a_turn() {+ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("boot.log"), "READY on port 1337\n").unwrap();+ let mut app = test_app();+ app.history+ .push(serde_json::json!({ "role": "user", "content": "watch the build" }));+ app.history+ .push(serde_json::json!({ "role": "assistant", "content": "watching" }));+ app.monitor_set+ .start(+ session_monitor_spec("grep READY boot.log"),+ session_monitor_ctx(root.path()),+ )+ .unwrap();+ tokio::time::timeout(Duration::from_secs(5), app.monitor_set.wait_for_notice())+ .await+ .expect("the first evaluation matches");+ assert!(app.monitor_set.has_queued_notices());++ app.submit_monitor_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("READY on port 1337"));+ assert!(+ transcript_text(&app).contains("'ready' matched"),+ "{}",+ transcript_text(&app)+ );+ assert!(app.monitors.is_empty(), "matched, so the watcher retired");+ assert!(!app.monitor_set.has_queued_notices(), "taken");+ }++ /// The loop drains the set itself while a run is up, so the TUI's wait+ /// must stay parked then -- and with nothing to wait for -- rather than+ /// racing the run for the same ping.+ #[tokio::test]+ async fn await_monitor_ping_only_fires_between_runs() {+ let root = tempfile::tempdir().unwrap();+ std::fs::write(root.path().join("boot.log"), "READY\n").unwrap();+ let set = Arc::new(MonitorSet::new());+ let parked =+ tokio::time::timeout(Duration::from_millis(20), await_monitor_ping(&set, true));+ assert!(parked.await.is_err(), "nothing could fire, so it parks");++ set.start(+ session_monitor_spec("grep READY boot.log"),+ session_monitor_ctx(root.path()),+ )+ .unwrap();+ tokio::time::timeout(Duration::from_secs(5), await_monitor_ping(&set, true))+ .await+ .expect("idle: the ping is ours to deliver");+ let busy = tokio::time::timeout(Duration::from_millis(20), await_monitor_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 indiff --git a/web-app/src/components/left-sidebar/NavCowork.tsx b/web-app/src/components/left-sidebar/NavCowork.tsxindex feeeaa150..be726b679 100644--- a/web-app/src/components/left-sidebar/NavCowork.tsx+++ b/web-app/src/components/left-sidebar/NavCowork.tsx@@ -22,6 +22,8 @@ import {DialogTitle,} from '@/components/ui/dialog'import { Button } from '@/components/ui/button'+import { stopAgentSessionMonitors } from '@/lib/agentTools'+import { dropMonitorLane } from '@/lib/coworkMonitor'import { useTranslation } from '@/i18n/react-i18next-compat'import { useNavigate } from '@tanstack/react-router'import { route } from '@/constants/routes'@@ -173,7 +175,15 @@ export function NavCowork() {]const confirmDelete = () => {- if (pendingDelete) useCoworkSessions.getState().deleteSession(pendingDelete.id)+ if (pendingDelete) {+ const sid = pendingDelete.id+ // Watchers are the session's, so they go with it: stopped in Rust, their+ // lane forgotten, their rail entries dropped.+ void stopAgentSessionMonitors(sid)+ dropMonitorLane(sid)+ useCoworkRun.getState().clearMonitors(sid)+ useCoworkSessions.getState().deleteSession(sid)+ }setPendingDelete(null)}diff --git a/web-app/src/containers/CoworkTasksPanel.tsx b/web-app/src/containers/CoworkTasksPanel.tsxindex 39ed67772..3e5863541 100644--- a/web-app/src/containers/CoworkTasksPanel.tsx+++ b/web-app/src/containers/CoworkTasksPanel.tsx@@ -57,11 +57,20 @@ function TaskRow({ run, onSelect }: { run: SubagentRun; onSelect: () => void }))}-/** One file monitor: what it watches, how far along its conditions are. */+const MONITOR_OUTCOME_KEYS = {+ matched: 'common:monitorMatched',+ timeout: 'common:monitorTimedOut',+ stopped: 'common:monitorStopped',+} as const++/** One monitor: its name, how it ended (or that it is still polling), and the+ * script it polls. */function MonitorRow({ monitor }: { monitor: MonitorView }) {const { t } = useTranslation()const running = monitor.status === 'running'- const total = monitor.met.length + monitor.unmet.length+ const state = running+ ? t('common:monitorPolling')+ : t(MONITOR_OUTCOME_KEYS[monitor.outcome ?? 'stopped'])return (<divdata-testid="cowork-monitor-row"@@ -74,20 +83,20 @@ function MonitorRow({ monitor }: { monitor: MonitorView }) {<Eye size={14} className="shrink-0 text-main-view-fg/50" />)}<span className="truncate text-sm font-medium">- {monitor.file || monitor.monitorId}+ {monitor.name || monitor.monitorId}</span><span className="ml-auto shrink-0 font-mono text-xs text-main-view-fg/50">{monitor.monitorId}</span></div><span className="pl-6 font-mono text-xs tabular-nums text-main-view-fg/50">- {t('common:monitorConditionsMet', { met: monitor.met.length, total })}+ {state}{' · '}{formatDuration(monitor.startedAt, monitor.endedAt)}</span>- {running && monitor.unmet.length > 0 && (- <span className="truncate pl-6 text-xs text-main-view-fg/50">- {t('common:monitorWaitingOn', { names: monitor.unmet.join(', ') })}+ {monitor.script && (+ <span className="truncate pl-6 font-mono text-xs text-main-view-fg/50">+ {monitor.script}</span>)}</div>diff --git a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsxindex 3e380b6e0..cbb943cdd 100644--- a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx+++ b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx@@ -22,9 +22,8 @@ const run = (runId: string, status: SubagentRun['status']): SubagentRun => ({const monitor = (monitorId: string, status: MonitorView['status']): MonitorView => ({monitorId,- file: 'build.log',- met: [],- unmet: ['ok'],+ name: 'build',+ script: 'grep OK build.log',status,startedAt: 0,})diff --git a/web-app/src/hooks/__tests__/useCoworkRun.test.ts b/web-app/src/hooks/__tests__/useCoworkRun.test.tsindex 794473d60..9a1ec6280 100644--- a/web-app/src/hooks/__tests__/useCoworkRun.test.ts+++ b/web-app/src/hooks/__tests__/useCoworkRun.test.ts@@ -147,59 +147,59 @@ describe('useCoworkRun - monitors and parking', () => {const view = {monitorId: 'mon-1',- file: 'build.log',- met: [],- unmet: ['ok', 'green'],+ name: 'build',+ script: 'grep OK build.log',status: 'running' as const,startedAt: 0,}+ const update = (matched: boolean) => ({+ monitorId: 'mon-1',+ name: 'build',+ headline: 'h',+ text: 't',+ matched,+ })- it('tracks a monitor from start through its updates to done', () => {+ it('a match closes the monitor as matched', () => {const s = useCoworkRun.getState()s.startMonitor('sid', view)- s.updateMonitor('sid', {- monitorId: 'mon-1',- headline: 'h',- text: 't',- done: false,- met: ['ok'],- unmet: ['green'],- })expect(useCoworkRun.getState().monitors.sid[0]).toMatchObject({- met: ['ok'],- unmet: ['green'],+ name: 'build',status: 'running',})- s.updateMonitor('sid', {- monitorId: 'mon-1',- headline: 'h',- text: 't',- done: true,- met: ['ok', 'green'],- unmet: [],- })+ s.updateMonitor('sid', update(true))const done = useCoworkRun.getState().monitors.sid[0]- expect(done.status).toBe('done')+ expect(done).toMatchObject({ status: 'done', outcome: 'matched' })expect(done.endedAt).toBeDefined()})- it('an explicit stop closes the monitor with the progress it had', () => {+ it('a timeout closes the monitor as timed out', () => {+ const s = useCoworkRun.getState()+ s.startMonitor('sid', view)+ s.updateMonitor('sid', update(false))+ expect(useCoworkRun.getState().monitors.sid[0]).toMatchObject({+ status: 'done',+ outcome: 'timeout',+ })+ })++ it('an explicit stop closes the monitor as stopped', () => {const s = useCoworkRun.getState()s.startMonitor('sid', view)s.stopMonitor('sid', 'mon-1')expect(useCoworkRun.getState().monitors.sid[0]).toMatchObject({status: 'done',- unmet: ['ok', 'green'],+ outcome: 'stopped',})})- it('a new run empties the previous monitors and the parked flag', () => {+ it('a new run keeps the session monitors and clears the parked flag', () => {const s = useCoworkRun.getState()s.startMonitor('sid', view)s.setParked('sid', true)expect(useCoworkRun.getState().parked.sid).toBe(true)s.beginRun('sid', 'run-2', 'again')- expect(useCoworkRun.getState().monitors.sid).toEqual([])+ expect(useCoworkRun.getState().monitors.sid).toHaveLength(1)expect(useCoworkRun.getState().parked.sid).toBeUndefined()})@@ -210,14 +210,16 @@ describe('useCoworkRun - monitors and parking', () => {expect(useCoworkRun.getState().parked).toEqual({})})- it('finalizeRun closes running monitors and clearCodeRun drops them', () => {+ it('a watcher outlives the run: only clearMonitors drops it', () => {const s = useCoworkRun.getState()s.startMonitor('sid', view)s.setParked('sid', true)s.finalizeRun('sid')- expect(useCoworkRun.getState().monitors.sid[0].status).toBe('done')+ expect(useCoworkRun.getState().monitors.sid[0].status).toBe('running')expect(useCoworkRun.getState().parked.sid).toBeUndefined()s.clearCodeRun('sid')+ expect(useCoworkRun.getState().monitors.sid).toHaveLength(1)+ s.clearMonitors('sid')expect(useCoworkRun.getState().monitors.sid).toBeUndefined()})})diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.tsindex 8fdff6884..7f697f945 100644--- a/web-app/src/hooks/useCoworkRun.ts+++ b/web-app/src/hooks/useCoworkRun.ts@@ -144,11 +144,12 @@ function omitKey<T>(map: Record<string, T>, key: string): Record<string, T> {type CoworkRunState = {liveTurns: Record<string, CoworkTurn[]>subagents: Record<string, SubagentRun[]>- // The run's file monitors, per session. Transient like the subagent lanes,- // but never committed: a watcher dies with its run.+ // The session's file monitors. Unlike the subagent lanes they survive the+ // run: a watcher keeps going after the model has answered, and a later+ // match starts a turn of its own. Dropped with the session (`clearMonitors`).monitors: Record<string, MonitorView[]>- // True while the run is parked on background work (a subagent still- // running, a monitor still watching) with the model idle.+ // True while the run is parked on a subagent still running with the model+ // idle. A running monitor never parks a run.parked: Record<string, boolean>runId: Record<string, string>// In-flight `ask` tool questions per session. A subagent's wrapped ask is@@ -197,10 +198,12 @@ type CoworkRunState = {routeIntoSubagent: (sid: string, runId: string, inner: StreamEvent) => voidattachSubagentOutput: (sid: string, runId: string, content: string) => voidstartMonitor: (sid: string, view: MonitorView) => void- /** Advance a monitor from a Rust update; a `done` one closes it. */+ /** Close a monitor from its Rust update (a match or the timeout). */updateMonitor: (sid: string, update: MonitorUpdate) => void/** An explicit `stop`: closed with the progress it had. */stopMonitor: (sid: string, monitorId: string) => void+ /** Session teardown: the watchers are stopped in Rust alongside. */+ clearMonitors: (sid: string) => voidsetParked: (sid: string, parked: boolean) => voidsetUsage: (sid: string, usage: Usage | null) => voidrequestPreview: (sessionId: string, path: string) => void@@ -248,7 +251,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({[sid]: [userTurn(userText, media)],},subagents: { ...s.subagents, [sid]: [] },- monitors: { ...s.monitors, [sid]: [] },parked: omitKey(s.parked, sid),pendingAsks: { ...s.pendingAsks, [sid]: [] },})),@@ -371,14 +373,12 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({monitors: {...s.monitors,[sid]: (s.monitors[sid] ?? []).map((m) =>- m.monitorId === update.monitorId+ m.monitorId === update.monitorId && m.status === 'running'? {...m,- met: update.met,- unmet: update.unmet,- ...(update.done && m.status === 'running'- ? { status: 'done' as const, endedAt: Date.now() }- : {}),+ status: 'done' as const,+ outcome: update.matched ? ('matched' as const) : ('timeout' as const),+ endedAt: Date.now(),}: m),@@ -391,12 +391,19 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({...s.monitors,[sid]: (s.monitors[sid] ?? []).map((m) =>m.monitorId === monitorId && m.status === 'running'- ? { ...m, status: 'done' as const, endedAt: Date.now() }+ ? {+ ...m,+ status: 'done' as const,+ outcome: 'stopped' as const,+ endedAt: Date.now(),+ }: m),},})),+ clearMonitors: (sid) => set((s) => ({ monitors: omitKey(s.monitors, sid) })),+setParked: (sid, parked) =>set((s) => ({parked: parked ? { ...s.parked, [sid]: true } : omitKey(s.parked, sid),@@ -466,13 +473,9 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({const subs = (get().subagents[sid] ?? []).map((r) =>r.status !== 'done' ? { ...r, status: 'done' as const, endedAt: Date.now() } : r)- const mons = (get().monitors[sid] ?? []).map((m) =>- m.status !== 'done' ? { ...m, status: 'done' as const, endedAt: Date.now() } : m- )set((s) => ({liveTurns: { ...s.liveTurns, [sid]: turns },subagents: { ...s.subagents, [sid]: subs },- monitors: { ...s.monitors, [sid]: mons },parked: omitKey(s.parked, sid),}))return { turns, subagents: subs }@@ -482,7 +485,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({set((s) => ({liveTurns: omitKey(s.liveTurns, sid),subagents: omitKey(s.subagents, sid),- monitors: omitKey(s.monitors, sid),parked: omitKey(s.parked, sid),runId: omitKey(s.runId, sid),pendingAsks: omitKey(s.pendingAsks, sid),diff --git a/web-app/src/lib/__tests__/coworkMonitor.test.ts b/web-app/src/lib/__tests__/coworkMonitor.test.tsindex 80020f451..f3dc12f17 100644--- a/web-app/src/lib/__tests__/coworkMonitor.test.ts+++ b/web-app/src/lib/__tests__/coworkMonitor.test.ts@@ -3,43 +3,24 @@ import type { MonitorUpdate } from '@/lib/agentTools'import {MONITOR_TOOL_NAME,MonitorLane,+ dropMonitorLane,+ monitorLaneFor,monitorSpecFromArgs,monitorTool,parseMonitorId,- type MonitorInbox,type MonitorViewSink,} from '@/lib/coworkMonitor'-import type { SubagentNotice } from '@/lib/coworkSubagent'import type { MonitorView } from '@/types/coworkSession'-function fakeInbox() {- const calls: string[] = []- const notices: SubagentNotice[] = []- const inbox: MonitorInbox = {- begin: () => calls.push('begin'),- finish: (n) => {- calls.push('finish')- notices.push(n)- },- note: (n) => {- calls.push('note')- notices.push(n)- },- abandon: () => calls.push('abandon'),- }- return { inbox, calls, notices }-}-const startResult = (id: string) =>- `Monitor started (monitor_id=${id}) watching build.log with 2 conditions.`+ `Monitor started (monitor_id=${id}): 'build' runs every 5s.`const update = (over: Partial<MonitorUpdate>): MonitorUpdate => ({monitorId: 'mon-1',- headline: 'Monitor mon-1: condition "x" matched',- text: 'Monitor mon-1 condition x matched on build.log:\nhit',- done: false,- met: ['x'],- unmet: ['y'],+ name: 'x',+ headline: "Monitor mon-1: 'x' matched",+ text: "Monitor 'mon-1' ('x') matched:\nhit\n\nIt has stopped.",+ matched: true,...over,})@@ -58,18 +39,21 @@ function fakeView() {}describe('monitorSpecFromArgs', () => {- it('reads the file and condition names out of a start call', () => {+ it('reads the name and script out of a start call', () => {expect(- monitorSpecFromArgs({- op: 'start',- file: 'build.log',- conditions: [{ name: 'ok', script: 'true' }, { script: 'nameless' }],- })- ).toEqual({ file: 'build.log', conditions: ['ok'] })+ monitorSpecFromArgs({ op: 'start', name: ' build ', script: 'grep OK log' })+ ).toEqual({ name: 'build', script: 'grep OK log' })+ })++ it('labels an unnamed monitor by its script, like the Rust parser', () => {+ expect(monitorSpecFromArgs({ op: 'start', script: 'test -f done' })).toEqual({+ name: 'test -f done',+ script: 'test -f done',+ })})it('is empty for malformed arguments', () => {- expect(monitorSpecFromArgs(null)).toEqual({ file: '', conditions: [] })+ expect(monitorSpecFromArgs(null)).toEqual({ name: '', script: '' })})})@@ -84,47 +68,79 @@ describe('parseMonitorId', () => {})describe('MonitorLane', () => {- it('claims a slot on start and releases it on the terminal update', () => {- const { inbox, calls, notices } = fakeInbox()- const lane = new MonitorLane(inbox)+ it('queues the update as a ping and closes the watcher, matched or not', () => {+ const lane = new MonitorLane()+ lane.started(startResult('mon-1'))+ lane.started(startResult('mon-2'))+ expect(lane.watching()).toBe(2)+ lane.update(update({ matched: true }))+ lane.update(update({ monitorId: 'mon-2', matched: false }))+ expect(lane.watching()).toBe(0)+ const notices = lane.take()+ expect(notices).toHaveLength(2)+ expect(notices[0].text).toContain('hit')+ expect(lane.hasQueued()).toBe(false)+ })++ it('a running watcher is not queued work: nothing parks on it', () => {+ const lane = new MonitorLane()lane.started(startResult('mon-1'))- lane.update(update({ done: false }))- lane.update(update({ done: true }))- expect(calls).toEqual(['begin', 'note', 'finish'])- expect(notices[1].text).toContain('hit')+ expect(lane.hasQueued()).toBe(false)})- it('does not claim a slot for a failed start', () => {- const { inbox, calls } = fakeInbox()- new MonitorLane(inbox).started('ERROR: outside the project')- expect(calls).toEqual([])+ it('opens nothing for a failed start', () => {+ const lane = new MonitorLane()+ lane.started('ERROR: outside the project')+ expect(lane.watching()).toBe(0)})- it('an explicit stop releases the slot without a ping', () => {- const { inbox, calls } = fakeInbox()- const lane = new MonitorLane(inbox)+ it('an explicit stop closes the watcher without a ping', () => {+ const lane = new MonitorLane()lane.started(startResult('mon-1'))- lane.stopped('mon-1', 'Monitor mon-1 stopped. Conditions met: none; unmet: x.')- expect(calls).toEqual(['begin', 'abandon'])+ lane.stopped('mon-1', "Monitor mon-1 ('x') stopped after 1 poll without a match.")+ expect(lane.watching()).toBe(0)+ expect(lane.hasQueued()).toBe(false)})- it('a stop that failed releases nothing', () => {- const { inbox, calls } = fakeInbox()- const lane = new MonitorLane(inbox)+ it('a stop that failed closes nothing', () => {+ const lane = new MonitorLane()lane.started(startResult('mon-1'))lane.stopped('mon-1', "ERROR: unknown or already-stopped monitor 'mon-1'")- expect(calls).toEqual(['begin'])+ expect(lane.watching()).toBe(1)+ })++ it('wait resolves on a ping, and onPing fires so an idle session can start a turn', async () => {+ const lane = new MonitorLane()+ let pings = 0+ lane.onPing = () => pings+++ const waited = lane.wait()+ lane.update(update({}))+ await waited+ expect(pings).toBe(1)+ expect(lane.hasQueued()).toBe(true)})- it('a terminal update racing an earlier stop cannot release the slot twice', () => {- const { inbox, calls } = fakeInbox()- const lane = new MonitorLane(inbox)+ it('wait resolves at once when a ping is already queued or the run is aborted', async () => {+ const lane = new MonitorLane()+ lane.update(update({}))+ await lane.wait()+ const aborted = new AbortController()+ aborted.abort()+ await new MonitorLane().wait(aborted.signal)+ })+})++describe('monitorLaneFor', () => {+ it('hands the same lane to every run of a session until it is dropped', () => {+ const lane = monitorLaneFor('sid-a')lane.started(startResult('mon-1'))- lane.stopped('mon-1', 'Monitor mon-1 stopped. Conditions met: none; unmet: x.')- lane.update(update({ done: true }))- // The late update is still shown as a note, but the shared running count- // (which also guards live subagents) comes down exactly once.- expect(calls).toEqual(['begin', 'abandon', 'note'])+ expect(monitorLaneFor('sid-a')).toBe(lane)+ expect(monitorLaneFor('sid-a').watching()).toBe(1)+ expect(monitorLaneFor('sid-b')).not.toBe(lane)+ dropMonitorLane('sid-a')+ expect(monitorLaneFor('sid-a')).not.toBe(lane)+ dropMonitorLane('sid-a')+ dropMonitorLane('sid-b')})})@@ -132,27 +148,25 @@ describe('MonitorLane view', () => {/// The rail has no other account of a watcher: it opens on the start (with/// what the call asked for), moves with every update, closes on a stop.it('mirrors start, update and stop into the view', () => {- const { inbox } = fakeInbox()const { view, events, views } = fakeView()- const lane = new MonitorLane(inbox, view)- lane.started(startResult('mon-1'), { file: 'build.log', conditions: ['x', 'y'] })+ const lane = new MonitorLane(view)+ lane.started(startResult('mon-1'), { name: 'x', script: 'grep x build.log' })+ lane.started(startResult('mon-2'), { name: 'y', script: 'grep y build.log' })lane.update(update({}))- lane.stopped('mon-1', 'Monitor mon-1 stopped. Conditions met: x; unmet: y.')- expect(events).toEqual(['started', 'updated:mon-1', 'stopped:mon-1'])+ lane.stopped('mon-2', "Monitor mon-2 ('y') stopped after 3 polls without a match.")+ expect(events).toEqual(['started', 'started', 'updated:mon-1', 'stopped:mon-2'])expect(views[0]).toMatchObject({monitorId: 'mon-1',- file: 'build.log',- met: [],- unmet: ['x', 'y'],+ name: 'x',+ script: 'grep x build.log',status: 'running',})})it('opens nothing for a failed start and closes nothing for a failed stop', () => {- const { inbox } = fakeInbox()const { view, events } = fakeView()- const lane = new MonitorLane(inbox, view)- lane.started('ERROR: outside the project', { file: 'x', conditions: [] })+ const lane = new MonitorLane(view)+ lane.started('ERROR: at most 8 monitors may be active', { name: 'x', script: 'x' })lane.stopped('mon-1', "ERROR: unknown or already-stopped monitor 'mon-1'")expect(events).toEqual([])})@@ -162,7 +176,7 @@ describe('monitorTool', () => {it('keeps the contract the Rust schema advertises', () => {expect(MONITOR_TOOL_NAME).toBe('monitor')const description = monitorTool().description ?? ''- expect(description).toContain('<SYSTEM> note per match')- expect(description).toContain('exit 0 means the condition matched')+ expect(description).toContain('<SYSTEM> note')+ expect(description).toContain('exits 0')})})diff --git a/web-app/src/lib/agentTools.ts b/web-app/src/lib/agentTools.tsindex f4412031c..89a5c339c 100644--- a/web-app/src/lib/agentTools.ts+++ b/web-app/src/lib/agentTools.ts@@ -350,8 +350,9 @@ export async function listAgentMonitors(sessionId: string): Promise<string> {}/**- * Abort every monitor a session still has. Best-effort teardown at run end: a- * failure leaves watchers whose updates go nowhere, not user-visible damage.+ * Abort every monitor a session still has. Best-effort teardown when the+ * session is deleted: a failure leaves watchers whose updates go nowhere, not+ * user-visible damage.*/export async function stopAgentSessionMonitors(sessionId: string): Promise<void> {try {diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.tsindex 9dac0ad31..ad656df87 100644--- a/web-app/src/lib/coworkDispatch.ts+++ b/web-app/src/lib/coworkDispatch.ts@@ -32,8 +32,8 @@ export type DispatchContext = {onAsk: (toolCallId: string, input: unknown) => Promise<ToolOutcome>/** Runs a nested subagent to completion. */onTask: (toolCallId: string, input: unknown) => Promise<ToolOutcome>- /** The run's monitor bookkeeping; `null` for a subagent's dispatch, which- * refuses the tool (a child has no inbox for a watcher to ping). */+ /** The session's monitor lane; `null` for a subagent's dispatch, which+ * refuses the tool (a child has no turn of its own for a match to start). */monitors: MonitorLane | null}@@ -57,8 +57,8 @@ function planRefusal(toolName: string): ToolOutcome {/*** One `monitor` op. The watcher runs in Rust; this routes the call and keeps- * the run's `MonitorLane` in step so the inbox parks the run while a watcher is- * owed work and never double-releases a slot.+ * the session's `MonitorLane` in step, so matches queue as pings and the rail+ * tracks each watcher.*/async function runMonitorOp(input: unknown,diff --git a/web-app/src/lib/coworkMonitor.ts b/web-app/src/lib/coworkMonitor.tsindex 1625f2d34..81de4e1d6 100644--- a/web-app/src/lib/coworkMonitor.ts+++ b/web-app/src/lib/coworkMonitor.ts@@ -12,7 +12,7 @@ import type { MonitorView } from '@/types/coworkSession'* `MonitorUpdate`. What lives here is the client half: the transcribed schema* (like `task`/`todo`), and the bookkeeping that turns updates into inbox pings* so a match reaches the model as the same `<SYSTEM>` note a finished subagent- * sends -- and keeps the run alive while a watcher is still owed work.+ * sends, whether a run is up to drain it or one has to be started for it.*/export const MONITOR_TOOL_NAME = 'monitor'@@ -22,41 +22,30 @@ export const MONITOR_TOOL_NAME = 'monitor'export function monitorTool(): Tool {return {description:- 'Watch a file a long-running job streams output into (e.g. a backgrounded bash job redirecting to a log) and evaluate condition scripts against it. Each condition is a shell script run from the project root whenever the file changes; exit 0 means the condition matched and its stdout is the matched content. You get a <SYSTEM> note per match, so start the monitor and keep working. The monitor stops when every condition has matched, on stop, or at its timeout. A met condition is never re-checked.',+ 'Wait for something in the background: poll a shell script on an interval until it exits 0, then get its stdout as a <SYSTEM> note while you keep working. Use it to wait on a backgrounded job, e.g. script "grep -m1 \'BUILD FAILED\' build.log" or "test -f done.flag". The script runs from the project root on every poll; a nonzero exit means not yet. The first match ends the monitor, as does its timeout. Start one monitor per thing you are waiting for.',inputSchema: jsonSchema({type: 'object',properties: {op: { type: 'string', enum: ['start', 'stop', 'list'] },- file: {+ script: {type: 'string',description:- 'For start: the file to watch, relative to the project root (or under /tmp). It may not exist yet.',+ 'For start: a cheap shell check that exits 0 once the thing has happened; its stdout is what you get back.',},- conditions: {- type: 'array',+ name: {+ type: 'string',+ description:+ 'For start: optional short label quoted back to you when it matches (defaults to the script).',+ },+ interval: {+ type: 'integer',description:- "For start: the conditions to watch for. Scripts should be cheap checks (e.g. grep -m1 'BUILD FAILED' build.log), not jobs.",- items: {- type: 'object',- properties: {- name: {- type: 'string',- description:- 'Short unique label, quoted back to you when it matches.',- },- script: {- type: 'string',- description:- 'Shell script; exit 0 = matched, stdout = the matched content.',- },- },- required: ['name', 'script'],- },+ 'For start: seconds between polls (default 5, min 1, max 300).',},timeout: {type: 'integer',description:- 'For start: seconds before the monitor gives up and reports its unmet conditions (default 1800, max 7200).',+ 'For start: seconds before the monitor gives up (default 1800, max 7200).',},monitor_id: {type: 'string',@@ -75,21 +64,19 @@ export function parseMonitorId(startResult: string): string | null {}/** What a `start` call asked for, as the panel shows it before any update. */-export type MonitorSpec = { file: string; conditions: string[] }+export type MonitorSpec = { name: string; script: string }-/** The watched file and condition names out of a `start` call's arguments. */+/** The name and script out of a `start` call's arguments. The name falls back+ * to the script, as Rust's parser does. */export function monitorSpecFromArgs(input: unknown): MonitorSpec {const args =input && typeof input === 'object' ? (input as Record<string, unknown>) : {}- const file = typeof args.file === 'string' ? args.file : ''- const conditions = Array.isArray(args.conditions)- ? args.conditions.flatMap((c) => {- const name =- c && typeof c === 'object' ? (c as { name?: unknown }).name : null- return typeof name === 'string' ? [name] : []- })- : []- return { file, conditions }+ const script = typeof args.script === 'string' ? args.script.trim() : ''+ const name =+ typeof args.name === 'string' && args.name.trim()+ ? args.name.trim()+ : script+ return { name, script }}/**@@ -104,71 +91,107 @@ export type MonitorViewSink = {}/**- * What the run's inbox needs to hear about monitors. Structurally what- * `SubagentInbox` provides, so the two kinds of background work share one- * inbox and one park/resume path.- */-export type MonitorInbox = {- begin: () => void- finish: (notice: SubagentNotice) => void- note: (notice: SubagentNotice) => void- abandon: () => void-}--/**- * One run's view of its monitors, bridging Rust updates to the inbox.+ * One session's monitors, outliving any single run.*- * The open-set exists because the inbox's running count is shared with the- * subagents: `finish`/`abandon` must fire exactly once per started monitor, and- * a stop racing the monitor's own terminal update would otherwise decrement- * twice -- reading `pending()` false while a subagent is still running.+ * A watcher does not hold a run open: the model answers, the run ends and the+ * user keeps talking. Matches queue here as the same `<SYSTEM>` pings a+ * finished subagent sends. A running loop drains them at the top of its next+ * step; while no run is up, `onPing` lets the route start one. The open-set is+ * display bookkeeping only (`watching`, the rail's view).*/export class MonitorLane {private open = new Set<string>()+ private queue: SubagentNotice[] = []+ private waiters: Array<() => void> = []+ /** Fired on every queued ping, so an idle session can start a turn for it. */+ onPing: (() => void) | null = null- constructor(- private readonly inbox: MonitorInbox,- private readonly view?: MonitorViewSink- ) {}+ constructor(private readonly view?: MonitorViewSink) {}- /** Record a successful start (its result names the id) and claim a running- * slot, so the run parks on the watcher instead of ending under it. */+ /** Record a successful start (its result names the id). */started(startResult: string, spec?: MonitorSpec): void {const id = parseMonitorId(startResult)if (!id) returnthis.open.add(id)- this.inbox.begin()this.view?.started({monitorId: id,- file: spec?.file ?? '',- met: [],- unmet: spec?.conditions ?? [],+ name: spec?.name ?? '',+ script: spec?.script ?? '',status: 'running',startedAt: Date.now(),})}- /** Route one Rust update: a terminal one closes the slot, any other is a- * ping the model reacts to while the watcher keeps going. */+ /** Route one Rust update: shown in the rail, queued for the model. Every+ * update ends its monitor (a match or the timeout). */update(update: MonitorUpdate): void {this.view?.updated(update)- const notice: SubagentNotice = {- headline: update.headline,- text: update.text,- }- if (update.done && this.open.delete(update.monitorId)) {- this.inbox.finish(notice)- return- }- this.inbox.note(notice)+ this.open.delete(update.monitorId)+ this.queue.push({ headline: update.headline, text: update.text })+ this.wake()+ this.onPing?.()}- /** Account for an explicit `stop`: the slot is released with no ping, since- * the model's own tool result already reports the outcome. */+ /** Account for an explicit `stop`. No ping: the model's own tool result+ * already reports the outcome. */stopped(monitorId: string, stopResult: string): void {if (!stopResult.startsWith('ERROR') && this.open.delete(monitorId)) {- this.inbox.abandon()this.view?.stopped(monitorId)}}++ /** Monitors still running. */+ watching(): number {+ return this.open.size+ }++ hasQueued(): boolean {+ return this.queue.length > 0+ }++ /** Take every queued ping, oldest first. */+ take(): SubagentNotice[] {+ const out = this.queue+ this.queue = []+ return out+ }++ /** Resolve when a ping is queued or the run waiting on it is cancelled. */+ wait(signal?: AbortSignal): Promise<void> {+ if (this.hasQueued() || signal?.aborted) return Promise.resolve()+ return new Promise<void>((resolve) => {+ const done = () => {+ signal?.removeEventListener('abort', done)+ resolve()+ }+ this.waiters.push(done)+ signal?.addEventListener('abort', done, { once: true })+ })+ }++ private wake(): void {+ const waiters = this.waiters+ this.waiters = []+ for (const resolve of waiters) resolve()+ }+}++const lanes = new Map<string, MonitorLane>()++/** The session's lane, created on first use with `view` when given. */+export function monitorLaneFor(+ sessionId: string,+ view?: () => MonitorViewSink+): MonitorLane {+ let lane = lanes.get(sessionId)+ if (!lane) {+ lane = new MonitorLane(view?.())+ lanes.set(sessionId, lane)+ }+ return lane+}++/** Forget a session's lane; its Rust watchers are stopped separately. */+export function dropMonitorLane(sessionId: string): void {+ lanes.delete(sessionId)}diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.jsonindex 37d171250..b36636bb5 100644--- a/web-app/src/locales/en/common.json+++ b/web-app/src/locales/en/common.json@@ -648,8 +648,10 @@"backgroundRunning_one": "{{count}} background task running","backgroundRunning_other": "{{count}} background tasks running","monitors": "Monitors",- "monitorConditionsMet": "{{met}}/{{total}} conditions met",- "monitorWaitingOn": "Waiting on {{names}}",+ "monitorPolling": "Polling",+ "monitorMatched": "Matched",+ "monitorTimedOut": "Timed out",+ "monitorStopped": "Stopped","coworkWatching_one": "Watching {{count}} monitor…","coworkWatching_other": "Watching {{count}} monitors…","coworkWaitingBackground": "Waiting on background tasks…",diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 063e0ce09..fe395c31c 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -92,9 +92,8 @@ import {fillSubagentResult,importAttachment,reserveSubagentResult,- stopAgentSessionMonitors,} from '@/lib/agentTools'-import { MonitorLane } from '@/lib/coworkMonitor'+import { monitorLaneFor, type MonitorLane } from '@/lib/coworkMonitor'import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'import type { MonitorView } from '@/types/coworkSession'import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'@@ -152,6 +151,15 @@ const MANUAL_COMPACT_CONFIG: ContextManagerConfig = {// store write the way a fresh `[]` from the selector would.const NO_MONITORS: MonitorView[] = []+/** The session's monitor lane, mirrored into the run store for the rail. */+function sessionMonitorLane(sid: string): MonitorLane {+ return monitorLaneFor(sid, () => ({+ started: (view) => useCoworkRun.getState().startMonitor(sid, view),+ updated: (update) => useCoworkRun.getState().updateMonitor(sid, update),+ stopped: (id) => useCoworkRun.getState().stopMonitor(sid, id),+ }))+}+function CoworkPage() {const { t } = useTranslation()const serviceHub = useServiceHub()@@ -354,7 +362,7 @@ function CoworkPage() {() => liveSubagents ?? session?.subagents ?? [],[liveSubagents, session?.subagents])- // Monitors and the parked flag are run-only: a watcher dies with its run.+ // Monitors are the session's and outlive a run; the parked flag is run-only.const monitors = useCoworkRun((s) => (session?.id ? s.monitors[session.id] : undefined) ?? NO_MONITORS)@@ -495,14 +503,9 @@ function CoworkPage() {// Owned by this request: children cannot outlive the run whose signal// aborts them, so a fresh inbox per run can never hold a stale ping.const inbox = new SubagentInbox()- // Bridges Rust monitor updates into the same inbox, so a watcher parks the- // run exactly the way a running subagent does, and mirrors each one into- // the run store for the background-tasks rail.- const monitorLane = new MonitorLane(inbox, {- started: (view) => useCoworkRun.getState().startMonitor(sid, view),- updated: (update) => useCoworkRun.getState().updateMonitor(sid, update),- stopped: (id) => useCoworkRun.getState().stopMonitor(sid, id),- })+ // The session's, not the run's: a watcher keeps going after this run has+ // answered, and its pings are drained by whichever run is up next.+ const monitorLane = sessionMonitorLane(sid)const sink: StreamSink = {onText: (delta) => {@@ -793,7 +796,7 @@ function CoworkPage() {// reacts to a subagent finishing has the note it is replying to// directly above it.take: () => {- const notices = inbox.take()+ const notices = [...inbox.take(), ...monitorLane.take()]// The row gets the headline; the model gets the instructions that// follow it, which are addressed to it alone.pushLive(@@ -804,8 +807,14 @@ function CoworkPage() {)return notices.map((n) => n.text)},- pending: () => inbox.pending(),- wait: () => inbox.wait(controller.signal),+ // A running watcher is not pending work: only a queued match is,+ // so the run ends under a monitor and the user can keep talking.+ pending: () => inbox.pending() || monitorLane.hasQueued(),+ wait: () =>+ Promise.race([+ inbox.wait(controller.signal),+ monitorLane.wait(controller.signal),+ ]),// The model is idle for the whole wait; the transcript says so// instead of showing a "Working…" spinner over nothing.onParked: (p) => useCoworkRun.getState().setParked(sid, p),@@ -823,9 +832,6 @@ function CoworkPage() {errorText: e instanceof Error ? e.message : String(e),}} finally {- // Watchers are run-scoped, like the children the abort signal covers: an- // update landing after this point would have no run to resume.- void stopAgentSessionMonitors(sid)useAppState.getState().updateLoadingModel(false)useCoworkSessions.getState()@@ -1168,6 +1174,25 @@ function CoworkPage() {useCoworkRun.getState().clearPendingPreview()}, [pendingPreview, session?.id])+ // A match landing while no run is up starts one: the queued ping is drained+ // at the top of that run's first step, exactly as a mid-run one would be.+ // Re-checked whenever the run state flips, since a ping arriving in the gap+ // between a run ending and this render sees a stale `running`.+ useEffect(() => {+ const sid = session?.id+ if (!sid) return+ const lane = sessionMonitorLane(sid)+ const deliver = () => {+ if (running || !lane.hasQueued()) return+ void runRequestRef.current(null)+ }+ lane.onPing = deliver+ deliver()+ return () => {+ if (lane.onPing === deliver) lane.onPing = null+ }+ }, [session?.id, running])+// Nothing to show once the session changes: both panels describe the session// they were opened from.useEffect(() => setRail(null), [session?.id])diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.tsindex 9e298e6e3..3d951f74c 100644--- a/web-app/src/types/coworkSession.ts+++ b/web-app/src/types/coworkSession.ts@@ -87,15 +87,17 @@ export type SubagentRun = {}/**- * One file monitor the run started, for the background-tasks rail. Transient:- * a watcher dies with its run, so nothing here is committed onto the session.+ * One monitor the session started, for the background-tasks rail. Kept in the+ * run store only: a watcher dies with the app, so nothing here is committed+ * onto the session.*/export type MonitorView = {monitorId: string- file: string- met: string[]- unmet: string[]+ name: string+ script: stringstatus: 'running' | 'done'+ /** How a done monitor ended. */+ outcome?: 'matched' | 'timeout' | 'stopped'startedAt: numberendedAt?: number}