diff --git a/cmux-tui/crates/acpmux/src/adopt_replay.rs b/cmux-tui/crates/acpmux/src/adopt_replay.rs index 57da9f516226..dd818a9a56b1 100644 --- a/cmux-tui/crates/acpmux/src/adopt_replay.rs +++ b/cmux-tui/crates/acpmux/src/adopt_replay.rs @@ -3,8 +3,9 @@ //! Adopting resumes a Claude Code or Codex conversation in a new acpmux session (`adopt.rs`). //! Claude Code's `--resume` replays nothing to the client, so the pane showed an empty chat. This //! reads the harness's own transcript (the file `adopt::find` found) into turns: each person -//! prompt and the assistant text that answered it. `Hub::replay_adopted` appends them as acpmux -//! history (`turn_started`, `user_message`, `agent_message_chunk`, `turn_end`) before the session +//! prompt, the tool calls the turn made (`adopt_tools.rs`) and the assistant text that answered +//! it. `Hub::replay_adopted` appends them as acpmux history (`turn_started`, `user_message`, +//! `tool_call` and `tool_call_update`, `agent_message_chunk`, `turn_end`) before the session //! continues, the same records a live turn leaves, so every client draws them. use std::io::{BufRead, BufReader, Seek, SeekFrom}; @@ -12,10 +13,14 @@ use std::path::Path; use serde_json::Value; -/// One past exchange: the person's prompt and the assistant's answer text. +use crate::adopt_tools::{PastTool, ToolResult}; + +/// One past exchange: the person's prompt, the tool calls it led to, in order, and the +/// assistant's answer text. #[derive(Debug, Clone, PartialEq, Eq, Default)] pub struct PastTurn { pub prompt: String, + pub tools: Vec, pub answer: String, /// When the prompt was sent and the answer last written (ms since the epoch), when recorded. pub prompt_at: Option, @@ -25,6 +30,8 @@ pub struct PastTurn { /// At most this many turns (the newest) and this much text per answer: a long chat stays cheap. const MAX_TURNS: usize = 200; const MAX_ANSWER: usize = 20_000; +/// At most this many tool calls per turn (the first). +const MAX_TOOLS: usize = 400; /// A transcript bigger than this is read for its newest part only. const MAX_BYTES: u64 = 64 << 20; @@ -45,6 +52,9 @@ pub fn read(family: &str, file: &Path) -> Vec { // Current Codex writes no event messages: from its first annotated item on (a chat begun on // an older Codex and resumed on a current one), items are the turns. let mut current = false; + // Current Codex records each finished tool call as an `item_completed` event; older Codex + // wrote `exec_command_end` and patch events, read until the first such item. + let mut tool_items = false; for (index, line) in BufReader::new(f).lines().map_while(Result::ok).enumerate() { if skip_first && index == 0 { continue; @@ -54,14 +64,22 @@ pub fn read(family: &str, file: &Path) -> Vec { match family { "codex" => { current = current || has_item_kinds(&record); - if let Some(step) = codex_step(&record) { + if let Some((tool, item)) = crate::adopt_tools::codex_tool(&record, at) { + tool_items = tool_items || item; + if item || !tool_items { + // With the turns that are being read: event messages, else items. + let into = + if current || !turns.is_empty() { &mut turns } else { &mut items }; + add(into, tool.map_or_else(Step::ToolResult, Step::Tool), at); + } + } else if let Some(step) = codex_step(&record) { add(&mut turns, step, at); } else if let Some(step) = codex_item_step(&record) { add(if current { &mut turns } else { &mut items }, step, at); } } _ => { - if let Some(step) = claude_step(&record) { + for step in claude_steps(&record, at) { add(&mut turns, step, at); } } @@ -78,17 +96,35 @@ pub fn read(family: &str, file: &Path) -> Vec { enum Step { Prompt(String), Answer(String), + Tool(PastTool), + ToolResult(ToolResult), } -/// A prompt starts a turn; an answer adds to the last one, capped at MAX_ANSWER. +/// A prompt starts a turn; an answer adds to the last one, capped at MAX_ANSWER; a tool call +/// joins the last one (once: a call recorded again replaces it), and a result settles its call. fn add(turns: &mut Vec, step: Step, at: Option) { match step { Step::Prompt(text) => turns.push(PastTurn { prompt: text, + tools: Vec::new(), answer: String::new(), prompt_at: at, answer_at: at, }), + Step::Tool(tool) => { + let Some(turn) = turns.last_mut() else { return }; + if let Some(known) = turn.tools.iter_mut().find(|t| t.id == tool.id) { + *known = tool; + } else if turn.tools.len() < MAX_TOOLS { + turn.tools.push(tool); + } + } + Step::ToolResult(result) => { + let Some(turn) = turns.last_mut() else { return }; + if let Some(tool) = turn.tools.iter_mut().rev().find(|t| t.id == result.id) { + tool.settle(&result, at); + } + } Step::Answer(text) => { let Some(turn) = turns.last_mut() else { return }; turn.answer_at = at.or(turn.answer_at); @@ -108,34 +144,50 @@ fn add(turns: &mut Vec, step: Step, at: Option) { } /// Claude Code: `{"type":"user","message":{"content":...}}` (a typed prompt: a string or text -/// blocks; tool results and meta lines are not prompts) and `{"type":"assistant",...}` text blocks. -fn claude_step(record: &Value) -> Option { +/// blocks; tool results settle their calls, and meta lines are not prompts) and +/// `{"type":"assistant",...}` text and `tool_use` blocks. +fn claude_steps(record: &Value, at: Option) -> Vec { let flag = |key: &str| record.get(key).and_then(Value::as_bool) == Some(true); if flag("isSidechain") || flag("isMeta") || flag("isCompactSummary") || !from_person(record) { - return None; + return Vec::new(); } - let content = record.pointer("/message/content")?; - match record.get("type").and_then(Value::as_str)? { - "user" => { - // A tool result is not a prompt, also beside text (as `hub::fork_at::is_prompt`). + let Some(content) = record.pointer("/message/content") else { return Vec::new() }; + match record.get("type").and_then(Value::as_str) { + // A tool result is not a prompt, also beside text (as `hub::fork_at::is_prompt`). + Some("user") if content.as_array().is_some_and(|blocks| { blocks.iter().any(|b| b.get("type").and_then(Value::as_str) == Some("tool_result")) - }) { - return None; - } - let text = text_of(content)?; - let start = text.trim_start(); - // Command and hook echoes and interruption markers are not prompts. - let echo = [" + { + crate::adopt_tools::claude_tool_results(content) + .into_iter() + .map(Step::ToolResult) + .collect() } - "assistant" => text_of(content).map(Step::Answer), - _ => None, + Some("assistant") => { + let mut steps: Vec = crate::adopt_tools::claude_tool_uses(content, at) + .into_iter() + .map(Step::Tool) + .collect(); + steps.extend(text_of(content).map(Step::Answer)); + steps + } + Some("user") => claude_prompt(content).into_iter().collect(), + _ => Vec::new(), } } +/// A Claude Code prompt: a user message's text, unless it echoes a command or a hook or marks +/// an interruption. +fn claude_prompt(content: &Value) -> Option { + let text = text_of(content)?; + let start = text.trim_start(); + let echo = ["`). diff --git a/cmux-tui/crates/acpmux/src/adopt_tools.rs b/cmux-tui/crates/acpmux/src/adopt_tools.rs new file mode 100644 index 000000000000..7228407e0744 --- /dev/null +++ b/cmux-tui/crates/acpmux/src/adopt_tools.rs @@ -0,0 +1,539 @@ +//! The tool calls of an adopted chat's past turns (hq#2569 item 3), read from the harness's own +//! transcript (`adopt_replay.rs`) as the ACP tool calls a live turn sends: a Codex command, file +//! change, MCP call or web search, and a Claude Code `tool_use` with its `tool_result`. Each is +//! the fields of its `tool_call` and of the `tool_call_update` that settles it, so the pane draws +//! a reopened turn's work as it drew it live ("Ran 3 commands", "Edited 2 files +4 -1"). +//! +//! The transcript is the record: no file is read, so an edit's before and after text are its +//! hunks' lines (context and removed, context and added), with each file's +/- counts. + +use serde_json::{Value, json}; + +/// One past tool call. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PastTool { + pub id: String, + /// The `tool_call` fields: `kind`, `title`, `rawInput`, `locations`. + pub call: Value, + /// The `tool_call_update` fields that settle it: `status`, `content`, `rawOutput`. + pub done: Value, + /// When it started and ended (ms since the epoch), when recorded. + pub started_at: Option, + pub ended_at: Option, +} + +/// A tool call's result, found after the call (Claude Code's `tool_result`, Codex's older +/// `patch_apply_end`): its `status`, and `content` unless the call already carries its own (an +/// edit's diff) and did not fail. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ToolResult { + pub id: String, + pub done: Value, +} + +impl PastTool { + /// Settles the call with `result` at `at`. + pub fn settle(&mut self, result: &ToolResult, at: Option) { + let failed = result.done["status"] == "failed"; + if let (Some(done), Some(update)) = (self.done.as_object_mut(), result.done.as_object()) { + for (key, value) in update { + if key != "content" || failed || !done.contains_key("content") { + done.insert(key.clone(), value.clone()); + } + } + } + // An edit that failed changed nothing: its files keep no +/- counts. + if failed + && let Some(changes) = + self.call.pointer_mut("/rawInput/changes").and_then(Value::as_array_mut) + { + for change in changes.iter_mut().filter_map(Value::as_object_mut) { + change.remove("additions"); + change.remove("deletions"); + } + } + self.ended_at = at.or(self.ended_at); + } +} + +/// The most of a call's output kept, and the most of one side of an edit's text. +const MAX_OUTPUT: usize = 8_000; +const MAX_DIFF_TEXT: usize = 64_000; + +fn s<'a>(v: &'a Value, key: &str) -> Option<&'a str> { + v.get(key).and_then(Value::as_str) +} + +/// `text` cut to at most `max` bytes, on a character boundary. +fn capped(text: &str, max: usize) -> String { + let mut cut = text.len().min(max); + while !text.is_char_boundary(cut) { + cut -= 1; + } + text[..cut].to_owned() +} + +fn text_content(text: &str) -> Value { + json!({"type": "content", "content": {"type": "text", "text": capped(text, MAX_OUTPUT)}}) +} + +fn file_name(path: &str) -> &str { + path.rsplit('/').find(|part| !part.is_empty()).unwrap_or(path) +} + +fn first_line(text: &str) -> String { + text.lines().next().unwrap_or("").chars().take(160).collect() +} + +/// A Codex duration (`{secs, nanos}`) in ms. +fn duration_ms(value: Option<&Value>) -> Option { + let value = value?; + let secs = value.get("secs").and_then(Value::as_u64)?; + let nanos = value.get("nanos").and_then(Value::as_u64).unwrap_or(0); + Some(secs.saturating_mul(1000).saturating_add(nanos / 1_000_000)) +} + +/// A Codex item status as an ACP one. +fn status(item: &Value) -> &'static str { + match s(item, "status") { + Some("failed" | "declined" | "interrupted") => "failed", + _ => "completed", + } +} + +/// The script a shell wrapper runs (`["/bin/zsh", "-lc", "git status"]` is `git status`), else +/// the command line as it reads. +fn shell_command(command: &Value) -> Option { + if let Some(line) = command.as_str() { + return Some(line.to_owned()); + } + let argv: Vec<&str> = command.as_array()?.iter().filter_map(Value::as_str).collect(); + if let [program, flag, script] = argv.as_slice() { + let shell = matches!(file_name(program), "sh" | "bash" | "zsh" | "dash" | "fish"); + if shell && matches!(*flag, "-c" | "-lc") { + return Some((*script).to_owned()); + } + } + (!argv.is_empty()).then(|| argv.join(" ")) +} + +/// A Codex command (`CommandExecution`, or an older `exec_command_end`): one read is a read, +/// one search or listing a search, anything else a command, as cmux-codex-acp draws them live. +fn codex_command(id: &str, item: &Value, at: Option) -> Option { + let script = shell_command(item.get("command")?)?; + let cwd = s(item, "cwd").map(|cwd| cwd.strip_prefix("file://").unwrap_or(cwd)); + let actions: Vec<&Value> = + item.get("parsed_cmd").and_then(Value::as_array).into_iter().flatten().collect(); + let path = actions.first().and_then(|a| s(a, "path")).map(str::to_owned); + let (kind, title) = match actions.as_slice() { + [a] if s(a, "type") == Some("read") => { + ("read", format!("Read {}", s(a, "name").or(path.as_deref()).unwrap_or(&script))) + } + [a] if s(a, "type") == Some("search") => { + ("search", s(a, "query").map_or_else(|| first_line(&script), |q| format!("Search {q}"))) + } + [a] if s(a, "type") == Some("list_files") => { + ("search", format!("List {}", path.as_deref().unwrap_or("."))) + } + _ => ("execute", first_line(&script)), + }; + let mut call = + json!({"kind": kind, "title": title, "rawInput": {"command": script, "cwd": cwd}}); + if kind != "execute" + && let Some(path) = path + { + call["locations"] = json!([{"path": path}]); + } + let output = ["aggregated_output", "formatted_output", "stdout"] + .iter() + .find_map(|key| s(item, key)) + .unwrap_or(""); + let exit_code = item.get("exit_code").and_then(Value::as_i64); + let took = duration_ms(item.get("duration")); + let failed = status(item) == "failed" || exit_code.is_some_and(|code| code != 0); + let mut done = json!({ + "status": if failed { "failed" } else { "completed" }, + "rawOutput": {"exit_code": exit_code, "duration_ms": took}, + }); + if !output.is_empty() { + done["content"] = json!([text_content(output)]); + } + Some(PastTool { + id: id.to_owned(), + call, + done, + started_at: at.map(|end| end.saturating_sub(took.unwrap_or(0))), + ended_at: at, + }) +} + +/// One file of a change: `add`, `update` or `delete`, its text (an added or deleted file's +/// content, an update's unified diff) and where a move put it. +struct Change { + path: String, + kind: String, + text: String, + move_path: Option, +} + +/// A change's files: current Codex's `{path: {type, unified_diff|content, move_path}}`, older +/// Codex's `{path: {"update": {unified_diff, move_path}}}`, or app-server's `[{path, kind, diff}]`. +fn changes(value: &Value) -> Vec { + let text = |v: &Value| { + ["unified_diff", "content", "diff"].iter().find_map(|k| s(v, k)).unwrap_or("").to_owned() + }; + let move_path = |v: &Value| s(v, "move_path").map(str::to_owned); + if let Some(list) = value.as_array() { + return list + .iter() + .filter_map(|c| { + let kind = c.pointer("/kind/type").and_then(Value::as_str).unwrap_or("update"); + Some(Change { + path: s(c, "path")?.to_owned(), + kind: kind.to_owned(), + text: text(c), + move_path: c + .pointer("/kind/move_path") + .and_then(Value::as_str) + .map(str::to_owned), + }) + }) + .collect(); + } + let Some(map) = value.as_object() else { return Vec::new() }; + map.iter() + .map(|(path, c)| { + let (kind, body) = match s(c, "type") { + Some(kind) => (kind.to_owned(), c), + None => match c.as_object().and_then(|o| o.iter().next()) { + Some((kind, body)) => (kind.clone(), body), + None => ("update".to_owned(), c), + }, + }; + Change { path: path.clone(), kind, text: text(body), move_path: move_path(body) } + }) + .collect() +} + +/// One hunk of a unified diff: its old start line, and the lines it expects and leaves. +struct Hunk { + old_start: u64, + old: Vec, + new: Vec, + additions: u64, + deletions: u64, +} + +fn hunks(diff: &str) -> Vec { + let mut out: Vec = Vec::new(); + for line in diff.strip_suffix('\n').unwrap_or(diff).split('\n') { + let header = if line == "@@" { Some("") } else { line.strip_prefix("@@ ") }; + if let Some(rest) = header { + let old_start = rest + .split(' ') + .find_map(|w| w.strip_prefix('-')) + .and_then(|range| range.split(',').next()?.parse().ok()) + .unwrap_or(1); + out.push(Hunk { + old_start, + old: Vec::new(), + new: Vec::new(), + additions: 0, + deletions: 0, + }); + continue; + } + // File headers ("--- a", "+++ b") come before the first hunk only. + let Some(hunk) = out.last_mut() else { continue }; + match line.chars().next() { + Some('-') => { + hunk.old.push(line[1..].to_owned()); + hunk.deletions += 1; + } + Some('+') => { + hunk.new.push(line[1..].to_owned()); + hunk.additions += 1; + } + Some(' ') => { + hunk.old.push(line[1..].to_owned()); + hunk.new.push(line[1..].to_owned()); + } + // A blank context line whose leading space was trimmed. + None => { + hunk.old.push(String::new()); + hunk.new.push(String::new()); + } + // "\ No newline at end of file". + Some(_) => {} + } + } + out +} + +fn joined(lines: &[String]) -> String { + let mut text = lines.join("\n"); + if !lines.is_empty() { + text.push('\n'); + } + text +} + +/// A Codex file change (`FileChange`, or an older patch event): one edit over its files, each +/// hunk an ACP `diff` of its lines, the call's input naming each file with its +/- counts (the +/// edited-files card's numbers). A hunk too big to draw is shown as the diff's text. A hunk is +/// part of its file, not the whole of it, so its diff says so (`_meta.acpmux.fragment`): the +/// card's Undo needs whole-file texts. A change that failed (declined, or a patch that did not +/// apply) changed nothing: it keeps its files and its error, but no diffs or counts. +fn codex_file_change( + id: &str, + value: &Value, + status: &str, + error: Option<&str>, + at: Option, +) -> Option { + let files = changes(value); + if files.is_empty() { + return None; + } + let failed = status == "failed"; + let mut content = Vec::new(); + let mut locations = Vec::new(); + let mut summary = Vec::new(); + for change in &files { + let target = change.move_path.as_deref().unwrap_or(&change.path); + let (additions, deletions) = match change.kind.as_str() { + "add" => { + content.push(json!({"type": "diff", "path": target, "newText": change.text})); + locations.push(json!({"path": target})); + (change.text.lines().count() as u64, 0) + } + "delete" => { + content.push( + json!({"type": "diff", "path": target, "oldText": change.text, "newText": ""}), + ); + locations.push(json!({"path": target})); + (0, change.text.lines().count() as u64) + } + _ => { + let parts = hunks(&change.text); + if parts.is_empty() && !change.text.is_empty() { + content.push(text_content(&format!("{target}\n{}", change.text))); + } + for hunk in &parts { + content.push(json!({"type": "diff", "path": target, "oldText": joined(&hunk.old), "newText": joined(&hunk.new), "_meta": {"acpmux": {"fragment": true}}})); + } + // A location's line numbers its file's diffs: only one hunk starts there. + locations.push(match parts.as_slice() { + [one] => json!({"path": target, "line": one.old_start}), + _ => json!({"path": target}), + }); + parts.iter().fold((0, 0), |(a, d), h| (a + h.additions, d + h.deletions)) + } + }; + let mut entry = json!({"path": target, "type": change.kind}); + if !failed { + entry["additions"] = json!(additions); + entry["deletions"] = json!(deletions); + } + if change.move_path.is_some() { + entry["from"] = json!(change.path); + } + summary.push(entry); + } + // An edit too big to draw shows its files' diffs as text. + let mut content = Value::Array(content); + if failed { + content = error.map(text_content).into_iter().collect(); + } else if oversize(&content) { + content = files + .iter() + .map(|c| { + text_content(&format!("{}\n{}", c.move_path.as_deref().unwrap_or(&c.path), c.text)) + }) + .collect(); + } + let title = match files.as_slice() { + [one] => { + let verb = match one.kind.as_str() { + "add" => "Write", + "delete" => "Delete", + _ => "Edit", + }; + format!("{verb} {}", file_name(one.move_path.as_deref().unwrap_or(&one.path))) + } + many => format!("Edit {} files", many.len()), + }; + Some(PastTool { + id: id.to_owned(), + call: json!({"kind": "edit", "title": title, "locations": locations, "rawInput": {"changes": summary}}), + done: json!({"status": status, "content": content}), + started_at: at, + ended_at: at, + }) +} + +/// MCP or tool result blocks as ACP content: their text. +fn result_text(blocks: Option<&Value>) -> Vec { + match blocks { + Some(Value::String(text)) if !text.is_empty() => vec![text_content(text)], + Some(Value::Array(blocks)) => { + let text: Vec<&str> = blocks.iter().filter_map(|b| s(b, "text")).collect(); + if text.is_empty() { Vec::new() } else { vec![text_content(&text.join("\n"))] } + } + _ => Vec::new(), + } +} + +/// A Codex MCP call. +fn codex_mcp(id: &str, item: &Value, at: Option) -> PastTool { + let server = s(item, "server").unwrap_or("mcp"); + let tool = s(item, "tool").unwrap_or("tool"); + let took = duration_ms(item.get("duration")); + let failed = status(item) == "failed" + || item.pointer("/result/isError").and_then(Value::as_bool) == Some(true); + PastTool { + id: id.to_owned(), + call: json!({"kind": "other", "title": format!("{server}: {tool}"), "rawInput": item.get("arguments")}), + done: json!({ + "status": if failed { "failed" } else { "completed" }, + "content": result_text(item.pointer("/result/content")), + }), + started_at: at.map(|end| end.saturating_sub(took.unwrap_or(0))), + ended_at: at, + } +} + +/// What a Codex rollout record says a tool did, at `at`. `items`: the record is current Codex's +/// `item_completed` (`Some(true)`), or an older event (`Some(false)`); None when neither. +pub fn codex_tool(record: &Value, at: Option) -> Option<(Result, bool)> { + if s(record, "type") != Some("event_msg") { + return None; + } + let payload = record.get("payload")?; + match s(payload, "type")? { + "item_completed" => { + let item = payload.get("item")?; + let id = s(item, "id")?; + let tool = match s(item, "type")? { + "CommandExecution" => codex_command(id, item, at)?, + "FileChange" => { + let error = s(item, "stderr").filter(|t| !t.is_empty()); + codex_file_change(id, item.get("changes")?, status(item), error, at)? + } + "McpToolCall" => codex_mcp(id, item, at), + "Extension" if s(item, "kind") == Some("web.search") => { + let query = s(item, "query").unwrap_or(""); + PastTool { + id: id.to_owned(), + call: json!({"kind": "fetch", "title": if query.is_empty() { "Web search".to_owned() } else { format!("Search {query}") }, "rawInput": {"query": query}}), + done: json!({"status": status(item)}), + started_at: at, + ended_at: at, + } + } + _ => return None, + }; + Some((Ok(tool), true)) + } + "exec_command_end" => { + Some((Ok(codex_command(s(payload, "call_id")?, payload, at)?), false)) + } + "patch_apply_begin" => { + let id = s(payload, "call_id")?; + Some(( + Ok(codex_file_change(id, payload.get("changes")?, "completed", None, at)?), + false, + )) + } + "patch_apply_end" => { + let id = s(payload, "call_id")?; + let state = if payload.get("success").and_then(Value::as_bool) == Some(false) { + "failed" + } else { + "completed" + }; + let error = s(payload, "stderr").filter(|t| state == "failed" && !t.is_empty()); + if let Some(tool) = + payload.get("changes").and_then(|c| codex_file_change(id, c, state, error, at)) + { + return Some((Ok(tool), false)); + } + let mut done = json!({"status": state}); + if state == "failed" { + // The begin event's diffs never applied: the error, or nothing, replaces them. + done["content"] = error.map(text_content).into_iter().collect(); + } + Some((Err(ToolResult { id: id.to_owned(), done }), false)) + } + "mcp_tool_call_end" => { + let id = s(payload, "call_id")?; + let invocation = payload.get("invocation").cloned().unwrap_or(Value::Null); + let result = payload.get("result"); + let ok = result.and_then(|r| r.get("Ok")); + let mut item = json!({ + "server": invocation.get("server"), + "tool": invocation.get("tool"), + "arguments": invocation.get("arguments"), + "duration": payload.get("duration"), + "status": if ok.is_some() { "completed" } else { "failed" }, + }); + if let Some(ok) = ok { + item["result"] = ok.clone(); + } + Some((Ok(codex_mcp(id, &item, at)), false)) + } + _ => None, + } +} + +/// Claude Code's `tool_use` blocks in an assistant message, as the calls a live turn sends +/// (`claude_stdio::tool_call_fields`), not yet settled: a call whose result never came (a turn +/// cut off) stays failed. An edit's diffs settle it with its result; one too big to draw is +/// left out. The todo list is the turn's plan, not a call. +pub fn claude_tool_uses(content: &Value, at: Option) -> Vec { + content + .as_array() + .into_iter() + .flatten() + .filter(|b| s(b, "type") == Some("tool_use")) + .filter_map(|block| { + let id = s(block, "id")?; + let name = s(block, "name").filter(|name| *name != "TodoWrite")?; + let input = block.get("input").cloned().unwrap_or(Value::Null); + let mut call = crate::claude_stdio::tool_call_fields(name, &input); + let diffs = call.as_object_mut().and_then(|c| c.remove("content")); + let mut done = json!({"status": "failed"}); + if let Some(diffs) = diffs.filter(|d| !oversize(d)) { + done["content"] = diffs; + } + Some(PastTool { id: id.to_owned(), call, done, started_at: at, ended_at: None }) + }) + .collect() +} + +/// Whether some diff in `content` has a side too big to draw. +fn oversize(content: &Value) -> bool { + content.as_array().into_iter().flatten().any(|c| { + ["oldText", "newText"].iter().any(|k| s(c, k).is_some_and(|t| t.len() > MAX_DIFF_TEXT)) + }) +} + +/// Claude Code's `tool_result` blocks in a user message. +pub fn claude_tool_results(content: &Value) -> Vec { + content + .as_array() + .into_iter() + .flatten() + .filter(|b| s(b, "type") == Some("tool_result")) + .filter_map(|block| { + let failed = block.get("is_error").and_then(Value::as_bool) == Some(true); + Some(ToolResult { + id: s(block, "tool_use_id")?.to_owned(), + done: json!({ + "status": if failed { "failed" } else { "completed" }, + "content": result_text(block.get("content")), + }), + }) + }) + .collect() +} diff --git a/cmux-tui/crates/acpmux/src/claude_stdio/inbound.rs b/cmux-tui/crates/acpmux/src/claude_stdio/inbound.rs index bb2ed7adee8d..d8b4e837df9b 100644 --- a/cmux-tui/crates/acpmux/src/claude_stdio/inbound.rs +++ b/cmux-tui/crates/acpmux/src/claude_stdio/inbound.rs @@ -212,16 +212,10 @@ impl Translator { }; self.background_shells.lock().await.insert(id.to_owned(), shell); } - let mut call = json!({ - "sessionUpdate": "tool_call", - "toolCallId": c.get("id"), - "title": tool_title(name, &input), - "kind": tool_kind(name), - "status": "in_progress", - "rawInput": input, - "_meta": {"claude": {"tool": name}} - }); - with_edit(&mut call, name, &input); + let mut call = tool_call_fields(name, &input); + call["sessionUpdate"] = json!("tool_call"); + call["toolCallId"] = c.get("id").cloned().unwrap_or(Value::Null); + call["status"] = json!("in_progress"); if let (Some(diffs), Some(id)) = (call.get("content"), c.get("id").and_then(Value::as_str)) { @@ -859,16 +853,6 @@ impl Translator { } } -/// Adds a file edit's diff and location to its ACP tool call. -fn with_edit(call: &mut Value, name: &str, input: &Value) { - if let Some(diffs) = edit_diffs(name, input) { - call["content"] = diffs; - if let Some(locations) = tool_locations(input) { - call["locations"] = locations; - } - } -} - /// TodoWrite's `todos` as an ACP `plan` update: each item's text and status /// (pending, in_progress or completed, as ACP names them). Nil for input /// that is not a todo list. diff --git a/cmux-tui/crates/acpmux/src/claude_stdio/mod.rs b/cmux-tui/crates/acpmux/src/claude_stdio/mod.rs index 43e5598bb9c3..4dd83d4508bb 100644 --- a/cmux-tui/crates/acpmux/src/claude_stdio/mod.rs +++ b/cmux-tui/crates/acpmux/src/claude_stdio/mod.rs @@ -556,6 +556,30 @@ impl Translator { } } +/// A Claude Code `tool_use` as the fields of the ACP `tool_call` a turn sends for it (without +/// its id and status): kind, title, input, and an edit's diffs and file. A live turn +/// (`inbound.rs`) and an adopted chat's past turns (`adopt_tools.rs`) both draw calls from it. +pub(crate) fn tool_call_fields(name: &str, input: &Value) -> Value { + let mut call = json!({ + "title": tool_title(name, input), + "kind": tool_kind(name), + "rawInput": input, + "_meta": {"claude": {"tool": name}} + }); + with_edit(&mut call, name, input); + call +} + +/// Adds a file edit's diff and location to its ACP tool call. +fn with_edit(call: &mut Value, name: &str, input: &Value) { + if let Some(diffs) = edit_diffs(name, input) { + call["content"] = diffs; + if let Some(locations) = tool_locations(input) { + call["locations"] = locations; + } + } +} + fn tool_kind(name: &str) -> &'static str { match name { "Read" | "Glob" | "Grep" | "NotebookRead" => "read", diff --git a/cmux-tui/crates/acpmux/src/hub/adoption.rs b/cmux-tui/crates/acpmux/src/hub/adoption.rs index 091504c5f954..1797190a54af 100644 --- a/cmux-tui/crates/acpmux/src/hub/adoption.rs +++ b/cmux-tui/crates/acpmux/src/hub/adoption.rs @@ -435,12 +435,16 @@ impl Hub { } self.save_meta(session); let agent_sid = session.meta().agent_session_id.unwrap_or_default(); + let update = |fields: Value| json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": agent_sid, "update": fields}}); for (i, turn) in turns.iter().enumerate() { let turn_id = format!("adopted-{i}"); let prompt_id = format!("adopted-prompt-{i}"); // Each record keeps the transcript's time, so a fork through it cuts Claude's - // transcript there (`fork_at.rs`) and the turn shows its real time. - let (started, ended) = (turn.prompt_at, turn.answer_at.or(turn.prompt_at)); + // transcript there (`fork_at.rs`) and the turn shows its real time. The turn ends + // with its answer, or its last tool call when that ended later. + let started = turn.prompt_at; + let answered = turn.answer_at.or(started); + let ended = turn.tools.iter().filter_map(|t| t.ended_at).chain(answered).max(); let turn_seq = self .append_at( session, @@ -460,14 +464,35 @@ impl Hub { None, started, ); + // The turn's tool calls, before its answer, as a live turn sends them: each starts + // running and its update settles it, so the pane folds them under "Worked for". + for tool in &turn.tools { + let start = tool.started_at.or(tool.ended_at).or(started); + let mut call = tool.call.clone(); + call["sessionUpdate"] = json!("tool_call"); + call["toolCallId"] = json!(tool.id); + call["status"] = json!("in_progress"); + self.append_at(session, "in", "tool_call", update(call), None, start); + let mut done = tool.done.clone(); + done["sessionUpdate"] = json!("tool_call_update"); + done["toolCallId"] = json!(tool.id); + self.append_at( + session, + "in", + "tool_call_update", + update(done), + None, + tool.ended_at.or(start), + ); + } if !turn.answer.is_empty() { self.append_at( session, "in", "agent_message_chunk", - json!({"jsonrpc": "2.0", "method": "session/update", "params": {"sessionId": agent_sid, "update": {"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": turn.answer}}}}), + update(json!({"sessionUpdate": "agent_message_chunk", "content": {"type": "text", "text": turn.answer}})), None, - ended, + answered, ); } self.append_at( diff --git a/cmux-tui/crates/acpmux/src/lib.rs b/cmux-tui/crates/acpmux/src/lib.rs index e6e108510691..af22e4b9d6c8 100644 --- a/cmux-tui/crates/acpmux/src/lib.rs +++ b/cmux-tui/crates/acpmux/src/lib.rs @@ -15,6 +15,7 @@ pub mod adopt; pub mod adopt_live; pub mod adopt_replay; +pub mod adopt_tools; pub mod agent; pub mod agent_displays; pub mod agent_host; diff --git a/cmux-tui/crates/acpmux/tests/fixtures/codex-rollout-tool-calls.jsonl b/cmux-tui/crates/acpmux/tests/fixtures/codex-rollout-tool-calls.jsonl new file mode 100644 index 000000000000..ffacc614bae1 --- /dev/null +++ b/cmux-tui/crates/acpmux/tests/fixtures/codex-rollout-tool-calls.jsonl @@ -0,0 +1,14 @@ +{"timestamp": "2026-10-02T08:59:59.900Z", "type": "session_meta", "payload": {"id": "{ID}", "cwd": "{CWD}", "originator": "Codex Desktop", "cli_version": "0.163.0"}} +{"timestamp": "2026-10-02T08:59:59.950Z", "type": "event_msg", "payload": {"type": "task_started", "turn_id": "turn-1"}} +{"timestamp": "2026-10-02T08:59:59.980Z", "type": "response_item", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "# AGENTS.md instructions for {CWD}\n\nKeep the changelog current."}], "internal_chat_message_metadata_passthrough": {"content_item_kinds": ["agents_md.instructions"]}}} +{"timestamp": "2026-10-02T09:00:00.000Z", "type": "response_item", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Bump the version to 1.3.0 and note it in the changelog"}], "internal_chat_message_metadata_passthrough": {"content_item_kinds": ["user.text"]}}} +{"timestamp": "2026-10-02T09:00:00.010Z", "type": "event_msg", "payload": {"type": "item_completed", "thread_id": "{ID}", "turn_id": "turn-1", "item": {"type": "UserMessage", "id": "u-1", "content": [{"type": "text", "text": "Bump the version to 1.3.0 and note it in the changelog"}]}}} +{"timestamp": "2026-10-02T09:00:04.000Z", "type": "response_item", "payload": {"type": "message", "role": "assistant", "phase": "commentary", "content": [{"type": "output_text", "text": "I'll check the current version and changelog first."}]}} +{"timestamp": "2026-10-02T09:00:05.000Z", "type": "response_item", "payload": {"type": "custom_tool_call", "status": "completed", "call_id": "call-1", "name": "exec", "input": "const r = await tools.exec_command({cmd: \"git status --short\"}); text(r.output);"}} +{"timestamp": "2026-10-02T09:00:06.000Z", "type": "event_msg", "payload": {"type": "item_completed", "thread_id": "{ID}", "turn_id": "turn-1", "item": {"type": "CommandExecution", "id": "exec-1", "command": ["/bin/zsh", "-lc", "git status --short"], "cwd": "file://{CWD}", "parsed_cmd": [{"type": "unknown", "cmd": "git status --short"}], "source": "unified_exec_startup", "status": "completed", "aggregated_output": "", "exit_code": 0, "duration": {"secs": 0, "nanos": 210000000}}}} +{"timestamp": "2026-10-02T09:00:06.100Z", "type": "response_item", "payload": {"type": "custom_tool_call_output", "call_id": "call-1", "output": [{"type": "input_text", "text": "Script completed\n"}]}} +{"timestamp": "2026-10-02T09:00:09.000Z", "type": "event_msg", "payload": {"type": "item_completed", "thread_id": "{ID}", "turn_id": "turn-1", "item": {"type": "CommandExecution", "id": "exec-2", "command": ["/bin/zsh", "-lc", "grep -n '^version' Cargo.toml"], "cwd": "file://{CWD}", "parsed_cmd": [{"type": "unknown", "cmd": "grep -n '^version' Cargo.toml"}], "source": "unified_exec_startup", "status": "completed", "aggregated_output": "3:version = \"1.2.0\"\n", "exit_code": 0, "duration": {"secs": 0, "nanos": 50000000}}}} +{"timestamp": "2026-10-02T09:00:12.000Z", "type": "event_msg", "payload": {"type": "item_completed", "thread_id": "{ID}", "turn_id": "turn-1", "item": {"type": "CommandExecution", "id": "exec-3", "command": ["/bin/zsh", "-lc", "sed -n 1,8p CHANGELOG.md"], "cwd": "file://{CWD}", "parsed_cmd": [{"type": "unknown", "cmd": "sed -n 1,8p CHANGELOG.md"}], "source": "unified_exec_startup", "status": "completed", "aggregated_output": "# Changelog\n\n## 1.2.0\n- Faster startup\n", "exit_code": 0, "duration": {"secs": 0, "nanos": 40000000}}}} +{"timestamp": "2026-10-02T09:01:10.000Z", "type": "event_msg", "payload": {"type": "item_completed", "thread_id": "{ID}", "turn_id": "turn-1", "item": {"type": "FileChange", "id": "exec-4", "status": "completed", "changes": {"{CWD}/Cargo.toml": {"type": "update", "unified_diff": "@@ -1,4 +1,4 @@\n [package]\n name = \"demo\"\n-version = \"1.2.0\"\n+version = \"1.3.0\"\n edition = \"2021\"\n", "move_path": null}, "{CWD}/CHANGELOG.md": {"type": "update", "unified_diff": "@@ -1,3 +1,6 @@\n # Changelog\n \n+## 1.3.0\n+- Bump the version to 1.3.0\n+\n ## 1.2.0\n", "move_path": null}}, "stdout": "Success. Updated the following files:\nM {CWD}/Cargo.toml\nM {CWD}/CHANGELOG.md\n", "stderr": ""}}} +{"timestamp": "2026-10-02T09:01:32.000Z", "type": "response_item", "payload": {"type": "message", "role": "assistant", "phase": "final_answer", "content": [{"type": "output_text", "text": "Bumped demo to 1.3.0 and added a 1.3.0 entry to CHANGELOG.md."}]}} +{"timestamp": "2026-10-02T09:01:32.100Z", "type": "event_msg", "payload": {"type": "task_complete", "turn_id": "turn-1", "last_agent_message": "Bumped demo to 1.3.0 and added a 1.3.0 entry to CHANGELOG.md."}} diff --git a/cmux-tui/crates/acpmux/tests/hub_integration.rs b/cmux-tui/crates/acpmux/tests/hub_integration.rs index 0326e92f9cdf..7c45ac96d73d 100644 --- a/cmux-tui/crates/acpmux/tests/hub_integration.rs +++ b/cmux-tui/crates/acpmux/tests/hub_integration.rs @@ -2,8 +2,10 @@ #[path = "support/daemon_env.rs"] mod daemon_env; -// This process runs stand-in agents (the fake agents under tests/). -const HERMETIC: daemon_env::Process = daemon_env::Process::stand_in(); +// This process runs stand-in agents (the fake agents under tests/). `ACPMUX_UPDATE_FIXTURES=1` +// rewrites the pane fixtures the tests check (`adopt.rs`). +const HERMETIC: daemon_env::Process = + daemon_env::Process::stand_in().keep(&["ACPMUX_UPDATE_FIXTURES"]); use acpmux::config::{Config, HarnessProfile, PermissionPolicy, StoreMode}; use acpmux::hub::Hub; diff --git a/cmux-tui/crates/acpmux/tests/hub_integration/adopt.rs b/cmux-tui/crates/acpmux/tests/hub_integration/adopt.rs index 617a6caeb701..206d374a4839 100644 --- a/cmux-tui/crates/acpmux/tests/hub_integration/adopt.rs +++ b/cmux-tui/crates/acpmux/tests/hub_integration/adopt.rs @@ -240,6 +240,337 @@ async fn adopt_forks_a_live_claude_chat_when_asked() { let _ = std::fs::remove_dir_all(root); } +/// The replayed history of an adopted chat: its records from the first `turn_started` on. +fn replayed(hub: &Hub, id: &str) -> Vec { + let events = hub.events(id, 0, 10_000).unwrap(); + let start = events.iter().position(|e| e.kind == "turn_started").expect("a replayed turn"); + events[start..].to_vec() +} + +/// The session update of an `in` record. +fn update_of(e: &acpmux::store::EventRecord) -> &Value { + e.msg.pointer("/params/update").unwrap_or(&Value::Null) +} + +/// An adopted Codex chat shows each turn's tool calls, not only its final message +/// (hq#2569 item 3): a reopened turn that ran three commands and edited two files replays +/// them as `tool_call` records, each settled by a `tool_call_update` with its output, before +/// the answer, so the pane's "Worked for" opens to "Ran 3 commands" and "Edited 2 files". +/// The edit carries each file's before and after text and +/- counts (the edited-files card). +/// +/// The replayed records are also the pane's fixture +/// (`webviews/test/fixtures/adopted-codex-turn.events.json`, read by +/// `agent-pane-adopted-tool-calls.test.ts`): `ACPMUX_UPDATE_FIXTURES=1` rewrites it. +#[tokio::test] +async fn adopt_replays_a_codex_turns_commands_and_file_edits() { + let (hub, mut c, root, project, chat) = adopt_setup().await; + let rollout = + root.join(format!("codex/sessions/2026/10/02/rollout-2026-10-02T09-00-00-{chat}.jsonl")); + let fixture = include_str!("../fixtures/codex-rollout-tool-calls.jsonl") + .replace("{ID}", &chat) + .replace("{CWD}", &project.to_string_lossy()); + std::fs::write(&rollout, fixture).unwrap(); + + let s = c.request(method::SESSION_NEW, adopt("fakecodex", &chat)).await.unwrap(); + let id = s["sessionId"].as_str().unwrap().to_owned(); + let events = replayed(&hub, &id); + write_pane_fixture(&events, &chat, &root); + let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect(); + assert_eq!( + kinds, + [ + "turn_started", + "user_message", + "tool_call", + "tool_call_update", + "tool_call", + "tool_call_update", + "tool_call", + "tool_call_update", + "tool_call", + "tool_call_update", + "agent_message_chunk", + "turn_end", + "turn_result" + ], + "{events:#?}" + ); + assert_eq!(events[1].msg["text"], "Bump the version to 1.3.0 and note it in the changelog"); + let calls: Vec<&Value> = + events.iter().filter(|e| e.kind == "tool_call").map(update_of).collect(); + let commands: Vec<&str> = calls + .iter() + .filter_map(|u| u.pointer("/rawInput/command").and_then(Value::as_str)) + .collect(); + assert_eq!( + commands, + ["git status --short", "grep -n '^version' Cargo.toml", "sed -n 1,8p CHANGELOG.md"] + ); + assert!(calls[..3].iter().all(|u| u["kind"] == "execute" && u["status"] == "in_progress")); + assert_eq!(calls[0]["rawInput"]["cwd"], json!(project)); + // Each command settles with its output and exit code, at the time it ended. + let done: Vec<&acpmux::store::EventRecord> = + events.iter().filter(|e| e.kind == "tool_call_update").collect(); + let grep = update_of(done[1]); + assert_eq!(grep["toolCallId"], "exec-2"); + assert_eq!(grep["status"], "completed"); + assert_eq!(grep["rawOutput"]["exit_code"], 0); + assert_eq!(grep.pointer("/content/0/content/text"), Some(&json!("3:version = \"1.2.0\"\n"))); + let started = + events.iter().find(|e| e.kind == "tool_call" && update_of(e)["toolCallId"] == "exec-2"); + assert_eq!(done[1].at - started.unwrap().at, 50, "the call ran 50ms"); + + // The edit: one call over two files (in path order: Codex records them as a map), each a + // diff with its before and after text. + let edit = calls[3]; + assert_eq!(edit["kind"], "edit"); + let cargo = project.join("Cargo.toml").to_string_lossy().into_owned(); + let changelog = project.join("CHANGELOG.md").to_string_lossy().into_owned(); + assert_eq!( + edit["locations"], + json!([{"path": changelog, "line": 1}, {"path": cargo, "line": 1}]) + ); + let edit_done = update_of(done[3]); + assert_eq!(edit_done["status"], "completed"); + let diffs = edit_done["content"].as_array().unwrap(); + assert_eq!(diffs.len(), 2, "{edit_done}"); + assert_eq!(diffs[0]["type"], "diff"); + assert_eq!(diffs[0]["path"], changelog.as_str()); + assert!( + diffs[0]["newText"].as_str().unwrap().contains("## 1.3.0\n- Bump the version to 1.3.0") + ); + assert_eq!(diffs[1]["path"], cargo.as_str()); + assert!(diffs[1]["oldText"].as_str().unwrap().contains("version = \"1.2.0\"")); + assert!(diffs[1]["newText"].as_str().unwrap().contains("version = \"1.3.0\"")); + assert_eq!( + edit["rawInput"]["changes"], + json!([ + {"path": changelog, "type": "update", "additions": 3, "deletions": 0}, + {"path": cargo, "type": "update", "additions": 1, "deletions": 1} + ]) + ); + + // The final answer only (commentary is progress narration), after the work. + let answer = &events[10]; + assert_eq!( + update_of(answer).pointer("/content/text"), + Some(&json!("Bumped demo to 1.3.0 and added a 1.3.0 entry to CHANGELOG.md.")) + ); + // Worked for 1m 32s: the prompt at 09:00:00, the answer at 09:01:32. + assert_eq!(answer.at - events[1].at, 92_000); + + let _ = std::fs::remove_dir_all(root); +} + +/// A reopened Codex turn whose patch failed shows the failed edit and its error, but none of +/// the edits it proposed: they never applied, so the pane draws no diff and counts no lines. +/// A hunk that did apply is marked as part of its file (`_meta.acpmux.fragment`), so the +/// edited-files card never offers a whole-file Undo it cannot do. +#[tokio::test] +async fn adopt_replays_a_failed_codex_patch_without_its_edits() { + let (hub, mut c, root, project, chat) = adopt_setup().await; + let rollout = + root.join(format!("codex/sessions/2026/10/02/rollout-2026-10-02T09-00-00-{chat}.jsonl")); + let cwd = project.to_string_lossy().into_owned(); + let change = |id: &str, status: &str, stderr: &str| { + json!({"timestamp": "2026-10-02T10:00:10.000Z", "type": "event_msg", "payload": { + "type": "item_completed", "thread_id": chat, "turn_id": "turn-1", + "item": {"type": "FileChange", "id": id, "status": status, + "changes": {format!("{cwd}/Cargo.toml"): {"type": "update", "move_path": null, + "unified_diff": "@@ -3,1 +3,1 @@\n-version = \"1.2.0\"\n+version = \"1.3.0\"\n"}}, + "stdout": "", "stderr": stderr}}}) + }; + let lines = [ + json!({"timestamp": "2026-10-02T09:59:59.900Z", "type": "session_meta", "payload": {"id": chat, "cwd": cwd, "originator": "Codex Desktop", "cli_version": "0.163.0"}}), + json!({"timestamp": "2026-10-02T09:59:59.950Z", "type": "event_msg", "payload": {"type": "task_started", "turn_id": "turn-1"}}), + json!({"timestamp": "2026-10-02T10:00:00.000Z", "type": "response_item", "payload": {"type": "message", "role": "user", "content": [{"type": "input_text", "text": "Bump the version"}], "internal_chat_message_metadata_passthrough": {"content_item_kinds": ["user.text"]}}}), + change("patch-1", "failed", "patch rejected: Cargo.toml changed on disk"), + change("patch-2", "completed", ""), + json!({"timestamp": "2026-10-02T10:00:20.000Z", "type": "response_item", "payload": {"type": "message", "role": "assistant", "phase": "final_answer", "content": [{"type": "output_text", "text": "Bumped it on the second try."}]}}), + json!({"timestamp": "2026-10-02T10:00:20.100Z", "type": "event_msg", "payload": {"type": "task_complete", "turn_id": "turn-1"}}), + ]; + let text: String = lines.iter().map(|l| format!("{l}\n")).collect(); + std::fs::write(&rollout, text).unwrap(); + + let s = c.request(method::SESSION_NEW, adopt("fakecodex", &chat)).await.unwrap(); + let id = s["sessionId"].as_str().unwrap().to_owned(); + let events = replayed(&hub, &id); + let call = |id: &str, kind: &str| { + events + .iter() + .filter(|e| e.kind == kind) + .map(update_of) + .find(|u| u["toolCallId"] == id) + .cloned() + .unwrap_or_else(|| panic!("no {kind} for {id}: {events:#?}")) + }; + let cargo = project.join("Cargo.toml").to_string_lossy().into_owned(); + + let failed = call("patch-1", "tool_call_update"); + assert_eq!(failed["status"], "failed"); + assert_eq!( + failed["content"], + json!([{"type": "content", "content": {"type": "text", "text": "patch rejected: Cargo.toml changed on disk"}}]) + ); + assert_eq!( + call("patch-1", "tool_call")["rawInput"]["changes"], + json!([{"path": cargo, "type": "update"}]) + ); + + let applied = call("patch-2", "tool_call_update"); + assert_eq!(applied["status"], "completed"); + assert_eq!( + applied["content"], + json!([{"type": "diff", "path": cargo, "oldText": "version = \"1.2.0\"\n", "newText": "version = \"1.3.0\"\n", "_meta": {"acpmux": {"fragment": true}}}]) + ); + assert_eq!( + call("patch-2", "tool_call")["rawInput"]["changes"], + json!([{"path": cargo, "type": "update", "additions": 1, "deletions": 1}]) + ); + + let _ = std::fs::remove_dir_all(root); +} + +/// Checks (or with `ACPMUX_UPDATE_FIXTURES=1` rewrites) the pane's adopted-turn fixture: the +/// replayed records with the machine-specific folder and ids made stable, and numbered from 1 +/// (`seq`, and the `turnSeq` that names the turn's start). +fn write_pane_fixture(events: &[acpmux::store::EventRecord], chat: &str, root: &std::path::Path) { + let base = events[0].seq - 1; + let records: Vec = events + .iter() + .map(|e| { + let mut msg = e.msg.clone(); + if let Some(turn) = msg.get("turnSeq").and_then(Value::as_u64) { + msg["turnSeq"] = json!(turn - base); + } + json!({"seq": e.seq - base, "at": e.at, "dir": e.dir, "kind": e.kind, "msg": msg}) + }) + .collect(); + let text = serde_json::to_string_pretty(&records) + .unwrap() + .replace(&root.join("project").to_string_lossy().into_owned(), "/home/dev/demo") + .replace(chat, "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60") + + "\n"; + let path = concat!( + env!("CARGO_MANIFEST_DIR"), + "/../../../webviews/test/fixtures/adopted-codex-turn.events.json" + ); + if std::env::var("ACPMUX_UPDATE_FIXTURES").as_deref() == Ok("1") { + std::fs::write(path, &text).unwrap(); + } else if let Ok(stored) = std::fs::read_to_string(path) { + // A checkout without the webviews (a crate-only build) has nothing to check. + assert_eq!( + stored, text, + "the pane's fixture is stale: rerun with ACPMUX_UPDATE_FIXTURES=1" + ); + } +} + +/// An adopted Claude Code chat shows its tool calls too: a `tool_use` replays as a +/// `tool_call` and its `tool_result` settles it (an error result fails it), before the answer. +#[tokio::test] +async fn adopt_replays_a_claude_turns_tool_calls() { + let root = std::path::PathBuf::from("/tmp") + .join(format!("acpmux-adopt-claude-tools-{}", uuid::Uuid::now_v7())); + let claude = root.join("claude"); + let project = root.join("project"); + std::fs::create_dir_all(&project).unwrap(); + let chat = session_id(); + let file = project.join("src/lib.rs").to_string_lossy().into_owned(); + let line = |kind: &str, content: Value, at: &str| { + json!({"type": kind, "isSidechain": false, "cwd": project, "sessionId": chat, + "timestamp": at, "message": {"role": kind, "content": content}}) + }; + let lines = [ + line("user", json!("Rename old_helper and run the tests"), "2026-10-02T10:00:00.000Z"), + line( + "assistant", + json!([{"type": "tool_use", "id": "toolu_1", "name": "Bash", "input": {"command": "rg -n old_helper", "description": "Find uses"}}]), + "2026-10-02T10:00:03.000Z", + ), + line( + "user", + json!([{"type": "tool_result", "tool_use_id": "toolu_1", "content": "src/lib.rs:3:fn old_helper() {}"}]), + "2026-10-02T10:00:04.000Z", + ), + line( + "assistant", + json!([{"type": "tool_use", "id": "toolu_2", "name": "Edit", "input": {"file_path": file, "old_string": "fn old_helper() {}", "new_string": "fn new_helper() {}"}}]), + "2026-10-02T10:00:06.000Z", + ), + line( + "user", + json!([{"type": "tool_result", "tool_use_id": "toolu_2", "content": [{"type": "text", "text": "The file has been updated."}]}]), + "2026-10-02T10:00:07.000Z", + ), + line( + "assistant", + json!([{"type": "tool_use", "id": "toolu_3", "name": "Bash", "input": {"command": "cargo test -q"}}]), + "2026-10-02T10:00:08.000Z", + ), + line( + "user", + json!([{"type": "tool_result", "tool_use_id": "toolu_3", "content": "error: 1 test failed", "is_error": true}]), + "2026-10-02T10:00:30.000Z", + ), + line( + "assistant", + json!([{"type": "text", "text": "Renamed old_helper to new_helper; one test still fails."}]), + "2026-10-02T10:00:40.000Z", + ), + ]; + let transcript = claude.join(format!("projects/p/{chat}.jsonl")); + std::fs::create_dir_all(transcript.parent().unwrap()).unwrap(); + std::fs::write(&transcript, lines.iter().map(|l| format!("{l}\n")).collect::()) + .unwrap(); + let (hub, mut c) = super::fork_through::claude_setup(&claude, &[]).await; + + let s = c.request(method::SESSION_NEW, adopt("claude", &chat)).await.unwrap(); + let id = s["sessionId"].as_str().unwrap().to_owned(); + let events = replayed(&hub, &id); + let kinds: Vec<&str> = events.iter().map(|e| e.kind.as_str()).collect(); + assert_eq!( + kinds, + [ + "turn_started", + "user_message", + "tool_call", + "tool_call_update", + "tool_call", + "tool_call_update", + "tool_call", + "tool_call_update", + "agent_message_chunk", + "turn_end", + "turn_result" + ], + "{events:#?}" + ); + let calls: Vec<&Value> = + events.iter().filter(|e| e.kind == "tool_call").map(update_of).collect(); + assert_eq!(calls[0]["kind"], "execute"); + assert_eq!(calls[0]["rawInput"]["command"], "rg -n old_helper"); + assert_eq!(calls[1]["kind"], "edit"); + assert_eq!(calls[1]["locations"], json!([{"path": file}])); + let done: Vec<&Value> = + events.iter().filter(|e| e.kind == "tool_call_update").map(update_of).collect(); + assert_eq!(done[0]["status"], "completed"); + assert_eq!( + done[0].pointer("/content/0/content/text"), + Some(&json!("src/lib.rs:3:fn old_helper() {}")) + ); + assert_eq!( + done[1]["content"], + json!([{"type": "diff", "path": file, "oldText": "fn old_helper() {}", "newText": "fn new_helper() {}"}]) + ); + assert_eq!(done[2]["status"], "failed"); + assert_eq!( + update_of(&events[8]).pointer("/content/text"), + Some(&json!("Renamed old_helper to new_helper; one test still fails.")) + ); + let _ = std::fs::remove_dir_all(root); +} + /// A process that holds `lock` the way a running Codex holds its thread writer lock (an /// exclusive `flock`), until it is killed; returns once the lock is held. The kernel releases /// it when the process ends, as it does for a `codex exec` that finished. diff --git a/cmux-tui/crates/acpmux/tests/hub_integration/fork_through.rs b/cmux-tui/crates/acpmux/tests/hub_integration/fork_through.rs index ff902e63b372..9e0717c5e9c7 100644 --- a/cmux-tui/crates/acpmux/tests/hub_integration/fork_through.rs +++ b/cmux-tui/crates/acpmux/tests/hub_integration/fork_through.rs @@ -125,7 +125,10 @@ async fn a_fork_through_the_latest_turn_opens_a_new_session_and_an_earlier_turn_ /// A hub whose default agent is a Claude stdio profile keeping Claude Code's /// own store layout under `claude` (fake_claude.py with CLAUDE_CONFIG_DIR). -async fn claude_setup(claude: &std::path::Path, env: &[(&str, &str)]) -> (Arc, TestClient) { +pub(super) async fn claude_setup( + claude: &std::path::Path, + env: &[(&str, &str)], +) -> (Arc, TestClient) { let fake_claude = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/fake_claude.py"); let mut env: BTreeMap = env.iter().map(|(k, v)| ((*k).to_owned(), (*v).to_owned())).collect(); diff --git a/webviews/src/agent-session/acpmux/conversation/toolRunSummary.ts b/webviews/src/agent-session/acpmux/conversation/toolRunSummary.ts index 941d3f780565..7a9688d61741 100644 --- a/webviews/src/agent-session/acpmux/conversation/toolRunSummary.ts +++ b/webviews/src/agent-session/acpmux/conversation/toolRunSummary.ts @@ -2,6 +2,7 @@ // "Edited a file, read files, ran commands", opened to list the calls. import type { Translate } from "../i18n"; import type { AcpmuxActivity } from "../model"; +import { editedPaths } from "../toolPaths"; import { mcpCall } from "./mcpCalls"; /// What a call did, in the order a run's summary names them. @@ -54,10 +55,12 @@ export function toolRunCategories(items: readonly AcpmuxActivity[]): ToolRunCate export function toolRunSummary(t: Translate, items: readonly AcpmuxActivity[]): string { const tools = items.filter((item) => item.tool); const count = (category: ToolRunCategory) => - tools.filter((item) => { - const own = callCategory(item.tool!); - return own === category || (category === "read" && own === "searched"); - }).length; + category === "edited" + ? editedFiles(tools) + : tools.filter((item) => { + const own = callCategory(item.tool!); + return own === category || (category === "read" && own === "searched"); + }).length; const phrase = (category: ToolRunCategory) => { const one = count(category) === 1; switch (category) { @@ -80,3 +83,20 @@ export function toolRunSummary(t: Translate, items: readonly AcpmuxActivity[]): const text = toolRunCategories(items).map(phrase).join(t("toolRun.separator")); return text.charAt(0).toUpperCase() + text.slice(1); } + +/// The files a run's edits changed: one Codex change can edit several, so a call counts each +/// file its diffs and locations name; one with no diff, each file its input names (a +/// multi-file patch, toolPaths.ts); or one when it names none. +function editedFiles(tools: readonly AcpmuxActivity[]): number { + const paths = new Set(); + let unnamed = 0; + for (const { tool } of tools) { + if (toolRunCategory(tool!.kind) !== "edited") continue; + const named = tool!.diffs?.length + ? [...tool!.diffs, ...(tool!.locations ?? [])].map((file) => file.path) + : editedPaths(tool!); + if (named.length === 0) unnamed += 1; + for (const path of named) paths.add(path); + } + return paths.size + unnamed; +} diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts index 1cabd910db99..4132f4e12519 100644 --- a/webviews/src/agent-session/acpmux/direct.ts +++ b/webviews/src/agent-session/acpmux/direct.ts @@ -355,6 +355,7 @@ export function toolDiffs(content: any, locations: any): AcpmuxFileDiff[] | unde oldText: typeof item.oldText === "string" ? item.oldText : undefined, newText: item.newText, line: lines.get(item.path), + ...(item.fragment === true || item._meta?.acpmux?.fragment === true ? { fragment: true as const } : {}), })); return diffs.length ? diffs : undefined; } diff --git a/webviews/src/agent-session/acpmux/model.ts b/webviews/src/agent-session/acpmux/model.ts index 49a36a15aac8..32b46311af07 100644 --- a/webviews/src/agent-session/acpmux/model.ts +++ b/webviews/src/agent-session/acpmux/model.ts @@ -208,8 +208,9 @@ export type AcpmuxActivity = { }; /// A file change from an ACP tool call's `diff` content: `oldText` is absent for a new file. -/// `line` is where the change starts, when the tool call's locations name it. -export type AcpmuxFileDiff = { path: string; oldText?: string; newText: string; line?: number }; +/// `line` is where the change starts, when the tool call's locations name it. `fragment`: the +/// texts are part of the file, not all of it (`_meta.acpmux.fragment`, a reopened Codex hunk). +export type AcpmuxFileDiff = { path: string; oldText?: string; newText: string; line?: number; fragment?: true }; /// An agent's ask for a secret (cx-ncc.42, acpmux `hub/secrets.rs`): the `secret_request` record /// holds only the name and reason, never a value. The card answers with `_acpmux/secret_submit`. diff --git a/webviews/src/agent-session/acpmux/turnChanges/model.ts b/webviews/src/agent-session/acpmux/turnChanges/model.ts index 6e2ec7eb2079..8520fafc88f5 100644 --- a/webviews/src/agent-session/acpmux/turnChanges/model.ts +++ b/webviews/src/agent-session/acpmux/turnChanges/model.ts @@ -42,6 +42,8 @@ export function fileUndo(diffs: readonly AcpmuxFileDiff[]): FileUndo { const last = diffs[diffs.length - 1]; // The host takes absolute paths only; a path as the agent wrote it (`~/x`, `src/x`) is not one. if (!first || !last || !first.path.startsWith("/")) return { kind: "cannot" }; + // A diff marked as part of its file (a reopened Codex hunk) has no whole-file text to restore. + if (diffs.some((diff) => diff.fragment)) return { kind: "cannot" }; for (let index = 1; index < diffs.length; index++) if (diffs[index]!.oldText !== diffs[index - 1]!.newText) return { kind: "cannot" }; // An empty result could be a replace-all of a fragment: the original is not known. diff --git a/webviews/test/agent-pane-adopted-tool-calls.test.ts b/webviews/test/agent-pane-adopted-tool-calls.test.ts new file mode 100644 index 000000000000..67b93d4ec022 --- /dev/null +++ b/webviews/test/agent-pane-adopted-tool-calls.test.ts @@ -0,0 +1,172 @@ +// l10n-allow-file: test fixture prompts and replies, not shipped UI. +// A reopened Codex chat shows each turn's work (hq#2569 item 3): the turn that ran three commands +// and edited two files opens its "Worked for 1m 32s" line to those calls, grouped as the pane +// groups a live turn's ("Ran 3 commands", "Edited 2 files +4 -1"), and each command opens to its +// line. +// +// Before: adopting a Codex chat replayed only the prompt and the final answer, so the turn showed +// the answer and a "Worked for 1m 32s" footer that opened nothing. +// +// The records are acpmux's own replay of a Codex rollout (`adopt_replays_a_codex_turns_commands_and_file_edits` +// in cmux-tui/crates/acpmux/tests/hub_integration/adopt.rs writes the fixture). The page is the +// pane's dev entry with its browser host, talking JSON-RPC to a stand-in acpmux serving them. +// Real Chromium from Playwright; CI fails the file when it cannot launch (requireBrowserLane). +import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from "bun:test"; +import path from "node:path"; +import { chromium, type Browser, type Page } from "playwright"; +import { requireBrowserLane } from "./support/requireBrowserLane"; +import { warmViteServer } from "./support/warmDevServer"; + +await requireBrowserLane("agent-pane-adopted-tool-calls.test.ts", async () => { + setDefaultTimeout(120_000); + try { + await (await chromium.launch({ headless: true })).close(); + } catch { + console.warn("agent-pane-adopted-tool-calls: skipping (run `bunx playwright install chromium`)"); + describe.skip("adopted tool calls", () => test("chromium", () => {})); + return; + } + const { createServer } = await import("vite"); + const webviews = path.resolve(import.meta.dir, ".."); + + const CHAT = "0190a000-0000-7000-8000-0000000000f7"; + const ANSWER = "Bumped demo to 1.3.0"; + const replay = (await Bun.file(path.join(import.meta.dir, "fixtures/adopted-codex-turn.events.json")).json()) as { + seq: number; + at: number; + dir: string; + kind: string; + msg: unknown; + }[]; + // The same turn, its edit recorded as a patch whose files only its input names: no diffs and + // no locations, as an edit too big to draw or a harness that sends no diff content. + const PATCH_CHAT = "0190a000-0000-7000-8000-0000000000f8"; + const patchOnly = replay.map((record) => { + const update = (record.msg as { params?: { update?: Record } }).params?.update; + if (!update || (update.toolCallId !== "exec-4" && update.kind !== "edit")) return record; + const { locations: _locations, content: _content, ...rest } = update; + const params = (record.msg as { params: Record }).params; + return { ...record, msg: { ...(record.msg as object), params: { ...params, update: rest } } }; + }); + const chats = new Map( + [ + [CHAT, replay], + [PATCH_CHAT, patchOnly], + ].map(([id, records]) => { + const events = (records as typeof replay).map((record) => ({ sessionId: id as string, ...record })); + const session = { + sessionId: id as string, + cwd: "/home/dev/demo", + title: "Bump the version", + harness: "codex", + family: "codex", + status: "idle", + turnCount: 1, + updatedAt: events.at(-1)!.at, + }; + return [id as string, { session, events, lastSeq: events.at(-1)!.seq }]; + }), + ); + function answer(method: string, params: { sessionId?: string } = {}): unknown { + const chat = chats.get(params.sessionId ?? CHAT) ?? chats.get(CHAT)!; + switch (method) { + case "initialize": + return { protocolVersion: 1, _meta: { acpmux: { origin: "local", extensions: [], operations: [] } } }; + case "_acpmux/watch": + return { sessions: [...chats.values()].map((c) => c.session) }; + case "_acpmux/attach": + return { session: chat.session, lastSeq: chat.lastSeq, events: chat.events }; + case "_acpmux/events": + return { events: [], hasMore: false, lastSeq: chat.lastSeq }; + default: + return null; + } + } + + let daemon: ReturnType | undefined; + let vite: Awaited> | undefined; + let browser: Browser | undefined; + const url = (chat = CHAT) => { + const { port } = vite!.httpServer!.address() as { port: number }; + const endpoint = `ws://127.0.0.1:${daemon!.port}/`; + return `http://127.0.0.1:${port}/#endpoint=${encodeURIComponent(endpoint)}&token=t&session=${chat}`; + }; + const open = async (chat = CHAT): Promise => { + const page = await browser!.newPage({ viewport: { width: 900, height: 900 } }); + await page.goto(url(chat)); + await page.getByText(ANSWER).waitFor(); + return page; + }; + beforeAll(async () => { + daemon = Bun.serve({ + port: 0, + hostname: "127.0.0.1", + fetch(request, server) { + return server.upgrade(request, { data: undefined }) ? undefined : new Response("acpmux", { status: 426 }); + }, + websocket: { + message(ws, raw) { + const message = JSON.parse(String(raw)) as { id?: number; method: string; params?: { sessionId?: string } }; + if (message.id !== undefined) + ws.send(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: answer(message.method, message.params) })); + }, + }, + }); + vite = await createServer({ + configFile: path.join(webviews, "vite.config.acpmux-pane.mjs"), + server: { port: 0, host: "127.0.0.1", strictPort: false }, + logLevel: "error", + }); + await vite.listen(); + await warmViteServer(vite, "/"); + browser = await chromium.launch({ headless: true }); + // A cold dev server's first load can stall in CI: load it here, again if it stalls. + for (let attempt = 1; ; attempt++) { + const warm = await browser.newPage(); + try { + await warm.goto(url()); + await warm.getByText(ANSWER).waitFor({ timeout: 25_000 }); + await warm.close(); + break; + } catch (error) { + await warm.close(); + if (attempt === 3) throw error; + } + } + }); + afterAll(async () => { + await browser?.close(); + await vite?.close(); + await daemon?.stop(true); + }); + + test("the adopted turn's Worked for opens to its commands and edited files", async () => { + const page = await open(); + const worked = page.locator("button.cv-worked"); + await expect(worked.textContent()).resolves.toBe("Worked for 1m 32s"); + expect(await worked.getAttribute("aria-expanded")).toBe("false"); + await worked.click(); + expect(await worked.getAttribute("aria-expanded")).toBe("true"); + + // The settled run's line, then its groups, as a live turn's run settles. + await page.getByRole("button", { name: "Edited files, ran commands" }).click(); + const commands = page.locator("button.cv-tool", { hasText: "Ran 3 commands" }); + const edits = page.locator("button.cv-tool", { hasText: "Edited 2 files" }); + await commands.waitFor(); + await expect(edits.textContent()).resolves.toBe("Edited 2 files+4-1"); + + await commands.click(); + const lines = await page.locator(".cv-command__line").allTextContents(); + expect(lines).toEqual(["git status --short", "grep -n '^version' Cargo.toml", "sed -n 1,8p CHANGELOG.md"]); + // The answer stays outside the fold, after the work. + await page.getByText(ANSWER).waitFor(); + await page.close(); + }); + + test("a patch whose files only its input names counts each file, not one", async () => { + const page = await open(PATCH_CHAT); + await page.locator("button.cv-worked").click(); + await page.getByRole("button", { name: "Edited files, ran commands" }).waitFor(); + await page.close(); + }); +}); diff --git a/webviews/test/fixtures/adopted-codex-turn.events.json b/webviews/test/fixtures/adopted-codex-turn.events.json new file mode 100644 index 000000000000..e1723e9ae0e8 --- /dev/null +++ b/webviews/test/fixtures/adopted-codex-turn.events.json @@ -0,0 +1,315 @@ +[ + { + "at": 1790931600000, + "dir": "mux", + "kind": "turn_started", + "msg": { + "client": "adopt", + "control": "local", + "prompt": "Bump the version to 1.3.0 and note it in the changelog", + "promptId": "adopted-prompt-0", + "turnId": "adopted-0" + }, + "seq": 1 + }, + { + "at": 1790931600000, + "dir": "mux", + "kind": "user_message", + "msg": { + "client": "adopt", + "promptId": "adopted-prompt-0", + "text": "Bump the version to 1.3.0 and note it in the changelog", + "turnId": "adopted-0" + }, + "seq": 2 + }, + { + "at": 1790931605790, + "dir": "in", + "kind": "tool_call", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "kind": "execute", + "rawInput": { + "command": "git status --short", + "cwd": "/home/dev/demo" + }, + "sessionUpdate": "tool_call", + "status": "in_progress", + "title": "git status --short", + "toolCallId": "exec-1" + } + } + }, + "seq": 3 + }, + { + "at": 1790931606000, + "dir": "in", + "kind": "tool_call_update", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "rawOutput": { + "duration_ms": 210, + "exit_code": 0 + }, + "sessionUpdate": "tool_call_update", + "status": "completed", + "toolCallId": "exec-1" + } + } + }, + "seq": 4 + }, + { + "at": 1790931608950, + "dir": "in", + "kind": "tool_call", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "kind": "execute", + "rawInput": { + "command": "grep -n '^version' Cargo.toml", + "cwd": "/home/dev/demo" + }, + "sessionUpdate": "tool_call", + "status": "in_progress", + "title": "grep -n '^version' Cargo.toml", + "toolCallId": "exec-2" + } + } + }, + "seq": 5 + }, + { + "at": 1790931609000, + "dir": "in", + "kind": "tool_call_update", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "content": [ + { + "content": { + "text": "3:version = \"1.2.0\"\n", + "type": "text" + }, + "type": "content" + } + ], + "rawOutput": { + "duration_ms": 50, + "exit_code": 0 + }, + "sessionUpdate": "tool_call_update", + "status": "completed", + "toolCallId": "exec-2" + } + } + }, + "seq": 6 + }, + { + "at": 1790931611960, + "dir": "in", + "kind": "tool_call", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "kind": "execute", + "rawInput": { + "command": "sed -n 1,8p CHANGELOG.md", + "cwd": "/home/dev/demo" + }, + "sessionUpdate": "tool_call", + "status": "in_progress", + "title": "sed -n 1,8p CHANGELOG.md", + "toolCallId": "exec-3" + } + } + }, + "seq": 7 + }, + { + "at": 1790931612000, + "dir": "in", + "kind": "tool_call_update", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "content": [ + { + "content": { + "text": "# Changelog\n\n## 1.2.0\n- Faster startup\n", + "type": "text" + }, + "type": "content" + } + ], + "rawOutput": { + "duration_ms": 40, + "exit_code": 0 + }, + "sessionUpdate": "tool_call_update", + "status": "completed", + "toolCallId": "exec-3" + } + } + }, + "seq": 8 + }, + { + "at": 1790931670000, + "dir": "in", + "kind": "tool_call", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "kind": "edit", + "locations": [ + { + "line": 1, + "path": "/home/dev/demo/CHANGELOG.md" + }, + { + "line": 1, + "path": "/home/dev/demo/Cargo.toml" + } + ], + "rawInput": { + "changes": [ + { + "additions": 3, + "deletions": 0, + "path": "/home/dev/demo/CHANGELOG.md", + "type": "update" + }, + { + "additions": 1, + "deletions": 1, + "path": "/home/dev/demo/Cargo.toml", + "type": "update" + } + ] + }, + "sessionUpdate": "tool_call", + "status": "in_progress", + "title": "Edit 2 files", + "toolCallId": "exec-4" + } + } + }, + "seq": 9 + }, + { + "at": 1790931670000, + "dir": "in", + "kind": "tool_call_update", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "content": [ + { + "_meta": { + "acpmux": { + "fragment": true + } + }, + "newText": "# Changelog\n\n## 1.3.0\n- Bump the version to 1.3.0\n\n## 1.2.0\n", + "oldText": "# Changelog\n\n## 1.2.0\n", + "path": "/home/dev/demo/CHANGELOG.md", + "type": "diff" + }, + { + "_meta": { + "acpmux": { + "fragment": true + } + }, + "newText": "[package]\nname = \"demo\"\nversion = \"1.3.0\"\nedition = \"2021\"\n", + "oldText": "[package]\nname = \"demo\"\nversion = \"1.2.0\"\nedition = \"2021\"\n", + "path": "/home/dev/demo/Cargo.toml", + "type": "diff" + } + ], + "sessionUpdate": "tool_call_update", + "status": "completed", + "toolCallId": "exec-4" + } + } + }, + "seq": 10 + }, + { + "at": 1790931692000, + "dir": "in", + "kind": "agent_message_chunk", + "msg": { + "jsonrpc": "2.0", + "method": "session/update", + "params": { + "sessionId": "0199a1b2-c3d4-7e5f-8a9b-0c1d2e3f4a60", + "update": { + "content": { + "text": "Bumped demo to 1.3.0 and added a 1.3.0 entry to CHANGELOG.md.", + "type": "text" + }, + "sessionUpdate": "agent_message_chunk" + } + } + }, + "seq": 11 + }, + { + "at": 1790931692000, + "dir": "mux", + "kind": "turn_end", + "msg": { + "stopReason": "end_turn", + "turnId": "adopted-0", + "turnSeq": 1 + }, + "seq": 12 + }, + { + "at": 1790931692000, + "dir": "mux", + "kind": "turn_result", + "msg": { + "promptId": "adopted-prompt-0", + "status": "completed", + "stopReason": "end_turn", + "turnId": "adopted-0", + "turnSeq": 1 + }, + "seq": 13 + } +]