Skip to content

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

fix(composer): reference pasted disk files with sizes

Linuxdazhao46c6788c888b
diff --git a/apps/desktop/electron/main/composer-clipboard-directories.ts b/apps/desktop/electron/main/composer-clipboard-directories.ts
index 821505039..8ede35970 100644
--- a/apps/desktop/electron/main/composer-clipboard-directories.ts
+++ b/apps/desktop/electron/main/composer-clipboard-directories.ts
@@ -100,7 +100,7 @@ export async function nativeClipboardPaths(
return paths;
}
-/** Directories stay path references; regular files use the existing picker capability. */
+/** Capture native paths without reading file contents. */
export async function readComposerClipboardDirectories(
clipboard: NativeClipboard,
rememberFiles: (paths: string[]) => string,
@@ -117,7 +117,7 @@ export async function readComposerClipboardDirectories(
if (!metadata.isDirectory() && !metadata.isFile()) throw new Error("clipboard item is not a file or directory");
return { path: canonical, name: basename(path) || path, directory: metadata.isDirectory() };
}));
- if (!entries.some(entry => entry.directory)) return null;
+ if (!entries.length) return null;
const files = entries.filter(entry => !entry.directory).map(entry => entry.path);
return {
items: entries.map(entry => entry.directory
diff --git a/apps/desktop/electron/main/composer-file-references.ts b/apps/desktop/electron/main/composer-file-references.ts
new file mode 100644
index 000000000..446036f21
--- /dev/null
+++ b/apps/desktop/electron/main/composer-file-references.ts
@@ -0,0 +1,69 @@
+import { randomUUID } from "node:crypto";
+import { mkdir, readFile, realpath, stat, writeFile } from "node:fs/promises";
+import { basename, isAbsolute, join } from "node:path";
+import { ErrorCodes, type ComposerPastedFile } from "@pi-desktop/shared";
+import { mimeTypeForPath } from "./composer-paste.ts";
+
+const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+type FileReference = { version: 1; path: string; projectPath: string; sessionId: string };
+
+async function referenceRoot(dataDir: string): Promise<string> {
+ const data = await realpath(dataDir);
+ const root = join(data, "composer-file-references");
+ await mkdir(root, { recursive: true });
+ if (await realpath(root) !== root) throw new Error("file reference directory was redirected");
+ return root;
+}
+
+/** Called only with paths consumed from a sender-bound native selection. */
+export async function referenceComposerFiles(
+ dataDir: string,
+ sessionId: string,
+ projectPath: string,
+ paths: string[],
+): Promise<ComposerPastedFile[]> {
+ if (!/^[A-Za-z0-9_-]+$/.test(sessionId)) throw new Error("invalid session id");
+ if (paths.length > 20) throw new Error("too many referenced files (maximum 20)");
+ const project = await realpath(projectPath);
+ const prepared = await Promise.all(paths.map(async path => {
+ if (!isAbsolute(path)) throw new Error("file reference path must be absolute");
+ const canonical = await realpath(path);
+ const info = await stat(canonical);
+ if (!info.isFile()) throw new Error("selected path is not a file");
+ return { path: canonical, size: info.size };
+ }));
+ const root = await referenceRoot(dataDir);
+ return Promise.all(prepared.map(async ({ path, size }) => {
+ const localReference = randomUUID();
+ const record: FileReference = { version: 1, path, projectPath: project, sessionId };
+ await writeFile(join(root, `${localReference}.json`), JSON.stringify(record), { flag: "wx", mode: 0o600 });
+ return { path, name: basename(path), kind: "file" as const, mimeType: mimeTypeForPath(path), size, localReference };
+ }));
+}
+
+/** Refresh metadata only; reading contents still belongs to normal tool admission. */
+export async function resolveComposerFileReference(
+ dataDir: string,
+ projectPath: string | undefined,
+ path: string,
+ localReference: string,
+): Promise<ComposerPastedFile> {
+ if (!UUID.test(localReference) || !projectPath) {
+ throw Object.assign(new Error("local file reference is unavailable in this project"), { errorCode: ErrorCodes.PATH_OUTSIDE_WORKSPACE });
+ }
+ const root = await referenceRoot(dataDir);
+ const recordPath = join(root, `${localReference}.json`);
+ if (await realpath(recordPath) !== recordPath) throw new Error("file reference record was redirected");
+ const record: FileReference = JSON.parse(await readFile(recordPath, "utf8"));
+ if (record.version !== 1 || record.path !== path || record.projectPath !== await realpath(projectPath)) {
+ throw Object.assign(new Error("local file reference does not belong to this project"), { errorCode: ErrorCodes.PATH_OUTSIDE_WORKSPACE });
+ }
+ try {
+ if (await realpath(path) !== path) throw new Error("referenced file was redirected");
+ const info = await stat(path);
+ if (!info.isFile()) throw new Error("referenced path is not a file");
+ return { path, name: basename(path), kind: "file", mimeType: mimeTypeForPath(path), size: info.size, localReference };
+ } catch (cause) {
+ throw Object.assign(new Error(`Referenced file is unavailable: ${path}`, { cause }), { errorCode: ErrorCodes.NOT_FOUND });
+ }
+}
diff --git a/apps/desktop/electron/main/composer-paste.ts b/apps/desktop/electron/main/composer-paste.ts
index 56946b407..f1bfd29d1 100644
--- a/apps/desktop/electron/main/composer-paste.ts
+++ b/apps/desktop/electron/main/composer-paste.ts
@@ -87,7 +87,7 @@ function fileNameOf(name: unknown, mimeType: string, index: number): string {
return extname(candidate) ? candidate : `${candidate}${extension}`;
}
-function mimeTypeForPath(path: string): string {
+export function mimeTypeForPath(path: string): string {
return MIME_BY_EXTENSION[extname(path).toLowerCase()] ?? "application/octet-stream";
}
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 0215cc68b..967002dda 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -1,6 +1,7 @@
import { clipboard } from "electron";
import { registerSidebarPreferencesIpc } from "./sidebar-preferences-ipc";
import { readComposerClipboardDirectories } from "../composer-clipboard-directories";
+import { referenceComposerFiles } from "../composer-file-references";
import { BrowserWindow, dialog, shell, type OpenDialogOptions } from "electron";
import { dirname } from "node:path";
import { homedir } from "node:os";
@@ -596,8 +597,9 @@ export function registerWorkspaceIpc({
IPC.invoke.composerImportFiles,
async (
event,
- input: { sessionId?: unknown; token?: unknown } = {},
+ input: { sessionId?: unknown; token?: unknown; reference?: unknown } = {},
) => {
+ assertMainWindowSender(event);
if (!host) throw new Error("host unavailable");
const sessionId =
typeof input.sessionId === "string" ? input.sessionId.trim() : "";
@@ -607,7 +609,7 @@ export function registerWorkspaceIpc({
});
}
const session = (await host.call("session.get", { id: sessionId, messageLimit: 1 })) as {
- session?: unknown;
+ session?: { projectPath?: string; remoteWorkspace?: unknown };
};
if (!session.session) {
throw Object.assign(new Error("session not found"), {
@@ -615,6 +617,10 @@ export function registerWorkspaceIpc({
});
}
const paths = consumeComposerPickerSelection(input.token, event.sender.id);
+ if (input.reference === true) {
+ if (!session.session.projectPath || session.session.remoteWorkspace) throw new Error("local file references require a local project");
+ return { files: await referenceComposerFiles(dataDir, sessionId, session.session.projectPath, paths) };
+ }
return {
files: await importComposerFiles(
dataDir,
diff --git a/apps/desktop/electron/main/prompt-attachments.ts b/apps/desktop/electron/main/prompt-attachments.ts
index 7063434b1..0770bc201 100644
--- a/apps/desktop/electron/main/prompt-attachments.ts
+++ b/apps/desktop/electron/main/prompt-attachments.ts
@@ -18,8 +18,10 @@ import {
} from "node:fs";
import { copyFile, readFile } from "node:fs/promises";
import { isAbsolute, join, relative, resolve } from "node:path";
+import { resolveComposerFileReference } from "./composer-file-references.ts";
import {
ErrorCodes,
+ appendLocalFileReferenceContext,
formatFileInsert,
formatPromptPathText,
imageExceedsInlineDimensions,
@@ -247,6 +249,18 @@ export async function preparePromptAttachments(
attachments.map((attachment) => attachment.path),
);
for (const [index, attachment] of attachments.entries()) {
+ if (attachment.localReference !== undefined) {
+ const file = await resolveComposerFileReference(dataRoot, projectPath, attachment.path, attachment.localReference);
+ prepared.push({
+ message: {
+ kind: "file", name: file.name, ref: file.path, mimeType: file.mimeType,
+ size: file.size, localReference: file.localReference,
+ ...(inlineSpans[index] ? { inlinePath: formatPromptPathText(file.path) } : {}),
+ },
+ fallbackPath: file.path,
+ });
+ continue;
+ }
const source = resolvePromptPath(dataRoot, sessionId, projectPath, attachment.path);
if (!source) {
throw Object.assign(new Error(`Attachment path is outside the session roots: ${attachment.path}`), {
@@ -347,7 +361,7 @@ export function appendPromptFallbackPaths(
attachments: readonly PreparedPromptAttachment[],
): string {
const paths = attachments
- .filter((attachment) => !attachment.inlineData)
+ .filter((attachment) => !attachment.inlineData && !attachment.message.localReference)
// A path the prompt already names at the user's own position needs no second
// copy at the end; a rewritten fallback (a replayed copy) still travels.
.filter(
@@ -358,6 +372,6 @@ export function appendPromptFallbackPaths(
.join("")
.trim();
const text = content.trim();
- if (!text) return paths;
- return paths ? `${text}\n${paths}` : text;
+ return appendLocalFileReferenceContext([text, paths].filter(Boolean).join("\n"),
+ attachments.map(attachment => ({ ...attachment.message, path: attachment.fallbackPath })));
}
diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.ts
index b344fc3d9..7ecf55b25 100644
--- a/apps/desktop/src/features/chat/composer/editor.ts
+++ b/apps/desktop/src/features/chat/composer/editor.ts
@@ -39,6 +39,8 @@ export function createFileReference(
preferredName?: string,
sessionId = "",
metadata?: {
+ size?: number;
+ localReference?: string;
kind?: "image" | "file" | "session" | "directory" | "agent";
mimeType?: string;
token?: string;
@@ -58,6 +60,8 @@ export function createFileReference(
? (preferredName ?? "")
: fileReferenceLabel(path, preferredName),
kind: metadata?.kind ?? (isImageFilePath(path) ? "image" : "file"),
+ ...(metadata?.size !== undefined ? { size: metadata.size } : {}),
+ ...(metadata?.localReference ? { localReference: metadata.localReference } : {}),
...(metadata?.mimeType ? { mimeType: metadata.mimeType } : {}),
...(metadata?.token ? { token: metadata.token } : {}),
...(metadata?.plugin ? { plugin: metadata.plugin } : {}),
@@ -283,6 +287,7 @@ function chipSvg(key: string, size = 13): string {
}
export function isEditableTextReference(reference: ComposerFileReference): boolean {
+ if (reference.localReference) return false;
if (isPluginMark(reference) || reference.kind === "directory" || reference.kind === "agent") return false;
return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);
}
@@ -312,7 +317,7 @@ function buildChipElement(
chip.title = origin;
// An image keeps the compact chip and opens its preview, a session chip opens
// that conversation, and only plain text expands into editable draft text.
- const image = chipIconKey(reference) === "image";
+ const image = !reference.localReference && chipIconKey(reference) === "image";
if (image) chip.dataset.image = "";
const session = reference.kind === "session";
if (session) chip.dataset.sessionId = reference.path;
@@ -352,6 +357,13 @@ function buildChipElement(
const nameSpan = document.createElement("span");
nameSpan.className = "composer-chip-name";
nameSpan.textContent = reference.name;
+ if (reference.localReference && reference.size !== undefined) {
+ const unit = Math.min(3, Math.floor(Math.log2(Math.max(1, reference.size)) / 10));
+ const size = reference.size / 1024 ** unit;
+ nameSpan.textContent += ` · ${Number(size.toFixed(1))} ${["B", "KiB", "MiB", "GiB"][unit]}`;
+ chip.title += ` (${reference.size} B)`;
+ chip.setAttribute("aria-label", `${reference.name} — ${chip.title}`);
+ }
const remove = document.createElement("button");
remove.type = "button";
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
index 038d9f251..45c5652b3 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
@@ -289,10 +289,10 @@ export function useComposerAttachments({
let result;
if (native) {
- const imported = native.token ? await api.importFiles(sessionId, native.token) : { files: [] };
+ const imported = native.token ? await api.importFiles(sessionId, native.token, true) : { files: [] };
let index = 0;
result = { files: native.items.map(item => item.kind === "directory"
- ? { path: item.path, name: item.name, kind: "directory" as const, mimeType: undefined }
+ ? { path: item.path, name: item.name, kind: "directory" as const, mimeType: undefined, size: undefined, localReference: undefined }
: imported.files[index++]) };
} else {
result = await api.pasteFiles(sessionId, payload);
@@ -319,6 +319,8 @@ export function useComposerAttachments({
reference: createFileReference(file.path, file.name, sessionId, {
kind: file.kind,
mimeType: file.mimeType,
+ size: file.size,
+ localReference: file.localReference,
token,
}),
};
diff --git a/apps/desktop/src/features/chat/composer/image-attachments.ts b/apps/desktop/src/features/chat/composer/image-attachments.ts
index 554522ded..23e2d8323 100644
--- a/apps/desktop/src/features/chat/composer/image-attachments.ts
+++ b/apps/desktop/src/features/chat/composer/image-attachments.ts
@@ -1,6 +1,7 @@
import type { ComposerFileReference } from "./model";
export function isImageReference(reference: ComposerFileReference): boolean {
+ if (reference.localReference) return false;
return reference.kind === "image" || Boolean(reference.mimeType?.toLowerCase().startsWith("image/"));
}
diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.ts
index 7d3ccfd8e..fdc2bd1c9 100644
--- a/apps/desktop/src/features/chat/composer/model.ts
+++ b/apps/desktop/src/features/chat/composer/model.ts
@@ -59,6 +59,8 @@ export type ComposerPrefill = {
};
export type ComposerFileReference = {
+ size?: number;
+ localReference?: string;
id: string;
sessionId: string;
path: string;
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 59e4308f7..fcf471cb1 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -1126,10 +1126,11 @@ export const api = {
window.piDesktop?.getDroppedFilePath?.(file) ?? null,
pickPhotos: () =>
invoke<{ token: string | null; canceled?: boolean }>(IPC.invoke.composerPickPhotos),
- importFiles: (sessionId: string, token: string) =>
+ importFiles: (sessionId: string, token: string, reference = false) =>
invoke<{ files: ComposerPastedFile[] }>(IPC.invoke.composerImportFiles, {
sessionId,
token,
+ reference,
}),
pasteFiles: (sessionId: string, files: ComposerPasteFile[]) =>
invoke<{ files: ComposerPastedFile[] }>(IPC.invoke.composerPasteFiles, {
diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.ts
index a6ea2df11..795853e91 100644
--- a/apps/desktop/src/lib/composer-draft-cache.ts
+++ b/apps/desktop/src/lib/composer-draft-cache.ts
@@ -21,6 +21,8 @@ type CachedComposerDraft = ComposerDraftSnapshot & {
export const HOME_DRAFT_KEY = "__home__";
export type ComposerDraftFileInput = {
+ size?: number;
+ localReference?: string;
sessionId?: string;
path: string;
name: string;
@@ -32,6 +34,8 @@ export type ComposerDraftFileInput = {
/** The draft-snapshot form of a live reference: its fields without session or id. */
export function draftFileReference({
+ size,
+ localReference,
path,
name,
kind,
@@ -40,6 +44,8 @@ export function draftFileReference({
plugin,
}: ComposerDraftFileInput): ComposerDraftFileReference {
return {
+ ...(size !== undefined ? { size } : {}),
+ ...(localReference ? { localReference } : {}),
path,
name,
kind,
@@ -72,6 +78,8 @@ export function sameDraftFileReference(
a.name === b.name &&
a.kind === b.kind &&
a.mimeType === b.mimeType &&
+ a.size === b.size &&
+ a.localReference === b.localReference &&
a.token === b.token &&
samePluginPart(a.plugin, b.plugin)
);
diff --git a/apps/desktop/src/lib/composer-input-history.ts b/apps/desktop/src/lib/composer-input-history.ts
index 613ab6869..cc5019c95 100644
--- a/apps/desktop/src/lib/composer-input-history.ts
+++ b/apps/desktop/src/lib/composer-input-history.ts
@@ -44,6 +44,8 @@ function readReference(value: unknown): HistoryReference | null {
path: row.path,
name: row.name,
kind,
+ ...(typeof row.size === "number" && Number.isSafeInteger(row.size) && row.size >= 0 ? { size: row.size } : {}),
+ ...(typeof row.localReference === "string" ? { localReference: row.localReference } : {}),
...(typeof row.mimeType === "string" && row.mimeType ? { mimeType: row.mimeType } : {}),
...(typeof row.token === "string" && row.token ? { token: row.token } : {}),
};
diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.ts
index f90bbcaaa..40e07a640 100644
--- a/apps/desktop/src/lib/composer-smart-stop.ts
+++ b/apps/desktop/src/lib/composer-smart-stop.ts
@@ -23,6 +23,8 @@ export type ComposerPluginPart =
};
export type ComposerDraftFileReference = {
+ size?: number;
+ localReference?: string;
path: string;
name: string;
kind?: "image" | "file" | "session" | "directory" | "agent";
diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.ts
index c893d30bf..72a6b70aa 100644
--- a/apps/desktop/src/lib/session-transcript.ts
+++ b/apps/desktop/src/lib/session-transcript.ts
@@ -9,6 +9,8 @@ import {
} from "./session-transcript-updates";
type OptimisticFileReference = {
+ size?: number;
+ localReference?: string;
path: string;
name: string;
kind?: "image" | "file" | "session" | "directory" | "agent";
@@ -41,7 +43,7 @@ export function optimisticUserMessage(
const kind =
reference.kind ??
(IMAGE_PATH_PATTERN.test(reference.path) ? ("image" as const) : ("file" as const));
- return reference.token && kind !== "image" ? [] : [{ reference, kind }];
+ return reference.token && kind !== "image" && !reference.localReference ? [] : [{ reference, kind }];
});
const spans = locateInlinePromptPaths(
content,
@@ -51,6 +53,8 @@ export function optimisticUserMessage(
kind,
name: reference.name,
ref: reference.path,
+ ...(reference.size !== undefined ? { size: reference.size } : {}),
+ ...(reference.localReference ? { localReference: reference.localReference } : {}),
...(reference.mimeType ? { mimeType: reference.mimeType } : {}),
...(spans[index] ? { inlinePath: formatPromptPathText(reference.path) } : {}),
}));
diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.ts
index 7feefee74..638064fd0 100644
--- a/apps/desktop/src/stores/helpers/store-helpers.ts
+++ b/apps/desktop/src/stores/helpers/store-helpers.ts
@@ -37,12 +37,14 @@ export function promptAttachmentsFromDraft(
// Inline chips use tokens for both files and images. Ordinary file chips
// already serialize to @path text (the model can Read them); only image
// chips need the structured transport for vision/fallback handling.
- if (reference.token && kind !== "image") return [];
+ if (reference.token && kind !== "image" && !reference.localReference) return [];
return [
{
path: reference.path,
name: reference.name,
kind,
+ ...(reference.size !== undefined ? { size: reference.size } : {}),
+ ...(reference.localReference ? { localReference: reference.localReference } : {}),
...(reference.mimeType ? { mimeType: reference.mimeType } : {}),
},
];
@@ -62,6 +64,7 @@ export function promptAttachmentsFromMessage(
kind: attachment.kind,
...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),
...(attachment.size !== undefined ? { size: attachment.size } : {}),
+ ...(attachment.localReference ? { localReference: attachment.localReference } : {}),
}));
}
diff --git a/apps/desktop/test/composer-clipboard-directories.test.mjs b/apps/desktop/test/composer-clipboard-directories.test.mjs
index 1139a606e..5080a79c1 100644
--- a/apps/desktop/test/composer-clipboard-directories.test.mjs
+++ b/apps/desktop/test/composer-clipboard-directories.test.mjs
@@ -203,7 +203,9 @@ test("directory metadata never copies a tree and mixed files use the existing im
assert.equal(captured.length, 1);
assert.equal(result.items[1].path, undefined, "regular source paths stay in main");
assert.equal(await readFile(join(folder, "keep.txt"), "utf8"), "original");
- assert.equal(await readComposerClipboardDirectories(clipboard({}), () => assert.fail("regular-only paste keeps its current flow"), () => [file]), null);
+ const regular = await readComposerClipboardDirectories(clipboard({}), () => "file-selection", () => [file]);
+ assert.equal(regular.token, "file-selection");
+ assert.deepEqual(regular.items, [{ kind: "file", name: "notes.txt" }]);
});
test("both send serializers include one directory instruction and escaped path markers", () => {
diff --git a/apps/desktop/test/composer-directory-paste.test.mjs b/apps/desktop/test/composer-directory-paste.test.mjs
index 6f9a605e1..af34fc718 100644
--- a/apps/desktop/test/composer-directory-paste.test.mjs
+++ b/apps/desktop/test/composer-directory-paste.test.mjs
@@ -49,9 +49,10 @@ function harness(native, { files = [], text = "", items = [], paused, sourceSess
getDroppedFilePath: () => null,
readClipboardDirectories: async () => { nativeReads.push(true); if (paused) await paused; return native; },
recordClipboardPaste: async () => {},
- importFiles: async (session, token) => {
+ importFiles: async (session, token, reference) => {
imported.push({ session, token });
- return { files: [{ path: "/synthetic/scratch/notes.txt", name: "notes.txt", kind: "file" }] };
+ assert.equal(reference, true);
+ return { files: [{ path: "/synthetic/original/notes.txt", name: "notes.txt", kind: "file", size: 67108865, localReference: "selection-id" }] };
},
pasteFiles: async (_session, payload) => {
transfers.push(payload);
@@ -145,6 +146,18 @@ test("ordinary native files keep their existing byte attachment flow", async ()
assert.equal(new TextDecoder().decode(run.transfers[0][0].data), "notes");
});
+test("native large-file paste keeps original path and size without reading browser bytes", async () => {
+ const file = new File([], "notes.txt", { type: "text/plain" });
+ file.arrayBuffer = () => assert.fail("disk file contents must not cross IPC");
+ const run = harness({ items: [{ kind: "file", name: "notes.txt" }], token: "selection" }, { files: [file] });
+ await run.paste();
+ assert.equal(run.drafts[0].references[0].path, "/synthetic/original/notes.txt");
+ assert.equal(run.drafts[0].references[0].size, 67108865);
+ assert.equal(run.drafts[0].references[0].localReference, "selection-id");
+ assert.equal(run.writes[0].snapshot.fileReferences[0].size, 67108865);
+ assert.deepEqual(run.transfers, []);
+});
+
for (const navigate of ["switchSession", "switchProject"]) {
test(`pending home folder paste cannot materialize in a destination after ${navigate}`, async () => {
let resume;
diff --git a/apps/desktop/test/composer-file-reference-draft.test.mjs b/apps/desktop/test/composer-file-reference-draft.test.mjs
new file mode 100644
index 000000000..f372a8a94
--- /dev/null
+++ b/apps/desktop/test/composer-file-reference-draft.test.mjs
@@ -0,0 +1,57 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import vm from "node:vm";
+import test from "node:test";
+import ts from "typescript";
+import { isRenderableAttachment } from "@pi-desktop/shared";
+import { snapshotComposerDraft } from "../src/lib/composer-draft-cache.ts";
+
+function loadFunction(path, name, globals = {}) {
+ const source = readFileSync(new URL(path, import.meta.url), "utf8");
+ const tree = ts.createSourceFile("module.ts", source, ts.ScriptTarget.Latest, true);
+ const node = tree.statements.find(node => ts.isFunctionDeclaration(node) && node.name?.text === name);
+ assert.ok(node, name);
+ const code = ts.transpileModule(node.getText(tree).replace(/^export\s+/, ""), {
+ compilerOptions: { target: ts.ScriptTarget.ES2022 },
+ }).outputText;
+ return vm.runInNewContext(`${code}\n${name};`, globals);
+}
+
+const reference = {
+ path: "/outside/large.bin", name: "large.bin", kind: "file", token: "\ue001",
+ localReference: "11111111-2222-4333-8444-555555555555", size: 67108865,
+};
+
+test("draft snapshot and dispatch preserve reference identity and exact size", () => {
+ const draft = snapshotComposerDraft("Inspect \ue001", [{ ...reference, sessionId: "source" }], "source");
+ assert.deepEqual(draft.fileReferences, [reference]);
+ const fromDraft = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromDraft");
+ const [attachment] = fromDraft(draft.fileReferences);
+ assert.equal(attachment.localReference, reference.localReference);
+ assert.equal(attachment.size, reference.size);
+ const fromMessage = loadFunction("../src/stores/helpers/store-helpers.ts", "promptAttachmentsFromMessage", { isRenderableAttachment });
+ const [retry] = fromMessage([{ ...attachment, ref: reference.path }]);
+ assert.equal(retry.localReference, reference.localReference);
+ assert.equal(retry.size, reference.size);
+});
+
+test("file card shows size, remains removable, and does not expand or preview contents", () => {
+ function element() {
+ return { dataset: {}, attrs: {}, events: {}, children: [], title: "", textContent: "",
+ setAttribute(key, value) { this.attrs[key] = value; },
+ addEventListener(key, handler) { this.events[key] = handler; },
+ append(...items) { this.children.push(...items); },
+ };
+ }
+ const globals = { document: { createElement: element }, chipIconKey: () => "file", chipSvg: () => "", isPluginMark: () => false };
+ globals.isEditableTextReference = loadFunction("../src/features/chat/composer/editor.ts", "isEditableTextReference", globals);
+ const build = loadFunction("../src/features/chat/composer/editor.ts", "buildChipElement", globals);
+ let removed;
+ const chip = build(reference, reference.token, "Remove", token => { removed = token; });
+ assert.equal(chip.children[1].textContent, "large.bin · 64 MiB");
+ assert.ok(chip.title.includes("67108865 B"));
+ assert.equal(chip.attrs.role, "listitem");
+ assert.equal(chip.dataset.image, undefined);
+ chip.children[2].events.click({ stopPropagation() {} });
+ assert.equal(removed, reference.token);
+});
diff --git a/apps/desktop/test/composer-file-references.test.mjs b/apps/desktop/test/composer-file-references.test.mjs
new file mode 100644
index 000000000..d5e0002cb
--- /dev/null
+++ b/apps/desktop/test/composer-file-references.test.mjs
@@ -0,0 +1,102 @@
+import assert from "node:assert/strict";
+import { readFileSync } from "node:fs";
+import vm from "node:vm";
+import ts from "typescript";
+import { mkdir, mkdtemp, open, readdir, realpath, rename, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import test from "node:test";
+import { referenceComposerFiles, resolveComposerFileReference } from "../electron/main/composer-file-references.ts";
+import { preparePromptAttachments, appendPromptFallbackPaths } from "../electron/main/prompt-attachments.ts";
+import { appendLocalFileReferenceContext } from "@pi-desktop/shared";
+import { consumeComposerPickerSelection, rememberComposerPickerSelection } from "../electron/main/composer-picker.ts";
+
+async function fixture(t) {
+ const root = await realpath(await mkdtemp(join(tmpdir(), "pi-file-reference-")));
+ t.after(() => rm(root, { recursive: true, force: true }));
+ const data = join(root, "data"), project = join(root, "project"), other = join(root, "other");
+ await Promise.all([data, project, other].map(path => mkdir(path)));
+ const path = join(root, "outside project & 中文.bin");
+ const file = await open(path, "w");
+ await file.truncate(64 * 1024 * 1024 + 1);
+ await file.close();
+ return { root, data, project, other, path };
+}
+
+test("large disk file becomes metadata, survives a new session, and refreshes size on send", async t => {
+ const { data, project, path } = await fixture(t);
+ const [reference] = await referenceComposerFiles(data, "source", project, [path]);
+ assert.equal(reference.path, path);
+ assert.equal(reference.size, 67108865);
+ assert.equal(reference.kind, "file");
+ assert.deepEqual(await readdir(data), ["composer-file-references"], "no scratch copy or content-addressed blob");
+ await writeFile(path, "changed");
+ const [prepared] = await preparePromptAttachments(data, "restored", project, [{ ...reference, size: 1 }], true, `Review @"${path}"`);
+ assert.equal(prepared.message.size, 7, "renderer size is not authoritative");
+ assert.equal(prepared.message.localReference, reference.localReference);
+ assert.equal(prepared.inlineData, undefined);
+ const prompt = appendPromptFallbackPaths("Review", [prepared]);
+ assert.ok(prompt.includes(path));
+ assert.ok(prompt.includes("7 bytes"));
+ assert.equal(appendLocalFileReferenceContext(prompt, [{ ...prepared.message, path }]), prompt, "history replay is idempotent");
+ assert.deepEqual(await readdir(data), ["composer-file-references"]);
+});
+
+test("selection records reject forged paths, another project, remote context, and redirected files", async t => {
+ const { data, project, other, path, root } = await fixture(t);
+ const [reference] = await referenceComposerFiles(data, "source", project, [path]);
+ const resolve = (projectPath, source = path, id = reference.localReference) => resolveComposerFileReference(data, projectPath, source, id);
+ await assert.rejects(resolve(other), /does not belong/);
+ await assert.rejects(resolve(undefined), /unavailable/);
+ await assert.rejects(resolve(project, path, "../../escape"), /unavailable/);
+ await assert.rejects(resolve(project, join(root, "forged")), /does not belong/);
+ const moved = join(root, "moved.bin");
+ await rename(path, moved);
+ await assert.rejects(resolve(project), /Referenced file is unavailable/);
+ await symlink(moved, path);
+ await assert.rejects(resolve(project), /Referenced file is unavailable/);
+});
+
+test("a reference to an image remains metadata and never hydrates outside-project image bytes", async t => {
+ const { data, project, path } = await fixture(t);
+ const image = path + ".png";
+ await rename(path, image);
+ const [reference] = await referenceComposerFiles(data, "source", project, [image]);
+ const [prepared] = await preparePromptAttachments(data, "source", project, [reference], true, "Inspect");
+ assert.equal(prepared.message.kind, "file");
+ assert.equal(prepared.inlineData, undefined);
+ await assert.rejects(preparePromptAttachments(data, "source", project, [{ ...reference, localReference: undefined }], true, "Inspect"), /outside the session roots/);
+});
+
+test("native selection IPC binds sender and session before registering and dispatching a large reference", async t => {
+ const { data, project, path } = await fixture(t);
+ const source = readFileSync(new URL("../electron/main/ipc/workspace-ipc.ts", import.meta.url), "utf8");
+ const tree = ts.createSourceFile("workspace.ts", source, ts.ScriptTarget.Latest, true);
+ let callback;
+ function visit(node) {
+ if (ts.isCallExpression(node) && node.arguments[0]?.getText(tree) === "IPC.invoke.composerImportFiles") callback = node.arguments[1];
+ ts.forEachChild(node, visit);
+ }
+ visit(tree);
+ assert.ok(callback);
+ const code = ts.transpileModule(`(${callback.getText(tree)})`, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText;
+ const host = { call: async (_method, input) => ({ session: input.id === "source" ? { projectPath: project } : null }) };
+ const handler = vm.runInNewContext(code, {
+ host, getHost: () => host, dataDir: data,
+ assertMainWindowSender: event => assert.equal(event.sender.id, 1, "main sender required"),
+ consumeComposerPickerSelection, referenceComposerFiles,
+ importComposerFiles: () => assert.fail("reference must not invoke the byte importer"),
+ ErrorCodes: { NOT_FOUND: "NOT_FOUND", INVALID_ARGUMENT: "INVALID_ARGUMENT" },
+ });
+ const input = { sessionId: "source", token: rememberComposerPickerSelection([path], 1), reference: true };
+ await assert.rejects(handler({ sender: { id: 2 } }, input), /main sender/);
+ await assert.rejects(handler({ sender: { id: 1 } }, { ...input, sessionId: "deleted" }), /session not found/);
+ const { files } = await handler({ sender: { id: 1 } }, input);
+ assert.equal(files[0].path, path);
+ assert.equal(files[0].size, 67108865);
+ await assert.rejects(handler({ sender: { id: 1 } }, input), /selection is unavailable/);
+ const [prepared] = await preparePromptAttachments(data, "source", project, files, false, "Inspect");
+ assert.equal(prepared.message.size, 67108865);
+ assert.ok(appendPromptFallbackPaths("Inspect", [prepared]).includes("67108865 bytes"));
+ assert.deepEqual(await readdir(data), ["composer-file-references"]);
+});
diff --git a/apps/desktop/test/composer-inline-image-chips.test.mjs b/apps/desktop/test/composer-inline-image-chips.test.mjs
index 2fb4cefbc..73304baea 100644
--- a/apps/desktop/test/composer-inline-image-chips.test.mjs
+++ b/apps/desktop/test/composer-inline-image-chips.test.mjs
@@ -17,7 +17,7 @@ const [composer, editor, hoverCard, hoverHook, card, cardStyles, styles, submitH
]);
test("pasted images stay inline chips like every other attachment", () => {
- assert.match(editor, /const image = chipIconKey\(reference\) === "image";/);
+ assert.match(editor, /const image = !reference\.localReference && chipIconKey\(reference\) === "image";/);
assert.match(editor, /if \(image\) chip\.dataset\.image = "";/);
assert.match(editor, /const editableText = !image && !session && isEditableTextReference\(reference\);/);
// Activating an image chip opens the preview; it never expands draft text.
diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjs
index f4a61dbc3..fb6054b82 100644
--- a/apps/desktop/test/composer-paste-files.test.mjs
+++ b/apps/desktop/test/composer-paste-files.test.mjs
@@ -101,7 +101,7 @@ test("paste IPC is a typed renderer-to-main bridge", () => {
assert.match(protocol, /composerImportFiles: "pi-desktop\/composer\/importFiles"/);
assert.match(api, /pasteFiles: \(sessionId: string, files: ComposerPasteFile\[\]\)/);
assert.match(api, /pickFiles: \(\) =>[\s\S]*token: string \| null/);
- assert.match(api, /importFiles: \(sessionId: string, token: string\)/);
+ assert.match(api, /importFiles: \(sessionId: string, token: string, reference = false\)/);
assert.match(api, /IPC\.invoke\.composerPasteFiles/);
assert.match(api, /recordClipboardPaste: \(text: string\)/);
assert.match(api, /IPC\.invoke\.clipboardRecordPaste/);
diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rs
index f6a9d8eba..433f5183a 100644
--- a/crates/host-core/src/sessions.rs
+++ b/crates/host-core/src/sessions.rs
@@ -190,6 +190,8 @@ pub struct MessageUsage {
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MessageAttachment {
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub local_reference: Option<String>,
pub kind: String,
pub name: String,
#[serde(rename = "ref")]
@@ -570,6 +572,9 @@ pub(crate) fn ui_to_record(message: &UiMessage) -> (MessageRecord, Option<String
if let Some(size) = attachment.size {
block.insert("size".into(), json!(size));
}
+ if let Some(reference) = &attachment.local_reference {
+ block.insert("localReference".into(), json!(reference));
+ }
if let Some(text) = &attachment.text {
block.insert("text".into(), json!(text));
}
@@ -714,6 +719,10 @@ pub(crate) fn record_to_ui(record: MessageRecord) -> UiMessage {
return None;
}
Some(MessageAttachment {
+ local_reference: block
+ .get("localReference")
+ .and_then(|v| v.as_str())
+ .map(str::to_string),
kind: block.get("kind").and_then(|v| v.as_str())?.to_string(),
name: block.get("name").and_then(|v| v.as_str())?.to_string(),
reference: block.get("ref").and_then(|v| v.as_str())?.to_string(),
@@ -5947,12 +5956,33 @@ mod tests {
);
}
+ #[test]
+ fn local_file_attachments_roundtrip_as_canonical_blocks() {
+ let db = test_db();
+ let session = create_session(&db, None, None, None, None, None).unwrap();
+ let mut user = user_msg("local-file", "Inspect the reference", "2026-11-13T00:00:00Z");
+ user.attachments = Some(vec![MessageAttachment {
+ local_reference: Some("11111111-2222-4333-8444-555555555555".into()),
+ kind: "file".into(),
+ name: "large.bin".into(),
+ reference: "/synthetic/large.bin".into(),
+ mime_type: None,
+ size: Some(67_108_865),
+ text: None,
+ inline_path: Some("@/synthetic/large.bin".into()),
+ }]);
+ append_message(&db, &session.id, &user, None).unwrap();
+ let detail = get_session(&db, &session.id).unwrap().unwrap();
+ assert_eq!(detail.messages[0].attachments, user.attachments);
+ }
+
#[test]
fn user_attachments_roundtrip_as_canonical_blocks() {
let db = test_db();
let session = create_session(&db, None, None, None, None, None).unwrap();
let mut user = user_msg("image-1", "这是什么", "2025-05-01T00:00:00Z");
user.attachments = Some(vec![MessageAttachment {
+ local_reference: None,
kind: "image".into(),
name: "image.png".into(),
reference: "attachments/abc123".into(),
diff --git a/docs/adr/composer-local-file-references.md b/docs/adr/composer-local-file-references.md
new file mode 100644
index 000000000..4f20b6084
--- /dev/null
+++ b/docs/adr/composer-local-file-references.md
@@ -0,0 +1,40 @@
+# ADR: Pasted local files are live references
+
+- Status: Accepted
+- Date: 2026-11-13
+- Related: composer-pasted-directory-references, issue #2314
+
+## Context
+
+Copying disk-backed clipboard files into session scratch eagerly allocates and
+transfers their full contents. The 64 MiB transfer bound prevents attaching a
+large file even when the task needs only a bounded read.
+
+## Decision
+
+Native clipboard files use the existing sender-bound, one-shot selection token
+to register live references in the owning local project. Main creates a UUID
+record under `<data_dir>/composer-file-references/` containing only the canonical
+path, project path, and originating session id. These small records are retained
+with local application data so input history can restore references in another
+session of the same project. They contain no file bytes and grant no tool access.
+
+Drafts, queued input and messages carry the additive `localReference` id and byte
+size. Composer shows the name and human-readable size. On dispatch, main validates
+the record and project, rejects a changed canonical target or unavailable file,
+and refreshes size from filesystem metadata. The Agent receives path and size as
+context and reads relevant parts through normal tool permissions. Main does not
+hydrate referenced images; the Agent can request an image through its normal
+Read path. Screenshots and other generated clipboard payloads retain existing
+scratch materialization and model image checks. Native picker and drop behavior
+is unchanged.
+
+## Consequences
+
+The file transfer byte limits still protect actual transfers, while native
+references retain the 20-item selection limit. The attachment-root validator is
+unchanged for ordinary attachments; a registered external reference is metadata
+only. A restored reference observes current file contents and can become
+unavailable after deletion, movement, unmounting, or project relocation. There is
+no snapshot or implicit upload. Older records without `localReference` retain
+their original behavior. Protocol and database schema versions are unchanged.
diff --git a/docs/adr/composer-pasted-directory-references.md b/docs/adr/composer-pasted-directory-references.md
index b9a8e92aa..fc9045a66 100644
--- a/docs/adr/composer-pasted-directory-references.md
+++ b/docs/adr/composer-pasted-directory-references.md
@@ -14,8 +14,8 @@ Copying its tree into scratch would create an expensive and stale snapshot.
On an explicit native-file paste, Electron main captures bounded native clipboard
file metadata. Directories become typed draft references and removable folder
cards above the editable text, with a name, localized Folder label and full-path
-tooltip. Mixed regular files use the existing sender-bound one-shot import
-capability. Main
+tooltip. Mixed regular files use the sender-bound one-shot selection
+capability to register [live file references](composer-local-file-references.md). Main
captures the selection before filesystem awaits and accepts no renderer paths.
The bridge is main-window-only and blocked from MCP/plugin callers. macOS reads
raw pasteboard types, Linux reads native file URI lists, and Windows reads the
@@ -33,7 +33,8 @@ action reveals the directory in the system file manager and returns no contents.
## Consequences
-Normal file/image/text paste and the existing directory-drop choice remain.
+Generated image/text paste and the existing directory-drop choice remain.
+Native disk files follow the local-file-reference decision above.
Clipboard file metadata is read only for a paste gesture, never polled or added
to clipboard history. Draft/history metadata retains directory paths rather than
contents. Directories may change or disappear before later use. The existing JSON
diff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.md
index 2430370e2..2894ff0b2 100644
--- a/docs/spec/00-baseline.md
+++ b/docs/spec/00-baseline.md
@@ -2,6 +2,9 @@
> [Pasted directory references](../adr/composer-pasted-directory-references.md) add
> folder cards and lazy dir prompt context without copying trees or granting access.
+> [Pasted local file references](../adr/composer-local-file-references.md) extend
+> native clipboard paste to live file paths and byte sizes, with metadata-only
+> dispatch and unchanged tool permissions.
- Baseline Version: `0.4.22`
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index c0a75ee31..0a6b093e7 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -2352,20 +2352,39 @@ renderer receives the token but never receives the selected absolute paths.
### composer/importFiles
```ts
-composer/importFiles({ sessionId, token }) -> {
+composer/importFiles({ sessionId, token, reference?: boolean }) -> {
files: ComposerPastedFile[];
}
```
Electron main consumes the sender-bound picker token, resolves each recorded
path through `realpath`, requires an existing regular file, applies the same
-20-file / 64 MiB per file / 128 MiB total limits as clipboard transfer, and
+20-file / 64 MiB per file / 128 MiB total limits as clipboard byte transfer, and
copies the bytes into `<data_dir>/scratch/<sessionId>/pasted/` under a
UUID-backed sanitized name. The token is deleted before import starts, so it
cannot be replayed. The returned `ComposerPastedFile` records are the only
paths the renderer stores or dispatches, so a picker selection cannot leave an
external source path in the prompt or bypass the attachment-root boundary.
+For native clipboard files, `reference: true` consumes the same one-shot token
+but registers metadata instead of copying bytes. Main requires a local project,
+stores a durable UUID selection record, and returns the canonical original path,
+name, MIME, exact byte size and additive `localReference` id. Only the main window
+may invoke this flow. Ordinary file-only and mixed file/folder clipboard lists
+both use it; no `File.arrayBuffer()` is needed and transfer byte limits do not
+apply. The 20-item clipboard limit remains. Screenshots/generated payloads use
+`pasteFiles`; picker imports without `reference` retain the copy behavior above.
+
+Drafts, queue entries and message attachments retain `localReference` and `size`.
+On dispatch, main matches the id/path to the selection record and current local
+project, rejects missing files or canonical-target changes, and refreshes size.
+The Agent receives path and byte size as reference context. No referenced file
+or image contents are read, hashed, snapshotted or uploaded by dispatch; normal
+tool access policy governs subsequent reads, including outside-project approval.
+Input history can restore the live reference into another session in the same
+project. Original contents can change and the reference can become unavailable.
+See [the decision record](../../adr/composer-local-file-references.md).
+
### composer/pasteFiles
```ts
@@ -2382,6 +2401,7 @@ type ComposerPasteFile = {
};
type ComposerPastedFile = {
+ localReference?: string; // main-owned metadata record for a live disk reference
path: string; // UUID-backed absolute storage path
name: string; // sanitized original leaf display name
kind: "image" | "file";
diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.md
index 70c251343..a5d0502be 100644
--- a/docs/spec/03-runtime/03-tools-and-permissions.md
+++ b/docs/spec/03-runtime/03-tools-and-permissions.md
@@ -322,7 +322,11 @@ session gets a scratch directory outside the workspace:
<data_dir>/scratch/<sessionId>/
```
-OS clipboard files and images pasted into the composer are materialized by
+Native disk-file pastes retain main-registered live paths and byte sizes; they
+do not copy or read file contents, including referenced images. Subsequent reads
+use normal tool permissions. See [local file references](../../adr/composer-local-file-references.md).
+
+Generated clipboard files and images pasted into the composer are materialized by
Electron main below `<data_dir>/scratch/<sessionId>/pasted/` before their
paths and metadata are captured as transient composer references. At dispatch,
main validates the source against the session scratch/project roots. Images are
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 8c283ef1b..ee02644bb 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -9721,6 +9721,29 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
candidate and record its revision; PR integration validation follows the
authoritative `AGENTS.md` workflow without merging into local main first.
+#### E2E-COMPOSER-local-file-references: Native file paste keeps paths and sizes
+
+- **Preconditions**: Local project and synthetic disk files, including a sparse
+ 64 MiB + 1 byte file outside the project, a small text file and an image.
+- **Steps**: Copy each file in the OS file manager and paste into Composer;
+ also paste a mixed file/folder selection. Remove a card, switch sessions,
+ restore input history, queue a prompt and restart before delivery. Modify,
+ move, delete or replace a source with a symlink before sending. Separately
+ paste a screenshot and a large text selection.
+- **Expected**: Native disk files retain original paths and exact byte sizes;
+ removable inline cards show human-readable size. No source contents cross
+ paste IPC or enter scratch/content-addressed snapshots. Small and large disk
+ files use the same reference flow; screenshots and generated text retain their
+ existing scratch/image behavior. Dispatch refreshes size, preserves metadata
+ through messages and model history, and clearly rejects unavailable or
+ redirected sources. Forged ids/paths, another project and remote contexts are
+ refused. Agent reads use normal permissions; referencing an external file does
+ not grant access. Metadata-only input history restores the live path and size.
+- **Targeted coverage**: `composer-file-references.test.mjs`,
+ `composer-directory-paste.test.mjs`, `composer-clipboard-directories.test.mjs`,
+ draft/history tests and the host attachment roundtrip test. Native clipboard
+ gestures and full provider delivery require a separate desktop E2E run.
+
#### E2E-102h: Composer picker imports files into session scratch
- **Preconditions**: The app is running with a home or Agent composer and a
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 5e09ebfa1..de67f3f21 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -5781,6 +5781,32 @@ describe("DesktopAgentRuntime session collaboration provenance", () => {
await runtime.dispose();
await restored.dispose();
});
+ it("preserves local file reference size in live input and restored history", async () => {
+ const attachment = {
+ kind: "file" as const, name: "large.png", ref: "/external/large.png",
+ size: 67108865, localReference: "11111111-2222-4333-8444-555555555555",
+ };
+ const restored = createRuntime({ history: [{
+ id: "reference-user", role: "user", content: "Inspect",
+ createdAt: "2026-11-13T00:00:00Z", attachments: [attachment],
+ }] });
+ const live = createRuntime();
+ try {
+ const message = (restored as unknown as { agent: Agent }).agent.state.messages.find(row => row.role === "user");
+ expect(typeof message?.content).toBe("string");
+ expect(message?.content).toContain("/external/large.png");
+ expect(message?.content).toContain("67108865 bytes");
+ const agent = (live as unknown as { agent: Agent }).agent;
+ const prompt = vi.spyOn(agent, "prompt").mockResolvedValue();
+ vi.spyOn(agent, "waitForIdle").mockResolvedValue();
+ await live.prompt({ text: "Inspect", attachments: [{ ...attachment, path: attachment.ref }] }, "user", "turn");
+ expect(prompt).toHaveBeenCalledWith(expect.objectContaining({ role: "user", content: message?.content }));
+ } finally {
+ await live.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");
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index fc18934c7..b9bc9565f 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -1,3 +1,4 @@
+import { appendLocalFileReferenceContext } from "@pi-desktop/shared";
import { buildJobTools } from "./background-job-tools.js";
import {
MAX_MUTATION_RECOVERY_FAILURES, BASH_PATCH_FAILURE_KEY,
@@ -372,9 +373,10 @@ function promptText(input: RuntimePrompt): string {
const references = (input.attachments ?? [])
.map((attachment) => sessionReferenceBlock(attachment))
.filter((block): block is string => block !== null);
- return references.length
+ const text = references.length
? `${input.text}\n\n${references.join("\n\n")}`.trim()
: input.text;
+ return appendLocalFileReferenceContext(text, input.attachments ?? []);
}
/** One provider image block for an attachment whose bytes crossed this turn. */
@@ -430,6 +432,7 @@ function runtimeAttachmentFromMessage(
kind: attachment.kind,
...(attachment.mimeType ? { mimeType: attachment.mimeType } : {}),
...(attachment.size !== undefined ? { size: attachment.size } : {}),
+ ...(attachment.localReference ? { localReference: attachment.localReference } : {}),
...(attachment.text ? { text: attachment.text } : {}),
// Recorded placement: the message content names this image at that spot, so
// the restored prompt keeps the block there too.
diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts
index 7b40bf2b2..169501f33 100644
--- a/packages/shared/src/index.ts
+++ b/packages/shared/src/index.ts
@@ -87,3 +87,4 @@ export * from "./session-todos.js";
export * from "./tool-call-lineage.js";
export * from "./event-usage.js";
export * from "./storage.js";
+export { appendLocalFileReferenceContext } from "./local-file-references.js";
diff --git a/packages/shared/src/local-file-references.ts b/packages/shared/src/local-file-references.ts
new file mode 100644
index 000000000..6b6d58111
--- /dev/null
+++ b/packages/shared/src/local-file-references.ts
@@ -0,0 +1,13 @@
+import { formatFileInsert } from "./composer-trigger.js";
+
+/** Metadata is context only; tool admission still owns file access. */
+export function appendLocalFileReferenceContext(
+ content: string,
+ files: ReadonlyArray<{ path: string; size?: number; localReference?: string }>,
+): string {
+ const references = files.filter(file => file.localReference).map(file =>
+ `${formatFileInsert(file.path, "file").trim()} (${file.size} bytes)`).join("\n");
+ if (!references) return content;
+ const block = `Local file references (sizes recorded when sent; read relevant parts as needed using normal tool permissions):\n${references}`;
+ return content.endsWith(block) ? content : [content, block].filter(Boolean).join("\n");
+}
diff --git a/packages/shared/src/types/agent.ts b/packages/shared/src/types/agent.ts
index 6d3e1bf90..ff266a101 100644
--- a/packages/shared/src/types/agent.ts
+++ b/packages/shared/src/types/agent.ts
@@ -61,6 +61,8 @@ export type AgentPromptRequest = {
};
export type AgentPromptAttachment = {
+ /** Main-owned selection id; metadata only, with no implicit file access. */
+ localReference?: string;
path: string;
name: string;
kind: "image" | "file";
diff --git a/packages/shared/src/types/composer.ts b/packages/shared/src/types/composer.ts
index ad83754e1..2f22b9cbe 100644
--- a/packages/shared/src/types/composer.ts
+++ b/packages/shared/src/types/composer.ts
@@ -41,9 +41,11 @@ export type ComposerPasteFile = {
data: ArrayBuffer;
};
-/** A clipboard file materialized in the originating session's scratch root. */
+/** One pasted item: an original disk-file reference or a materialized payload. */
export type ComposerPastedFile = {
- /** UUID-backed canonical path used by the prompt and file tools. */
+ /** Durable main-owned selection record; contents are read only through tools. */
+ localReference?: string;
+ /** Canonical original path for references, or a unique session scratch path. */
path: string;
/** Sanitized original leaf name used only for compact composer display. */
name: string;
diff --git a/packages/shared/src/types/messages.ts b/packages/shared/src/types/messages.ts
index bd585ae68..81f6e8f69 100644
--- a/packages/shared/src/types/messages.ts
+++ b/packages/shared/src/types/messages.ts
@@ -70,6 +70,7 @@ export type SessionUsageCost = {
export { addUsage, contextOccupancyTokens, withUsageIdentity } from "../message-usage.js";
export type MessageAttachment = {
+ localReference?: string;
kind: "image" | "file" | "session";
name: string;
/** Workspace-relative path, session-scratch absolute path, or a session id. */