Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix: render ACP tool-call content blocks in chat cards (#17407)

Matteo ATKINSONef0c86d3455f
diff --git a/__tests__/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.test.ts b/__tests__/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.test.ts
index b686f18fc2..72e3bbd91e 100644
--- a/__tests__/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.test.ts
+++ b/__tests__/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.test.ts
@@ -116,6 +116,226 @@ describe("getACPToolCallContent", () => {
expect(content).toContain('"status": 200');
expect(content).toContain('"body": "ok"');
});
+
+ it("fences raw_output with a longer fence when it carries its own code fence", () => {
+ const readme = "# Demo\n\n```bash\nnpm start\n```\n\n## Links";
+ const content = getACPToolCallContent(
+ makeEvent({
+ raw_input: { command: "cat README.md" },
+ raw_output: readme,
+ }),
+ );
+
+ expect(content).toContain(`Output:\n\`\`\`\`\n${readme}\n\`\`\`\``);
+ });
+});
+
+describe("getACPToolCallContent β€” ACP content blocks", () => {
+ // Captured from agent-server 1.46.0 running claude-agent-acp: the diff only
+ // exists in ``content``; ``raw_output`` is the model-facing tool result.
+ const claudeEdit = makeEvent({
+ tool_call_id: "toolu_01Jw2BG94dFwH8rJazTPZUAw",
+ title: "Edit demo.py",
+ tool_kind: "edit",
+ raw_input: {
+ replace_all: false,
+ file_path: "/workspace/demo.py",
+ old_string: "port = 3000",
+ new_string: "port = 8080",
+ },
+ raw_output:
+ "The file /workspace/demo.py has been updated successfully. (file state is current in your context β€” no need to Read it back)",
+ content: [
+ {
+ field_meta: null,
+ new_text: "port = 8080",
+ old_text: "port = 3000",
+ path: "/workspace/demo.py",
+ type: "diff",
+ },
+ ],
+ });
+
+ it("renders a diff block under its path instead of the raw input and model-facing output", () => {
+ const content = getACPToolCallContent(claudeEdit);
+
+ expect(content).toBe(
+ "`/workspace/demo.py`\n```diff\n- port = 3000\n+ port = 8080\n```",
+ );
+ });
+
+ it("renders a full-file write (old_text null) as additions only", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ title: "Write demo.py",
+ tool_kind: "edit",
+ raw_input: { file_path: "/workspace/demo.py", content: "a\nb\n" },
+ raw_output: "File created successfully at: /workspace/demo.py",
+ content: [
+ {
+ type: "diff",
+ path: "/workspace/demo.py",
+ old_text: null,
+ new_text: "a\nb\n",
+ },
+ ],
+ }),
+ );
+
+ expect(content).toBe("`/workspace/demo.py`\n```diff\n+ a\n+ b\n```");
+ });
+
+ it("accepts the camelCase diff fields used on the ACP wire", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ tool_kind: "edit",
+ raw_input: null,
+ raw_output: null,
+ content: [
+ {
+ type: "diff",
+ path: "/workspace/app.ts",
+ oldText: "const port = 3000;\n",
+ newText: "const port = 8080;\n",
+ },
+ ],
+ }),
+ );
+
+ expect(content).toContain("- const port = 3000;\n+ const port = 8080;");
+ expect(content).not.toContain("OBSERVATION$COMMAND_NO_OUTPUT");
+ });
+
+ it("renders text content when raw_output is absent (Gemini CLI)", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ title: "README.md",
+ tool_kind: "read",
+ raw_input: null,
+ raw_output: null,
+ content: [
+ {
+ type: "content",
+ content: { type: "text", text: "# Demo\n\nRun it:\n" },
+ },
+ ],
+ }),
+ );
+
+ expect(content).toBe("Output:\n```\n# Demo\n\nRun it:\n```");
+ });
+
+ it("shows the error text carried in content for a failed call", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ status: "failed",
+ is_error: true,
+ raw_input: { command: "npm test" },
+ raw_output: null,
+ content: [
+ {
+ type: "content",
+ content: {
+ type: "text",
+ text: "Command rejected: npm is not on the allowlist",
+ },
+ },
+ ],
+ }),
+ );
+
+ expect(content).toContain(
+ "**Error:**\n```\nCommand rejected: npm is not on the allowlist\n```",
+ );
+ });
+
+ it("prefers a markdown-escaped text block over raw_output and keeps its language", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ raw_input: { command: "ls" },
+ raw_output: "a.txt\n<system-reminder>model-only</system-reminder>",
+ content: [
+ {
+ type: "content",
+ content: { type: "text", text: "```console\na.txt\n```" },
+ },
+ ],
+ }),
+ );
+
+ expect(content).toBe("Command: `ls`\n\nOutput:\n```console\na.txt\n```");
+ });
+
+ it("re-fences a truncated markdown-escaped block so the fence stays closed", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ raw_output: null,
+ content: [
+ {
+ type: "content",
+ content: {
+ type: "text",
+ text: `\`\`\`\n${"x".repeat(5000)}\n\`\`\``,
+ },
+ },
+ ],
+ }),
+ );
+
+ expect(content).toMatch(/```\nx{1000}\.\.\.\n```$/);
+ });
+
+ it("keeps a diff path containing backticks inside its inline code span", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ tool_kind: "edit",
+ content: [
+ {
+ type: "diff",
+ path: "/workspace/we`ird [x](y).py",
+ old_text: null,
+ new_text: "a",
+ },
+ ],
+ }),
+ );
+
+ expect(content).toBe("``/workspace/we`ird [x](y).py``\n```diff\n+ a\n```");
+ });
+
+ it("keeps the raw_output error next to the diff of a failed edit", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ tool_kind: "edit",
+ status: "failed",
+ is_error: true,
+ raw_output: { message: "old_string not found in file" },
+ content: [
+ {
+ type: "diff",
+ path: "/workspace/demo.py",
+ old_text: "port = 3000",
+ new_text: "port = 8080",
+ },
+ ],
+ }),
+ );
+
+ expect(content).toContain("```diff\n- port = 3000\n+ port = 8080\n```");
+ expect(content).toContain("**Error:**");
+ expect(content).toContain("old_string not found in file");
+ });
+
+ it("falls back to raw_output when content has nothing displayable", () => {
+ const content = getACPToolCallContent(
+ makeEvent({
+ raw_output: "total 0",
+ content: [{ type: "terminal", terminalId: "term-1" }],
+ }),
+ );
+
+ expect(content).toContain("Output:\n```\ntotal 0\n```");
+ });
});
describe("stripRedundantTitlePrefix", () => {
diff --git a/__tests__/components/conversation-events/chat/event-message-acp-tool-call.test.tsx b/__tests__/components/conversation-events/chat/event-message-acp-tool-call.test.tsx
index 094adb0d65..12a73d3b83 100644
--- a/__tests__/components/conversation-events/chat/event-message-acp-tool-call.test.tsx
+++ b/__tests__/components/conversation-events/chat/event-message-acp-tool-call.test.tsx
@@ -149,6 +149,45 @@ describe("EventMessage - ACPToolCallEvent dispatch", () => {
expect(screen.getByText(/diff output here/)).toBeInTheDocument();
});
+ it("shows the diff from content instead of the model-facing raw_output for an edit", async () => {
+ const user = userEvent.setup();
+ const { container } = renderWithProviders(
+ <EventMessage
+ event={makeEvent({
+ title: "Edit demo.py",
+ tool_kind: "edit",
+ raw_input: {
+ file_path: "/workspace/demo.py",
+ old_string: "port = 3000",
+ new_string: "port = 8080",
+ },
+ raw_output:
+ "The file /workspace/demo.py has been updated successfully. (file state is current in your context β€” no need to Read it back)",
+ content: [
+ {
+ type: "diff",
+ path: "/workspace/demo.py",
+ old_text: "port = 3000",
+ new_text: "port = 8080",
+ },
+ ],
+ })}
+ messages={[]}
+ isLastMessage={false}
+ isInLast10Actions={false}
+ />,
+ );
+
+ await user.click(screen.getByRole("button", { name: "BUTTON$EXPAND" }));
+
+ // The diff is syntax-highlighted, which splits each line across token
+ // spans, so assert on the rendered text rather than a single element.
+ expect(container).toHaveTextContent(
+ "/workspace/demo.py - port = 3000 + port = 8080",
+ );
+ expect(container).not.toHaveTextContent("no need to Read it back");
+ });
+
it("dismisses the timestamp when details are expanded with a pointer", async () => {
const user = userEvent.setup();
renderWithProviders(
diff --git a/__tests__/utils/markdown-fence.test.ts b/__tests__/utils/markdown-fence.test.ts
new file mode 100644
index 0000000000..43b7d1bd93
--- /dev/null
+++ b/__tests__/utils/markdown-fence.test.ts
@@ -0,0 +1,45 @@
+import { describe, it, expect } from "vitest";
+
+import { markdownFence, markdownInlineCode } from "#/utils/markdown-fence";
+
+describe("markdownFence", () => {
+ it("wraps plain content in a three-backtick fence", () => {
+ expect(markdownFence("echo hi")).toBe("```\necho hi\n```");
+ });
+
+ it("appends the language after the opening fence", () => {
+ expect(markdownFence('{"a": 1}', "json")).toBe('```json\n{"a": 1}\n```');
+ });
+
+ it("keeps a three-backtick fence when content only has shorter runs", () => {
+ expect(markdownFence("use `ls` or ``pwd``")).toBe(
+ "```\nuse `ls` or ``pwd``\n```",
+ );
+ });
+
+ it("uses a fence longer than the longest backtick run in the content", () => {
+ const readme = "```bash\nnpm start\n```";
+ expect(markdownFence(readme)).toBe(`\`\`\`\`\n${readme}\n\`\`\`\``);
+
+ const nested = "````md\n```js\nx\n```\n````";
+ expect(markdownFence(nested, "text")).toBe(
+ `\`\`\`\`\`text\n${nested}\n\`\`\`\`\``,
+ );
+ });
+});
+
+describe("markdownInlineCode", () => {
+ it("wraps plain content in single backticks", () => {
+ expect(markdownInlineCode("src/app.ts")).toBe("`src/app.ts`");
+ });
+
+ it("uses a delimiter longer than the longest backtick run in the content", () => {
+ expect(markdownInlineCode("a`b")).toBe("``a`b``");
+ expect(markdownInlineCode("a``b")).toBe("```a``b```");
+ });
+
+ it("pads content that starts or ends with a backtick", () => {
+ expect(markdownInlineCode("`a")).toBe("`` `a ``");
+ expect(markdownInlineCode("a`")).toBe("`` a` ``");
+ });
+});
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.ts b/src/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.ts
index b53c07bebe..052694d1ab 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/get-acp-tool-call-content.ts
@@ -2,6 +2,7 @@ import { ACPToolCallEvent } from "#/types/agent-server/core/events/acp-tool-call
import i18n from "#/i18n";
import { MAX_CONTENT_LENGTH } from "./shared";
import { I18nKey } from "#/i18n/declaration";
+import { markdownFence, markdownInlineCode } from "#/utils/markdown-fence";
/**
* Pick the translation key used for the ACP tool call title row. Mirrors
@@ -86,16 +87,100 @@ const truncate = (content: string): string =>
? `${content.slice(0, MAX_CONTENT_LENGTH)}...`
: content;
+const asRecord = (value: unknown): Record<string, unknown> | null =>
+ value !== null && typeof value === "object"
+ ? (value as Record<string, unknown>)
+ : null;
+
+type ACPDisplayBlock =
+ | { type: "text"; text: string; language: string }
+ | { type: "diff"; path: string; oldText: string | null; newText: string };
+
+// A text block that is exactly one fenced code block (claude-agent-acp
+// markdown-escapes file reads and shell output this way). Captures the fence,
+// its language and the body so the body can be re-fenced after truncation
+// without leaving an unterminated fence behind.
+const WHOLLY_FENCED_RE = /^(`{3,})([^`\n]*)\n([\s\S]*?)\n?\1[ \t]*$/;
+
+const toTextBlock = (text: string): ACPDisplayBlock | null => {
+ const trimmed = text.trim();
+ if (!trimmed) return null;
+ const fenced = WHOLLY_FENCED_RE.exec(trimmed);
+ return fenced
+ ? { type: "text", text: fenced[3], language: fenced[2].trim() }
+ : { type: "text", text: trimmed, language: "" };
+};
+
+/**
+ * Normalize ``event.content`` β€” the client-facing view of an ACP tool call β€”
+ * into the blocks the card can display. The SDK persists blocks as snake_case
+ * (``old_text``) while the ACP wire uses camelCase (``oldText``); both are
+ * accepted. ``terminal`` blocks and non-text media carry nothing renderable
+ * here and are skipped.
+ */
+const getACPDisplayBlocks = (event: ACPToolCallEvent): ACPDisplayBlock[] => {
+ const blocks: ACPDisplayBlock[] = [];
+ for (const block of event.content ?? []) {
+ if (block.type === "diff") {
+ const path = block.path;
+ const newText = block.new_text ?? block.newText;
+ const oldText = block.old_text ?? block.oldText ?? null;
+ if (
+ typeof path === "string" &&
+ typeof newText === "string" &&
+ (oldText === null || typeof oldText === "string")
+ ) {
+ blocks.push({ type: "diff", path, oldText, newText });
+ }
+ } else if (block.type === "content") {
+ const inner = asRecord(block.content);
+ let text: unknown;
+ if (inner?.type === "text") {
+ text = inner.text;
+ } else if (inner?.type === "resource") {
+ text = asRecord(inner.resource)?.text;
+ }
+ const textBlock = typeof text === "string" ? toTextBlock(text) : null;
+ if (textBlock) blocks.push(textBlock);
+ }
+ }
+ return blocks;
+};
+
+const diffLines = (text: string | null, prefix: string): string[] =>
+ text
+ ? text
+ .replace(/\n$/, "")
+ .split("\n")
+ .map((line) => prefix + line)
+ : [];
+
+const formatDiffBlock = (
+ block: Extract<ACPDisplayBlock, { type: "diff" }>,
+): string => {
+ const body = [
+ ...diffLines(block.oldText, "- "),
+ ...diffLines(block.newText, "+ "),
+ ].join("\n");
+ return `${markdownInlineCode(block.path)}\n${markdownFence(truncate(body), "diff")}`;
+};
+
/**
* Build the markdown-flavored body for an ACP tool call card. Mirrors the
* shape of ``getTerminalObservationContent`` (``Command:`` + ``Output:``
* fenced blocks) so the rendered card lines up with regular OpenHands
* observations.
*
+ * The body prefers ``content``, the ACP field meant for display: ``diff``
+ * blocks render as a diff under the file path, and text blocks as the output.
+ * ``raw_output`` is provider-defined β€” absent for Gemini CLI, the model-facing
+ * tool result for Claude Code β€” so it is only used when ``content`` has
+ * nothing displayable, with the same "(no output)" fallback copy used by the
+ * bash observation renderer.
+ *
* For ``tool_kind === "execute"`` we surface ``raw_input.command`` as the
* command line; for others we fall back to a pretty-printed JSON dump of
- * the input. Output is always dumped as a fenced block, with the same
- * "(no output)" fallback copy used by the bash observation renderer.
+ * the input, unless a diff already shows what the call changed.
*/
export const getACPToolCallContent = (event: ACPToolCallEvent): string => {
const toolKind = event.tool_kind;
@@ -103,7 +188,11 @@ export const getACPToolCallContent = (event: ACPToolCallEvent): string => {
const rawOutput = event.raw_output;
const isError = event.is_error;
- let output = "";
+ const blocks = getACPDisplayBlocks(event);
+ const diffBlocks = blocks.filter((block) => block.type === "diff");
+ const textBlocks = blocks.filter((block) => block.type === "text");
+
+ const sections: string[] = [];
// Input block β€” command for execute, JSON dump otherwise.
if (
@@ -114,19 +203,40 @@ export const getACPToolCallContent = (event: ACPToolCallEvent): string => {
typeof (rawInput as { command: unknown }).command === "string"
) {
const { command } = rawInput as { command: string };
- output += `Command: \`${command}\`\n\n`;
- } else if (rawInput !== null && rawInput !== undefined && rawInput !== "") {
+ sections.push(`Command: \`${command}\``);
+ } else if (
+ diffBlocks.length === 0 &&
+ rawInput !== null &&
+ rawInput !== undefined &&
+ rawInput !== ""
+ ) {
const inputStr = stringifyPayload(rawInput);
if (inputStr.trim()) {
- output += `Input:\n\`\`\`json\n${inputStr}\n\`\`\`\n\n`;
+ sections.push(`Input:\n${markdownFence(inputStr, "json")}`);
}
}
- // Output block β€” matches the bash observation layout exactly.
- const outputStr = truncate(stringifyPayload(rawOutput).trim());
+ sections.push(...diffBlocks.map(formatDiffBlock));
+
const outputLabel = isError ? "**Error:**" : "Output:";
- const outputBody = outputStr || i18n.t(I18nKey.OBSERVATION$COMMAND_NO_OUTPUT);
- output += `${outputLabel}\n\`\`\`\n${outputBody}\n\`\`\``;
+ if (textBlocks.length > 0) {
+ const outputs = textBlocks.map((block) =>
+ markdownFence(truncate(block.text), block.language),
+ );
+ sections.push(`${outputLabel}\n${outputs.join("\n\n")}`);
+ } else {
+ // Output block β€” matches the bash observation layout exactly. A diff
+ // already shows what the call did, so raw_output is skipped alongside
+ // one β€” except on failure, where it may be the only place the error lives.
+ const outputStr = truncate(stringifyPayload(rawOutput).trim());
+ if (diffBlocks.length === 0) {
+ const outputBody =
+ outputStr || i18n.t(I18nKey.OBSERVATION$COMMAND_NO_OUTPUT);
+ sections.push(`${outputLabel}\n${markdownFence(outputBody)}`);
+ } else if (isError && outputStr) {
+ sections.push(`${outputLabel}\n${markdownFence(outputStr)}`);
+ }
+ }
- return output;
+ return sections.join("\n\n");
};
diff --git a/src/types/agent-server/core/events/acp-tool-call-event.ts b/src/types/agent-server/core/events/acp-tool-call-event.ts
index 5adcb10970..612e832575 100644
--- a/src/types/agent-server/core/events/acp-tool-call-event.ts
+++ b/src/types/agent-server/core/events/acp-tool-call-event.ts
@@ -5,7 +5,17 @@ import { BaseEvent } from "../base/event";
* Tool kinds emitted by ACP agents. Matches ACP's ``ToolKind`` enum,
* with ``"other"`` as the catch-all fallback.
*/
-export type ACPToolKind = "execute" | "edit" | "read" | "fetch" | "other";
+export type ACPToolKind =
+ | "read"
+ | "edit"
+ | "delete"
+ | "move"
+ | "search"
+ | "execute"
+ | "think"
+ | "fetch"
+ | "switch_mode"
+ | "other";
/**
* Status of an ACP tool call. The SDK persists two events per
@@ -21,9 +31,11 @@ export type ACPToolCallStatus =
| "failed";
/**
- * An ACP content block as surfaced on ``ACPToolCallEvent.content``. ACP
- * allows a mix of text, image, resource and resource_link blocks; only the
- * shape needed for rendering is captured here.
+ * An ACP tool call content block as surfaced on ``ACPToolCallEvent.content``:
+ * ``content`` (wrapping a text, image, resource or resource_link block),
+ * ``diff`` (``path`` + ``old_text`` / ``new_text``; camelCase on the ACP wire)
+ * or ``terminal``. Only the discriminator is typed; fields are read
+ * defensively by ``getACPToolCallContent``.
*/
export interface ACPToolCallContentBlock {
type: string;
diff --git a/src/utils/markdown-fence.ts b/src/utils/markdown-fence.ts
new file mode 100644
index 0000000000..903137b7e8
--- /dev/null
+++ b/src/utils/markdown-fence.ts
@@ -0,0 +1,28 @@
+const longestBacktickRun = (content: string): number =>
+ Math.max(
+ 0,
+ ...Array.from(content.matchAll(/`+/g), (match) => match[0].length),
+ );
+
+/**
+ * Wrap ``content`` in a fenced code block whose fence is longer than any
+ * backtick run inside it, so content that carries its own fences (a README,
+ * a markdown-escaped tool result) can't close the block early and spill out
+ * as live markdown.
+ */
+export const markdownFence = (content: string, language = ""): string => {
+ const fence = "`".repeat(Math.max(3, longestBacktickRun(content) + 1));
+ return `${fence}${language}\n${content}\n${fence}`;
+};
+
+/**
+ * Inline-code counterpart of {@link markdownFence}: the delimiter is one
+ * backtick longer than any run inside ``content``, and content that starts or
+ * ends with a backtick is padded with a space (which CommonMark strips) so it
+ * can't merge with the delimiter.
+ */
+export const markdownInlineCode = (content: string): string => {
+ const ticks = "`".repeat(longestBacktickRun(content) + 1);
+ const padded = /^`|`$/.test(content) ? ` ${content} ` : content;
+ return `${ticks}${padded}${ticks}`;
+};
diff --git a/src/utils/transcript-export/index.ts b/src/utils/transcript-export/index.ts
index 63d2b49115..635d7bf780 100644
--- a/src/utils/transcript-export/index.ts
+++ b/src/utils/transcript-export/index.ts
@@ -18,6 +18,7 @@ import {
isSwitchLLMObservationEvent,
} from "#/types/agent-server/type-guards";
import { handleEventForUI } from "#/utils/handle-event-for-ui";
+import { markdownFence } from "#/utils/markdown-fence";
import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
import { parseMessageFromEvent } from "#/components/conversation-events/chat/event-content-helpers/parse-message-from-event";
import { getActionContent } from "#/components/conversation-events/chat/event-content-helpers/get-action-content";
@@ -502,15 +503,6 @@ const markdownTimestamp = (
? `<sub>${escapeHtml(formatTimestamp(entry.timestamp))}</sub>\n\n`
: "";
-const markdownFence = (content: string): string => {
- const longestRun = Math.max(
- 0,
- ...Array.from(content.matchAll(/`+/g), (match) => match[0].length),
- );
- const fence = "`".repeat(Math.max(3, longestRun + 1));
- return `${fence}text\n${content}\n${fence}`;
-};
-
export const eventsToMarkdown = (
events: OpenHandsEvent[],
options: TranscriptExportOptions,
@@ -563,7 +555,7 @@ export const eventsToMarkdown = (
"<details>",
`<summary><strong>${escapeHtml(i18n.t(I18nKey.TRANSCRIPT_EXPORT$TOOL))}:</strong> ${escapeHtml(entry.summary)}</summary>`,
"",
- timestamp + markdownFence(entry.details),
+ timestamp + markdownFence(entry.details, "text"),
"",
"</details>",
"",