Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
fix(cowork,tui): report a subagent's outcome, without the model's instructions
Akarshan Biswasd9d2f626a564
diff --git a/src-tauri/src/core/agent/events.rs b/src-tauri/src/core/agent/events.rsindex ad81f44c2..ddd6c37ba 100644--- a/src-tauri/src/core/agent/events.rs+++ b/src-tauri/src/core/agent/events.rs@@ -92,7 +92,18 @@ pub enum StreamEvent {},/// A backgrounded subagent run finished (success or error). Pairs with the/// `SubagentStart` of the same `run_id`.- SubagentEnd { run_id: String, name: String },+ SubagentEnd {+ run_id: String,+ name: String,+ /// Why the child failed, when it did: the same reason the parent's+ /// `<SYSTEM>` completion ping carries. Carried on the event because a+ /// background child's answer never reaches a consumer -- only the model+ /// reads it -- so without this a failed run is indistinguishable from a+ /// clean one on screen. `None` for a clean finish, and for a child cut+ /// off at parent teardown, which is not its own failure.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ error: Option<String>,+ },/// A backgrounded subagent's own internal event, tagged with its run so a/// consumer can attribute it to the right child even when several run/// concurrently. `event` is a non-terminal child event (Token/Step/ToolCall/@@ -445,6 +456,7 @@ mod tests {let end = serde_json::to_value(StreamEvent::SubagentEnd {run_id: "sub-1".into(),name: "rust-reviewer".into(),+ error: None,}).unwrap();assert_eq!(diff --git a/src-tauri/src/core/agent/subagent.rs b/src-tauri/src/core/agent/subagent.rsindex 95768b0ef..4b3be776c 100644--- a/src-tauri/src/core/agent/subagent.rs+++ b/src-tauri/src/core/agent/subagent.rs@@ -751,6 +751,7 @@ impl BackgroundSubagents {let _ = entry.events.send(StreamEvent::SubagentEnd {run_id: entry.run_id,name: entry.name,+ error: None,});}self.notices.lock().unwrap().clear();@@ -880,12 +881,16 @@ async fn run_subagent(drop(child_tx);let _ = forwarder.await;- let _ = events.send(StreamEvent::SubagentEnd { run_id, name });-- match result {+ let outcome = match result {Ok(completion) => Ok(final_assistant_text(&completion)),Err(message) => Err(SubagentError::Upstream(message)),- }+ };+ let _ = events.send(StreamEvent::SubagentEnd {+ run_id,+ name,+ error: outcome.as_ref().err().map(|e| e.to_string()),+ });+ outcome}/// Resolve and start a subagent on a background task, returning its `run_id`@@ -1912,7 +1917,7 @@ mod tests {assert!(bg.inner.lock().unwrap().is_empty(), "abort_all drains the map");assert!(handle.await.unwrap_err().is_cancelled(), "child was aborted");match ev_rx.try_recv() {- Ok(crate::core::agent::events::StreamEvent::SubagentEnd { run_id, name }) => {+ Ok(crate::core::agent::events::StreamEvent::SubagentEnd { run_id, name, .. }) => {assert_eq!(run_id, "r1");assert_eq!(name, "reviewer");}diff --git a/src-tauri/src/core/cli/journal.rs b/src-tauri/src/core/cli/journal.rsindex a9d922c8f..7a178f33f 100644--- a/src-tauri/src/core/cli/journal.rs+++ b/src-tauri/src/core/cli/journal.rs@@ -52,6 +52,10 @@ pub enum DisplayEntry {/// `SubagentEnd`, which the row reports as `interrupted`.#[serde(default = "default_true")]finished: bool,+ /// Why a child that ended on its own ended badly. `None` is a clean+ /// finish; a journal written before this field existed replays as one.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ error: Option<String>,},}@@ -211,6 +215,7 @@ mod tests {name: "scout".into(),calls: vec!["Read a.txt".into()],finished: true,+ error: None,},DisplayEntry::Assistant {text: "Done.".into(),diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 303cf17cd..637b87a16 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -1380,9 +1380,10 @@ async fn print_event(ev: StreamEvent, registry: &PermissionRegistry) {StreamEvent::SubagentQueued { name, waiting, .. } => {eprintln!("\x1b[2m[subagent:{name}] queued ({waiting} waiting)\x1b[0m")}- StreamEvent::SubagentEnd { name, .. } => {- eprintln!("\x1b[2m[subagent:{name}] finished\x1b[0m")- }+ StreamEvent::SubagentEnd { name, error, .. } => match error {+ Some(e) => eprintln!("\x1b[2m[subagent:{name}] failed: {e}\x1b[0m"),+ None => eprintln!("\x1b[2m[subagent:{name}] finished\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.rsindex f26e665ac..0538b296b 100644--- a/src-tauri/src/core/cli/tui.rs+++ b/src-tauri/src/core/cli/tui.rs@@ -2203,6 +2203,19 @@ struct SubagentPanel {waiting: u32,}+/// How a closed child's summary row reads. `Failed` carries the reason the+/// parent's `<SYSTEM>` ping carries, which is otherwise the only account of it:+/// a background child reports its failure to the model, not to the screen, so a+/// row that said "finished" either way left the user reading an answer built on+/// work that never happened. `Interrupted` is the run ending out from under a+/// child, which is not the child's failure.+#[derive(Clone, PartialEq)]+enum SubagentOutcome {+ Finished,+ Failed(String),+ Interrupted,+}+/// A committed finished-subagent summary row, folded to one line but retaining/// its full tool-call list so the row can expand back to it (like a tool group).struct SubagentBlock {@@ -2768,28 +2781,38 @@ impl App {}/// Fold one finished child into a summary row, retaining its call list so- /// the row can expand back to it (like a tool group). `finished` separates a- /// clean `SubagentEnd` from a child the run ended out from under.- fn push_subagent_summary(&mut self, name: &str, calls: Vec<String>, finished: bool) {+ /// the row can expand back to it (like a tool group).+ fn push_subagent_summary(&mut self, name: &str, calls: Vec<String>, outcome: SubagentOutcome) {self.display_log.push(DisplayEntry::Subagent {name: name.to_string(),calls: calls.clone(),- finished,+ finished: !matches!(outcome, SubagentOutcome::Interrupted),+ error: match &outcome {+ SubagentOutcome::Failed(e) => Some(e.clone()),+ _ => None,+ },});let total = calls.len();let noun = if total == 1 { "call" } else { "calls" };- let verb = if finished { "finished" } else { "interrupted" };- let style = if finished {- Style::new().magenta().dim()- } else {- Style::new().yellow()+ let done = format!("({total} tool {noun})");+ let (verb, style) = match &outcome {+ SubagentOutcome::Finished => ("finished", Style::new().magenta().dim()),+ SubagentOutcome::Failed(_) => ("failed", Style::new().red()),+ SubagentOutcome::Interrupted => ("interrupted", Style::new().yellow()),+ };+ let label = match &outcome {+ SubagentOutcome::Failed(e) => format!("subagent {name} {verb} {done}: {e}"),+ _ => format!("subagent {name} {verb} {done}"),};self.gap(Kind::Tool);self.push_row(RowKind::Tool {tag: "↲".to_string(),tag_style: style,- label: format!("subagent {name} {verb} ({total} tool {noun})"),- label_style: if finished { style } else { Style::new().dim() },+ label,+ label_style: match outcome {+ SubagentOutcome::Finished => style,+ _ => Style::new().dim(),+ },reserve: TOOL_ROW_RESERVE,});if total > 0 {@@ -2806,7 +2829,7 @@ impl App {/// accounted for rather than vanishing with the panel.fn close_live_subagents(&mut self) {for panel in std::mem::take(&mut self.subagents) {- self.push_subagent_summary(&panel.name, panel.calls, false);+ self.push_subagent_summary(&panel.name, panel.calls, SubagentOutcome::Interrupted);}self.awaiting.clear();}@@ -4795,7 +4818,11 @@ impl App {waiting,});}- StreamEvent::SubagentEnd { run_id, name } => {+ StreamEvent::SubagentEnd {+ run_id,+ name,+ error,+ } => {let calls = self.subagents.iter()@@ -4804,7 +4831,11 @@ impl App {.unwrap_or_default();self.subagents.retain(|p| p.run_id != run_id);self.awaiting.retain(|(_, r, _)| r != &run_id);- self.push_subagent_summary(&name, calls, true);+ let outcome = match error {+ Some(e) => SubagentOutcome::Failed(e),+ None => SubagentOutcome::Finished,+ };+ self.push_subagent_summary(&name, calls, outcome);}StreamEvent::Subagent {run_id,@@ -13537,9 +13568,15 @@ fn replay_display_log(app: &mut App, entries: Vec<DisplayEntry>) {name,calls,finished,+ error,} => {app.finalize_tool_group();- app.push_subagent_summary(name, calls.clone(), *finished);+ let outcome = match (finished, error) {+ (_, Some(e)) => SubagentOutcome::Failed(e.clone()),+ (true, None) => SubagentOutcome::Finished,+ (false, None) => SubagentOutcome::Interrupted,+ };+ app.push_subagent_summary(name, calls.clone(), outcome);}}}@@ -16468,7 +16505,9 @@ mod tests {std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()))}use super::journal::{self, DisplayEntry};- use super::{cancel_command, next_event, RunEvent, SessionLimits, SteeringRequest};+ use super::{+ cancel_command, next_event, RunEvent, SessionLimits, SteeringRequest, SubagentOutcome,+ };use tokio::sync::mpsc;use super::{age_closed_todos, alt_scroll_restore, alt_scroll_save_off, answer_without_reasoning,@@ -17428,7 +17467,11 @@ mod tests {fn expanded_subagent_detail_wraps_instead_of_eliding() {let mut app = test_app();let long = "Executing: cargo test --no-default-features --features cli -- cli::tui::tests";- app.push_subagent_summary("reviewer", vec![long.to_string()], true);+ app.push_subagent_summary(+ "reviewer",+ vec![long.to_string()],+ SubagentOutcome::Finished,+ );let block = app.subagent_blocks.last().expect("no subagent block");let lines = block.detail_lines(50);assert!(lines.len() > 1, "detail was not wrapped: {lines:?}");@@ -21561,6 +21604,7 @@ mod tests {app.apply(StreamEvent::SubagentEnd {run_id: "sub-reviewer-1".into(),name: "reviewer".into(),+ error: None,});assert_eq!(app.awaiting.len(),@@ -23197,6 +23241,7 @@ mod tests {app.apply(StreamEvent::SubagentEnd {run_id: "r1".into(),name: "reviewer".into(),+ error: None,});// A collapsed summary row + a retained expandable block.assert_eq!(app.subagent_blocks.len(), 1);@@ -23252,6 +23297,7 @@ mod tests {app.apply(StreamEvent::SubagentEnd {run_id: "r1".into(),name: "reviewer".into(),+ error: None,});assert!(app.subagents.iter().all(|p| p.run_id != "r1"));assert!(app@@ -23260,6 +23306,72 @@ mod tests {.any(|r| row_text(r).contains("subagent reviewer finished (1 tool call)")));}+ /// A background child reports its failure to the model (the `<SYSTEM>`+ /// ping) and nowhere else, so the summary row is the user's only account of+ /// it. Saying "finished" would leave them reading an answer built on work+ /// that never happened.+ #[test]+ fn a_failed_subagent_says_so_and_names_the_reason() {+ let mut app = test_app();+ app.apply(StreamEvent::SubagentStart {+ run_id: "r1".into(),+ name: "reviewer".into(),+ task: None,+ });+ app.apply(StreamEvent::SubagentEnd {+ run_id: "r1".into(),+ name: "reviewer".into(),+ error: Some("upstream: 429 rate limited".into()),+ });+ let row = app+ .transcript+ .iter()+ .map(row_text)+ .find(|t| t.contains("subagent reviewer"))+ .expect("no summary row");+ assert!(+ row.contains("failed") && row.contains("429 rate limited"),+ "row hides the failure: {row}"+ );+ assert!(!row.contains("finished"), "row reads as a clean run: {row}");+ }++ /// The journal replays the outcome too: a resumed session must not turn a+ /// failure back into a clean finish.+ #[test]+ fn a_failed_subagent_survives_a_journal_round_trip() {+ let entry = DisplayEntry::Subagent {+ name: "reviewer".into(),+ calls: Vec::new(),+ finished: true,+ error: Some("upstream: 429 rate limited".into()),+ };+ let encoded = serde_json::to_string(&entry).unwrap();+ assert_eq!(+ serde_json::from_str::<DisplayEntry>(&encoded).unwrap(),+ entry+ );+ let mut app = test_app();+ super::replay_display_log(&mut app, vec![entry.clone()]);+ assert!(app+ .transcript+ .iter()+ .any(|r| row_text(r).contains("subagent reviewer failed")));+ // A journal written before the field existed still replays as a clean+ // finish rather than being dropped.+ let old: DisplayEntry =+ serde_json::from_str(r#"{"kind":"subagent","name":"scout","calls":[]}"#).unwrap();+ assert_eq!(+ old,+ DisplayEntry::Subagent {+ name: "scout".into(),+ calls: Vec::new(),+ finished: true,+ error: None,+ }+ );+ }+#[test]fn parent_tokens_still_render_while_subagent_active() {let mut app = test_app();@@ -26480,6 +26592,7 @@ mod tests {app.apply(StreamEvent::SubagentEnd {run_id: "r0".into(),name: "alpha".into(),+ error: None,});assert!(app.subagents.is_empty(), "live panel closed");let rows = render_rows(&mut app, 100, 24);diff --git a/web-app/src/lib/__tests__/coworkSubagent.test.ts b/web-app/src/lib/__tests__/coworkSubagent.test.tsindex de050911c..edc66d013 100644--- a/web-app/src/lib/__tests__/coworkSubagent.test.ts+++ b/web-app/src/lib/__tests__/coworkSubagent.test.ts@@ -52,15 +52,21 @@ describe('the task result and its completion ping', () => {expect(out).toContain('You will be given its answer')})- it('points the ping at the file rather than repeating the answer', () => {+ /// The row shows the headline and the model gets the instructions after it:+ /// "read that file when you need it" is addressed to the model alone.+ it('splits the fact from the instructions that follow it', () => {const out = subagentCompletionNotice({name: 'researcher',callId: 'c1',savedPath: '/tmp/subagents/r.md',output: 'the findings',})- expect(out).toContain('/tmp/subagents/r.md')- expect(out).not.toContain('the findings')+ expect(out.headline).toBe("Subagent 'researcher' (c1) finished")+ expect(out.headline).not.toContain('/tmp/')+ expect(out.text.startsWith(out.headline)).toBe(true)+ expect(out.text).toContain('/tmp/subagents/r.md')+ // The answer is on disk; repeating it here would spend the context twice.+ expect(out.text).not.toContain('the findings')})// Nothing else would carry it: with no file, the ping is the only delivery.@@ -72,11 +78,15 @@ describe('the task result and its completion ping', () => {savedPath: null,output,})- expect(out).toContain('y'.repeat(SUBAGENT_INLINE_MAX))- expect(out.length).toBeLessThan(output.length + 200)+ expect(out.text).toContain('y'.repeat(SUBAGENT_INLINE_MAX))+ expect(out.text.length).toBeLessThan(output.length + 200)+ // Still just the fact: the answer is for the model, not the transcript.+ expect(out.headline).toBe("Subagent 'researcher' (c1) finished")})- it('reports a failure as one, with no file named', () => {+ /// A failure has no instructions to strip, so both registers are the reason+ /// it failed -- which is the one thing here worth reading on screen.+ it('reports a failure as one, in both registers', () => {const out = subagentCompletionNotice({name: 'researcher',callId: 'c1',@@ -84,21 +94,24 @@ describe('the task result and its completion ping', () => {output: 'the model refused',isError: true,})- expect(out).toContain('failed: the model refused')+ expect(out.headline).toBe("Subagent 'researcher' (c1) failed: the model refused")+ expect(out.text).toBe(out.headline)})})describe('SubagentInbox', () => {+ const done = { headline: 'done', text: 'done, in full' }+it('reports work outstanding from dispatch until the ping is taken', async () => {const inbox = new SubagentInbox()expect(inbox.pending()).toBe(false)inbox.begin()expect(inbox.pending()).toBe(true)- inbox.finish('done')+ inbox.finish(done)// Still pending: the ping has been queued but not delivered, so a run that// stopped here would drop it.expect(inbox.pending()).toBe(true)- expect(inbox.take()).toEqual(['done'])+ expect(inbox.take()).toEqual([done])expect(inbox.take()).toEqual([])expect(inbox.pending()).toBe(false)})@@ -112,7 +125,7 @@ describe('SubagentInbox', () => {})await Promise.resolve()expect(woke).toBe(false)- inbox.finish('done')+ inbox.finish(done)await waitingexpect(woke).toBe(true)})diff --git a/web-app/src/lib/coworkSubagent.ts b/web-app/src/lib/coworkSubagent.tsindex 94e9b5656..330388ef8 100644--- a/web-app/src/lib/coworkSubagent.ts+++ b/web-app/src/lib/coworkSubagent.ts@@ -73,23 +73,37 @@ export function dispatchedSubagentResult(}/**- * The `<SYSTEM>` ping the parent gets when a child finishes. Port of the Rust+ * What a finished child is reported as, in the two registers it needs.+ *+ * `text` is the `<SYSTEM>` ping the model gets (port of the Rust* `completion_notice`, with one difference: with no file to point at, the answer- * itself rides along, since nothing else would carry it.+ * itself rides along, since nothing else would carry it). `headline` is the+ * transcript row -- the same fact without the instructions, which are addressed+ * to the model and read as clutter to anyone else.+ *+ * Two fields rather than one string the UI trims: the split is a fact about+ * what was written, and recovering it by cutting at the first full stop would+ * be guessing at text this module produced.*/+export type SubagentNotice = { headline: string; text: string }+export function subagentCompletionNotice(opts: {name: stringcallId: stringsavedPath: string | nulloutput: stringisError?: boolean-}): string {+}): SubagentNotice {const who = `Subagent '${opts.name}' (${opts.callId})`- if (opts.isError) return `${who} failed: ${opts.output}`- if (opts.savedPath) {- return `${who} finished. Its full answer is in ${opts.savedPath} -- read that file when you need it.`+ if (opts.isError) {+ const headline = `${who} failed: ${opts.output}`+ return { headline, text: headline }}- return `${who} finished. Its answer:\n\n${opts.output.slice(0, SUBAGENT_INLINE_MAX)}`+ const headline = `${who} finished`+ const detail = opts.savedPath+ ? `Its full answer is in ${opts.savedPath} -- read that file when you need it.`+ : `Its answer:\n\n${opts.output.slice(0, SUBAGENT_INLINE_MAX)}`+ return { headline, text: `${headline}. ${detail}` }}/**@@ -102,7 +116,7 @@ export function subagentCompletionNotice(opts: {* so `pending` can never read false in the window between the two.*/export class SubagentInbox {- private queue: string[] = []+ private queue: SubagentNotice[] = []private running = 0private waiters: Array<() => void> = []@@ -110,14 +124,14 @@ export class SubagentInbox {this.running += 1}- finish(notice: string): void {+ finish(notice: SubagentNotice): void {this.queue.push(notice)this.running -= 1this.wake()}/** Take every queued ping, oldest first. */- take(): string[] {+ take(): SubagentNotice[] {const out = this.queuethis.queue = []return outdiff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsxindex 5ef5c2446..0814056c6 100644--- a/web-app/src/routes/cowork.tsx+++ b/web-app/src/routes/cowork.tsx@@ -636,11 +636,16 @@ function CoworkPage() {// reacts to a subagent finishing has the note it is replying to// directly above it.take: () => {- const pings = inbox.take()+ const notices = inbox.take()+ // The row gets the headline; the model gets the instructions that+ // follow it, which are addressed to it alone.pushLive(- pings.map((content) => ({ role: 'system' as const, content }))+ notices.map((n) => ({+ role: 'system' as const,+ content: n.headline,+ })))- return pings+ return notices.map((n) => n.text)},pending: () => inbox.pending(),wait: () => inbox.wait(controller.signal),