Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(agent): show running monitors and the parked state on both surfaces

Akarshan Biswas5617b348909c
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.ts
index dd5db071b..440d01a43 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
@@ -66,4 +66,7 @@ export type MonitorUpdate = {
headline: string
text: string
done: boolean
+ /** Condition names met so far, and those still outstanding, at this update. */
+ met: string[]
+ unmet: string[]
}
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.rs
index 22dda2ef7..c3940ee54 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
@@ -108,6 +108,8 @@ 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.
#[derive(Debug, Clone, PartialEq, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MonitorUpdate {
@@ -115,6 +117,19 @@ pub struct MonitorUpdate {
pub headline: String,
pub text: String,
pub done: bool,
+ pub met: Vec<String>,
+ pub unmet: Vec<String>,
+}
+
+/// Display-only view of one active monitor, for a status panel: what it
+/// watches and how far along its conditions are.
+#[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>,
}
/// Parse and validate a `monitor {op:"start"}` call.
@@ -378,6 +393,25 @@ impl MonitorSet {
out.trim_end().to_string()
}
+ /// Every active monitor, ordered by id, for a live status display. Same
+ /// source as `list`, so the screen and the model never disagree.
+ pub fn snapshot(&self) -> Vec<MonitorSnapshot> {
+ let inner = self.inner.lock().unwrap();
+ let mut ids: Vec<&String> = inner.keys().collect();
+ ids.sort();
+ ids.into_iter()
+ .map(|id| {
+ let status = inner[id].status.lock().unwrap();
+ MonitorSnapshot {
+ monitor_id: id.clone(),
+ file: status.file.clone(),
+ met: status.met.clone(),
+ unmet: status.unmet.clone(),
+ }
+ })
+ .collect()
+ }
+
/// Abort and forget every monitor. Called at owner teardown; nothing is
/// queued, since no turn is left to read it.
pub fn stop_all(&self) {
@@ -451,13 +485,17 @@ async fn run_monitor(
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;
- set.push_update(match_update(monitor_id, &spec.file, &name, &content, last));
+ 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;
@@ -466,6 +504,7 @@ async fn run_monitor(
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();
set.push_update(MonitorUpdate {
monitor_id: monitor_id.to_string(),
headline: format!("Monitor {monitor_id}: timed out"),
@@ -477,6 +516,8 @@ async fn run_monitor(
name_list(&names)
),
done: true,
+ met,
+ unmet: names,
});
return;
}
@@ -508,6 +549,8 @@ fn match_update(
headline,
text,
done: last,
+ met: Vec::new(),
+ unmet: Vec::new(),
}
}
@@ -751,6 +794,8 @@ mod tests {
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"),
@@ -767,6 +812,37 @@ mod tests {
assert!(second.done);
}
+ #[tokio::test]
+ async fn snapshot_lists_active_monitors_with_their_progress() {
+ 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.stop("mon-1");
+ assert!(set.snapshot().is_empty());
+ }
+
#[tokio::test]
async fn an_unmet_monitor_times_out_and_names_its_conditions() {
let dir = unique_root();
@@ -782,6 +858,8 @@ mod tests {
assert!(update.done);
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()]);
}
#[tokio::test]
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rs
index 55d1451d6..02f7d42ce 100644
--- a/src-tauri/src/core/agent/events.rs
+++ b/src-tauri/src/core/agent/events.rs
@@ -120,6 +120,19 @@ pub enum StreamEvent {
/// transcript reads in the order the model saw things. Display-only and
/// transient, like notes: it is never journaled.
Notice { text: String },
+ /// The run's active file monitors, as a whole replacing the previous set.
+ /// Emitted whenever the set changes (a `monitor` start or stop, a condition
+ /// matching, a monitor finishing), so a consumer keeps a live view without
+ /// bookkeeping of its own. Display-only and never journaled. Not forwarded
+ /// from a child: a child's monitors are its own.
+ Monitors {
+ monitors: Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot>,
+ },
+ /// The model has finished its turn and the loop is parked on background
+ /// work it started (a subagent still running, a monitor still watching).
+ /// Nothing is being generated until a ping resumes the run, which the next
+ /// `Step` marks. Lets a consumer say "watching" rather than "working".
+ Parked,
/// The loop's compaction reduced the conversation while retrying a
/// context overflow. The client should replace its session history with
/// `messages` for subsequent turns.
diff --git a/src-tauri/src/core/agent/loop.rs b/src-tauri/src/core/agent/loop.rs
index 67521c726..3beab723e 100644
--- a/src-tauri/src/core/agent/loop.rs
+++ b/src-tauri/src/core/agent/loop.rs
@@ -175,6 +175,28 @@ pub(crate) trait ToolInvoker: Send + Sync {
/// left to wait for. Only called while `background_pending` holds, so the
/// default's immediate return cannot spin.
async fn await_background(&self) {}
+
+ /// The run's active file monitors, for [`StreamEvent::Monitors`].
+ fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {
+ Vec::new()
+ }
+}
+
+/// Emit [`StreamEvent::Monitors`] when the set differs from what was last
+/// shown. Called wherever the set can have changed: after tool calls (start,
+/// stop), after a ping drain (match, timeout) and after a park.
+fn publish_monitors(
+ tools: &dyn ToolInvoker,
+ events: &mpsc::UnboundedSender<StreamEvent>,
+ shown: &mut Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot>,
+) {
+ let now = tools.monitor_snapshot();
+ if now != *shown {
+ let _ = events.send(StreamEvent::Monitors {
+ monitors: now.clone(),
+ });
+ *shown = now;
+ }
}
struct HttpModelInvoker {
@@ -979,6 +1001,10 @@ impl ToolInvoker for CompositeToolInvoker {
|| self.monitors.has_pending_work()
}
+ fn monitor_snapshot(&self) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {
+ self.monitors.snapshot()
+ }
+
async fn await_background(&self) {
// Each wait returns on a notice OR when its own side has nothing left,
// so an exhausted side must not be selected over: it would win
@@ -2390,6 +2416,8 @@ async fn run_turn_cycle(
let mut mid_run_nudge_count: u32 = 0;
// One-shot: asked the model to close out its todos before handing back.
let mut closeout_nudged = false;
+ // The monitor set last published as `StreamEvent::Monitors`.
+ let mut shown_monitors = Vec::new();
while unlimited || turn < max_turns {
receive_steering(steering, &mut conversation_messages, run_mode).await;
@@ -2429,6 +2457,8 @@ async fn run_turn_cycle(
let _ = events.send(StreamEvent::MessagesUpdated {
messages: conversation_messages.clone(),
});
+ // A drained ping is how a match or a timeout reaches the display.
+ publish_monitors(tools, events, &mut shown_monitors);
}
// On a context-overflow error, compact the conversation and retry.
@@ -2574,7 +2604,11 @@ async fn run_turn_cycle(
// closeout nudge above records it, or the reminder would attach to
// a conversation missing the answer it follows.
if tools.background_pending() {
+ // Nothing is generated until a ping lands; the display should
+ // say so rather than keep a working badge on an idle model.
+ let _ = events.send(StreamEvent::Parked);
tools.await_background().await;
+ publish_monitors(tools, events, &mut shown_monitors);
// Re-checked rather than assumed: the wait also returns when
// there is nothing left to wait for (a cancelled run drops its
// queued pings), and resuming on that would spend a turn asking
@@ -2779,6 +2813,7 @@ async fn run_turn_cycle(
// Results are matched to calls by id, so appending the failed calls
// after the executed ones keeps the protocol intact.
tool_results.append(&mut error_outcomes);
+ publish_monitors(tools, events, &mut shown_monitors);
// Standard OpenAI tool protocol: each result is a `role: "tool"` message
// carrying its `tool_call_id` (see note above the assistant push -- the
@@ -4140,6 +4175,19 @@ mod tests {
async fn await_background(&self) {
*self.armed.lock().unwrap() = true;
}
+ fn monitor_snapshot(
+ &self,
+ ) -> Vec<tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot> {
+ if *self.delivered.lock().unwrap() {
+ return Vec::new();
+ }
+ 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()],
+ }]
+ }
}
/// A monitor match is delivered in both registers: the model gets the
@@ -4189,6 +4237,61 @@ mod tests {
assert!(saw_notice, "the headline must be emitted as a Notice event");
}
+ /// The display learns about a park and about the monitor set from the
+ /// stream: `Parked` before the wait, the live set once it returns, and the
+ /// emptied set when the delivered ping retires the monitor.
+ #[tokio::test]
+ async fn a_parked_run_publishes_parked_and_its_monitor_set() {
+ let (tx, mut rx) = mpsc::unbounded_channel();
+ let model = MockModel::new(vec![final_answer("watching"), final_answer("reacted")]);
+ let tool = HeadlinedTool {
+ armed: StdMutex::new(false),
+ delivered: StdMutex::new(false),
+ };
+ let mut budget = SessionBudget::new(None);
+ run_turn_cycle(
+ &tx,
+ &json!({}),
+ "m",
+ &[],
+ vec![json!({ "role": "user", "content": "watch the build" })],
+ 8,
+ &mut budget,
+ &model,
+ &tool,
+ crate::core::agent::plan::RunMode::Normal,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let mut events = Vec::new();
+ while let Ok(event) = rx.try_recv() {
+ events.push(event);
+ }
+ let parked = events
+ .iter()
+ .position(|e| matches!(e, StreamEvent::Parked))
+ .expect("Parked before the wait");
+ let live = events
+ .iter()
+ .position(|e| matches!(e, StreamEvent::Monitors { monitors } if monitors.len() == 1))
+ .expect("the live set after the wait");
+ let notice = events
+ .iter()
+ .position(|e| matches!(e, StreamEvent::Notice { .. }))
+ .expect("the match headline");
+ let retired = events
+ .iter()
+ .position(|e| matches!(e, StreamEvent::Monitors { monitors } if monitors.is_empty()))
+ .expect("the emptied set at delivery");
+ assert!(
+ parked < live && live < notice && notice < retired,
+ "{events:?}"
+ );
+ }
+
struct FixedTool {
content: String,
}
diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rs
index 4b3be776c..65f931bfa 100644
--- a/src-tauri/src/core/agent/subagent.rs
+++ b/src-tauri/src/core/agent/subagent.rs
@@ -563,7 +563,8 @@ fn resolve_dispatch(
/// Child stream events are folded into the parent's own stream, except the
/// child's terminal `Done`/`Error`: the parent must not see the child terminate
/// its stream. Dispatch turns the child's result into a synthetic tool result
-/// instead, bracketed by `SubagentStart`/`SubagentEnd`.
+/// instead, bracketed by `SubagentStart`/`SubagentEnd`. A child's monitor set
+/// and its parked state describe the child alone, so they stay with it too.
fn forward_to_parent(ev: &crate::core::agent::events::StreamEvent) -> bool {
use crate::core::agent::events::StreamEvent;
!matches!(
@@ -571,6 +572,8 @@ fn forward_to_parent(ev: &crate::core::agent::events::StreamEvent) -> bool {
StreamEvent::Done { .. }
| StreamEvent::Error { .. }
| StreamEvent::MessagesUpdated { .. }
+ | StreamEvent::Monitors { .. }
+ | StreamEvent::Parked
)
}
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index 075d71a98..76c5f5c12 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -1387,6 +1387,12 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {
StreamEvent::Notice { text } => {
eprintln!("\x1b[2m[notice] {text}\x1b[0m")
}
+ // The snapshot backs a live panel the headless printer has no room
+ // for; `Notice` already reports each match as it lands.
+ StreamEvent::Monitors { .. } => {}
+ StreamEvent::Parked => {
+ eprintln!("\x1b[2m[parked] waiting on background work\x1b[0m")
+ }
StreamEvent::Subagent { name, event, .. } => {
if let StreamEvent::ToolCall { name: tool, args, .. } = *event {
eprintln!(
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index d5d8c35ca..d96fb8342 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -52,6 +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::workspace;
/// Mouse tracking, hand-rolled instead of crossterm's `EnableMouseCapture`,
@@ -1951,6 +1952,14 @@ 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.
+ monitors: Vec<MonitorSnapshot>,
+ /// 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]`.
+ parked: bool,
/// Committed finished-subagent summary rows, expandable to their full
/// tool-call list via Ctrl-O (parallel to `groups`/`reasoning_blocks`).
subagent_blocks: Vec<SubagentBlock>,
@@ -2401,6 +2410,8 @@ impl App {
should_quit: false,
exit_armed: false,
subagents: Vec::new(),
+ monitors: Vec::new(),
+ parked: false,
subagent_blocks: Vec::new(),
awaiting: Vec::new(),
starting: Vec::new(),
@@ -2827,11 +2838,15 @@ impl App {
/// run -- a stranded block spins in the dock on an idle session -- but a
/// child that did work still earns its summary row, so the calls it made are
/// accounted for rather than vanishing with the panel.
- fn close_live_subagents(&mut self) {
+ fn close_live_background(&mut self) {
for panel in std::mem::take(&mut self.subagents) {
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();
+ self.parked = false;
}
/// The live shell panel for `group`'s newest unresolved *command*, or no rows
@@ -4543,6 +4558,8 @@ impl App {
}
self.starting.clear();
self.turn = (index, max);
+ // A new turn means a ping resumed the run.
+ self.parked = false;
}
StreamEvent::ToolCallStarted { id, name } => {
// Commit buffered prose/reasoning so it renders above the
@@ -4845,6 +4862,8 @@ impl App {
self.flush_assistant();
self.note(&text);
}
+ StreamEvent::Monitors { monitors } => self.monitors = monitors,
+ StreamEvent::Parked => self.parked = true,
StreamEvent::Subagent {
run_id,
name,
@@ -5018,7 +5037,7 @@ impl App {
// Children cannot outlive the run that dispatched them: their events
// arrive on its stream. Any panel still open here never got its own
// `SubagentEnd`.
- self.close_live_subagents();
+ self.close_live_background();
// Capture the turn's reasoning before `take_answer` flushes it: native
// reasoning lives in `reasoning_segs` until the flush, and inline
// ` thinking` blocks are folded into the buffer. Preserved so the
@@ -5142,7 +5161,7 @@ impl App {
fn on_error(&mut self, code: String, message: String) {
self.abort_tool_rows();
- self.close_live_subagents();
+ self.close_live_background();
self.flush_assistant();
self.status = Status::Idle;
self.run_started = None;
@@ -5283,7 +5302,7 @@ impl App {
// snapshot readiness); otherwise the loop starts it once ready and the
// cancel is silently undone.
self.want_start = false;
- self.close_live_subagents();
+ self.close_live_background();
self.detail = "cancelled".to_string();
self.scrollback = 0;
self.system(Level::Warn, "cancelled");
@@ -15880,6 +15899,15 @@ fn header_spans(app: &App) -> Vec<Span<'static>> {
(kind.label().to_string(), Style::new().magenta().bold())
} else if app.status == Status::Idle {
("ready".to_string(), Style::new().green())
+ } else if app.parked {
+ // The model is done and the loop waits on background work; a
+ // `[working]` badge over an idle model would misreport it.
+ let label = if app.monitors.is_empty() {
+ "waiting"
+ } else {
+ "watching"
+ };
+ (label.to_string(), Style::new().cyan())
} else if !app.show_reasoning {
// Reasoning folding is on: show the live thought state in place of the
// generic 'working'. [thinking] while a block streams; [thought for
@@ -16175,35 +16203,128 @@ fn status_panel(app: &mut App, width: u16, rows: usize) -> Vec<Line<'static>> {
// known (configured, catalog, or fallback), so it is always a denominator.
let context_window = app.context_window;
let has_todos = !app.todos.is_empty() && !app.todos_expired();
- let has_agents = !app.subagents.is_empty();
- match (has_todos, has_agents) {
+ let has_activity = !app.subagents.is_empty() || !app.monitors.is_empty();
+ match (has_todos, has_activity) {
(false, false) => Vec::new(),
(true, false) => todo_column(&app.todos, width, rows),
- (false, true) => agents_column(&mut app.subagents, context_window, width, rows, frame),
+ (false, true) => activity_column(
+ &mut app.subagents,
+ &app.monitors,
+ context_window,
+ width,
+ rows,
+ frame,
+ ),
(true, true) if width < PANEL_SPLIT_MIN_WIDTH => {
// Stacked: the plan keeps its head line plus whatever is left after
- // the agents, which are the thing actually moving.
- let agents = agents_column(
+ // the activity, which is the thing actually moving.
+ let activity = activity_column(
&mut app.subagents,
+ &app.monitors,
context_window,
width,
rows.saturating_sub(1),
frame,
);
- let mut out = todo_column(&app.todos, width, rows - agents.len());
- out.extend(agents);
+ let mut out = todo_column(&app.todos, width, rows - activity.len());
+ out.extend(activity);
out
}
(true, true) => {
let left_w = (width.saturating_sub(PANEL_GUTTER)) / 2;
let right_w = width.saturating_sub(left_w + PANEL_GUTTER);
let left = todo_column(&app.todos, left_w, rows);
- let right = agents_column(&mut app.subagents, context_window, right_w, rows, frame);
+ let right = activity_column(
+ &mut app.subagents,
+ &app.monitors,
+ context_window,
+ right_w,
+ rows,
+ frame,
+ );
join_columns(left, right, left_w)
}
}
}
+/// The right-hand panel column: the live fan-out over the live monitors.
+/// Monitors are laid out first since they are compact (one line each) and
+/// capped at half the budget; the agents take whatever they leave.
+fn activity_column(
+ panels: &mut [SubagentPanel],
+ monitors: &[MonitorSnapshot],
+ context_window: u64,
+ width: u16,
+ rows: usize,
+ frame: &str,
+) -> Vec<Line<'static>> {
+ let monitor_rows = if panels.is_empty() {
+ rows
+ } else {
+ (1 + monitors.len()).min(rows / 2)
+ };
+ let monitors = monitors_column(monitors, width, monitor_rows);
+ let mut out = agents_column(panels, context_window, width, rows - monitors.len(), frame);
+ out.extend(monitors);
+ 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.
+fn monitors_column(monitors: &[MonitorSnapshot], width: u16, rows: usize) -> Vec<Line<'static>> {
+ if monitors.is_empty() || rows == 0 {
+ return Vec::new();
+ }
+ let dim = Style::new().dark_gray();
+ let max = width.max(8) as usize;
+ let mut out = vec![Line::from(vec![
+ Span::styled("◔ ", Style::new().cyan()),
+ Span::styled(
+ pluralize("monitor", monitors.len()),
+ Style::new().cyan().bold(),
+ ),
+ ])];
+ let body = rows - 1;
+ let (shown, hidden) = if monitors.len() <= body {
+ (monitors.len(), 0)
+ } else {
+ (
+ body.saturating_sub(1),
+ monitors.len() - body.saturating_sub(1),
+ )
+ };
+ 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);
+ out.push(Line::from(vec![
+ Span::styled("◔ ", Style::new().cyan()),
+ Span::styled(
+ truncate(&label, max.saturating_sub(2 + stats.len())),
+ Style::new().cyan(),
+ ),
+ Span::styled(stats, dim),
+ ]));
+ if detail && !monitor.unmet.is_empty() {
+ let waiting = format!("waiting on {}", monitor.unmet.join(", "));
+ out.push(Line::from(vec![
+ Span::raw(" "),
+ Span::styled(truncate(&waiting, max.saturating_sub(3)), dim),
+ ]));
+ }
+ }
+ if hidden > 0 {
+ out.push(Line::from(vec![Span::styled(
+ format!(" +{hidden} more watching"),
+ dim,
+ )]));
+ }
+ out.truncate(rows);
+ out
+}
+
/// Max content rows the input box grows to before it scrolls internally.
const MAX_INPUT_ROWS: u16 = 8;
@@ -16595,6 +16716,7 @@ mod tests {
use std::sync::Arc;
use std::time::{Duration, Instant};
use tauri_plugin_agent_tools::tools::gate::PermissionDecision;
+ use tauri_plugin_agent_tools::tools::monitor::MonitorSnapshot;
use unicode_width::UnicodeWidthStr;
/// A bare key press with no modifiers.
@@ -29278,6 +29400,85 @@ mod tests {
);
}
+ fn monitor(id: &str, file: &str, met: &[&str], unmet: &[&str]) -> 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(),
+ }
+ }
+
+ /// 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.
+ #[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"]),
+ ],
+ });
+ 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}");
+
+ start_subagent(&mut app, "r0", "alpha");
+ let text = render_rows(&mut app, 100, 24).join("\n");
+ assert!(text.contains("1 agent"), "{text}");
+ assert!(text.contains("2 monitors"), "{text}");
+
+ // The set is replaced wholesale; an emptied set drops the column.
+ app.apply(StreamEvent::Monitors {
+ monitors: Vec::new(),
+ });
+ let text = render_rows(&mut app, 100, 24).join("\n");
+ assert!(!text.contains("monitor"), "{text}");
+ assert!(text.contains("1 agent"), "{text}");
+ }
+
+ /// A run parked on background work is not working: the header says
+ /// `[watching]` while monitors are up, `[waiting]` otherwise, and goes back
+ /// to `[working]` once a ping starts the next turn. Run end clears both.
+ #[test]
+ fn a_parked_run_is_watching_not_working() {
+ let mut app = test_app();
+ app.submit_user("go".into());
+ let header = |app: &mut App| render_rows(app, 100, 24)[0].clone();
+ assert!(header(&mut app).contains("[working]"));
+
+ app.apply(StreamEvent::Monitors {
+ monitors: vec![monitor("mon-1", "build.log", &[], &["ok"])],
+ });
+ app.apply(StreamEvent::Parked);
+ let text = header(&mut app);
+ assert!(text.contains("[watching]"), "{text}");
+ assert!(!text.contains("[working]"), "{text}");
+
+ app.apply(StreamEvent::Step { index: 2, max: 0 });
+ assert!(header(&mut app).contains("[working]"));
+
+ app.apply(StreamEvent::Monitors {
+ monitors: Vec::new(),
+ });
+ app.apply(StreamEvent::Parked);
+ assert!(header(&mut app).contains("[waiting]"));
+
+ app.apply(StreamEvent::Monitors {
+ monitors: vec![monitor("mon-2", "build.log", &[], &["ok"])],
+ });
+ app.on_error("upstream".into(), "gone".into());
+ assert!(app.monitors.is_empty(), "monitors die with the run");
+ assert!(!app.parked);
+ assert!(header(&mut app).contains("[ready]"));
+ }
+
/// A child's panel normally closes on its own `SubagentEnd`. A run that
/// ends without one -- an upstream error mid-fan-out, a `Done` that beats
/// the child's own event -- used to strand the block: it kept spinning in
diff --git a/web-app/src/components/left-sidebar/NavCowork.tsx b/web-app/src/components/left-sidebar/NavCowork.tsx
index 30ef8697a..feeeaa150 100644
--- a/web-app/src/components/left-sidebar/NavCowork.tsx
+++ b/web-app/src/components/left-sidebar/NavCowork.tsx
@@ -37,7 +37,11 @@ import {
MessageCircleIcon,
type MessageCircleIconHandle,
} from '@/components/animated-icon/message-circle'
-import { useCoworkSessions, type CoworkSession } from '@/hooks/useCoworkSessions'
+import {
+ startNewSession,
+ useCoworkSessions,
+ type CoworkSession,
+} from '@/hooks/useCoworkSessions'
import { useCoworkRun, useIsSessionActive } from '@/hooks/useCoworkRun'
import { memo, useCallback, useMemo, useRef, useState } from 'react'
import SkillsManagerDialog from '@/containers/dialogs/SkillsManagerDialog'
@@ -143,8 +147,7 @@ export function NavCowork() {
const goCowork = useCallback(() => navigate({ to: route.cowork }), [navigate])
const newSessionIconRef = useRef<MessageCircleIconHandle>(null)
const newSession = () => {
- useCoworkSessions.getState().createSession()
- pruneEmpty()
+ startNewSession(Object.keys(useCoworkRun.getState().runId))
goCowork()
}
const selectSession = useCallback(
diff --git a/web-app/src/components/left-sidebar/NavTabs.tsx b/web-app/src/components/left-sidebar/NavTabs.tsx
index cd2c54168..708ccef03 100644
--- a/web-app/src/components/left-sidebar/NavTabs.tsx
+++ b/web-app/src/components/left-sidebar/NavTabs.tsx
@@ -3,14 +3,22 @@ import { Handshake, HomeIcon } from 'lucide-react'
import { route, isCoworkRoute } from '@/constants/routes'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
+import { startNewSession } from '@/hooks/useCoworkSessions'
+import { useCoworkRun } from '@/hooks/useCoworkRun'
type TabItem = {
label: string
to: string
icon: typeof HomeIcon
isActive: boolean
+ onClick?: () => void
}
+// The tab is the start page, like Home: it opens a fresh session rather than
+// landing on whichever one was viewed last. Sessions are picked from the list.
+const openCoworkStart = () =>
+ startNewSession(Object.keys(useCoworkRun.getState().runId))
+
export function NavTabs() {
const { t } = useTranslation()
const { pathname } = useLocation()
@@ -24,7 +32,13 @@ export function NavTabs() {
const tabs: TabItem[] = [
{ label: t('common:home'), to: route.home, icon: HomeIcon, isActive: isHome },
- { label: t('common:cowork'), to: route.cowork, icon: Handshake, isActive: isCowork },
+ {
+ label: t('common:cowork'),
+ to: route.cowork,
+ icon: Handshake,
+ isActive: isCowork,
+ onClick: openCoworkStart,
+ },
]
return (
@@ -35,6 +49,7 @@ export function NavTabs() {
<Link
key={tab.to}
to={tab.to}
+ onClick={tab.onClick}
className={cn(
'flex flex-1 items-center justify-center gap-1.5 rounded-md px-2 py-1 text-sm font-medium transition-colors',
tab.isActive
diff --git a/web-app/src/containers/CoworkParkedNotice.tsx b/web-app/src/containers/CoworkParkedNotice.tsx
new file mode 100644
index 000000000..b196bf986
--- /dev/null
+++ b/web-app/src/containers/CoworkParkedNotice.tsx
@@ -0,0 +1,27 @@
+import { Eye, Hourglass } from 'lucide-react'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+
+/**
+ * Stands in for the "Working…" indicator while the run is parked: the model has
+ * answered and the loop is waiting on background work it started. Nothing is
+ * generating, so a spinner that says "working" would misreport an idle model.
+ * Names the monitors when any are up, since a watcher is otherwise invisible.
+ */
+export function CoworkParkedNotice({ watching }: { watching: number }) {
+ const { t } = useTranslation()
+ const Icon = watching > 0 ? Eye : Hourglass
+ return (
+ <div
+ role="status"
+ data-testid="cowork-parked-notice"
+ className="inline-flex items-center gap-2 rounded-lg border border-border/40 bg-muted/30 px-3 py-2 text-sm"
+ >
+ <Icon size={14} aria-hidden className="shrink-0 text-primary" />
+ <span className="font-medium text-foreground">
+ {watching > 0
+ ? t('common:coworkWatching', { count: watching })
+ : t('common:coworkWaitingBackground')}
+ </span>
+ </div>
+ )
+}
diff --git a/web-app/src/containers/CoworkTasksChip.tsx b/web-app/src/containers/CoworkTasksChip.tsx
index 651178194..4b98f39d6 100644
--- a/web-app/src/containers/CoworkTasksChip.tsx
+++ b/web-app/src/containers/CoworkTasksChip.tsx
@@ -7,7 +7,7 @@ import {
} from '@/components/ui/tooltip'
import { cn } from '@/lib/utils'
import { useTranslation } from '@/i18n/react-i18next-compat'
-import type { SubagentRun } from '@/types/coworkSession'
+import type { MonitorView, SubagentRun } from '@/types/coworkSession'
/**
* Opens the background-tasks rail, and stays out of the way until the agent
@@ -21,17 +21,32 @@ import type { SubagentRun } from '@/types/coworkSession'
*/
export function CoworkTasksChip({
subagents,
+ monitors = [],
open,
onToggle,
}: {
subagents: SubagentRun[]
+ /** The run's file monitors: background work like the children, so they
+ * count here too and open the same rail. */
+ monitors?: MonitorView[]
open: boolean
onToggle: () => void
}) {
const { t } = useTranslation()
- if (subagents.length === 0) return null
+ const total = subagents.length + monitors.length
+ if (total === 0) return null
- const active = subagents.filter((s) => s.status !== 'done').length
+ const activeSubagents = subagents.filter((s) => s.status !== 'done').length
+ const activeMonitors = monitors.filter((m) => m.status === 'running').length
+ const active = activeSubagents + activeMonitors
+ const label =
+ active === 0
+ ? t('common:backgroundTasks')
+ : activeMonitors === 0
+ ? t('common:subagentsRunning', { count: active })
+ : activeSubagents === 0
+ ? t('common:monitorsRunning', { count: active })
+ : t('common:backgroundRunning', { count: active })
return (
<Tooltip>
@@ -40,11 +55,7 @@ export function CoworkTasksChip({
variant="ghost"
size="xs"
aria-pressed={open}
- aria-label={
- active > 0
- ? t('common:subagentsRunning', { count: active })
- : t('common:backgroundTasks')
- }
+ aria-label={label}
onClick={onToggle}
className={cn('shrink-0', open && 'text-primary')}
>
@@ -54,15 +65,11 @@ export function CoworkTasksChip({
<Sparkles className="size-3.5 shrink-0" />
)}
<span className="font-mono tabular-nums text-muted-foreground">
- {active > 0 ? `${active}/${subagents.length}` : subagents.length}
+ {active > 0 ? `${active}/${total}` : total}
</span>
</Button>
</TooltipTrigger>
- <TooltipContent>
- {active > 0
- ? t('common:subagentsRunning', { count: active })
- : t('common:backgroundTasks')}
- </TooltipContent>
+ <TooltipContent>{label}</TooltipContent>
</Tooltip>
)
}
diff --git a/web-app/src/containers/CoworkTasksPanel.tsx b/web-app/src/containers/CoworkTasksPanel.tsx
index 2f83301e8..39ed67772 100644
--- a/web-app/src/containers/CoworkTasksPanel.tsx
+++ b/web-app/src/containers/CoworkTasksPanel.tsx
@@ -1,9 +1,13 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { useEffect, useMemo, useState } from 'react'
-import { ChevronLeft, ChevronDown, Loader2, Sparkles } from 'lucide-react'
+import { ChevronLeft, ChevronDown, Eye, Loader2, Sparkles } from 'lucide-react'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { cn, formatDuration, formatTokenCount } from '@/lib/utils'
-import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'
+import type {
+ CoworkTurn,
+ MonitorView,
+ SubagentRun,
+} from '@/types/coworkSession'
import { coworkTurnsToUIMessages } from '@/lib/coworkTurns'
import { MessageItem } from '@/containers/MessageItem'
import { useAutoScroll } from '@/hooks/useAutoScroll'
@@ -53,6 +57,43 @@ function TaskRow({ run, onSelect }: { run: SubagentRun; onSelect: () => void })
)
}
+/** One file monitor: what it watches, how far along its conditions are. */
+function MonitorRow({ monitor }: { monitor: MonitorView }) {
+ const { t } = useTranslation()
+ const running = monitor.status === 'running'
+ const total = monitor.met.length + monitor.unmet.length
+ return (
+ <div
+ data-testid="cowork-monitor-row"
+ className="flex w-full flex-col gap-1 rounded-lg border bg-main-view-fg/2 px-3 py-2.5 text-left"
+ >
+ <div className="flex items-center gap-2">
+ {running ? (
+ <Loader2 size={14} className="shrink-0 animate-spin text-accent" />
+ ) : (
+ <Eye size={14} className="shrink-0 text-main-view-fg/50" />
+ )}
+ <span className="truncate text-sm font-medium">
+ {monitor.file || 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 })}
+ {' · '}
+ {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(', ') })}
+ </span>
+ )}
+ </div>
+ )
+}
+
/** The run's trace plus its final answer, unless that answer already streamed
* as the last assistant turn — appending it again would show it twice. */
function visibleSubagentTurns(run: SubagentRun): CoworkTurn[] {
@@ -155,9 +196,13 @@ function Section({
*/
export function CoworkTasksPanel({
subagents,
+ monitors = [],
onClose,
}: {
subagents: SubagentRun[]
+ /** The run's file monitors. Transient: they die with the run, so unlike
+ * finished children they never come back from the session. */
+ monitors?: MonitorView[]
onClose: () => void
}) {
const { t } = useTranslation()
@@ -167,7 +212,9 @@ export function CoworkTasksPanel({
// Skipped while a detail view is open — that view doesn't render the
// duration text, so ticking would just re-render the mounted transcript.
const [, tick] = useState(0)
- const anyRunning = subagents.some((s) => s.status === 'running')
+ const anyRunning =
+ subagents.some((s) => s.status === 'running') ||
+ monitors.some((m) => m.status === 'running')
useEffect(() => {
if (!anyRunning || selectedRunId) return
const id = setInterval(() => tick((n) => n + 1), 1000)
@@ -202,12 +249,19 @@ export function CoworkTasksPanel({
<TaskDetail run={selected} />
) : (
<div className="flex h-full flex-col gap-4 overflow-y-auto p-3">
- {subagents.length === 0 ? (
+ {subagents.length === 0 && monitors.length === 0 ? (
<p className="px-1 py-6 text-center text-sm text-main-view-fg/50">
{t('common:noBackgroundTasks')}
</p>
) : (
<>
+ {monitors.length > 0 && (
+ <Section label={t('common:monitors')} count={monitors.length}>
+ {monitors.map((monitor) => (
+ <MonitorRow key={monitor.monitorId} monitor={monitor} />
+ ))}
+ </Section>
+ )}
{runningRuns.length > 0 && (
<Section label={t('common:running')} count={runningRuns.length}>
{runningRuns.map((run) => (
diff --git a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx
index 518fab427..3e380b6e0 100644
--- a/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx
+++ b/web-app/src/containers/__tests__/CoworkTasksChip.test.tsx
@@ -10,7 +10,7 @@ vi.mock('@/i18n/react-i18next-compat', () => ({
}))
import { CoworkTasksChip } from '../CoworkTasksChip'
-import type { SubagentRun } from '@/types/coworkSession'
+import type { MonitorView, SubagentRun } from '@/types/coworkSession'
const run = (runId: string, status: SubagentRun['status']): SubagentRun => ({
runId,
@@ -20,6 +20,15 @@ const run = (runId: string, status: SubagentRun['status']): SubagentRun => ({
turns: [],
})
+const monitor = (monitorId: string, status: MonitorView['status']): MonitorView => ({
+ monitorId,
+ file: 'build.log',
+ met: [],
+ unmet: ['ok'],
+ status,
+ startedAt: 0,
+})
+
describe('CoworkTasksChip', () => {
// Nothing dispatched is nothing to say, so the dock row stays quiet.
it('renders nothing before a subagent is dispatched', () => {
@@ -46,6 +55,36 @@ describe('CoworkTasksChip', () => {
).toBeInTheDocument()
})
+ /// A watcher is background work like a child: it counts, and it is enough
+ /// on its own to show the chip.
+ it('counts running monitors as background work', () => {
+ render(
+ <CoworkTasksChip
+ subagents={[]}
+ monitors={[monitor('mon-1', 'running'), monitor('mon-2', 'done')]}
+ open={false}
+ onToggle={vi.fn()}
+ />
+ )
+ expect(screen.getByText('1/2')).toBeInTheDocument()
+ expect(screen.getByLabelText('common:monitorsRunning 1')).toBeInTheDocument()
+ })
+
+ it('names both kinds when children and monitors run together', () => {
+ render(
+ <CoworkTasksChip
+ subagents={[run('a', 'running')]}
+ monitors={[monitor('mon-1', 'running')]}
+ open={false}
+ onToggle={vi.fn()}
+ />
+ )
+ expect(screen.getByText('2/2')).toBeInTheDocument()
+ expect(
+ screen.getByLabelText('common:backgroundRunning 2')
+ ).toBeInTheDocument()
+ })
+
it('reports the total once they have all finished', () => {
render(
<CoworkTasksChip
diff --git a/web-app/src/hooks/__tests__/useCoworkRun.test.ts b/web-app/src/hooks/__tests__/useCoworkRun.test.ts
index bb53442c4..794473d60 100644
--- a/web-app/src/hooks/__tests__/useCoworkRun.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkRun.test.ts
@@ -139,3 +139,85 @@ describe('useCoworkRun - subagent lanes', () => {
expect(runs.find((r) => r.runId === 'b')?.turns).toEqual([])
})
})
+
+describe('useCoworkRun - monitors and parking', () => {
+ beforeEach(() => {
+ useCoworkRun.setState({ monitors: {}, parked: {}, runId: {}, liveTurns: {}, subagents: {} })
+ })
+
+ const view = {
+ monitorId: 'mon-1',
+ file: 'build.log',
+ met: [],
+ unmet: ['ok', 'green'],
+ status: 'running' as const,
+ startedAt: 0,
+ }
+
+ it('tracks a monitor from start through its updates to done', () => {
+ 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'],
+ status: 'running',
+ })
+ s.updateMonitor('sid', {
+ monitorId: 'mon-1',
+ headline: 'h',
+ text: 't',
+ done: true,
+ met: ['ok', 'green'],
+ unmet: [],
+ })
+ const done = useCoworkRun.getState().monitors.sid[0]
+ expect(done.status).toBe('done')
+ expect(done.endedAt).toBeDefined()
+ })
+
+ it('an explicit stop closes the monitor with the progress it had', () => {
+ 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'],
+ })
+ })
+
+ it('a new run empties the previous monitors and 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().parked.sid).toBeUndefined()
+ })
+
+ it('setParked false clears the key rather than storing false', () => {
+ const s = useCoworkRun.getState()
+ s.setParked('sid', true)
+ s.setParked('sid', false)
+ expect(useCoworkRun.getState().parked).toEqual({})
+ })
+
+ it('finalizeRun closes running monitors and clearCodeRun drops them', () => {
+ 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().parked.sid).toBeUndefined()
+ s.clearCodeRun('sid')
+ expect(useCoworkRun.getState().monitors.sid).toBeUndefined()
+ })
+})
diff --git a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
index 35b94200d..c1888c07f 100644
--- a/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
+++ b/web-app/src/hooks/__tests__/useCoworkSessions.test.ts
@@ -8,7 +8,7 @@ vi.mock('@/lib/backendStorage', () => ({
},
}))
-import { useCoworkSessions } from '../useCoworkSessions'
+import { startNewSession, useCoworkSessions } from '../useCoworkSessions'
import type { CoworkTurn, SubagentRun } from '@/types/coworkSession'
const reset = () =>
@@ -22,6 +22,50 @@ const sub = (runId: string, name: string): SubagentRun => ({
turns: [],
})
+describe('startNewSession', () => {
+ beforeEach(reset)
+
+ /// The Cowork tab is the start page: it must not land on the session viewed
+ /// last, but it also must not pile up empties on repeated clicks.
+ it('opens a fresh session when the current one has a conversation', () => {
+ const store = useCoworkSessions.getState()
+ const used = store.createSession()
+ store.commitTurns(used, [{ role: 'user', content: 'hi' }], [], [])
+ const fresh = startNewSession([])
+ expect(fresh).not.toBe(used)
+ expect(useCoworkSessions.getState().currentId).toBe(fresh)
+ expect(useCoworkSessions.getState().sessions.map((s) => s.id)).toEqual([
+ fresh,
+ used,
+ ])
+ })
+
+ it('reuses an untouched current session', () => {
+ const empty = useCoworkSessions.getState().createSession()
+ expect(startNewSession([])).toBe(empty)
+ expect(useCoworkSessions.getState().sessions).toHaveLength(1)
+ })
+
+ it('sweeps abandoned empties but keeps one whose first run is streaming', () => {
+ const store = useCoworkSessions.getState()
+ const used = store.createSession()
+ store.commitTurns(used, [{ role: 'user', content: 'hi' }], [], [])
+ useCoworkSessions.setState((s) => ({
+ sessions: [
+ { ...s.sessions[0], id: 'abandoned', turns: [] },
+ { ...s.sessions[0], id: 'streaming', turns: [] },
+ ...s.sessions,
+ ],
+ }))
+ const fresh = startNewSession(['streaming'])
+ const ids = useCoworkSessions.getState().sessions.map((s) => s.id)
+ expect(ids).toContain(fresh)
+ expect(ids).toContain('streaming')
+ expect(ids).toContain(used)
+ expect(ids).not.toContain('abandoned')
+ })
+})
+
describe('useCoworkSessions', () => {
beforeEach(reset)
diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.ts
index 12e30bef7..8fdff6884 100644
--- a/web-app/src/hooks/useCoworkRun.ts
+++ b/web-app/src/hooks/useCoworkRun.ts
@@ -2,11 +2,13 @@ import { create } from 'zustand'
import type {
CoworkMediaPart,
CoworkTurn,
+ MonitorView,
SubagentRun,
Usage,
TodoList,
AskRequestPayload,
} from '@/types/coworkSession'
+import type { MonitorUpdate } from '@/lib/agentTools'
import { userTurn } from '@/lib/coworkTurns'
import type { ModelLoadProgress } from '@/hooks/useAppState'
@@ -142,6 +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.
+ 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.
+ parked: Record<string, boolean>
runId: Record<string, string>
// In-flight `ask` tool questions per session. A subagent's wrapped ask is
// attributed to the parent session the same way.
@@ -188,6 +196,12 @@ type CoworkRunState = {
endSubagent: (sid: string, runId: string, usage?: Usage | null) => void
routeIntoSubagent: (sid: string, runId: string, inner: StreamEvent) => void
attachSubagentOutput: (sid: string, runId: string, content: string) => void
+ startMonitor: (sid: string, view: MonitorView) => void
+ /** Advance a monitor from a Rust update; a `done` one closes it. */
+ updateMonitor: (sid: string, update: MonitorUpdate) => void
+ /** An explicit `stop`: closed with the progress it had. */
+ stopMonitor: (sid: string, monitorId: string) => void
+ setParked: (sid: string, parked: boolean) => void
setUsage: (sid: string, usage: Usage | null) => void
requestPreview: (sessionId: string, path: string) => void
clearPendingPreview: () => void
@@ -215,6 +229,8 @@ type CoworkRunState = {
export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
liveTurns: {},
subagents: {},
+ monitors: {},
+ parked: {},
runId: {},
pendingAsks: {},
usage: {},
@@ -232,6 +248,8 @@ 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]: [] },
})),
@@ -343,6 +361,47 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
},
})),
+ startMonitor: (sid, view) =>
+ set((s) => ({
+ monitors: { ...s.monitors, [sid]: [...(s.monitors[sid] ?? []), view] },
+ })),
+
+ updateMonitor: (sid, update) =>
+ set((s) => ({
+ monitors: {
+ ...s.monitors,
+ [sid]: (s.monitors[sid] ?? []).map((m) =>
+ m.monitorId === update.monitorId
+ ? {
+ ...m,
+ met: update.met,
+ unmet: update.unmet,
+ ...(update.done && m.status === 'running'
+ ? { status: 'done' as const, endedAt: Date.now() }
+ : {}),
+ }
+ : m
+ ),
+ },
+ })),
+
+ stopMonitor: (sid, monitorId) =>
+ set((s) => ({
+ monitors: {
+ ...s.monitors,
+ [sid]: (s.monitors[sid] ?? []).map((m) =>
+ m.monitorId === monitorId && m.status === 'running'
+ ? { ...m, status: 'done' as const, endedAt: Date.now() }
+ : m
+ ),
+ },
+ })),
+
+ setParked: (sid, parked) =>
+ set((s) => ({
+ parked: parked ? { ...s.parked, [sid]: true } : omitKey(s.parked, sid),
+ })),
+
setUsage: (sid, usage) =>
set((s) => (usage ? { usage: { ...s.usage, [sid]: usage } } : {})),
@@ -407,9 +466,14 @@ 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 }
},
@@ -418,6 +482,8 @@ 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),
usage: omitKey(s.usage, sid),
diff --git a/web-app/src/hooks/useCoworkSessions.ts b/web-app/src/hooks/useCoworkSessions.ts
index 9515515db..cb31bad0d 100644
--- a/web-app/src/hooks/useCoworkSessions.ts
+++ b/web-app/src/hooks/useCoworkSessions.ts
@@ -344,6 +344,18 @@ export const useCoworkSessions = create<CoworkSessionsState>()(
)
)
+/**
+ * Open the start page: a fresh session (or the untouched current one), with the
+ * empty sessions left behind swept out. `runningIds` keeps a session whose
+ * first run is still streaming its turns and so has nothing committed yet.
+ */
+export function startNewSession(runningIds: string[]): string {
+ const store = useCoworkSessions.getState()
+ const id = store.createSession()
+ store.pruneEmptySessions(runningIds)
+ return id
+}
+
/** Return the current session, creating one if none is selected. */
export function ensureCurrentSession(): string {
const { currentId, sessions, createSession } = useCoworkSessions.getState()
diff --git a/web-app/src/lib/__tests__/coworkMonitor.test.ts b/web-app/src/lib/__tests__/coworkMonitor.test.ts
index 67cddd172..80020f451 100644
--- a/web-app/src/lib/__tests__/coworkMonitor.test.ts
+++ b/web-app/src/lib/__tests__/coworkMonitor.test.ts
@@ -3,11 +3,14 @@ import type { MonitorUpdate } from '@/lib/agentTools'
import {
MONITOR_TOOL_NAME,
MonitorLane,
+ 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[] = []
@@ -35,9 +38,41 @@ const update = (over: Partial<MonitorUpdate>): MonitorUpdate => ({
headline: 'Monitor mon-1: condition "x" matched',
text: 'Monitor mon-1 condition x matched on build.log:\nhit',
done: false,
+ met: ['x'],
+ unmet: ['y'],
...over,
})
+function fakeView() {
+ const events: string[] = []
+ const views: MonitorView[] = []
+ const view: MonitorViewSink = {
+ started: (v) => {
+ events.push('started')
+ views.push(v)
+ },
+ updated: (u) => events.push(`updated:${u.monitorId}`),
+ stopped: (id) => events.push(`stopped:${id}`),
+ }
+ return { view, events, views }
+}
+
+describe('monitorSpecFromArgs', () => {
+ it('reads the file and condition names 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'] })
+ })
+
+ it('is empty for malformed arguments', () => {
+ expect(monitorSpecFromArgs(null)).toEqual({ file: '', conditions: [] })
+ })
+})
+
describe('parseMonitorId', () => {
it('extracts the id a start result names', () => {
expect(parseMonitorId(startResult('mon-3'))).toBe('mon-3')
@@ -93,6 +128,36 @@ describe('MonitorLane', () => {
})
})
+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'] })
+ 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'])
+ expect(views[0]).toMatchObject({
+ monitorId: 'mon-1',
+ file: 'build.log',
+ met: [],
+ unmet: ['x', 'y'],
+ 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: [] })
+ lane.stopped('mon-1', "ERROR: unknown or already-stopped monitor 'mon-1'")
+ expect(events).toEqual([])
+ })
+})
+
describe('monitorTool', () => {
it('keeps the contract the Rust schema advertises', () => {
expect(MONITOR_TOOL_NAME).toBe('monitor')
diff --git a/web-app/src/lib/__tests__/coworkRunner.test.ts b/web-app/src/lib/__tests__/coworkRunner.test.ts
index 65e270b96..a30987edb 100644
--- a/web-app/src/lib/__tests__/coworkRunner.test.ts
+++ b/web-app/src/lib/__tests__/coworkRunner.test.ts
@@ -176,6 +176,35 @@ describe('runTurn', () => {
expect(sent[sent.length - 2].role).toBe('assistant')
})
+ /// The park is the one stretch where nothing is generated; the display is
+ /// told when it starts and when it ends, in that order, around the wait.
+ it('brackets the park with onParked so the display can say watching', async () => {
+ const d = deps([textStep('dispatched'), textStep('reacted')])
+ const queue: string[] = []
+ let running = 1
+ const parked: boolean[] = []
+ let parkedDuringWait: boolean | null = null
+ await runTurn({
+ messages: [user('go')],
+ signal: new AbortController().signal,
+ deps: {
+ ...d,
+ inbox: {
+ take: () => queue.splice(0, queue.length),
+ pending: () => queue.length > 0 || running > 0,
+ wait: async () => {
+ parkedDuringWait = parked.at(-1) ?? null
+ queue.push('Monitor mon-1: condition matched')
+ running -= 1
+ },
+ onParked: (p) => parked.push(p),
+ },
+ },
+ })
+ expect(parkedDuringWait).toBe(true)
+ expect(parked).toEqual([true, false])
+ })
+
/// Two children finishing together take one turn: consecutive user messages
/// are rejected outright by some providers.
it('fuses pings that arrive together into one marked turn', async () => {
diff --git a/web-app/src/lib/coworkDispatch.ts b/web-app/src/lib/coworkDispatch.ts
index ee2047632..9dac0ad31 100644
--- a/web-app/src/lib/coworkDispatch.ts
+++ b/web-app/src/lib/coworkDispatch.ts
@@ -11,7 +11,11 @@ import {
TASK_TOOL_NAME,
TODO_TOOL_NAME,
} from '@/lib/coworkTools'
-import { MONITOR_TOOL_NAME, type MonitorLane } from '@/lib/coworkMonitor'
+import {
+ MONITOR_TOOL_NAME,
+ monitorSpecFromArgs,
+ type MonitorLane,
+} from '@/lib/coworkMonitor'
import type { PendingToolCall, ToolOutcome } from '@/lib/coworkRunner'
import { WEB_TOOL_NAMES, executeWebTool } from '@/lib/webSearchTool'
@@ -79,7 +83,8 @@ async function runMonitorOp(
// Cowork mounts the attached folder writable (shared-folder mode).
true
)
- if (!started.isError) monitors.started(started.output)
+ if (!started.isError)
+ monitors.started(started.output, monitorSpecFromArgs(input))
return { output: started.output, isError: started.isError }
}
if (op === 'stop') {
diff --git a/web-app/src/lib/coworkMonitor.ts b/web-app/src/lib/coworkMonitor.ts
index 058148403..1625f2d34 100644
--- a/web-app/src/lib/coworkMonitor.ts
+++ b/web-app/src/lib/coworkMonitor.ts
@@ -1,6 +1,7 @@
import { jsonSchema, type Tool } from 'ai'
import type { MonitorUpdate } from '@/lib/agentTools'
import type { SubagentNotice } from '@/lib/coworkSubagent'
+import type { MonitorView } from '@/types/coworkSession'
/**
* The `monitor` tool on the Cowork surface.
@@ -73,6 +74,35 @@ export function parseMonitorId(startResult: string): string | null {
return match ? match[1] : null
}
+/** What a `start` call asked for, as the panel shows it before any update. */
+export type MonitorSpec = { file: string; conditions: string[] }
+
+/** The watched file and condition names out of a `start` call's arguments. */
+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 }
+}
+
+/**
+ * The display's view of the run's monitors: opened on a successful start,
+ * advanced by every update, closed by an explicit stop. Optional, since a
+ * headless run has no panel to feed.
+ */
+export type MonitorViewSink = {
+ started: (view: MonitorView) => void
+ updated: (update: MonitorUpdate) => void
+ stopped: (monitorId: string) => void
+}
+
/**
* What the run's inbox needs to hear about monitors. Structurally what
* `SubagentInbox` provides, so the two kinds of background work share one
@@ -96,20 +126,32 @@ export type MonitorInbox = {
export class MonitorLane {
private open = new Set<string>()
- constructor(private readonly inbox: MonitorInbox) {}
+ constructor(
+ private readonly inbox: MonitorInbox,
+ 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. */
- started(startResult: string): void {
+ started(startResult: string, spec?: MonitorSpec): void {
const id = parseMonitorId(startResult)
if (!id) return
this.open.add(id)
this.inbox.begin()
+ this.view?.started({
+ monitorId: id,
+ file: spec?.file ?? '',
+ met: [],
+ unmet: spec?.conditions ?? [],
+ 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. */
update(update: MonitorUpdate): void {
+ this.view?.updated(update)
const notice: SubagentNotice = {
headline: update.headline,
text: update.text,
@@ -126,6 +168,7 @@ export class MonitorLane {
stopped(monitorId: string, stopResult: string): void {
if (!stopResult.startsWith('ERROR') && this.open.delete(monitorId)) {
this.inbox.abandon()
+ this.view?.stopped(monitorId)
}
}
}
diff --git a/web-app/src/lib/coworkRunner.ts b/web-app/src/lib/coworkRunner.ts
index 9937dc197..98b8e74b9 100644
--- a/web-app/src/lib/coworkRunner.ts
+++ b/web-app/src/lib/coworkRunner.ts
@@ -366,6 +366,10 @@ export type RunDeps = {
take: () => string[]
pending: () => boolean
wait: () => Promise<void>
+ /** Brackets the park: `true` as the wait begins, `false` when it ends
+ * (a ping, or the abort). Nothing is generated in between, so a display
+ * can say "watching" rather than "working". */
+ onParked?: (parked: boolean) => void
}
}
@@ -582,7 +586,12 @@ export async function runTurn(opts: {
// the next step resume the conversation. Re-checked after the wait, which
// also returns on cancellation.
if (deps.inbox?.pending()) {
- await deps.inbox.wait()
+ deps.inbox.onParked?.(true)
+ try {
+ await deps.inbox.wait()
+ } finally {
+ deps.inbox.onParked?.(false)
+ }
if (signal.aborted) {
return {
messages,
diff --git a/web-app/src/locales/en/common.json b/web-app/src/locales/en/common.json
index e6d0114cb..37d171250 100644
--- a/web-app/src/locales/en/common.json
+++ b/web-app/src/locales/en/common.json
@@ -643,6 +643,16 @@
"backgroundTasks": "Background tasks",
"subagentsRunning_one": "{{count}} subagent running",
"subagentsRunning_other": "{{count}} subagents running",
+ "monitorsRunning_one": "{{count}} monitor running",
+ "monitorsRunning_other": "{{count}} monitors running",
+ "backgroundRunning_one": "{{count}} background task running",
+ "backgroundRunning_other": "{{count}} background tasks running",
+ "monitors": "Monitors",
+ "monitorConditionsMet": "{{met}}/{{total}} conditions met",
+ "monitorWaitingOn": "Waiting on {{names}}",
+ "coworkWatching_one": "Watching {{count}} monitor…",
+ "coworkWatching_other": "Watching {{count}} monitors…",
+ "coworkWaitingBackground": "Waiting on background tasks…",
"noBackgroundTasks": "No background tasks yet.",
"running": "Running",
"queued": "Queued",
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index 6d9c25a0e..063e0ce09 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -95,6 +95,8 @@ import {
stopAgentSessionMonitors,
} from '@/lib/agentTools'
import { MonitorLane } from '@/lib/coworkMonitor'
+import { CoworkParkedNotice } from '@/containers/CoworkParkedNotice'
+import type { MonitorView } from '@/types/coworkSession'
import { useWebSearchConfig } from '@/hooks/useWebSearchConfig'
import { MAX_AGENT_STEPS } from '@/lib/coworkBudget'
import {
@@ -146,6 +148,10 @@ const MANUAL_COMPACT_CONFIG: ContextManagerConfig = {
autoCompact: true,
}
+// Stable empty set, so a session with no monitors does not re-render on every
+// store write the way a fresh `[]` from the selector would.
+const NO_MONITORS: MonitorView[] = []
+
function CoworkPage() {
const { t } = useTranslation()
const serviceHub = useServiceHub()
@@ -348,6 +354,17 @@ function CoworkPage() {
() => liveSubagents ?? session?.subagents ?? [],
[liveSubagents, session?.subagents]
)
+ // Monitors and the parked flag are run-only: a watcher dies with its run.
+ const monitors = useCoworkRun(
+ (s) => (session?.id ? s.monitors[session.id] : undefined) ?? NO_MONITORS
+ )
+ const parked = useCoworkRun((s) =>
+ session?.id ? (s.parked[session.id] ?? false) : false
+ )
+ const watchingCount = useMemo(
+ () => monitors.filter((m) => m.status === 'running').length,
+ [monitors]
+ )
const fileDiffs = useMemo(
() => collectCodeFileDiffs(displayedTurns, subagents),
[displayedTurns, subagents]
@@ -479,8 +496,13 @@ function CoworkPage() {
// 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.
- const monitors = new MonitorLane(inbox)
+ // 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),
+ })
const sink: StreamSink = {
onText: (delta) => {
@@ -580,7 +602,7 @@ function CoworkPage() {
readOnlyFolder: current?.folder ?? null,
planMode: current?.planMode ?? false,
webSearch,
- monitors,
+ monitors: monitorLane,
onTodo: async (input) => {
const result = applyTodoOp(
useCoworkSessions
@@ -784,6 +806,9 @@ function CoworkPage() {
},
pending: () => inbox.pending(),
wait: () => inbox.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),
},
},
})
@@ -1230,10 +1255,14 @@ function CoworkPage() {
// column flex, which stretches the indicator's own
// `inline-flex` box across the whole column.
<div className="flex flex-row items-center gap-2">
- <PromptProgress
- hideIdle={!awaitingModel}
- stateKey={session?.id}
- />
+ {parked ? (
+ <CoworkParkedNotice watching={watchingCount} />
+ ) : (
+ <PromptProgress
+ hideIdle={!awaitingModel}
+ stateKey={session?.id}
+ />
+ )}
</div>
)}
{stoppedBy === 'steps' && (
@@ -1346,6 +1375,7 @@ function CoworkPage() {
/>
<CoworkTasksChip
subagents={subagents}
+ monitors={monitors}
open={rail?.kind === 'tasks'}
onToggle={() =>
setRail((r) =>
@@ -1409,6 +1439,7 @@ function CoworkPage() {
{rail?.kind === 'tasks' && (
<CoworkTasksPanel
subagents={subagents}
+ monitors={monitors}
onClose={() => setRail(null)}
/>
)}
diff --git a/web-app/src/types/coworkSession.ts b/web-app/src/types/coworkSession.ts
index 80c6d4104..9e298e6e3 100644
--- a/web-app/src/types/coworkSession.ts
+++ b/web-app/src/types/coworkSession.ts
@@ -86,6 +86,20 @@ export type SubagentRun = {
usage?: Usage
}
+/**
+ * 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.
+ */
+export type MonitorView = {
+ monitorId: string
+ file: string
+ met: string[]
+ unmet: string[]
+ status: 'running' | 'done'
+ startedAt: number
+ endedAt?: number
+}
+
/** Mirrors the Rust `TodoItem`/`TodoPhase`/`TodoList` structs (todo.rs). */
export type TodoStatus = 'pending' | 'in_progress' | 'completed' | 'abandoned'