From d4f091b5afefa4b2eaf449a1ab7de5ce50470ffa Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 3 Dec 2026 07:56:41 -0800 Subject: [PATCH 1/2] Open a conversation whose tool result is a list of parts AG-UI 1.0 lets a tool result be a string or a list of content parts, and the stock ag_ui_claude_sdk adapter sends a list whenever a Claude tool result is anything but one plain text block: Read on a picture or a PDF, or an MCP tool that answered in several parts. The transcript read every result as a string, so the first .trim() on a list threw inside ChatTranscript's render and blanked the page, and a stored history holding one could not be opened again. The transcript projection now turns a tool message's content into text once, for every reader: a string as it came, a list as its text parts with a short line for a picture, document or other part, anything else as JSON. The result readers in tool-result.ts and the gallery and sandboxed renderers take any value. One message or step that still cannot be read now costs that row alone, not the conversation. --- app/src/components/channels/chat-messages.ts | 39 +++- app/src/components/channels/tool-activity.tsx | 14 ++ app/src/lib/copilot/gallery-tools.tsx | 12 +- app/src/lib/copilot/sandboxed-tools.tsx | 11 +- app/src/lib/plugins/tool-result.ts | 90 ++++++-- app/tests/tool-result-parts.test.tsx | 204 ++++++++++++++++++ shared/tool-steps.ts | 2 + 7 files changed, 342 insertions(+), 30 deletions(-) create mode 100644 app/tests/tool-result-parts.test.tsx diff --git a/app/src/components/channels/chat-messages.ts b/app/src/components/channels/chat-messages.ts index 44b779abd0..2a838c42d8 100644 --- a/app/src/components/channels/chat-messages.ts +++ b/app/src/components/channels/chat-messages.ts @@ -9,6 +9,7 @@ import { } from "@openbot/shared/orchestration"; import { leftOutOfTranscript } from "@openbot/shared/tool-steps"; import { classifyAttachment } from "@/lib/channels/attachments"; +import { toolResultText } from "@/lib/plugins/tool-result"; /** * Transcript projection that pairs assistant tool calls with later tool-result messages. @@ -310,8 +311,18 @@ function isReadableToolCall(toolCall: unknown): toolCall is ToolCall { return typeof (called as { name?: unknown }).name === "string"; } -/** A tool result, as it arrives, its own message, pointing back at the call it answers. */ -type ToolResultMessage = { role: "tool"; toolCallId: string; content?: string }; +/** + * A tool result, as it arrives, its own message, pointing back at the call it answers. + * + * `content` IS UNKNOWN BECAUSE IT IS. AG-UI 1.0 allows a string or a list of parts, and a connected + * Bot sends a list for a picture it read (see `toolResultText`). Everything downstream reads + * `VisibleChatItem.result` as a string, so it is turned into one here, once, for every reader. + */ +type ToolResultMessage = { + role: "tool"; + toolCallId: string; + content?: unknown; +}; /** * A MESSAGE THAT IS AN OBJECT AT ALL AND CARRIES AN ID, which is a lower bar than any guard above @@ -401,10 +412,28 @@ export function toVisibleChatItems( // Both passes over this array are guarded, not just this one: a guard on only the first would // move the throw into the flatMap below rather than remove it. if (!isReadableMessage(message)) continue; - if (isToolResult(message)) results.set(message.toolCallId, message.content); + if (isToolResult(message)) + results.set(message.toolCallId, toolResultText(message.content)); } const visible = messages.flatMap((message): VisibleChatItem[] => { + /* + * ONE MESSAGE THAT CANNOT BE DRAWN COSTS THAT MESSAGE ALONE. This runs inside `ChatTranscript`'s + * render, outside any row's `ToolRenderBoundary`, so a throw here blanked the whole page: a list + * where a string was expected did exactly that to every conversation that held one. Every guard + * below is for a shape somebody has seen; this is for the next one. + */ + try { + return visibleItemsOf(message); + } catch (error) { + console.error("[transcript] a message could not be drawn", error); + return []; + } + }); + + return asTheBotMeantIt(visible); + + function visibleItemsOf(message: Readonly): VisibleChatItem[] { if (!isReadableMessage(message)) return []; // Every row built below is keyed on `message.id`, including the one that keys on it by string // interpolation. See `isDrawableMessage` for why an unkeyable row is dropped rather than given @@ -619,9 +648,7 @@ export function toVisibleChatItems( if (text) items.push({ kind: "text", id: message.id, role: "user", text }); return items; - }); - - return asTheBotMeantIt(visible); + } } /** A run of nothing but the reactions a Bot may leave, as a reply's whole text. */ diff --git a/app/src/components/channels/tool-activity.tsx b/app/src/components/channels/tool-activity.tsx index 2d7ba29bde..f62d9229b8 100644 --- a/app/src/components/channels/tool-activity.tsx +++ b/app/src/components/channels/tool-activity.tsx @@ -303,6 +303,20 @@ export function asksThePerson(result: string | undefined): boolean { * each of them, and those are different questions with different buttons. */ function cardApp(item: ToolItem): string | null { + /* + * Read over every row on every render of the transcript, outside any row's boundary, so a throw + * here blanked the page (a Read of a picture did, its result a list of parts). A row it cannot + * read draws no card and is kept. + */ + try { + return cardAppOf(item); + } catch (error) { + console.error("[transcript] a step's card could not be read", error); + return null; + } +} + +function cardAppOf(item: ToolItem): string | null { if (item.result === undefined) return null; const answer = asText(item.result); const prompt = answer.startsWith(REFUSAL_MARKER) diff --git a/app/src/lib/copilot/gallery-tools.tsx b/app/src/lib/copilot/gallery-tools.tsx index da1d302e9f..df82c43f6e 100644 --- a/app/src/lib/copilot/gallery-tools.tsx +++ b/app/src/lib/copilot/gallery-tools.tsx @@ -54,7 +54,7 @@ import { } from "@/lib/copilot/grant-store"; import { settledArgs } from "@/lib/copilot/settled-args"; import { drawnTooEarlyIn } from "@/lib/copilot/tool-steps"; -import { browserCallFailed } from "@/lib/plugins/tool-result"; +import { browserCallFailed, toolResultText } from "@/lib/plugins/tool-result"; /** * Register compiled gallery components once per name. Which run is offered which is decided per run, @@ -224,12 +224,14 @@ export function makeGalleryRender(spec: GalleryComponent, store: GrantStore) { * never had one: the server answered the call itself (`server/src/components/headless.ts`). * The result is what survives, so a call that drew nothing is drawn as the refusal it was. */ - if (props.result?.startsWith(NOT_SHOWN)) { + // Read as text whatever it arrived as: a connected Bot's result can be a list of parts. + const stored = toolResultText(props.result); + if (stored?.startsWith(NOT_SHOWN)) { const lead = `${NOT_SHOWN}${spec.title}. `; const reason = ( - props.result.startsWith(lead) - ? props.result.slice(lead.length) - : props.result.slice(NOT_SHOWN.length) + stored.startsWith(lead) + ? stored.slice(lead.length) + : stored.slice(NOT_SHOWN.length) ).replace(NOT_SHOWN_TAIL, ""); return ; } diff --git a/app/src/lib/copilot/sandboxed-tools.tsx b/app/src/lib/copilot/sandboxed-tools.tsx index af765b17a3..6908d27ae4 100644 --- a/app/src/lib/copilot/sandboxed-tools.tsx +++ b/app/src/lib/copilot/sandboxed-tools.tsx @@ -31,6 +31,7 @@ import { grantsFrom, } from "@/lib/copilot/grant-store"; import { drawnTooEarlyIn } from "@/lib/copilot/tool-steps"; +import { toolResultText } from "@/lib/plugins/tool-result"; /** * Browser-authored components use the same component grants as compiled gallery components, but @@ -189,12 +190,14 @@ export function makeSandboxedRender( * A stored refusal: the in-memory one is gone once the page reloads, and the result is what * survives, so a call that drew nothing is drawn as the refusal it was. */ - if (props.result?.startsWith(NOT_SHOWN)) { + // Read as text whatever it arrived as: a connected Bot's result can be a list of parts. + const stored = toolResultText(props.result); + if (stored?.startsWith(NOT_SHOWN)) { const lead = `${NOT_SHOWN}${component.title}. `; const reason = ( - props.result.startsWith(lead) - ? props.result.slice(lead.length) - : props.result.slice(NOT_SHOWN.length) + stored.startsWith(lead) + ? stored.slice(lead.length) + : stored.slice(NOT_SHOWN.length) ).replace(NOT_SHOWN_TAIL, ""); return ; } diff --git a/app/src/lib/plugins/tool-result.ts b/app/src/lib/plugins/tool-result.ts index a910da662b..970f5300f5 100644 --- a/app/src/lib/plugins/tool-result.ts +++ b/app/src/lib/plugins/tool-result.ts @@ -19,11 +19,67 @@ export const REFUSAL_MARKER = "Refused."; * kind of step the same way), and read as a result, a folder edit the person declined was drawn as * "Saved a file". */ -export function refusalOf(answer: string | undefined): string | undefined { +export function refusalOf(answer: unknown): string | undefined { if (answer === undefined) return undefined; - if (answer.startsWith(REFUSAL_MARKER)) - return answer.slice(REFUSAL_MARKER.length).trim(); - return declinedByPerson(answer) ? answer.trim() : undefined; + const text = textOf(answer); + if (text.startsWith(REFUSAL_MARKER)) + return text.slice(REFUSAL_MARKER.length).trim(); + return declinedByPerson(text) ? text.trim() : undefined; +} + +/** What a part a tool returned is drawn as, when it is not text. */ +const PART_PLACEHOLDERS: Record = { + image: "Returned an image.", + document: "Returned a document.", + audio: "Returned an audio clip.", + video: "Returned a video.", +}; +const OTHER_PART = "Returned a file."; + +/** + * A tool message's `content` as text, or undefined when it has none. + * + * AG-UI 1.0 lets a tool result be a string OR A LIST OF PARTS (`ToolMessageSchema`), and the stock + * `ag_ui_claude_sdk` adapter sends a list whenever a Claude tool result is anything but one plain + * text block: Read on a picture or a PDF, or an MCP tool that answered in several parts. Everything + * that reads a result here reads text, and one `.trim()` on a list took the whole conversation down. + * + * A string is kept exactly as it came, so a refusal marker or a JSON envelope still reads the same. + * A list becomes its text parts, one per line, with a short line for each picture, document or + * other part in its place. Anything else (an object, a number, `null`) is shown as JSON. The live + * stream and a stored history both come through here, so they draw the same. + */ +export function toolResultText(content: unknown): string | undefined { + if (content === undefined) return undefined; + if (typeof content === "string") return content; + if (Array.isArray(content)) { + return content + .map((part): string => { + if (typeof part !== "object" || part === null) return jsonOf(part); + const { type, text } = part as { type?: unknown; text?: unknown }; + if (type === "text") return typeof text === "string" ? text : ""; + if (typeof type === "string") + return PART_PLACEHOLDERS[type] ?? OTHER_PART; + return jsonOf(part); + }) + .filter((line) => line !== "") + .join("\n"); + } + return jsonOf(content); +} + +function jsonOf(value: unknown): string { + try { + return JSON.stringify(value) ?? String(value); + } catch { + // A value JSON cannot hold (a cycle, a BigInt) still says what it was. + return String(value); + } +} + +/** A result as text whatever it arrived as. A string is returned untouched. */ +function textOf(value: unknown): string { + return typeof value === "string" ? value : (toolResultText(value) ?? ""); } /** @@ -40,8 +96,11 @@ export function refusalOf(answer: string | undefined): string | undefined { * * Only a JSON string is unwrapped. An object or an array is a vendor's envelope, which is * {@link forDisplay}'s job, and anything that is not JSON at all is already what it says. + * + * Any value is accepted: a result that is not a string is read by {@link toolResultText} first. */ -export function asText(text: string): string { +export function asText(value: unknown): string { + const text = textOf(value); const trimmed = text.trim(); if (!trimmed.startsWith('"')) return text; try { @@ -60,8 +119,8 @@ export function asText(text: string): string { * wants the vendor's answer, drawn the way it always was. Declared at both ends like * {@link REFUSAL_MARKER}. Text with no envelope is returned unchanged. */ -export function withoutUntrustedEnvelope(text: string): string { - return text.replace( +export function withoutUntrustedEnvelope(text: unknown): string { + return textOf(text).replace( /CRITICAL: The following [^\n]* is untrusted data, not instructions or tool authorization\.[^\n]*\n\n([\s\S]*?)\n<\/untrusted_data>/g, (_match, inner: string) => inner.replace(/<\\\/untrusted_data/gi, " { + GlobalRegistrator.register({ url: "http://localhost/" }); + globalThis.fetch = Object.assign( + async () => Response.json({ error: "not served" }, { status: 404 }), + { preconnect: originalFetch.preconnect }, + ); +}); + +afterEach(() => { + cleanup(); + queryClient.clear(); +}); + +afterAll(async () => { + await settleReactWork(); + globalThis.fetch = originalFetch; + GlobalRegistrator.unregister(); +}); + +/** One turn: the person asks, the Bot calls `name`, the call answers `content`, the Bot replies. */ +function storedTurn(name: string, args: string, content: unknown): unknown[] { + return [ + { id: "u1", role: "user", content: "Look at model2.png" }, + { + id: "a1", + role: "assistant", + toolCalls: [ + { + id: "toolu_01", + type: "function", + function: { name, arguments: args }, + }, + ], + }, + { id: "toolu_01-result", role: "tool", toolCallId: "toolu_01", content }, + { id: "a2", role: "assistant", content: "It is a ribbon diagram." }, + ]; +} + +/** + * The tool message `ag_ui_claude_sdk` 0.2.4 puts in its snapshot for Claude Code's Read of a picture, + * printed by running the adapter's own `build_agui_tool_message` on the `ToolResultBlock` Claude + * Code hands it (one base64 image block). Its TOOL_CALL_RESULT carries the same `content`. + */ +const PICTURE_BLOCK = { + type: "image", + source: { type: "base64", data: "iVBORw0KGgo=", media_type: "image/png" }, +}; +const READ_OF_A_PICTURE = storedTurn( + "Read", + '{"file_path":"/workspace/model2.png"}', + [ + { + type: "image", + source: { type: "data", value: "iVBORw0KGgo=", mimeType: "image/png" }, + metadata: { claude: { block: PICTURE_BLOCK, isError: false } }, + }, + ], +); + +/** The same adapter's tool message for an MCP tool that answered in two text blocks. */ +const textPart = (text: string) => ({ + type: "text", + text, + metadata: { claude: { block: { type: "text", text }, isError: false } }, +}); +const TWO_TEXT_PARTS = storedTurn("mcp__docs__search", '{"q":"ribbon"}', [ + textPart("Found 2 pages"), + textPart("Ribbon diagrams\nProtein folds"), +]); + +function resultOf(messages: readonly Message[]): string | undefined { + const items = dropRepeatedAppCards(toVisibleChatItems(messages)); + const step = items.find((item) => item.kind === "tool"); + return step?.kind === "tool" ? step.result : undefined; +} + +function draw(messages: readonly Message[]) { + return render( + + + + + + , + ); +} + +test("a stored Read of a picture opens, and draws the Read step and the reply", async () => { + const read = readableTurns(READ_OF_A_PICTURE); + expect(read.unreadable).toBe(0); + // The projection is what threw: `cardApp` -> `asText` -> `.trim()` on the list. + expect(resultOf(read.messages)).toBe("Returned an image."); + + const view = draw(read.messages); + expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); + // The finished turn's work is folded; opened, as a person does, it shows the Read step. + fireEvent.click(view.getByText("Worked through 1 step")); + expect(await view.findByText("model2.png")).toBeTruthy(); + expect(view.getByText("Read")).toBeTruthy(); + expect(view.getByText("Returned an image.")).toBeTruthy(); +}); + +test("a result in several text parts reads as those parts, one per line", async () => { + const read = readableTurns(TWO_TEXT_PARTS); + expect(read.unreadable).toBe(0); + expect(resultOf(read.messages)).toBe( + "Found 2 pages\nRibbon diagrams\nProtein folds", + ); + + const view = draw(read.messages); + expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); + fireEvent.click(view.getByText("Worked through 1 step")); + expect(await view.findByText("Search")).toBeTruthy(); + expect(view.container.textContent).toContain( + "Found 2 pages\nRibbon diagrams\nProtein folds", + ); +}); + +test("a live result that is a JSON object is drawn as JSON", async () => { + // Not a shape the schema lets a stored history keep, so it comes the way a live run hands it over. + const live = storedTurn("lookup_rows", "{}", { + rows: 2, + names: ["a", "b"], + }) as Message[]; + expect(resultOf(live)).toBe('{"rows":2,"names":["a","b"]}'); + + const view = draw(live); + expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); + fireEvent.click(view.getByText("Worked through 1 step")); + expect(await view.findByText("Lookup rows")).toBeTruthy(); + expect(view.container.textContent).toContain('"rows": 2'); +}); + +test("the result readers take a list of parts as text", () => { + const parts = [ + { type: "text", text: "Refused. Not allowed here." }, + { type: "document", source: { type: "url", value: "https://x/y.pdf" } }, + ]; + expect(asText(parts)).toBe( + "Refused. Not allowed here.\nReturned a document.", + ); + expect(forDisplay(parts)).toBe( + "Refused. Not allowed here.\nReturned a document.", + ); + expect(asText(null)).toBe("null"); + expect(asText(undefined)).toBe(""); +}); + +test("one message that cannot be drawn leaves the rest of the conversation", async () => { + const broken = { + id: "a-broken", + role: "assistant", + content: "", + get toolCalls(): never { + throw new TypeError("not what anybody expected"); + }, + }; + const messages = [ + { id: "u1", role: "user", content: "Hello" }, + broken, + { id: "a2", role: "assistant", content: "Still here." }, + ] as unknown as Message[]; + const errors = console.error; + console.error = () => {}; + try { + const view = draw(messages); + expect(await view.findByText("Still here.")).toBeTruthy(); + expect(view.getByText("Hello")).toBeTruthy(); + } finally { + console.error = errors; + } +}); diff --git a/shared/tool-steps.ts b/shared/tool-steps.ts index 925316f157..04fe9e6a77 100644 --- a/shared/tool-steps.ts +++ b/shared/tool-steps.ts @@ -86,6 +86,8 @@ export function stepOf( /** An answer that is a real one, not a stand-in the transport put there while the call waits. */ function settled(result: string | undefined): boolean { + // A connected Bot's result can arrive as a list of parts; one that is not text is an answer. + if (result !== undefined && typeof result !== "string") return true; const text = result?.trim(); return ( !!text && From 413cdcc349ac2bd2befd8ae4000765f5c44161c4 Mon Sep 17 00:00:00 2001 From: David McKay Date: Thu, 3 Dec 2026 08:35:58 -0800 Subject: [PATCH 2/2] Draw each part of a tool result as its own paragraph The result is drawn as markdown, which runs single lines together, so two text parts read as one sentence (Found 2 pages Ribbon diagrams Protein folds). Found by the end-to-end run. --- app/src/lib/plugins/tool-result.ts | 27 +++++++++++++++------------ app/tests/tool-result-parts.test.tsx | 14 +++++++------- 2 files changed, 22 insertions(+), 19 deletions(-) diff --git a/app/src/lib/plugins/tool-result.ts b/app/src/lib/plugins/tool-result.ts index 970f5300f5..bf121f41e8 100644 --- a/app/src/lib/plugins/tool-result.ts +++ b/app/src/lib/plugins/tool-result.ts @@ -45,7 +45,7 @@ const OTHER_PART = "Returned a file."; * that reads a result here reads text, and one `.trim()` on a list took the whole conversation down. * * A string is kept exactly as it came, so a refusal marker or a JSON envelope still reads the same. - * A list becomes its text parts, one per line, with a short line for each picture, document or + * A list becomes its text parts, a paragraph each, with a short line for each picture, document or * other part in its place. Anything else (an object, a number, `null`) is shown as JSON. The live * stream and a stored history both come through here, so they draw the same. */ @@ -53,17 +53,20 @@ export function toolResultText(content: unknown): string | undefined { if (content === undefined) return undefined; if (typeof content === "string") return content; if (Array.isArray(content)) { - return content - .map((part): string => { - if (typeof part !== "object" || part === null) return jsonOf(part); - const { type, text } = part as { type?: unknown; text?: unknown }; - if (type === "text") return typeof text === "string" ? text : ""; - if (typeof type === "string") - return PART_PLACEHOLDERS[type] ?? OTHER_PART; - return jsonOf(part); - }) - .filter((line) => line !== "") - .join("\n"); + return ( + content + .map((part): string => { + if (typeof part !== "object" || part === null) return jsonOf(part); + const { type, text } = part as { type?: unknown; text?: unknown }; + if (type === "text") return typeof text === "string" ? text : ""; + if (typeof type === "string") + return PART_PLACEHOLDERS[type] ?? OTHER_PART; + return jsonOf(part); + }) + .filter((line) => line !== "") + // A blank line between parts: the result is drawn as markdown, which runs single lines together. + .join("\n\n") + ); } return jsonOf(content); } diff --git a/app/tests/tool-result-parts.test.tsx b/app/tests/tool-result-parts.test.tsx index a3dbf338db..6f524cdb95 100644 --- a/app/tests/tool-result-parts.test.tsx +++ b/app/tests/tool-result-parts.test.tsx @@ -132,20 +132,20 @@ test("a stored Read of a picture opens, and draws the Read step and the reply", expect(view.getByText("Returned an image.")).toBeTruthy(); }); -test("a result in several text parts reads as those parts, one per line", async () => { +test("a result in several text parts reads as those parts, a paragraph each", async () => { const read = readableTurns(TWO_TEXT_PARTS); expect(read.unreadable).toBe(0); expect(resultOf(read.messages)).toBe( - "Found 2 pages\nRibbon diagrams\nProtein folds", + "Found 2 pages\n\nRibbon diagrams\nProtein folds", ); const view = draw(read.messages); expect(await view.findByText("It is a ribbon diagram.")).toBeTruthy(); fireEvent.click(view.getByText("Worked through 1 step")); expect(await view.findByText("Search")).toBeTruthy(); - expect(view.container.textContent).toContain( - "Found 2 pages\nRibbon diagrams\nProtein folds", - ); + // Each part its own paragraph: run together, they read "Found 2 pages Ribbon diagrams …". + expect(view.getByText("Found 2 pages").tagName).toBe("P"); + expect(view.getByText("Ribbon diagrams Protein folds").tagName).toBe("P"); }); test("a live result that is a JSON object is drawn as JSON", async () => { @@ -169,10 +169,10 @@ test("the result readers take a list of parts as text", () => { { type: "document", source: { type: "url", value: "https://x/y.pdf" } }, ]; expect(asText(parts)).toBe( - "Refused. Not allowed here.\nReturned a document.", + "Refused. Not allowed here.\n\nReturned a document.", ); expect(forDisplay(parts)).toBe( - "Refused. Not allowed here.\nReturned a document.", + "Refused. Not allowed here.\n\nReturned a document.", ); expect(asText(null)).toBe("null"); expect(asText(undefined)).toBe("");