Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

fix(agent-runtime): restore tool images and MCP resources when resuming a delegate

xpeng5278-weba0f9ae4490c2
diff --git a/packages/agent-runtime/src/delegation-history.test.ts b/packages/agent-runtime/src/delegation-history.test.ts
index b86c027ef..aea0fe8b6 100644
--- a/packages/agent-runtime/src/delegation-history.test.ts
+++ b/packages/agent-runtime/src/delegation-history.test.ts
@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";
import { estimateTokens } from "./pi-runtime-estimates.js";
import type { Message } from "@earendil-works/pi-ai";
import { MAX_RESUMABLE_READ_LINES, type UiMessage } from "@pi-desktop/shared";
+import { timestampMs } from "./agent-messages.js";
+import { toolResultFromUi } from "./runtime.js";
import {
contextBudgetLimitsFor,
type ContextBudgetLimits,
@@ -1002,3 +1004,146 @@ describe("rebuildChainsFromTranscript settled copies and replay (ADR 0279)", ()
]);
});
});
+
+describe("chainRowsToMessages tool result content", () => {
+ // Long enough that stringifying the payload into a text block would dump
+ // image bytes into the resumed delegate prompt (#1073 / #1360).
+ const imageData = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJ".repeat(20);
+
+ function resumedToolResult(row: UiMessage) {
+ const messages = chainRowsToMessages(
+ [delegateAssistant("a1", "reading", "call-1"), row],
+ provider(),
+ buildProviderModel(provider()),
+ );
+ const restored = messages.find((message) => message.role === "toolResult");
+ expect(restored?.role).toBe("toolResult");
+ if (restored?.role !== "toolResult") {
+ throw new Error("expected a toolResult message");
+ }
+ expect(restored.content).toEqual(
+ toolResultFromUi(row, timestampMs(row.createdAt)).content,
+ );
+ return restored;
+ }
+
+ function expectNoBase64Text(
+ content: ReadonlyArray<{ type: string; text?: string }>,
+ data: string,
+ ): void {
+ for (const block of content) {
+ if (block.type === "text") expect(block.text).not.toContain(data);
+ }
+ }
+
+ it("restores a host Read image as an image block instead of base64 JSON text", () => {
+ // Host tool_read shape from #1073: top-level images, not content blocks.
+ const row = delegateTool(
+ "t1",
+ "Read",
+ { path: "shot.png" },
+ {
+ path: "shot.png",
+ text: "Image file shot.png (17 bytes, image/png); the image is attached to this result.",
+ images: [{ data: imageData, mimeType: "image/png" }],
+ },
+ "call-1",
+ );
+ const restored = resumedToolResult(row);
+
+ expect(restored.content).toContainEqual({
+ type: "image",
+ data: imageData,
+ mimeType: "image/png",
+ });
+ expectNoBase64Text(restored.content, imageData);
+ });
+
+ it("restores a bare plugin content-block array without flattening it to JSON", () => {
+ const row = delegateTool(
+ "t1",
+ "plugin_shot",
+ {},
+ [
+ { type: "text", text: "ok" },
+ { type: "image", data: imageData, mimeType: "image/png" },
+ ],
+ "call-1",
+ );
+ const restored = resumedToolResult(row);
+
+ expect(restored.content).toEqual([
+ { type: "text", text: "ok" },
+ { type: "image", data: imageData, mimeType: "image/png" },
+ ]);
+ expectNoBase64Text(restored.content, imageData);
+ });
+
+ it("restores an MCP text resource instead of the missing-result placeholder", () => {
+ const row = delegateTool(
+ "t1",
+ "get_file_contents",
+ { path: "a.ts" },
+ {
+ content: [
+ {
+ type: "resource",
+ resource: {
+ uri: "file:///a.ts",
+ mimeType: "text/plain",
+ text: "export const answer = 42;\n",
+ },
+ },
+ ],
+ },
+ "call-1",
+ );
+ const restored = resumedToolResult(row);
+
+ expect(restored.content).toEqual([
+ { type: "text", text: "export const answer = 42;\n" },
+ ]);
+ expect(
+ restored.content.some(
+ (block) => block.type === "text" && block.text === "[no tool result recorded]",
+ ),
+ ).toBe(false);
+ });
+
+ it("restores sibling text, an MCP resource body, and a resource link", () => {
+ const row = delegateTool(
+ "t1",
+ "get_file_contents",
+ { path: "a.ts" },
+ {
+ content: [
+ { type: "text", text: "successfully downloaded text file (SHA: abc123)" },
+ {
+ type: "resource",
+ resource: {
+ uri: "file:///a.ts",
+ mimeType: "text/plain",
+ text: "export const answer = 42;\n",
+ },
+ },
+ {
+ type: "resource_link",
+ uri: "https://raw.githubusercontent.com/acme/app/main/big.json",
+ name: "big.json",
+ },
+ ],
+ },
+ "call-1",
+ );
+ const restored = resumedToolResult(row);
+
+ expect(restored.content).toEqual([
+ { type: "text", text: "successfully downloaded text file (SHA: abc123)" },
+ { type: "text", text: "export const answer = 42;\n" },
+ {
+ type: "text",
+ text: "[resource link] big.json: https://raw.githubusercontent.com/acme/app/main/big.json",
+ },
+ ]);
+ });
+});
diff --git a/packages/agent-runtime/src/delegation-history.ts b/packages/agent-runtime/src/delegation-history.ts
index 3af820a3c..eae1a91d9 100644
--- a/packages/agent-runtime/src/delegation-history.ts
+++ b/packages/agent-runtime/src/delegation-history.ts
@@ -18,7 +18,9 @@
* rows stay transcript-only, tool rows attach to the assistant above them, an
* orphan tool row gets a synthesized carrier) but is parameterized by the
* delegate's own provider: a pinned delegation model is not the session model,
- * and api/replay details depend on the binding.
+ * and api/replay details depend on the binding. Tool-result content blocks
+ * come from `restoredToolResultContent`, shared with the parent's
+ * `toolResultFromUi`.
*/
import { estimateTokens } from "./pi-runtime-estimates.js";
@@ -39,6 +41,7 @@ import {
type UiMessage,
} from "@pi-desktop/shared";
import { isRecord, timestampMs, toJsonObject, toJsonValue, usageToPi } from "./agent-messages.js";
+import { restoredToolResultContent } from "./tool-result-content.js";
import type { ContextBudgetLimits } from "./context-budget.js";
import {
apiBindingForProviderModel,
@@ -432,31 +435,7 @@ function truncateSeededMessages(
function toolResultFromUi(m: UiMessage, timestamp: number): ToolResultMessage {
const raw = m.toolResult;
- const blocks: ToolResultMessage["content"] = [];
- const rawBlocks =
- isRecord(raw) && Array.isArray(raw.content) ? raw.content : undefined;
- if (rawBlocks) {
- for (const block of rawBlocks) {
- if (!isRecord(block)) continue;
- if (block.type === "text" && typeof block.text === "string") {
- blocks.push({ type: "text", text: block.text });
- } else if (
- block.type === "image" &&
- typeof block.data === "string" &&
- typeof block.mimeType === "string"
- ) {
- blocks.push({
- type: "image",
- data: block.data,
- mimeType: block.mimeType,
- });
- }
- }
- } else if (typeof raw === "string" && raw.trim()) {
- blocks.push({ type: "text", text: raw });
- } else if (raw !== undefined && raw !== null) {
- blocks.push({ type: "text", text: safeJson(raw) });
- }
+ const blocks = restoredToolResultContent(raw);
if (blocks.length === 0) {
blocks.push({
type: "text",
@@ -504,14 +483,6 @@ function toolResultFromUi(m: UiMessage, timestamp: number): ToolResultMessage {
};
}
-function safeJson(value: unknown): string {
- try {
- return JSON.stringify(value);
- } catch {
- return String(value);
- }
-}
-
export type RebuiltTaskCall = {
toolCallId: string;
delegationId: string;
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 21934c3a2..d31d1199d 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -152,6 +152,10 @@ import {
usageFromPi,
usageToPi,
} from "./agent-messages.js";
+import {
+ hostContentBlockText,
+ restoredToolResultContent,
+} from "./tool-result-content.js";
import { withExplicitRequired } from "./tool-schema.js";
import { buildSessionContext } from "./session-context.js";
import {
@@ -1601,33 +1605,6 @@ function selectRetainedUserMessages(
return selected.reverse();
}
-/**
- * Model-visible text for one host tool content block. Besides plain `text`
- * blocks, MCP servers return file bodies as embedded text resources and large
- * payloads as resource links (github-mcp-server `get_file_contents` sends a
- * status line plus one of these), so dropping them next to a sibling text
- * block hides the actual result from the model. Binary resources and other
- * block kinds have no text to show and stay out of the text channel.
- */
-function hostContentBlockText(block: unknown): string | undefined {
- if (!isRecord(block)) return undefined;
- if (block.type === "text" && typeof block.text === "string") return block.text;
- if (
- block.type === "resource" &&
- isRecord(block.resource) &&
- typeof block.resource.text === "string"
- ) {
- return block.resource.text;
- }
- if (block.type === "resource_link" && typeof block.uri === "string") {
- const name = typeof block.name === "string" && block.name.trim()
- ? `${block.name.trim()}: `
- : "";
- return `[resource link] ${name}${block.uri}`;
- }
- return undefined;
-}
-
/**
* JSON text fallback for a host result that produced no text blocks. Image
* `data` and resource `blob` bytes stay off the text channel; type, mimeType,
@@ -1661,67 +1638,7 @@ export function toolResultFromUi(
timestamp: number,
): ToolResultMessage {
const raw: unknown = m.toolResult;
- const blocks: ToolResultMessage["content"] = [];
- const rawBlocks =
- isRecord(raw) && Array.isArray(raw.content) ? raw.content : undefined;
- if (rawBlocks) {
- for (const b of rawBlocks) {
- if (!isRecord(b)) continue;
- // Same text rule as live execution: embedded MCP resources and resource
- // links stay visible after a session restore. Binary resources have no
- // text and stay out.
- const blockText = hostContentBlockText(b);
- if (blockText !== undefined) {
- blocks.push({ type: "text", text: blockText });
- } else if (
- b.type === "image" &&
- typeof b.data === "string" &&
- typeof b.mimeType === "string"
- ) {
- blocks.push({ type: "image", data: b.data, mimeType: b.mimeType });
- }
- }
- } else if (Array.isArray(raw)) {
- // Plugin tools may return a bare content-block array; restore its text
- // and image blocks so a restart does not flatten them into JSON (#1360).
- for (const b of raw) {
- if (!isRecord(b)) continue;
- const blockText = hostContentBlockText(b);
- if (blockText !== undefined) {
- blocks.push({ type: "text", text: blockText });
- } else if (
- b.type === "image" &&
- typeof b.data === "string" &&
- typeof b.mimeType === "string"
- ) {
- blocks.push({ type: "image", data: b.data, mimeType: b.mimeType });
- }
- }
- } else if (typeof raw === "string" && raw.trim()) {
- blocks.push({ type: "text", text: raw });
- } else if (raw !== undefined && raw !== null) {
- // A host Read of an image file returns a top-level `images` array rather
- // than content blocks; restore those as real image content so the model
- // sees the picture across a restart, not just the JSON text (#1073).
- const rawObject = isRecord(raw) ? raw : undefined;
- const images = rawObject?.images;
- if (rawObject && Array.isArray(images)) {
- const rest = { ...rawObject };
- delete rest.images;
- blocks.push({ type: "text", text: safeJson(rest) });
- for (const image of images) {
- if (
- isRecord(image) &&
- typeof image.data === "string" &&
- typeof image.mimeType === "string"
- ) {
- blocks.push({ type: "image", data: image.data, mimeType: image.mimeType });
- }
- }
- } else {
- blocks.push({ type: "text", text: safeJson(raw) });
- }
- }
+ const blocks = restoredToolResultContent(raw);
const interrupted = m.toolStatus === "running";
const rawRecord: Record<string, unknown> | undefined = isRecord(raw)
? raw
diff --git a/packages/agent-runtime/src/tool-result-content.ts b/packages/agent-runtime/src/tool-result-content.ts
new file mode 100644
index 000000000..ea8f4e681
--- /dev/null
+++ b/packages/agent-runtime/src/tool-result-content.ts
@@ -0,0 +1,113 @@
+/**
+ * Model-visible content blocks for a persisted tool result.
+ *
+ * The parent session restore (`toolResultFromUi` in `runtime.ts`) and a
+ * delegate `Task(resume)` rebuild (`delegation-history.ts`) must apply the
+ * same rules. One helper keeps a resumed subagent from flattening image
+ * bytes into JSON text or dropping MCP resource bodies.
+ */
+
+import type { ToolResultMessage } from "@earendil-works/pi-ai";
+import { isRecord } from "./agent-messages.js";
+
+/**
+ * Model-visible text for one host tool content block. Besides plain `text`
+ * blocks, MCP servers return file bodies as embedded text resources and large
+ * payloads as resource links (github-mcp-server `get_file_contents` sends a
+ * status line plus one of these), so dropping them next to a sibling text
+ * block hides the actual result from the model. Binary resources and other
+ * block kinds have no text to show and stay out of the text channel.
+ */
+export function hostContentBlockText(block: unknown): string | undefined {
+ if (!isRecord(block)) return undefined;
+ if (block.type === "text" && typeof block.text === "string") return block.text;
+ if (
+ block.type === "resource" &&
+ isRecord(block.resource) &&
+ typeof block.resource.text === "string"
+ ) {
+ return block.resource.text;
+ }
+ if (block.type === "resource_link" && typeof block.uri === "string") {
+ const name = typeof block.name === "string" && block.name.trim()
+ ? `${block.name.trim()}: `
+ : "";
+ return `[resource link] ${name}${block.uri}`;
+ }
+ return undefined;
+}
+
+function safeJson(value: unknown): string {
+ try {
+ return JSON.stringify(value) ?? String(value);
+ } catch {
+ return String(value);
+ }
+}
+
+function appendContentBlocks(
+ blocks: ToolResultMessage["content"],
+ entries: readonly unknown[],
+): void {
+ for (const block of entries) {
+ if (!isRecord(block)) continue;
+ const blockText = hostContentBlockText(block);
+ if (blockText !== undefined) {
+ blocks.push({ type: "text", text: blockText });
+ } else if (
+ block.type === "image" &&
+ typeof block.data === "string" &&
+ typeof block.mimeType === "string"
+ ) {
+ blocks.push({ type: "image", data: block.data, mimeType: block.mimeType });
+ }
+ }
+}
+
+/**
+ * Content blocks for a persisted tool result. Does not insert the
+ * missing-result placeholder; each caller keeps its own placeholder, details,
+ * and error rules.
+ *
+ * Covers `raw.content`, a bare content-block array (#1360), a plain string,
+ * and a host Read image file's top-level `images` array (#1073). Image `data`
+ * stays on image blocks. Anything else present becomes JSON text.
+ */
+export function restoredToolResultContent(
+ raw: unknown,
+): ToolResultMessage["content"] {
+ const blocks: ToolResultMessage["content"] = [];
+ const rawBlocks =
+ isRecord(raw) && Array.isArray(raw.content) ? raw.content : undefined;
+ if (rawBlocks) {
+ appendContentBlocks(blocks, rawBlocks);
+ } else if (Array.isArray(raw)) {
+ appendContentBlocks(blocks, raw);
+ } else if (typeof raw === "string" && raw.trim()) {
+ blocks.push({ type: "text", text: raw });
+ } else if (raw !== undefined && raw !== null) {
+ const rawObject = isRecord(raw) ? raw : undefined;
+ const images = rawObject?.images;
+ if (rawObject && Array.isArray(images)) {
+ const rest = { ...rawObject };
+ delete rest.images;
+ blocks.push({ type: "text", text: safeJson(rest) });
+ for (const image of images) {
+ if (
+ isRecord(image) &&
+ typeof image.data === "string" &&
+ typeof image.mimeType === "string"
+ ) {
+ blocks.push({
+ type: "image",
+ data: image.data,
+ mimeType: image.mimeType,
+ });
+ }
+ }
+ } else {
+ blocks.push({ type: "text", text: safeJson(raw) });
+ }
+ }
+ return blocks;
+}