Skip to content

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

perf(agent-runtime): enforce aggregate byte budget and preserve replayed image context

Totopo2725a7dbc75f6a
diff --git a/packages/agent-runtime/src/attachment-history.test.ts b/packages/agent-runtime/src/attachment-history.test.ts
index 63bd3ebe9..988966d65 100644
--- a/packages/agent-runtime/src/attachment-history.test.ts
+++ b/packages/agent-runtime/src/attachment-history.test.ts
@@ -40,7 +40,7 @@ describe("hydrateAttachmentHistory", () => {
);
});
- it("limits inlined base64 images to the latest N user messages to prevent V8 OOM (#1077)", async () => {
+ it("limits inlined base64 images by message count to prevent V8 OOM (#1077)", async () => {
const tmp = resolve(os.tmpdir(), `test-attach-limits-${Date.now()}`);
await mkdir(tmp, { recursive: true });
@@ -65,22 +65,124 @@ describe("hydrateAttachmentHistory", () => {
});
}
- // 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
+ // Older messages outside the window retain disk references without inlined base64
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
+ // Recent messages within the window inline base64
for (let i = 5; i < 10; i++) {
expect(hydrated[i]?.attachments?.[0]?.data).toBeDefined();
}
});
+
+ it("bounds aggregate inlined image bytes across multiple images in a single user message [P1]", async () => {
+ const tmp = resolve(os.tmpdir(), `test-attach-multi-image-${Date.now()}`);
+ await mkdir(tmp, { recursive: true });
+
+ const attachments = [];
+ for (let j = 1; j <= 5; j++) {
+ const imgPath = resolve(tmp, `burst-${j}.png`);
+ await writeFile(imgPath, "x".repeat(100)); // 100 bytes each
+ attachments.push({
+ name: `burst-${j}.png`,
+ ref: imgPath,
+ kind: "image" as const,
+ mimeType: "image/png",
+ size: 100,
+ });
+ }
+
+ const history: UiMessage[] = [
+ {
+ id: "msg-burst",
+ role: "user",
+ content: "here are many images",
+ createdAt: new Date().toISOString(),
+ attachments,
+ },
+ ];
+
+ // Budget of 250 bytes: should allow exactly first 2-3 images without exceeding
+ const hydrated = await hydrateAttachmentHistory(history, {
+ projectPath: tmp,
+ supportsVision: true,
+ maxInlinedImageBytes: 250,
+ });
+
+ const inlined = hydrated[0]?.attachments?.filter((a) => Boolean(a.data)) ?? [];
+ const notInlined = hydrated[0]?.attachments?.filter((a) => !a.data) ?? [];
+
+ expect(inlined.length).toBe(2);
+ expect(notInlined.length).toBe(3);
+ // Non-inlined images still retain their file reference and fallback path
+ for (const a of notInlined) {
+ expect(a.ref).toBeDefined();
+ }
+ });
+
+ it("preserves image context on replayed historical turns [P2]", async () => {
+ const tmp = resolve(os.tmpdir(), `test-attach-replay-${Date.now()}`);
+ await mkdir(tmp, { recursive: true });
+
+ const img1 = resolve(tmp, "turn1.png");
+ await writeFile(img1, "turn1-image-data");
+
+ const img2 = resolve(tmp, "turn2.png");
+ await writeFile(img2, "turn2-image-data");
+
+ const history: UiMessage[] = [
+ {
+ id: "msg-turn-1",
+ role: "user",
+ content: "turn 1 prompt",
+ createdAt: new Date(Date.now() - 10000).toISOString(),
+ attachments: [
+ {
+ name: "turn1.png",
+ ref: img1,
+ kind: "image",
+ mimeType: "image/png",
+ size: 16,
+ },
+ ],
+ },
+ {
+ id: "msg-turn-2",
+ role: "user",
+ content: "turn 2 replayed prompt",
+ createdAt: new Date().toISOString(),
+ attachments: [
+ {
+ name: "turn2.png",
+ ref: img2,
+ kind: "image",
+ mimeType: "image/png",
+ size: 16,
+ },
+ ],
+ },
+ ];
+
+ const hydrated = await hydrateAttachmentHistory(history, {
+ projectPath: tmp,
+ supportsVision: true,
+ maxInlinedImageMessages: 5,
+ });
+
+ // Both replayed turns remain within the budget and keep their vision base64 data intact
+ expect(hydrated[0]?.attachments?.[0]?.data).toBe(
+ Buffer.from("turn1-image-data").toString("base64")
+ );
+ expect(hydrated[1]?.attachments?.[0]?.data).toBe(
+ Buffer.from("turn2-image-data").toString("base64")
+ );
+ });
});
diff --git a/packages/agent-runtime/src/attachment-history.ts b/packages/agent-runtime/src/attachment-history.ts
index 6b278eb1c..46b9ca2ce 100644
--- a/packages/agent-runtime/src/attachment-history.ts
+++ b/packages/agent-runtime/src/attachment-history.ts
@@ -7,6 +7,7 @@ import {
formatFileInsert,
isSvgAttachment,
MAX_INLINE_IMAGE_BYTES,
+ MAX_INLINED_IMAGE_HISTORY_BYTES,
SVG_MIME_TYPE,
type MessageAttachment,
type UiMessage,
@@ -18,9 +19,13 @@ export type AttachmentHistoryContext = {
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 into V8 memory during history restoration
+ * (default: 30,000,000 / 30 MB).
+ * Older or excess images retain their file reference and fallback path without multiplying base64 heaps.
+ */
+ maxInlinedImageBytes?: number;
+ /**
+ * Optional maximum count of recent user messages eligible for inlining image attachments (default: 10).
*/
maxInlinedImageMessages?: number;
};
@@ -60,7 +65,9 @@ export async function hydrateAttachmentHistory(
params: AttachmentHistoryContext,
): Promise<UiMessage[]> {
const supportsVision = params.supportsVision;
- const maxInlinedImageMessages = params.maxInlinedImageMessages ?? 5;
+ const maxInlinedImageBytes =
+ params.maxInlinedImageBytes ?? MAX_INLINED_IMAGE_HISTORY_BYTES;
+ const maxInlinedImageMessages = params.maxInlinedImageMessages ?? 10;
const roots = [
params.scratchDir,
params.projectPath,
@@ -76,22 +83,37 @@ 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++) {
+ // Pre-scan user messages from newest to oldest to allocate the cumulative inlining byte budget [P1].
+ // Restricts base64 inlining to the latest N user messages within the total byte budget.
+ // Excess or older images retain their file reference and fallback path without V8 heap bloat (#1077).
+ const inlinableAttachmentKeys = new Set<string>();
+ let remainingBudget = maxInlinedImageBytes;
+ let eligibleUserMessageCount = 0;
+
+ for (let i = history.length - 1; i >= 0; i--) {
const msg = history[i];
- if (msg?.role === "user" && msg.attachments?.some((a) => a.kind === "image")) {
- userMessagesWithAttachmentsIndices.push(i);
+ if (msg?.role !== "user" || !msg.attachments?.length) continue;
+ const hasImages = msg.attachments.some((a) => a.kind === "image");
+ if (!hasImages) continue;
+ if (eligibleUserMessageCount >= maxInlinedImageMessages) break;
+ eligibleUserMessageCount += 1;
+
+ for (let aIdx = 0; aIdx < msg.attachments.length; aIdx++) {
+ const attachment = msg.attachments[aIdx];
+ if (attachment?.kind !== "image") continue;
+ const size = attachment.size ?? 0;
+ if (size <= MAX_INLINE_IMAGE_BYTES && (remainingBudget >= size || remainingBudget === maxInlinedImageBytes)) {
+ inlinableAttachmentKeys.add(`${i}:${aIdx}`);
+ remainingBudget = Math.max(0, remainingBudget - size);
+ }
}
+ if (remainingBudget <= 0) break;
}
- const eligibleIndices = new Set(
- userMessagesWithAttachmentsIndices.slice(-maxInlinedImageMessages)
- );
const resolveAttachment = async (
sourceAttachment: NonNullable<UiMessage["attachments"]>[number],
- allowInlining: boolean,
+ msgIndex: number,
+ attachmentIndex: number,
): 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.
@@ -116,6 +138,7 @@ export async function hydrateAttachmentHistory(
if (!canonicalRoots.some((root) => root && pathInside(root, canonical))) {
return { attachment };
}
+ const allowInlining = inlinableAttachmentKeys.has(`${msgIndex}:${attachmentIndex}`);
const shouldInline = allowInlining && attachment.kind === "image" && supportsVision;
const size = (await stat(canonical)).size;
const bytes =
@@ -139,11 +162,12 @@ export async function hydrateAttachmentHistory(
};
return Promise.all(
- history.map(async (message, index) => {
+ history.map(async (message, msgIndex) => {
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))
+ message.attachments.map((a, aIndex) =>
+ resolveAttachment(a, msgIndex, aIndex)
+ )
);
const fallbackPaths = resolved
.map((item) => item.fallbackPath)
diff --git a/packages/shared/src/attachment-limits.test.ts b/packages/shared/src/attachment-limits.test.ts
index 5e6b70b1d..ceaad1480 100644
--- a/packages/shared/src/attachment-limits.test.ts
+++ b/packages/shared/src/attachment-limits.test.ts
@@ -1,8 +1,15 @@
import { describe, expect, it } from "vitest";
-import { MAX_INLINE_IMAGE_BYTES } from "./attachment-limits.js";
+import {
+ MAX_INLINE_IMAGE_BYTES,
+ MAX_INLINED_IMAGE_HISTORY_BYTES,
+} from "./attachment-limits.js";
describe("attachment transport limits", () => {
it("keeps inline images within MiniMax's 10 MB request limit", () => {
expect(MAX_INLINE_IMAGE_BYTES).toBe(10_000_000);
});
+
+ it("caps aggregate inlined history images to 30 MB", () => {
+ expect(MAX_INLINED_IMAGE_HISTORY_BYTES).toBe(30_000_000);
+ });
});
diff --git a/packages/shared/src/attachment-limits.ts b/packages/shared/src/attachment-limits.ts
index 4a2a72dc1..27ffefe6e 100644
--- a/packages/shared/src/attachment-limits.ts
+++ b/packages/shared/src/attachment-limits.ts
@@ -6,3 +6,9 @@
* cannot take a different transport path from a fresh prompt.
*/
export const MAX_INLINE_IMAGE_BYTES = 10_000_000;
+
+/**
+ * Maximum aggregate raw image bytes inlined into V8 memory during history restoration.
+ * Bounds total base64 memory footprint to protect against sidecar heap exhaustion (#1077).
+ */
+export const MAX_INLINED_IMAGE_HISTORY_BYTES = 30_000_000;