Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
perf(agent-runtime): bound inlined image history to prevent V8 sidecar heap exhaustion
Totopo2758c9f92abf4a
diff --git a/packages/agent-runtime/src/attachment-history.test.ts b/packages/agent-runtime/src/attachment-history.test.tsnew file mode 100644index 000000000..63bd3ebe9--- /dev/null+++ b/packages/agent-runtime/src/attachment-history.test.ts@@ -0,0 +1,86 @@+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 os from "node:os";++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");++ const history: UiMessage[] = [+ {+ id: "msg-1",+ role: "user",+ content: "look at this",+ createdAt: new Date().toISOString(),+ attachments: [+ {+ name: "sample.png",+ ref: imgPath,+ kind: "image",+ mimeType: "image/png",+ size: 14,+ },+ ],+ },+ ];++ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ });++ expect(hydrated[0]?.attachments?.[0]?.data).toBe(+ Buffer.from("fake-png-bytes").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 });++ 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: [+ {+ name: `sample-${i}.png`,+ ref: imgPath,+ kind: "image",+ mimeType: "image/png",+ size: 20,+ },+ ],+ });+ }++ // Default maxInlinedImageMessages is 5+ const hydrated = await hydrateAttachmentHistory(history, {+ projectPath: tmp,+ supportsVision: true,+ maxInlinedImageMessages: 5,+ });++ // 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 7868f9c81..6b278eb1c 100644--- a/packages/agent-runtime/src/attachment-history.ts+++ b/packages/agent-runtime/src/attachment-history.ts@@ -17,6 +17,12 @@ export type AttachmentHistoryContext = {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.+ */+ maxInlinedImageMessages?: number;};function pathInside(root: string, candidate: string): boolean {@@ -54,6 +60,7 @@ export async function hydrateAttachmentHistory(params: AttachmentHistoryContext,): Promise<UiMessage[]> {const supportsVision = params.supportsVision;+ const maxInlinedImageMessages = params.maxInlinedImageMessages ?? 5;const roots = [params.scratchDir,params.projectPath,@@ -68,8 +75,23 @@ 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.@@ -94,7 +116,7 @@ export async function hydrateAttachmentHistory(if (!canonicalRoots.some((root) => root && pathInside(root, canonical))) {return { attachment };}- const shouldInline = attachment.kind === "image" && supportsVision;+ const shouldInline = allowInlining && attachment.kind === "image" && supportsVision;const size = (await stat(canonical)).size;const bytes =shouldInline && size <= MAX_INLINE_IMAGE_BYTES@@ -117,9 +139,12 @@ export async function hydrateAttachmentHistory(};return Promise.all(- history.map(async (message) => {+ history.map(async (message, index) => {if (message.role !== "user" || !message.attachments?.length) return message;- const resolved = await Promise.all(message.attachments.map(resolveAttachment));+ 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))