YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
fix(acp): nested subagent transcripts and turn-lifecycle rendering (#5967)
Divanshu0fd1980db2da
diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.tsindex 0bb3a2608..782fe9e25 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts+++ b/apps/screenpipe-app-tauri/components/chat/standalone/hooks/use-pi-foreground-events.ts@@ -473,6 +473,7 @@ export function usePiForegroundEvents({startedAtMs: Date.now(),...(toolKind ? { kind: toolKind } : {}),...(parentToolCallId ? { parentToolCallId } : {}),+ ...(data.subagent === true ? { subagent: true } : {}),};// Add tool block (text before it is already its own block)piContentBlocksRef.current.push({ type: "tool", toolCall });diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsxindex dbef73439..9861c7a52 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/message-content.tsx@@ -457,13 +457,19 @@ function RunningToolStatus({ toolCall }: { toolCall: ToolCall }) {function ToolCallRailItem({toolCall,isLast,+ childToolCalls,onAskUserReply,}: {toolCall: ToolCall;isLast: boolean;+ // Nested tool calls (a subagent's own tools). Rendered inside this row's+ // expand so clicking the container toggles its whole subtree, rather than+ // leaving the children as always-on siblings that clutter the rail.+ childToolCalls?: ToolCall[];onAskUserReply?: (reply: string, displayLabel: string) => void | Promise<void>;}) {const [expanded, setExpanded] = useState(false);+ const hasChildren = (childToolCalls?.length ?? 0) > 0;const presentation = presentToolActivity(toolCall);const label = toolCall.isRunning ? presentation.runningLabel : presentation.completedLabel;const appName = extractAppFromToolCall(toolCall);@@ -524,6 +530,11 @@ function ToolCallRailItem({<span className="truncate flex-1 text-xs text-foreground/70 group-hover:text-foreground transition-colors duration-150">{label}</span>+ {hasChildren && !expanded && (+ <span className="flex-shrink-0 text-[11px] text-foreground/30">+ {childToolCalls!.length} {childToolCalls!.length === 1 ? "step" : "steps"}+ </span>+ )}{expanded ? (<ChevronDown className="h-3 w-3 flex-shrink-0 text-foreground/30 group-hover:text-foreground/60 transition-colors duration-150" />) : (@@ -546,14 +557,19 @@ function ToolCallRailItem({{/* Streamed output: live while running, and kept after the toolfinishes so what streamed doesn't vanish. Only for bash oncedone, since other tools already show their full result below. */}- {toolCall.progress && (toolCall.isRunning || toolCall.toolName === "bash") && (+ {toolCall.progress && (toolCall.isRunning || toolCall.toolName === "bash" || toolCall.subagent) && (<div className="mt-1 pt-1 border-t border-border/50"><pre className="whitespace-pre-wrap break-words max-h-[200px] overflow-y-auto overflow-x-hidden max-w-full text-xs font-mono text-foreground/50">{toolCall.progress}</pre></div>)}- {toolCall.result !== undefined && toolCall.toolName !== "bash" && (+ {/* A subagent launch's raw result is Claude's internal+ orchestration metadata ("Async agent launched ... never quote+ ... agentId ... output_file ..."), meant for the model, not the+ user. Its real content is the nested transcript above, so+ suppress the launch boilerplate. */}+ {toolCall.result !== undefined && toolCall.toolName !== "bash" && !toolCall.subagent && (<div className="mt-1 pt-1 border-t border-border/50"><pre className={cn("whitespace-pre-wrap break-words max-h-[300px] overflow-y-auto overflow-x-hidden max-w-full text-xs font-mono",@@ -563,6 +579,21 @@ function ToolCallRailItem({</pre></div>)}+ {/* A subagent's own tools nest inside its expand, so clicking+ the subagent row reveals or hides its whole subtree instead+ of leaving the children always on. */}+ {hasChildren && (+ <div className="mt-1">+ {childToolCalls!.map((child, j) => (+ <ToolCallRailItem+ key={toolCallRenderKey(child, j)}+ toolCall={child}+ isLast={j === childToolCalls!.length - 1}+ onAskUserReply={onAskUserReply}+ />+ ))}+ </div>+ )}</div></motion.div>)}@@ -1353,11 +1384,25 @@ function ToolCallGroup({setRunningSummary(runningLabel);return;}+ // No tool is running right now, but the turn is still marked working (the+ // model is streaming its final text, or a late agent_end hasn't cleared+ // isGenerating). The tool WORK is done, so freeze the duration at the last+ // tool's end instead of letting the wall clock run away past turn end —+ // that is the "2 min 26 sec · 7/7 done" bug. The spinner/label stay, so+ // there is no flicker between sequential tool calls; the number just stops.+ if (!hasRunningTool) {+ const settledMs = toolWorkEndedAt(toolCalls);+ const frozenMs = settledMs ? Math.max(1, settledMs - startedAtMs) : undefined;+ setRunningSummary(+ frozenMs ? `${runningLabel} · ${formatDurationParts(frozenMs)}` : runningLabel,+ );+ return;+ }const updateSummary = () => setRunningSummary(formatRunningWorkDuration(runningLabel, startedAtMs));updateSummary();const id = window.setInterval(updateSummary, 1000);return () => window.clearInterval(id);- }, [isWorking, runningLabel, startedAtMs]);+ }, [isWorking, runningLabel, startedAtMs, hasRunningTool, toolCalls]);useEffect(() => {if (isWorking) {@@ -1483,21 +1528,10 @@ function ToolCallGroup({><ToolCallRailItemtoolCall={tc}- isLast={isLastTop && children.length === 0}+ isLast={isLastTop}+ childToolCalls={children}onAskUserReply={onAskUserReply}/>- {children.length > 0 && (- <div className="ml-5">- {children.map((child, j) => (- <ToolCallRailItem- key={toolCallRenderKey(child, j)}- toolCall={child}- isLast={isLastTop && j === children.length - 1}- onAskUserReply={onAskUserReply}- />- ))}- </div>- )}</motion.div>);});diff --git a/apps/screenpipe-app-tauri/lib/acp/agents.json b/apps/screenpipe-app-tauri/lib/acp/agents.jsonindex 7eb454f12..e306715b5 100644--- a/apps/screenpipe-app-tauri/lib/acp/agents.json+++ b/apps/screenpipe-app-tauri/lib/acp/agents.json@@ -23,7 +23,7 @@"description": "Use your existing Claude Code account and configuration.","launch": {"kind": "npx",- "package": "@agentclientprotocol/[email protected]",+ "package": "@agentclientprotocol/[email protected]","args": ["--hide-claude-auth"]},"cloudRouting": {diff --git a/apps/screenpipe-app-tauri/lib/chat/tool-presentation.ts b/apps/screenpipe-app-tauri/lib/chat/tool-presentation.tsindex 91d9cf6eb..4e4964cbd 100644--- a/apps/screenpipe-app-tauri/lib/chat/tool-presentation.ts+++ b/apps/screenpipe-app-tauri/lib/chat/tool-presentation.ts@@ -462,6 +462,11 @@ export interface PresentableToolCall {kind?: string;isRunning?: boolean;isError?: boolean;+ // Set when this call is a subagent launch (Claude's Task/Agent tool). It is a+ // container for the nested transcript, so it is labeled as a subagent run+ // rather than by its `think` kind, which reads as "Thought it through".+ subagent?: boolean;+ subagentType?: string;}export interface ToolActivityPresentation {@@ -766,6 +771,23 @@ export function presentToolActivity(toolCall: PresentableToolCall): ToolActivityconst args = toolCall.args ?? {};const kind = toolCall.kind?.toLowerCase();+ // A subagent launch is a container for its nested transcript, not a step. The+ // adapter puts the task description in the title (surfaced here as toolName),+ // so use that as the real label instead of the generic "Thought it through"+ // its `think` kind would otherwise produce. Fall back to the subagent type,+ // then a plain "subagent", when there is no description.+ if (toolCall.subagent) {+ const type = toolCall.subagentType?.trim();+ const desc = toolCall.toolName?.trim();+ const title =+ desc && desc.toLowerCase() !== "task"+ ? desc+ : type+ ? `${type} subagent`+ : "subagent";+ return activity(title, title);+ }+// screenpipe MCP tools mirror the local REST endpoints — reuse the curl path.const mcpCommand = mcpScreenpipeCommand(rawName, args);if (mcpCommand) return commandActivity(mcpCommand);diff --git a/apps/screenpipe-app-tauri/lib/chat/types.ts b/apps/screenpipe-app-tauri/lib/chat/types.tsindex 224f3db40..c7a3940aa 100644--- a/apps/screenpipe-app-tauri/lib/chat/types.ts+++ b/apps/screenpipe-app-tauri/lib/chat/types.ts@@ -59,6 +59,9 @@ export interface ToolCall {endedAtMs?: number;/** Spawning Task's tool call id for subagent child calls (ACP `_meta`). */parentToolCallId?: string;+ /** This call is the launch of a subagent (Claude's Task/Agent tool), so it+ * is a container for the nested transcript rather than a step of its own. */+ subagent?: boolean;/** Agent-reported elapsed seconds from the latest progress heartbeat. */elapsedSeconds?: number;/** Subagent type from the heartbeat, e.g. "researcher". */diff --git a/apps/screenpipe-app-tauri/src-tauri/src/acp_runtime.rs b/apps/screenpipe-app-tauri/src-tauri/src/acp_runtime.rsindex 3a4455475..b0e38bc31 100644--- a/apps/screenpipe-app-tauri/src-tauri/src/acp_runtime.rs+++ b/apps/screenpipe-app-tauri/src-tauri/src/acp_runtime.rs@@ -738,17 +738,42 @@ fn resolve_windows_program_in(}#[derive(Clone)]-struct ParentOutput(Arc<Mutex<std::io::Stdout>>);+enum ParentOutput {+ Stdout(Arc<Mutex<std::io::Stdout>>),+ // A capturing sink so tests can assert the exact events handle_update /+ // close_turn_ex emit, which otherwise go straight to the parent's stdout.+ #[cfg(test)]+ Buffer(Arc<Mutex<Vec<Value>>>),+}impl ParentOutput {fn new() -> Self {- Self(Arc::new(Mutex::new(std::io::stdout())))+ Self::Stdout(Arc::new(Mutex::new(std::io::stdout())))+ }++ #[cfg(test)]+ fn buffer() -> Self {+ Self::Buffer(Arc::new(Mutex::new(Vec::new())))+ }++ #[cfg(test)]+ fn drain(&self) -> Vec<Value> {+ match self {+ Self::Buffer(events) => std::mem::take(&mut events.lock().unwrap()),+ Self::Stdout(_) => Vec::new(),+ }}fn send(&self, value: Value) {- if let Ok(mut stdout) = self.0.lock() {- let _ = writeln!(stdout, "{value}");- let _ = stdout.flush();+ match self {+ Self::Stdout(stdout) => {+ if let Ok(mut stdout) = stdout.lock() {+ let _ = writeln!(stdout, "{value}");+ let _ = stdout.flush();+ }+ }+ #[cfg(test)]+ Self::Buffer(events) => events.lock().unwrap().push(value),}}}@@ -1147,12 +1172,22 @@ impl RuntimeState {};self.close_thought_locked(&mut turn);for (tool_call_id, tool) in turn.active_tools.drain() {+ // A tool still open when the turn ends is usually one the agent left+ // running on purpose: Claude ends its turn while a background command+ // or a subagent Task keeps going. That is not a failure, so only a+ // cancel or a real error renders red; a normal end leaves a neutral+ // note instead of a false "the tool failed" card.+ let (result, is_error) = match stop_reason {+ "cancelled" => ("Cancelled", true),+ "error" => ("ACP turn ended before the tool reported completion", true),+ _ => ("Still running when the turn ended", false),+ };self.output.send(json!({"type": "tool_execution_end","toolCallId": tool_call_id,"toolName": tool_name(&tool),- "result": if stop_reason == "cancelled" { "Cancelled" } else { "ACP turn ended before the tool reported completion" },- "isError": true+ "result": result,+ "isError": is_error}));}if turn.message_open {@@ -1185,29 +1220,56 @@ impl RuntimeState {.unwrap_or_default();match kind {"agent_message_chunk" => {- self.close_thought_locked(&mut turn);- self.ensure_turn_locked(&mut turn);- if let Some(delta) = content_text(update.get("content")) {- self.output.send(json!({- "type": "message_update",- "assistantMessageEvent": { "type": "text_delta", "delta": delta }- }));+ // Subagent text rides on its launching Task via parentToolUseId;+ // attach it to that tool row as streamed output instead of+ // letting it pollute the assistant's own message.+ if let Some(parent) = parent_tool_call_id(&update) {+ if let Some(delta) = content_text(update.get("content")) {+ self.output.send(json!({+ "type": "tool_execution_progress",+ "toolCallId": parent,+ "outputDelta": delta,+ "subagentTranscript": true+ }));+ }+ } else {+ self.close_thought_locked(&mut turn);+ self.ensure_turn_locked(&mut turn);+ if let Some(delta) = content_text(update.get("content")) {+ self.output.send(json!({+ "type": "message_update",+ "assistantMessageEvent": { "type": "text_delta", "delta": delta }+ }));+ }}}"agent_thought_chunk" => {- self.ensure_turn_locked(&mut turn);- if !turn.thought_open {- turn.thought_open = true;- self.output.send(json!({- "type": "message_update",- "assistantMessageEvent": { "type": "thinking_start" }- }));- }- if let Some(delta) = content_text(update.get("content")) {- self.output.send(json!({- "type": "message_update",- "assistantMessageEvent": { "type": "thinking_delta", "delta": delta }- }));+ // Subagent thinking likewise nests under its Task row.+ if let Some(parent) = parent_tool_call_id(&update) {+ if let Some(delta) = content_text(update.get("content")) {+ self.output.send(json!({+ "type": "tool_execution_progress",+ "toolCallId": parent,+ "outputDelta": delta,+ "subagentTranscript": true,+ "thinking": true+ }));+ }+ } else {+ self.ensure_turn_locked(&mut turn);+ if !turn.thought_open {+ turn.thought_open = true;+ self.output.send(json!({+ "type": "message_update",+ "assistantMessageEvent": { "type": "thinking_start" }+ }));+ }+ if let Some(delta) = content_text(update.get("content")) {+ self.output.send(json!({+ "type": "message_update",+ "assistantMessageEvent": { "type": "thinking_delta", "delta": delta }+ }));+ }}}"plan" => {@@ -1237,11 +1299,7 @@ impl RuntimeState {"tool_call" => {self.close_thought_locked(&mut turn);self.ensure_turn_locked(&mut turn);- let id = update- .get("toolCallId")- .and_then(Value::as_str)- .map(str::to_owned)- .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ let id = tool_call_id(&update).unwrap_or_else(|| uuid::Uuid::new_v4().to_string());turn.active_tools.insert(id.clone(), update.clone());let mut start = json!({"type": "tool_execution_start",@@ -1258,6 +1316,10 @@ impl RuntimeState {if let Some(parent) = parent_tool_call_id(&update) {start["parentToolCallId"] = json!(parent);}+ // The Task/Agent call itself is the subagent container.+ if is_subagent_call(&update) {+ start["subagent"] = json!(true);+ }self.output.send(start);if update_status_finished(&update) {finish_tool(&self.output, &id, &update);@@ -1266,13 +1328,37 @@ impl RuntimeState {}"tool_call_update" => {self.ensure_turn_locked(&mut turn);- let id = update- .get("toolCallId")- .and_then(Value::as_str)- .unwrap_or_default()- .to_owned();+ let id = tool_call_id(&update).unwrap_or_default();+ // A subagent child's first surfaced event is often a+ // tool_call_update, not a tool_call — Claude Code stamps+ // parentToolUseId on the subagent's updates. Without a start the+ // chat has no row to render or group, so synthesize one from the+ // merged view and carry the parent linkage the tool_call arm+ // would have sent.+ let first_sighting = !id.is_empty() && !turn.active_tools.contains_key(&id);let merged = merge_json(turn.active_tools.get(&id), &update);turn.active_tools.insert(id.clone(), merged.clone());+ // Synthesize a start ONLY for a subagent child: it carries+ // parentToolUseId and its opening tool_call is never sent, so+ // without this it would not render. Every other agent (Cursor,+ // Copilot, Codex, ...) keeps the original pass-through — a+ // first-seen update with no start flows to the normal+ // finish/progress paths — so we never fabricate a nameless row+ // for a non-subagent tool that just streamed an update.+ if first_sighting && parent_tool_call_id(&merged).is_some() {+ let mut start = json!({+ "type": "tool_execution_start",+ "toolCallId": id,+ "toolName": tool_name(&merged),+ "kind": tool_kind(&merged),+ "args": tool_args(&merged),+ "parentToolCallId": parent_tool_call_id(&merged)+ });+ if is_subagent_call(&merged) {+ start["subagent"] = json!(true);+ }+ self.output.send(start);+ }if update_status_finished(&merged) {finish_tool(&self.output, &id, &merged);turn.active_tools.remove(&id);@@ -1281,6 +1367,11 @@ impl RuntimeState {"type": "tool_execution_progress","toolCallId": id,});+ // Carry the parent so a subagent heartbeat nests under its+ // Task row even when linkage only appears on updates.+ if let Some(parent) = parent_tool_call_id(&merged) {+ event["parentToolCallId"] = json!(parent);+ }if let (Some(event_map), Value::Object(fields)) =(event.as_object_mut(), progress){@@ -1487,6 +1578,49 @@ fn tool_content_item_text(item: &Value) -> Option<String> {}}+/// The client `_meta` that opts into nested subagent transcripts. Advertised on+/// `clientCapabilities._meta`; agents that don't know the key ignore it and keep+/// the flattened fallback.+fn subagent_transcript_capability() -> serde_json::Map<String, Value> {+ let mut meta = serde_json::Map::new();+ meta.insert("subagent-transcript".to_owned(), Value::Bool(true));+ meta+}++/// True when a tool call is the launch of a subagent, so the chat can mark it+/// as a container for the nested transcript beneath it. ACP has no standard+/// subagent flag and claude-agent-acp does not stamp `_meta.claudeCode.subagent`+/// on the wire (only `{toolName, parentToolUseId}`), so identify it by the tool+/// name: the Agent/Task tool (which the adapter maps to kind "think"). The real+/// name is in `_meta.claudeCode.toolName`, since the top-level title is the task+/// description, not the tool name. The `subagent` flag check stays for adapters+/// that start sending it.+fn is_subagent_call(update: &Value) -> bool {+ if let Some(name) = meta_tool_name(update) {+ if name.eq_ignore_ascii_case("agent") || name.eq_ignore_ascii_case("task") {+ return true;+ }+ }+ update+ .get("_meta")+ .and_then(|meta| meta.get("claudeCode"))+ .and_then(|claude| claude.get("subagent"))+ .and_then(Value::as_bool)+ .unwrap_or(false)+}++/// The tool call id, with control characters stripped. Cursor emits an id with+/// an embedded newline (`call-<uuid>-0\nfc_<...>`), and a raw control char in an+/// identifier silently breaks id-keyed matching and rendering downstream (the+/// tool start and its end no longer line up, so the row never resolves).+/// Normalizing here, at the single point every id is read, keeps start, update,+/// finish, and turn-close all agreeing on the same key.+fn tool_call_id(update: &Value) -> Option<String> {+ let raw = update.get("toolCallId").and_then(Value::as_str)?;+ let clean: String = raw.chars().filter(|c| !c.is_control()).collect();+ (!clean.is_empty()).then_some(clean)+}+/// Parent Task linkage for subagent child tool calls. Claude Code stamps/// `_meta.claudeCode.parentToolUseId` on every update a subagent produces.fn parent_tool_call_id(update: &Value) -> Option<&str> {@@ -1556,11 +1690,27 @@ fn tool_name(update: &Value) -> String {.get("title").and_then(Value::as_str).filter(|title| !title.trim().is_empty())+ // A title-less tool_call_update (a subagent or result-first tool whose+ // starting tool_call we never saw) still carries the real name here —+ // recover it before falling back to the bare kind, which the chat+ // renders as a generic "background step" with no name.+ .or_else(|| meta_tool_name(update)).or_else(|| update.get("kind").and_then(Value::as_str)).unwrap_or("tool").to_owned()}+/// The tool name Claude Code always stamps at `_meta.claudeCode.toolName`, even+/// on updates that omit the top-level `title`.+fn meta_tool_name(update: &Value) -> Option<&str> {+ update+ .get("_meta")?+ .get("claudeCode")?+ .get("toolName")?+ .as_str()+ .filter(|name| !name.trim().is_empty())+}+// The ACP tool-call `kind` category, forwarded so the desktop can label native// agent tools by kind when their title isn't a recognized tool name.fn tool_kind(update: &Value) -> Option<String> {@@ -2899,7 +3049,16 @@ async fn run_protocol(SessionConfigOptionsCapabilities::new().boolean(BooleanConfigOptionCapabilities::new()),),- ),+ )+ // Opt into nested subagent transcripts. ACP 1.2+ // has no standard for this, so it rides on _meta:+ // Claude Code then forwards a subagent's text,+ // thinking, and tool calls related to the+ // launching Task via+ // _meta.claudeCode.parentToolUseId, instead of+ // flattening (and dropping the subagent's text)+ // into the main turn.+ .meta(subagent_transcript_capability()),).client_info(Implementation::new("screenpipe", env!("CARGO_PKG_VERSION"))@@ -4031,16 +4190,260 @@ mod tests {assert_eq!(tool_progress(&json!({ "status": "in_progress" })), None);}+ fn test_state(output: &ParentOutput) -> RuntimeState {+ RuntimeState {+ output: output.clone(),+ project_dir: PathBuf::from("/tmp"),+ turn: Mutex::new(TurnState {+ prompt_in_flight: true,+ ..Default::default()+ }),+ ui_waiters: Mutex::new(HashMap::new()),+ terminals: Mutex::new(HashMap::new()),+ system_context: Mutex::new(None),+ }+ }++ fn events_of_type<'a>(events: &'a [Value], ty: &str) -> Vec<&'a Value> {+ events.iter().filter(|e| e["type"] == json!(ty)).collect()+ }++ #[test]+ fn turn_end_leaves_background_tools_running_not_failed() {+ // A tool still open at a normal end_turn is a background command or a+ // subagent the agent left running — not a failure. Only cancel/error+ // render red.+ let output = ParentOutput::buffer();+ let state = test_state(&output);+ {+ let mut turn = state.turn.lock().unwrap();+ turn.turn_open = true;+ turn.active_tools.insert(+ "bg1".into(),+ json!({ "toolCallId": "bg1", "title": "Bash", "status": "in_progress" }),+ );+ }+ state.close_turn_ex("end_turn", false);+ let ends = output.drain();+ let end = events_of_type(&ends, "tool_execution_end");+ assert_eq!(end.len(), 1);+ assert_eq!(end[0]["isError"], json!(false));+ assert_eq!(end[0]["result"], json!("Still running when the turn ended"));++ // Cancel still renders as an error card.+ let state = test_state(&output);+ {+ let mut turn = state.turn.lock().unwrap();+ turn.turn_open = true;+ turn.active_tools+ .insert("bg2".into(), json!({ "toolCallId": "bg2", "title": "Bash" }));+ }+ state.close_turn_ex("cancelled", false);+ let ends = output.drain();+ let end = events_of_type(&ends, "tool_execution_end");+ assert_eq!(end[0]["isError"], json!(true));+ assert_eq!(end[0]["result"], json!("Cancelled"));+ }++ #[test]+ fn subagent_update_without_a_start_synthesizes_a_linked_row() {+ // Claude Code surfaces subagent child activity as tool_call_updates that+ // carry parentToolUseId, often with no preceding tool_call. The runtime+ // must synthesize a start (with parent linkage) so the chat has a row to+ // group under the Task, and carry the parent on the progress heartbeat.+ let output = ParentOutput::buffer();+ let state = test_state(&output);+ state.handle_update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "child1",+ "title": "Grep",+ "kind": "search",+ "status": "in_progress",+ "_meta": { "claudeCode": {+ "parentToolUseId": "task_parent",+ "toolResponse": { "elapsedTimeSeconds": 3.0, "subagentType": "researcher" }+ } }+ }));+ let events = output.drain();++ let starts = events_of_type(&events, "tool_execution_start");+ assert_eq!(starts.len(), 1, "a start should be synthesized for the unseen child");+ assert_eq!(starts[0]["toolCallId"], json!("child1"));+ assert_eq!(starts[0]["parentToolCallId"], json!("task_parent"));++ let progress = events_of_type(&events, "tool_execution_progress");+ assert_eq!(progress.len(), 1);+ assert_eq!(progress[0]["parentToolCallId"], json!("task_parent"));+ assert_eq!(progress[0]["subagentType"], json!("researcher"));++ // A second update for the same child must NOT synthesize another start.+ state.handle_update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "child1",+ "status": "in_progress",+ "_meta": { "claudeCode": { "parentToolUseId": "task_parent",+ "toolResponse": { "elapsedTimeSeconds": 6.0 } } }+ }));+ let events = output.drain();+ assert!(events_of_type(&events, "tool_execution_start").is_empty());+ }++ #[test]+ fn non_subagent_first_seen_update_does_not_synthesize_a_row() {+ // A first-seen tool_call_update WITHOUT a subagent parent (Cursor,+ // Copilot, Codex streaming an update for a tool whose start we did not+ // get) must NOT fabricate a nameless start — that path is subagent-only,+ // so these agents keep their original behavior.+ let output = ParentOutput::buffer();+ let state = test_state(&output);+ state.handle_update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "cursor_tool_1",+ "title": "shell",+ "_meta": { "terminal_output_delta": { "data": "building...\n" } }+ }));+ let events = output.drain();+ assert!(+ events_of_type(&events, "tool_execution_start").is_empty(),+ "no start should be synthesized for a non-subagent update"+ );+ let progress = events_of_type(&events, "tool_execution_progress");+ assert_eq!(progress.len(), 1);+ assert_eq!(progress[0]["outputDelta"], json!("building...\n"));++ // A completed non-subagent first-seen update still finishes with its+ // result, exactly as before, and still synthesizes no start.+ state.handle_update(json!({+ "sessionUpdate": "tool_call_update",+ "toolCallId": "cursor_tool_2",+ "status": "completed",+ "content": [{ "type": "text", "text": "done" }]+ }));+ let events = output.drain();+ assert!(events_of_type(&events, "tool_execution_start").is_empty());+ assert_eq!(events_of_type(&events, "tool_execution_end").len(), 1);+ }++ #[test]+ fn advertises_and_detects_the_subagent_transcript_capability() {+ let meta = subagent_transcript_capability();+ assert_eq!(meta.get("subagent-transcript"), Some(&json!(true)));+ // The shipped adapter identifies the launch by tool name (Agent/Task),+ // not a subagent flag, so that is the primary detection.+ assert!(is_subagent_call(+ &json!({ "_meta": { "claudeCode": { "toolName": "Task" } } })+ ));+ assert!(is_subagent_call(+ &json!({ "_meta": { "claudeCode": { "toolName": "Agent" } } })+ ));+ assert!(!is_subagent_call(+ &json!({ "_meta": { "claudeCode": { "toolName": "Grep" } } })+ ));+ // The explicit flag still counts, for adapters that add it later.+ assert!(is_subagent_call(+ &json!({ "_meta": { "claudeCode": { "subagent": true } } })+ ));+ assert!(!is_subagent_call(&json!({ "_meta": { "claudeCode": {} } })));+ assert!(!is_subagent_call(&json!({})));+ }++ #[test]+ fn subagent_text_nests_under_its_task_not_the_main_message() {+ let output = ParentOutput::buffer();+ let state = test_state(&output);+ // Subagent text carries parentToolUseId → attach to the Task row.+ state.handle_update(json!({+ "sessionUpdate": "agent_message_chunk",+ "content": { "type": "text", "text": "searching the codebase" },+ "_meta": { "claudeCode": { "parentToolUseId": "task_1" } }+ }));+ let events = output.drain();+ let progress = events_of_type(&events, "tool_execution_progress");+ assert_eq!(progress.len(), 1);+ assert_eq!(progress[0]["toolCallId"], json!("task_1"));+ assert_eq!(progress[0]["outputDelta"], json!("searching the codebase"));+ assert_eq!(progress[0]["subagentTranscript"], json!(true));+ assert!(+ events_of_type(&events, "message_update").is_empty(),+ "subagent text must not land in the main assistant message"+ );++ // Top-level assistant text (no parent) still streams to the main message.+ state.handle_update(json!({+ "sessionUpdate": "agent_message_chunk",+ "content": { "type": "text", "text": "here is the summary" }+ }));+ let events = output.drain();+ assert!(events_of_type(&events, "message_update").iter().any(|e| {+ e["assistantMessageEvent"]["type"] == json!("text_delta")+ && e["assistantMessageEvent"]["delta"] == json!("here is the summary")+ }));+ assert!(events_of_type(&events, "tool_execution_progress").is_empty());+ }++ #[test]+ fn subagent_task_call_is_marked_as_a_container() {+ let output = ParentOutput::buffer();+ let state = test_state(&output);+ state.handle_update(json!({+ "sessionUpdate": "tool_call",+ "toolCallId": "task_1",+ "title": "Task",+ "kind": "other",+ "status": "in_progress",+ "_meta": { "claudeCode": { "subagent": true } }+ }));+ let events = output.drain();+ let starts = events_of_type(&events, "tool_execution_start");+ assert_eq!(starts.len(), 1);+ assert_eq!(starts[0]["subagent"], json!(true));+ }+#[test]fn tool_name_prefers_human_title_over_kind_category() {assert_eq!(tool_name(&json!({ "kind": "search", "title": "Grep" })),"Grep");+ // A title-less update recovers the real name from _meta.claudeCode+ // rather than collapsing to the kind category (a generic "background+ // step" in the chat).+ assert_eq!(+ tool_name(&json!({+ "kind": "search",+ "_meta": { "claudeCode": { "toolName": "Grep" } }+ })),+ "Grep"+ );+ // Title still wins over the meta name when present (it is friendlier).+ assert_eq!(+ tool_name(&json!({+ "title": "Grep 'foo'",+ "_meta": { "claudeCode": { "toolName": "Grep" } }+ })),+ "Grep 'foo'"+ );assert_eq!(tool_name(&json!({ "kind": "execute", "title": "" })), "execute");assert_eq!(tool_name(&json!({})), "tool");}+ #[test]+ fn tool_call_id_strips_embedded_control_chars() {+ // Cursor emits ids with an embedded newline (call-<uuid>-0\nfc_<...>); a+ // raw control char breaks start/end matching, so it must be stripped and+ // the two halves kept so the id stays unique.+ assert_eq!(+ tool_call_id(&json!({ "toolCallId": "call-abc-0\nfc_xyz" })).as_deref(),+ Some("call-abc-0fc_xyz")+ );+ assert_eq!(+ tool_call_id(&json!({ "toolCallId": "clean-123" })).as_deref(),+ Some("clean-123")+ );+ assert_eq!(tool_call_id(&json!({ "toolCallId": "\n\t" })), None);+ assert_eq!(tool_call_id(&json!({})), None);+ }+#[test]fn tool_kind_forwards_the_acp_category_or_none() {// Forwarded distinctly from the name so the desktop can label a native