Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(agent-runtime): bound restored image history bytes
vastsa9f92501ac757
diff --git a/docs/adr/0101-model-aware-image-attachments.md b/docs/adr/0101-model-aware-image-attachments.mdindex 66b53f827..f95018621 100644--- a/docs/adr/0101-model-aware-image-attachments.md+++ b/docs/adr/0101-model-aware-image-attachments.md@@ -32,11 +32,17 @@ renderer discovery and user-entered model ids are not sufficient evidence.the sidecar only as transient base64 data and becomes a pi-ai image contentblock. The base64 value is never persisted in SQLite, JSONL, or renderertranscript state.-5. For a non-vision model, an unknown model, or an image above the inline- limit, the prompt receives a safe `@path` fallback. Replayed content-store- images are copied into the session scratch `replayed/` directory before that- fallback is exposed to the model.-6. The Composer shows a compact accessible status row when an image is attached:+5. For a non-vision model, an unknown model, or an image above the per-image+ inline limit, the prompt receives a safe `@path` fallback. Replayed+ content-store images are copied into the session scratch `replayed/`+ directory before that fallback is exposed to the model.+6. Restored vision history has a 50 MB aggregate raw-image-byte budget in+ addition to the 10 MB per-image limit. The sidecar considers newest+ attachments first, preserving all images when the history fits; older images+ beyond the budget use the safe path fallback. The current prompt row is+ excluded before history hydration so its transient payload does not consume+ the history budget.+7. The Composer shows a compact accessible status row when an image is attached:it states whether the selected model can receive visual input. The modelpicker and session/provider summaries expose the same authoritative visioncapability.@@ -48,6 +54,9 @@ renderer discovery and user-entered model ids are not sufficient evidence.- Text-only and non-vision models retain the existing file-tool workflow.- Image bytes are deduplicated and can survive retry, fork, and runtimerecreation without putting binary data in the transcript.+- Restored sessions preserve historical vision blocks regardless of age while+ the images fit within one fixed aggregate budget; over-budget history has a+ deterministic memory ceiling and a safe path fallback for older images.- Attachment garbage collection remains a later storage task; references arecontent-addressed so it can be added without changing the message contract.- Full visual previews, drag-and-drop, image transforms, and provider-specificdiff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex a93949c33..cb7a64ba4 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -201,13 +201,15 @@ content-addressed attachment store, and derives the effective model transportfrom the published model record plus the exact binding's `supportsImages`override. An absent or `null` override follows the published image capability;`true` enables and `false` disables image input for that configured model.-Eligible images become transient pi-ai image blocks when the effective-capability is enabled. Unknown/custom models without an explicit override,-non-vision models, and images above the 10 MB inline bound receive a safe-`@path` fallback.-Main uses streamed hashing and file copying for images above that bound, and the-sidecar uses the same bounded-read rule when rebuilding history. The durable-user message stores `content` plus attachment metadata/ref, never base64.+For a vision-capable model, images within the 10 MB per-image bound become+transient pi-ai image blocks. Restored history also has a 50 MB aggregate raw+image-byte budget: the sidecar considers persisted attachments newest-first and+preserves every eligible image when the total fits. If the budget is exceeded,+older images use the existing safe `@path` fallback. Unknown/custom models+without an explicit image override, non-vision models, oversized images, and+unavailable refs also use the safe fallback. Main uses streamed hashing and file+copying for oversized images. The durable user message stores `content` plus+attachment metadata/ref, never base64.Invalid attachment paths fail with `PATH_OUTSIDE_WORKSPACE`.Regenerate history (D109) also uses session channels:@@ -219,11 +221,13 @@ Regenerate history (D109) also uses session channels:Root user turns may include `revisionRootId`, `revisionCount`, and`activeRevision`. Activating a revision replaces the live tail with`prefix + archived branch` and disposes the session agent.-The sidecar receives only the prepared attachment subset needed for the-current turn. On a vision runtime, persisted image refs are hydrated from the-session-bound attachment/scratch roots when history is rebuilt; oversized or-unavailable images remain path fallbacks. This keeps renderer, main, sidecar, the models.dev catalog, and host-persistence on one capability-aware contract.+The sidecar receives only the prepared attachment subset needed for the current+turn. On a vision runtime, persisted refs are hydrated from session-bound+attachment/scratch/project roots. The current prompt row is excluded by message+id before hydration, so it does not consume the history budget; oversized,+over-budget, or unavailable images remain safe path fallbacks. This keeps+renderer, main, sidecar, the models.dev catalog, and host persistence on one+capability-aware contract.### 5.1a Steer an active turndiff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex 2627266ef..4153a075f 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -730,12 +730,13 @@ criterion-by-criterion report of what was met and the evidence observed.restores as an errored result; a tool row whose assistant row was lostgets a synthesized call-only assistant carrier so call/result pairs staywell-formed for every provider API.-- Vision runtimes hydrate persisted image refs only from the session-bound- attachment, scratch, and project roots. Images within the 10 MB inline- safety bound become transient pi-ai image blocks; oversized or unavailable- images become safe `@path` fallbacks. Oversized history hydration copies- files without first loading their contents into memory. Base64 is never- restored into durable UI messages or transcript records.+Vision runtimes hydrate persisted image refs only from the session-bound+attachment, scratch, and project roots. Each image remains subject to the 10 MB+inline safety bound, and restored history has a 50 MB aggregate raw-byte budget.+The newest refs are considered first; all eligible images remain image blocks+when the history fits, while over-budget or oversized images become safe+`@path` fallbacks. Reads are bounded by the admitted file size. Base64 is+transient and never restored into durable UI messages or transcript records.- Failed assistant messages remain durable diagnostic transcript entries butare never restored into pi model context on a later turn.- A tool-call id is unique in every request. The transcript is an append-onlydiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 43c006aa4..b819fe8e7 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7363,6 +7363,32 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.- **Status**: Unit-covered (`model-capabilities.test.ts`, host-core attachmentroundtrip); provider/UI journey Draft (run only in a capable environment when this surface changes)+#### E2E-102j: Historical vision replay uses a bounded aggregate byte budget++- **Preconditions**: A vision-capable model, a session with no compaction boundary+ across the fixture turns, six distinct user image turns whose combined raw+ image size is below 50 MB, and a later text-only user turn. Capture the+ provider request during runtime recreation and edit/resend.+- **Steps**:+ 1. Send the six image turns and then a text-only turn.+ 2. Reload/recreate the runtime and edit/resend the text-only turn.+ 3. Inspect the provider request and the durable transcript.+- **Expected**:+ - All six historical images are replayed as image blocks; being older than+ five image messages does not drop visual context while the aggregate stays+ within budget.+ - The current text row is removed before history hydration and is not+ double-counted against the restored-history budget.+ - Durable turns retain only attachment refs/metadata, never base64. A unit+ case with a deliberately small budget verifies that many images in one+ message are capped and newest attachments win.+- **Specs linked**: `03-runtime/01-ipc-protocol.md` §5.1,+ `03-runtime/02-agent-runtime.md` §5c, `03-runtime/04-data-storage.md`, ADR 0101+- **Acceptance**: C (conversation & stream), F (persistence), Quality+- **Milestone**: M5+- **Status**: Documented; provider/UI journey Draft (run only in a capable environment when this surface changes)++#### E2E-ATTACHMENTS-svg-file-fallback: SVG inputs are sent as files, not model images- **Preconditions**: A vision-capable model; an Agent session; one SVG filediff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex 2deebf421..9d9d041c2 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -7155,3 +7155,15 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.duplicating an id), plus the `scripts/e2e/provider-api-style.tsx` and`scripts/e2e/image-generation-ui.tsx` probes, which no longer click Managemodels.+## 2026-09-26 — Bound aggregate image history without an arbitrary message cutoff (D628)++- Vision history restoration keeps the existing 10 MB per-image ceiling and adds+ a 50 MB aggregate raw-byte budget per runtime rebuild. Eligible refs are+ considered newest-first; every image remains a provider image block when the+ history fits, and only older attachments beyond the budget fall back to a+ safe `@path`. The current prompt row is excluded before hydration so it cannot+ consume the history allowance.+- The sidecar reads only files admitted by the budget and clears stale transient+ base64 from restored attachment objects. Durable host messages remain+ metadata/ref-only. See ADR 0101, `03-runtime/01-ipc-protocol.md` §5.1,+ `03-runtime/02-agent-runtime.md` §5c, and E2E-102j.diff --git a/packages/agent-runtime/src/attachment-history.test.ts b/packages/agent-runtime/src/attachment-history.test.tsindex 63bd3ebe9..da84318e0 100644--- a/packages/agent-runtime/src/attachment-history.test.ts+++ b/packages/agent-runtime/src/attachment-history.test.ts@@ -1,24 +1,40 @@import { describe, expect, it } from "vitest";import { hydrateAttachmentHistory } from "./attachment-history.js";import type { UiMessage } from "@pi-desktop/shared";-import { mkdir, writeFile } from "node:fs/promises";-import { resolve } from "node:path";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { join, resolve } from "node:path";import os from "node:os";+async function withTempDir(run: (path: string) => Promise<void>): Promise<void> {+ const path = await mkdtemp(join(os.tmpdir(), "test-attachment-history-"));+ try {+ await run(path);+ } finally {+ await rm(path, { recursive: true, force: true });+ }+}++function userMessage(+ id: string,+ attachments: NonNullable<UiMessage["attachments"]>,+): UiMessage {+ return {+ id,+ role: "user",+ content: id,+ createdAt: new Date().toISOString(),+ attachments,+ };+}+describe("hydrateAttachmentHistory", () => {- it("inlines image attachments when supportsVision is true and within byte limits", async () => {- const tmp = resolve(os.tmpdir(), `test-attach-${Date.now()}`);- await mkdir(tmp, { recursive: true });- const imgPath = resolve(tmp, "sample.png");- await writeFile(imgPath, "fake-png-bytes");+ it("inlines image attachments when supportsVision is true and within per-image byte limits", async () => {+ await withTempDir(async (tmp) => {+ const imgPath = resolve(tmp, "sample.png");+ await writeFile(imgPath, "fake-png-bytes");- const history: UiMessage[] = [- {- id: "msg-1",- role: "user",- content: "look at this",- createdAt: new Date().toISOString(),- attachments: [+ const history = [+ userMessage("msg-1", [{name: "sample.png",ref: imgPath,@@ -26,61 +42,115 @@ describe("hydrateAttachmentHistory", () => {mimeType: "image/png",size: 14,},- ],- },- ];+ ]),+ ];- const hydrated = await hydrateAttachmentHistory(history, {- projectPath: tmp,- supportsVision: true,+ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ });++ expect(hydrated[0]?.attachments?.[0]?.data).toBe(+ Buffer.from("fake-png-bytes").toString("base64"),+ );});+ });- expect(hydrated[0]?.attachments?.[0]?.data).toBe(- Buffer.from("fake-png-bytes").toString("base64")- );+ it("preserves all image turns when their aggregate size is within budget", async () => {+ await withTempDir(async (tmp) => {+ const history: UiMessage[] = [];+ const payloads: string[] = [];+ for (let i = 1; i <= 6; i++) {+ const payload = `image-${i}`;+ const imgPath = resolve(tmp, `sample-${i}.png`);+ await writeFile(imgPath, payload);+ payloads.push(payload);+ history.push(+ userMessage(`msg-${i}`, [+ {+ name: `sample-${i}.png`,+ ref: imgPath,+ kind: "image",+ mimeType: "image/png",+ size: payload.length,+ },+ ]),+ );+ }++ const budget = payloads.reduce((total, payload) => total + payload.length, 0);+ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ maxInlinedImageHistoryBytes: budget,+ });++ for (let i = 0; i < payloads.length; i++) {+ expect(hydrated[i]?.attachments?.[0]?.data).toBe(+ Buffer.from(payloads[i]!).toString("base64"),+ );+ }+ });});- it("limits inlined base64 images to the latest N user messages to prevent V8 OOM (#1077)", async () => {- const tmp = resolve(os.tmpdir(), `test-attach-limits-${Date.now()}`);- await mkdir(tmp, { recursive: true });+ it("bounds aggregate bytes across many attachments in one message and keeps the newest first", async () => {+ await withTempDir(async (tmp) => {+ const payloads = ["old1", "old2", "new3"];+ const attachments = await Promise.all(+ payloads.map(async (payload, index) => {+ const imgPath = resolve(tmp, `sample-${index + 1}.png`);+ await writeFile(imgPath, payload);+ return {+ name: `sample-${index + 1}.png`,+ ref: imgPath,+ kind: "image" as const,+ mimeType: "image/png",+ // The on-disk size, not caller-supplied metadata, controls the budget.+ size: 1,+ };+ }),+ );+ const history = [userMessage("msg-many-images", attachments)];++ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ maxInlinedImageHistoryBytes: 8,+ });++ expect(hydrated[0]?.attachments?.map((attachment) => attachment.data)).toEqual([+ undefined,+ Buffer.from("old2").toString("base64"),+ Buffer.from("new3").toString("base64"),+ ]);+ expect(hydrated[0]?.content).toContain("sample-1.png");+ });+ });- const history: UiMessage[] = [];- for (let i = 1; i <= 10; i++) {- const imgPath = resolve(tmp, `sample-${i}.png`);- await writeFile(imgPath, `fake-png-bytes-${i}`);- history.push({- id: `msg-${i}`,- role: "user",- content: `image ${i}`,- createdAt: new Date(Date.now() + i * 1000).toISOString(),- attachments: [+ it("treats a zero history budget as no images inlined", async () => {+ await withTempDir(async (tmp) => {+ const imgPath = resolve(tmp, "sample.png");+ await writeFile(imgPath, "image");+ const history = [+ userMessage("msg-1", [{- name: `sample-${i}.png`,+ name: "sample.png",ref: imgPath,kind: "image",mimeType: "image/png",- size: 20,+ size: 5,},- ],+ ]),+ ];++ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ maxInlinedImageHistoryBytes: 0,});- }- // Default maxInlinedImageMessages is 5- const hydrated = await hydrateAttachmentHistory(history, {- projectPath: tmp,- supportsVision: true,- maxInlinedImageMessages: 5,+ expect(hydrated[0]?.attachments?.[0]?.data).toBeUndefined();+ expect(hydrated[0]?.content).toContain("sample.png");});-- // Old messages (msg-1 through msg-5) should NOT have data inlined in memory- for (let i = 0; i < 5; i++) {- expect(hydrated[i]?.attachments?.[0]?.data).toBeUndefined();- expect(hydrated[i]?.attachments?.[0]?.ref).toContain(`sample-${i + 1}.png`);- }-- // Recent messages (msg-6 through msg-10) should have data inlined- for (let i = 5; i < 10; i++) {- expect(hydrated[i]?.attachments?.[0]?.data).toBeDefined();- }});});diff --git a/packages/agent-runtime/src/attachment-history.ts b/packages/agent-runtime/src/attachment-history.tsindex 6b278eb1c..916a6cdd4 100644--- a/packages/agent-runtime/src/attachment-history.ts+++ b/packages/agent-runtime/src/attachment-history.ts@@ -1,7 +1,7 @@/** Session-root-confined attachment hydration for restored user messages. */import { createHash } from "node:crypto";import { constants as fsConstants } from "node:fs";-import { copyFile, mkdir, readFile, realpath, stat } from "node:fs/promises";+import { copyFile, mkdir, open, realpath, stat } from "node:fs/promises";import { isAbsolute, relative, resolve } from "node:path";import {formatFileInsert,@@ -12,17 +12,26 @@ import {type UiMessage,} from "@pi-desktop/shared";+const DEFAULT_MAX_INLINE_IMAGE_HISTORY_BYTES = MAX_INLINE_IMAGE_BYTES * 5;++type ResolvedAttachment = {+ attachment: MessageAttachment;+ canonicalPath?: string;+ size?: number;+ fallbackPath?: string;+ inlined?: boolean;+};+export type AttachmentHistoryContext = {scratchDir?: string;projectPath?: string;attachmentsDir?: string;supportsVision: boolean;/**- * Maximum count of recent user messages whose image attachments may be inlined as- * base64 strings into V8 memory during history restoration (default: 5).- * Older images retain their file reference and fallback path without multiplying base64 heaps.+ * Maximum aggregate raw image bytes inlined while restoring history (default: 50 MB).+ * The newest attachments are considered first; older ones use the safe path fallback.*/- maxInlinedImageMessages?: number;+ maxInlinedImageHistoryBytes?: number;};function pathInside(root: string, candidate: string): boolean {@@ -55,12 +64,46 @@ async function replayedAttachmentPath(return target;}+/** Read only the size already admitted by the history budget. */+async function readFileAtRecordedSize(+ path: string,+ expectedSize: number,+): Promise<Buffer | undefined> {+ const file = await open(path, "r");+ try {+ const current = await file.stat();+ if (!current.isFile() || current.size !== expectedSize) return undefined;+ const bytes = Buffer.allocUnsafe(expectedSize);+ let offset = 0;+ while (offset < expectedSize) {+ const { bytesRead } = await file.read(+ bytes,+ offset,+ expectedSize - offset,+ offset,+ );+ if (bytesRead === 0) return undefined;+ offset += bytesRead;+ }+ return bytes;+ } finally {+ await file.close();+ }+}+export async function hydrateAttachmentHistory(history: UiMessage[],params: AttachmentHistoryContext,): Promise<UiMessage[]> {const supportsVision = params.supportsVision;- const maxInlinedImageMessages = params.maxInlinedImageMessages ?? 5;+ const requestedBudget = params.maxInlinedImageHistoryBytes;+ const maxInlinedImageHistoryBytes =+ requestedBudget === undefined || !Number.isFinite(requestedBudget)+ ? DEFAULT_MAX_INLINE_IMAGE_HISTORY_BYTES+ : Math.min(+ DEFAULT_MAX_INLINE_IMAGE_HISTORY_BYTES,+ Math.max(0, Math.floor(requestedBudget)),+ );const roots = [params.scratchDir,params.projectPath,@@ -76,30 +119,22 @@ export async function hydrateAttachmentHistory(}),);- // Identify user messages eligible for inlining base64 images (the latest N user messages with attachments).- // Older historical messages avoid holding multi-megabyte base64 strings in V8 memory (#1077).- const userMessagesWithAttachmentsIndices: number[] = [];- for (let i = 0; i < history.length; i++) {- const msg = history[i];- if (msg?.role === "user" && msg.attachments?.some((a) => a.kind === "image")) {- userMessagesWithAttachmentsIndices.push(i);- }- }- const eligibleIndices = new Set(- userMessagesWithAttachmentsIndices.slice(-maxInlinedImageMessages)- );-const resolveAttachment = async (sourceAttachment: NonNullable<UiMessage["attachments"]>[number],- allowInlining: boolean,- ): Promise<{ attachment: MessageAttachment; fallbackPath?: string }> => {- // Old transcripts can still label SVG as an image. Normalize before every- // early return, and discard any stale transient data without mutating history.+ ): Promise<ResolvedAttachment> => {+ // History from the host never contains transient data. Strip stale in-memory+ // payloads as well so a caller cannot bypass the aggregate hydration budget.+ const cleanAttachment: MessageAttachment = {+ ...sourceAttachment,+ data: undefined,+ };const attachment: MessageAttachment = isSvgAttachment(- sourceAttachment.mimeType, sourceAttachment.name, sourceAttachment.ref,+ sourceAttachment.mimeType,+ sourceAttachment.name,+ sourceAttachment.ref,)- ? { ...sourceAttachment, kind: "file", mimeType: SVG_MIME_TYPE, data: undefined }- : sourceAttachment;+ ? { ...cleanAttachment, kind: "file", mimeType: SVG_MIME_TYPE }+ : cleanAttachment;const ref = attachment.ref.trim();if (!ref) return { attachment };const candidate =@@ -116,15 +151,12 @@ export async function hydrateAttachmentHistory(if (!canonicalRoots.some((root) => root && pathInside(root, canonical))) {return { attachment };}- const shouldInline = allowInlining && attachment.kind === "image" && supportsVision;const size = (await stat(canonical)).size;- const bytes =- shouldInline && size <= MAX_INLINE_IMAGE_BYTES- ? await readFile(canonical)- : undefined;- if (attachment.kind === "image" && supportsVision && bytes) {- return { attachment: { ...attachment, data: bytes.toString("base64") } };- }+ const canInline =+ supportsVision &&+ attachment.kind === "image" &&+ size <= MAX_INLINE_IMAGE_BYTES;+ if (canInline) return { attachment, canonicalPath: canonical, size };return {attachment,fallbackPath: await replayedAttachmentPath(@@ -138,29 +170,91 @@ export async function hydrateAttachmentHistory(}};- return Promise.all(- history.map(async (message, index) => {- if (message.role !== "user" || !message.attachments?.length) return message;- const allowInlining = eligibleIndices.has(index);- const resolved = await Promise.all(- message.attachments.map((a) => resolveAttachment(a, allowInlining))- );- const fallbackPaths = resolved- .map((item) => item.fallbackPath)- .filter((path): path is string => Boolean(path))- .map((path) => formatFileInsert(path, "file"))- .join("")- .trim();- const content = message.content.trim()- ? fallbackPaths- ? `${message.content}\n${fallbackPaths}`- : message.content- : fallbackPaths;- return {- ...message,- content,- attachments: resolved.map((item) => item.attachment),- };+ const resolvedHistory = await Promise.all(+ history.map(async (message) => {+ if (message.role !== "user" || !message.attachments?.length) return undefined;+ return Promise.all(message.attachments.map(resolveAttachment));+ }),+ );++ // Allocate the byte budget in reverse transcript order, then reverse attachment+ // order within a message. This preserves every image when the history fits while+ // keeping the most recent visual context when the aggregate exceeds the cap.+ let remainingBytes = maxInlinedImageHistoryBytes;+ const selectedForInlining: ResolvedAttachment[] = [];+ for (let messageIndex = resolvedHistory.length - 1; messageIndex >= 0; messageIndex--) {+ const resolved = resolvedHistory[messageIndex];+ if (!resolved) continue;+ for (let attachmentIndex = resolved.length - 1; attachmentIndex >= 0; attachmentIndex--) {+ const item = resolved[attachmentIndex];+ if (+ !item?.canonicalPath ||+ item.size === undefined ||+ item.size > remainingBytes+ ) {+ continue;+ }+ remainingBytes -= item.size;+ selectedForInlining.push(item);+ }+ }++ await Promise.all(+ selectedForInlining.map(async (item) => {+ try {+ const bytes = await readFileAtRecordedSize(item.canonicalPath!, item.size!);+ if (!bytes) return;+ item.attachment = {+ ...item.attachment,+ data: bytes.toString("base64"),+ };+ item.inlined = true;+ } catch {+ // A failed transient read should not prevent the remaining history restoring.+ }}),);++ const fallbackTasks: Promise<void>[] = [];+ for (const resolved of resolvedHistory) {+ if (!resolved) continue;+ for (const item of resolved) {+ if (!item.canonicalPath || item.inlined) continue;+ fallbackTasks.push(+ (async () => {+ try {+ item.fallbackPath = await replayedAttachmentPath(+ params,+ item.attachment,+ item.canonicalPath!,+ );+ } catch {+ // Path fallback is best-effort, matching the existing restore contract.+ }+ })(),+ );+ }+ }+ await Promise.all(fallbackTasks);++ return history.map((message, index) => {+ const resolved = resolvedHistory[index];+ if (!resolved) return message;+ const fallbackPaths = resolved+ .map((item) => item.fallbackPath)+ .filter((path): path is string => Boolean(path))+ .map((path) => formatFileInsert(path, "file"))+ .join("")+ .trim();+ const content = message.content.trim()+ ? fallbackPaths+ ? `${message.content}\n${fallbackPaths}`+ : message.content+ : fallbackPaths;+ return {+ ...message,+ content,+ attachments: resolved.map((item) => item.attachment),+ };+ });}diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 8339bd109..df6d425ee 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -3559,6 +3559,39 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {await runtime.dispose();await restored.dispose();});+ it("replays every under-budget historical image as a provider image block", async () => {+ const history: UiMessage[] = Array.from({ length: 6 }, (_, index) => {+ const payload = Buffer.from(`historical-image-${index + 1}`).toString("base64");+ return {+ id: `image-${index + 1}`,+ role: "user",+ content: `image ${index + 1}`,+ createdAt: new Date(Date.now() + index).toISOString(),+ attachments: [+ {+ name: `image-${index + 1}.png`,+ ref: `attachments/image-${index + 1}`,+ kind: "image",+ mimeType: "image/png",+ data: payload,+ },+ ],+ };+ });+ const runtime = createRuntime({ history });+ try {+ const messages = buildSessionContext((runtime as any).fullEntries).messages;+ const imageBlocks = messages.flatMap((message) =>+ message.role === "user" && Array.isArray(message.content)+ ? message.content.filter((block) => block.type === "image")+ : [],+ );+ expect(imageBlocks).toHaveLength(6);+ } finally {+ await runtime.dispose();+ }+ });+});describe("DesktopAgentRuntime tool history restore (D120)", () => {diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex d23efc9cc..9b4816a14 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -244,8 +244,17 @@ async function runtimeFor(compaction?: ContextCompactionRecord;} | null;}>("session.get", { id: sessionId });+ let restoredMessages = detail?.session?.messages ?? [];+ // The current prompt is sent separately below. Exclude its persisted row+ // before attachment hydration so it cannot consume the history byte budget.+ if (currentPrompt !== undefined && params.userMessageId) {+ const last = restoredMessages.at(-1);+ if (last?.role === "user" && last.id === params.userMessageId) {+ restoredMessages = restoredMessages.slice(0, -1);+ }+ }const supportsVision = visionFromModelConfig(params.provider.modelConfig);- history = await hydrateAttachmentHistory(detail?.session?.messages ?? [], {+ history = await hydrateAttachmentHistory(restoredMessages, {scratchDir: params.scratchDir,projectPath: params.projectPath,attachmentsDir: params.attachmentsDir,@@ -255,13 +264,10 @@ async function runtimeFor(} catch {// History restore is best-effort; a prompt can still start cleanly.}- if (currentPrompt !== undefined) {+ // Older callers without a stable message id retain the previous content match.+ if (currentPrompt !== undefined && !params.userMessageId) {const last = history.at(-1);- if (- last?.role === "user" &&- ((params.userMessageId && last.id === params.userMessageId) ||- (!params.userMessageId && last.content === currentPrompt))- ) {+ if (last?.role === "user" && last.content === currentPrompt) {history = history.slice(0, -1);}}