Skip to content

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

Merge commit '25a7dbc75f6acf57d82411805870856e657dd447' into fix/attachment-history-byte-budget

vastsabfb57e3d4576
diff --cc docs/adr/0101-model-aware-image-attachments.md
index f95018621,66b53f827..eeaaecd88
--- a/docs/adr/0101-model-aware-image-attachments.md
+++ b/docs/adr/0101-model-aware-image-attachments.md
@@@ -32,17 -32,11 +32,17 @@@ renderer discovery and user-entered mod
the sidecar only as transient base64 data and becomes a pi-ai image content
block. The base64 value is never persisted in SQLite, JSONL, or renderer
transcript 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
++6. Restored vision history has a 30 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 model
picker and session/provider summaries expose the same authoritative vision
capability.
diff --cc docs/spec/03-runtime/01-ipc-protocol.md
index cb7a64ba4,a93949c33..eaf3b4aa3
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@@ -201,15 -201,13 +201,15 @@@ content-addressed attachment store, an
from 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
++transient pi-ai image blocks. Restored history also has a 30 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:
diff --cc docs/spec/03-runtime/02-agent-runtime.md
index 4153a075f,2627266ef..06aeb6d7f
--- a/docs/spec/03-runtime/02-agent-runtime.md
+++ b/docs/spec/03-runtime/02-agent-runtime.md
@@@ -730,13 -730,12 +730,13 @@@ criterion-by-criterion report of what w
restores as an errored result; a tool row whose assistant row was lost
gets a synthesized call-only assistant carrier so call/result pairs stay
well-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.
++safety bound, and restored history has a 30 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 but
are never restored into pi model context on a later turn.
- A tool-call id is unique in every request. The transcript is an append-only
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index 4daf69d82,afc9f1dd4..92f9365e8
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -7363,32 -7363,6 +7363,32 @@@ must keep splitting are covered by `mar
- **Status**: Unit-covered (`model-capabilities.test.ts`, host-core attachment
roundtrip); 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
++ image size is below 30 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 file
diff --cc docs/spec/08-meta/decisions-log.md
index 9d9d041c2,2deebf421..7a5f99c6f
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@@ -7155,15 -7155,3 +7155,15 @@@ must keep splitting are covered by `mar
duplicating an id), plus the `scripts/e2e/provider-api-style.tsx` and
`scripts/e2e/image-generation-ui.tsx` probes, which no longer click Manage
models.
+## 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
++ a 30 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 --cc packages/agent-runtime/src/attachment-history.test.ts
index da84318e0,988966d65..48c22ebf6
--- a/packages/agent-runtime/src/attachment-history.test.ts
+++ b/packages/agent-runtime/src/attachment-history.test.ts
@@@ -1,40 -1,24 +1,39 @@@
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";
-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");
+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,
+ };
+}
- const history: UiMessage[] = [
- {
- id: "msg-1",
- role: "user",
- content: "look at this",
- createdAt: new Date().toISOString(),
- attachments: [
+describe("hydrateAttachmentHistory", () => {
+ 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 = [
+ userMessage("msg-1", [
{
name: "sample.png",
ref: imgPath,
@@@ -42,115 -26,163 +41,117 @@@
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 () => {
- 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 });
-
- 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,
- },
- ],
++ it("preserves historical image turns beyond ten messages when within the default byte budget", async () => {
+ await withTempDir(async (tmp) => {
+ const history: UiMessage[] = [];
+ const payloads: string[] = [];
- for (let i = 1; i <= 6; i++) {
++ for (let i = 1; i <= 12; 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,
});
- }
- const hydrated = await hydrateAttachmentHistory(history, {
- projectPath: tmp,
- supportsVision: true,
- maxInlinedImageMessages: 5,
+ for (let i = 0; i < payloads.length; i++) {
+ expect(hydrated[i]?.attachments?.[0]?.data).toBe(
+ Buffer.from(payloads[i]!).toString("base64"),
+ );
+ }
});
-
- // 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 within the window inline base64
- for (let i = 5; i < 10; i++) {
- expect(hydrated[i]?.attachments?.[0]?.data).toBeDefined();
- }
});
- it("bounds aggregate bytes across many attachments in one message and keeps the newest first", async () => {
- 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,
++ it("bounds actual aggregate bytes across many attachments in one message", 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 attachments: NonNullable<UiMessage["attachments"]> = [];
++ for (let i = 1; i <= 5; i++) {
++ const imgPath = resolve(tmp, `burst-${i}.png`);
++ await writeFile(imgPath, "x".repeat(100));
++ attachments.push({
++ name: `burst-${i}.png`,
++ ref: imgPath,
++ kind: "image",
++ mimeType: "image/png",
++ // Deliberately incorrect metadata must not bypass the actual byte budget.
++ size: 1,
++ ...(i === 1 ? { data: "stale-base64-must-be-cleared" } : {}),
++ });
++ }
++ const history = [userMessage("msg-burst", attachments)];
+
+ const hydrated = await hydrateAttachmentHistory(history, {
+ projectPath: tmp,
+ supportsVision: true,
- maxInlinedImageHistoryBytes: 8,
++ maxInlinedImageBytes: 250,
});
- }
--
- expect(hydrated[0]?.attachments?.map((attachment) => attachment.data)).toEqual([
- 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 result = hydrated[0];
++ expect(result?.attachments?.map((attachment) => attachment.data)).toEqual([
++ undefined,
+ undefined,
- Buffer.from("old2").toString("base64"),
- Buffer.from("new3").toString("base64"),
++ undefined,
++ Buffer.from("x".repeat(100)).toString("base64"),
++ Buffer.from("x".repeat(100)).toString("base64"),
+ ]);
- expect(hydrated[0]?.content).toContain("sample-1.png");
++ for (let i = 1; i <= 3; i++) {
++ expect(result?.content).toContain(`burst-${i}.png`);
++ expect(result?.attachments?.[i - 1]?.ref).toContain(`burst-${i}.png`);
++ }
});
-
- 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("treats a zero history budget as no images inlined", async () => {
- 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: [
++ it("treats a zero history byte 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: "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,
+ name: "sample.png",
+ ref: imgPath,
kind: "image",
mimeType: "image/png",
- size: 16,
+ size: 5,
},
- ],
- },
- ];
+ ]),
+ ];
- const hydrated = await hydrateAttachmentHistory(history, {
- projectPath: tmp,
- supportsVision: true,
- maxInlinedImageMessages: 5,
- });
+ const hydrated = await hydrateAttachmentHistory(history, {
+ projectPath: tmp,
+ supportsVision: true,
- maxInlinedImageHistoryBytes: 0,
++ maxInlinedImageBytes: 0,
+ });
- // 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")
- );
+ expect(hydrated[0]?.attachments?.[0]?.data).toBeUndefined();
+ expect(hydrated[0]?.content).toContain("sample.png");
+ });
});
});
diff --cc packages/agent-runtime/src/attachment-history.ts
index 916a6cdd4,46b9ca2ce..930a52b6f
--- a/packages/agent-runtime/src/attachment-history.ts
+++ b/packages/agent-runtime/src/attachment-history.ts
@@@ -12,26 -13,21 +13,25 @@@ 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 aggregate raw image bytes inlined while restoring history (default: 50 MB).
- * 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.
++ * Maximum aggregate raw image bytes inlined during history restoration
++ * (default: 30 MB, hard-capped by MAX_INLINED_IMAGE_HISTORY_BYTES).
+ * The newest attachments are considered first; older ones use the safe path fallback.
*/
- maxInlinedImageHistoryBytes?: number;
+ maxInlinedImageBytes?: number;
- /**
- * Optional maximum count of recent user messages eligible for inlining image attachments (default: 10).
- */
- maxInlinedImageMessages?: number;
};
function pathInside(root: string, candidate: string): boolean {
@@@ -96,14 -65,9 +96,14 @@@ export async function hydrateAttachment
params: AttachmentHistoryContext,
): Promise<UiMessage[]> {
const supportsVision = params.supportsVision;
- const requestedBudget = params.maxInlinedImageHistoryBytes;
- const maxInlinedImageHistoryBytes =
++ const requestedBudget = params.maxInlinedImageBytes;
+ const maxInlinedImageBytes =
- params.maxInlinedImageBytes ?? MAX_INLINED_IMAGE_HISTORY_BYTES;
- const maxInlinedImageMessages = params.maxInlinedImageMessages ?? 10;
+ requestedBudget === undefined || !Number.isFinite(requestedBudget)
- ? DEFAULT_MAX_INLINE_IMAGE_HISTORY_BYTES
++ ? MAX_INLINED_IMAGE_HISTORY_BYTES
+ : Math.min(
- DEFAULT_MAX_INLINE_IMAGE_HISTORY_BYTES,
++ MAX_INLINED_IMAGE_HISTORY_BYTES,
+ Math.max(0, Math.floor(requestedBudget)),
+ );
const roots = [
params.scratchDir,
params.projectPath,
@@@ -170,91 -161,30 +170,91 @@@
}
};
- return Promise.all(
- history.map(async (message, msgIndex) => {
- if (message.role !== "user" || !message.attachments?.length) return message;
- const resolved = await Promise.all(
- message.attachments.map((a, aIndex) =>
- resolveAttachment(a, msgIndex, aIndex)
- )
- );
- 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;
++ let remainingBytes = maxInlinedImageBytes;
+ 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),
+ };
+ });
}