Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(composer): attach pasted image files as images
zszz30d9d8e306511
diff --git a/apps/desktop/electron/main/composer-file-references.ts b/apps/desktop/electron/main/composer-file-references.tsindex 446036f21..3e44a324a 100644--- a/apps/desktop/electron/main/composer-file-references.ts+++ b/apps/desktop/electron/main/composer-file-references.ts@@ -2,7 +2,7 @@ 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";+import { importComposerFiles, mimeTypeForPath, selectImportableComposerImages } 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 };@@ -41,6 +41,46 @@ export async function referenceComposerFiles(}));}+/**+ * Native clipboard disk files: image files are copied into session scratch+ * like picker imports so vision models receive their bytes even after the+ * source (often a screenshot tool's temp file) disappears. Everything else,+ * and images beyond the import bounds, stays a metadata-only live reference.+ * Results keep the paste order because the renderer pairs them by index.+ * Called only with paths consumed from a sender-bound native selection.+ */+export async function pasteComposerClipboardFiles(+ dataDir: string,+ sessionId: string,+ projectPath: string | undefined,+ 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 sources = 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 importable = selectImportableComposerImages(sources);+ const referencePaths = sources.filter((_, index) => !importable[index]).map(source => source.path);+ const imagePaths = sources.filter((_, index) => importable[index]).map(source => source.path);+ if (referencePaths.length > 0 && !projectPath) throw new Error("local file references require a local project");+ const referenced = referencePaths.length > 0 && projectPath+ ? await referenceComposerFiles(dataDir, sessionId, projectPath, referencePaths)+ : [];+ const imported = await importComposerFiles(dataDir, sessionId, imagePaths);+ let nextImage = 0;+ let nextReference = 0;+ return importable.map(isImage => {+ const file = isImage ? imported[nextImage++] : referenced[nextReference++];+ if (!file) throw new Error("pasted file result is missing");+ return file;+ });+}+/** Refresh metadata only; reading contents still belongs to normal tool admission. */export async function resolveComposerFileReference(dataDir: string,diff --git a/apps/desktop/electron/main/composer-paste.ts b/apps/desktop/electron/main/composer-paste.tsindex f1bfd29d1..44ea3da6f 100644--- a/apps/desktop/electron/main/composer-paste.ts+++ b/apps/desktop/electron/main/composer-paste.ts@@ -161,6 +161,29 @@ export async function saveComposerPasteFiles();}+/**+ * Decide, in order, which native disk files can be copied as image+ * attachments within the same per-file and batch bounds that+ * importComposerFiles enforces. Files that do not fit are left for the+ * caller's metadata-only reference flow instead of failing the whole paste.+ */+export function selectImportableComposerImages(+ files: ReadonlyArray<{ path: string; size: number }>,+): boolean[] {+ let count = 0;+ let totalBytes = 0;+ return files.map(({ path, size }) => {+ const name = basename(path);+ if (!isImageFile(name, mimeTypeForPath(path))) return false;+ if (count >= MAX_FILES || size > MAX_FILE_BYTES || totalBytes + size > MAX_TOTAL_BYTES) {+ return false;+ }+ count += 1;+ totalBytes += size;+ return true;+ });+}+/*** Copy native-picker selections into the owning session scratch directory.* The renderer only receives the resulting safe paths; source paths neverdiff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 967002dda..0071b9759 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -1,7 +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 { pasteComposerClipboardFiles } from "../composer-file-references";import { BrowserWindow, dialog, shell, type OpenDialogOptions } from "electron";import { dirname } from "node:path";import { homedir } from "node:os";@@ -618,8 +618,8 @@ 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) };+ const localProject = session.session.remoteWorkspace ? undefined : session.session.projectPath;+ return { files: await pasteComposerClipboardFiles(dataDir, sessionId, localProject, paths) };}return {files: await importComposerFiles(diff --git a/apps/desktop/test/composer-file-references.test.mjs b/apps/desktop/test/composer-file-references.test.mjsindex 8289129dc..851688526 100644--- a/apps/desktop/test/composer-file-references.test.mjs+++ b/apps/desktop/test/composer-file-references.test.mjs@@ -6,7 +6,7 @@ import { mkdir, mkdtemp, open, readdir, realpath, rename, rm, symlink, writeFileimport { 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 { pasteComposerClipboardFiles, 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";@@ -88,6 +88,66 @@ test("a reference to an image remains metadata and never hydrates outside-projecawait assert.rejects(preparePromptAttachments(data, "source", project, [{ ...reference, localReference: undefined }], true, "Inspect"), /outside the session roots/);});+const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNo2PDgPwAG1AMQ/5r/oAAAAABJRU5ErkJggg==", "base64");++test("native clipboard images are copied like picker imports while other files stay live references (#2529)", async t => {+ const { root, data, project, path } = await fixture(t);+ const image = join(root, "PixPin_2026-11-23_14-37-54.png");+ const notes = join(root, "notes.txt");+ await writeFile(image, PNG);+ await writeFile(notes, "notes");+ const files = await pasteComposerClipboardFiles(data, "source", project, [notes, image, path]);+ assert.deepEqual(files.map(file => file.name), ["notes.txt", "PixPin_2026-11-23_14-37-54.png", "outside project & 中文.bin"], "paste order is preserved");+ assert.equal(files[0].localReference !== undefined, true);+ assert.equal(files[2].localReference !== undefined, true);+ const [, pasted] = files;+ assert.equal(pasted.kind, "image");+ assert.equal(pasted.localReference, undefined);+ assert.equal(pasted.size, PNG.length);+ assert.ok(pasted.path.startsWith(join(data, "scratch", "source", "pasted")), "image is materialized in session scratch");+ assert.deepEqual(readFileSync(pasted.path), PNG);+ // The screenshot tool may clear its temp file before the user sends.+ await rm(image);+ const prepared = await preparePromptAttachments(data, "source", project, files, true, "What is in this screenshot?");+ assert.equal(prepared[1].message.kind, "image");+ assert.ok(prepared[1].inlineData, "vision models receive the image bytes");+ assert.match(prepared[1].message.ref, /^attachments\/[0-9a-f]{64}$/);+ assert.equal(prepared[0].inlineData, undefined);+ assert.equal(prepared[2].inlineData, undefined);+});++test("native clipboard images beyond the import bounds, SVGs, and non-images keep the reference flow", async t => {+ const { root, data, project } = await fixture(t);+ const large = join(root, "huge.png");+ const handle = await open(large, "w");+ await handle.truncate(64 * 1024 * 1024 + 1);+ await handle.close();+ const svg = join(root, "icon.svg");+ await writeFile(svg, "<svg xmlns=\"http://www.w3.org/2000/svg\"/>");+ const batch = [];+ for (let index = 0; index < 3; index++) {+ const part = join(root, `part-${index}.png`);+ const file = await open(part, "w");+ await file.truncate(60 * 1024 * 1024);+ await file.close();+ batch.push(part);+ }+ const files = await pasteComposerClipboardFiles(data, "source", project, [large, svg, ...batch]);+ assert.deepEqual(files.map(file => file.localReference !== undefined), [true, true, false, false, true], "the batch byte budget overflows to references");+ assert.deepEqual(files.map(file => file.kind), ["file", "file", "image", "image", "file"]);+});++test("native clipboard images paste without a local project; other files still require one", async t => {+ const { root, data } = await fixture(t);+ const image = join(root, "remote.png");+ await writeFile(image, PNG);+ const [pasted] = await pasteComposerClipboardFiles(data, "source", undefined, [image]);+ assert.equal(pasted.kind, "image");+ await writeFile(join(root, "notes.txt"), "notes");+ await assert.rejects(pasteComposerClipboardFiles(data, "source", undefined, [image, join(root, "notes.txt")]), /require a local project/);+ await assert.rejects(pasteComposerClipboardFiles(data, "source", undefined, [join(root, "missing.png")]));+});+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");@@ -100,12 +160,13 @@ test("native selection IPC binds sender and session before registering and dispavisit(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 sessions = { source: { projectPath: project }, remote: { projectPath: project, remoteWorkspace: { id: "remote" } } };+ const host = { call: async (_method, input) => ({ session: sessions[input.id] ?? 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"),+ consumeComposerPickerSelection, pasteComposerClipboardFiles,+ importComposerFiles: () => assert.fail("native clipboard files must not use the picker importer directly"),ErrorCodes: { NOT_FOUND: "NOT_FOUND", INVALID_ARGUMENT: "INVALID_ARGUMENT" },});const input = { sessionId: "source", token: rememberComposerPickerSelection([path], 1), reference: true };@@ -115,6 +176,8 @@ test("native selection IPC binds sender and session before registering and dispaassert.equal(files[0].path, path);assert.equal(files[0].size, 67108865);await assert.rejects(handler({ sender: { id: 1 } }, input), /selection is unavailable/);+ const remote = { sessionId: "remote", token: rememberComposerPickerSelection([path], 1), reference: true };+ await assert.rejects(handler({ sender: { id: 1 } }, remote), /require a local project/);const [prepared] = await preparePromptAttachments(data, "source", project, files, false, "Inspect");assert.equal(prepared.message.size, 67108865);assert.ok(appendPromptFallbackPaths("Inspect", [prepared]).includes("67108865 bytes"));diff --git a/docs/adr/composer-local-file-references.md b/docs/adr/composer-local-file-references.mdindex d097d1f89..5fdea7a70 100644--- a/docs/adr/composer-local-file-references.md+++ b/docs/adr/composer-local-file-references.md@@ -2,7 +2,7 @@- Status: Accepted- Date: 2026-11-13-- Related: composer-pasted-directory-references, issue #2314+- Related: composer-pasted-directory-references, issue #2314, issue #2529## Context@@ -10,16 +10,27 @@ Copying disk-backed clipboard files into session scratch eagerly allocates and ttheir full contents, and the transfer bound prevents attaching a large file even when thetask needs only a bounded read.+Image files are different: screenshot tools such as PixPin place a temporary image file+rather than a bitmap on the clipboard. Referencing that file sent the model only a path, so+vision models could not see the image, and the temporary file may be gone before an agent+reads it or a transcript is replayed (issue #2529).+## Decision-Native clipboard files use the existing sender-bound, one-shot selection token to register+Native clipboard image files (raster images, not SVG) that fit the existing import bounds+(64 MiB per file, 128 MiB and 20 files per batch) are copied into session scratch exactly+like native-picker imports and are sent as image attachments; images beyond those bounds+fall back to the reference flow below instead of failing the paste. Image imports do not+require a local project. Results keep the paste order.++Other native clipboard files use the existing sender-bound, one-shot selection token to registerlive references in the owning local project: Main creates a UUID record under`<data_dir>/composer-file-references/` holding only the canonical path, project path, andoriginating session id, with no file bytes and no tool access. Drafts, queued input, andmessages carry the additive `localReference` id and byte size shown as name and size, and ondispatch Main revalidates the record and project, rejects a changed or unavailable target,and refreshes the size before the agent receives path and size as context to read through-normal tool permissions, requesting referenced images through its Read path. Input history+normal tool permissions, requesting any referenced oversized image through its Read path. Input historyrestores references without reads or snapshots, screenshots and generated payloads keep theexisting scratch materialization, and records without `localReference` are unchanged.@@ -30,6 +41,11 @@ existing scratch materialization, and records without `localReference` are uncha- A restored reference observes current file contents and can become unavailable afterdeletion, movement, or project relocation; there is no snapshot and no implicit upload.+- Pasted image files behave like picked or dropped images: their bytes are snapshotted at+ paste time and survive deletion of the source file.+## Alternatives- Keep eager scratch materialization: the transfer bound still refuses large files.+- Reference image files too and let the agent read them: vision models receive only a path,+ and temporary screenshot files can disappear before they are read (issue #2529).diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex eb8a7d0c6..89f2ad056 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -2380,20 +2380,26 @@ cannot be replayed. The returned `ComposerPastedFile` records are the onlypaths the renderer stores or dispatches, so a picker selection cannot leave anexternal 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.+For native clipboard files, `reference: true` consumes the same one-shot token.+Raster image files (not SVG) that fit the import bounds above (64 MiB per file,+128 MiB and 20 files per batch, counted in paste order) are copied into session+scratch exactly like picker imports and returned as `kind: "image"` without+`localReference`; they do not require a local project. Every other file,+including images beyond those bounds, 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. Results keep the clipboard order. 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 to references. 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 localproject, 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+contents are read, hashed, snapshotted or uploaded by dispatch; normaltool access policy governs subsequent reads, including outside-project approval.Input history can restore the live reference into another session in the sameproject. Original contents can change and the reference can become unavailable.diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 70bfde7cd..51352ccfa 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -356,8 +356,10 @@ session gets a scratch directory outside the workspace:```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).+do not copy or read file contents. Native image files within the import bounds+are the exception: they are copied into session scratch like picker imports so+vision models receive the image. Subsequent reads of referenced files 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 byElectron main below `<data_dir>/scratch/<sessionId>/pasted/` before theirdiff --git a/docs/spec/06-delivery/e2e/conversation.md b/docs/spec/06-delivery/e2e/conversation.mdindex ef1992558..4dfffa3d1 100644--- a/docs/spec/06-delivery/e2e/conversation.md+++ b/docs/spec/06-delivery/e2e/conversation.md@@ -3310,9 +3310,13 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.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+ paste IPC or enter scratch/content-addressed snapshots. Small and large+ non-image disk files use the same reference flow. Native raster image files+ within the import bounds (for example a screenshot tool's temporary PNG) are+ copied into session scratch, attach as image chips and reach vision models as+ image bytes even after the source is deleted; oversized images and SVGs keep+ the reference flow. Screenshots and generated text retain their existing+ scratch/image behavior. Dispatch refreshes size, preserves metadatathrough messages and model history, and clearly rejects unavailable orredirected sources. Forged ids/paths, another project and remote contexts arerefused. Agent reads use normal permissions; referencing an external file does@@ -3325,7 +3329,9 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.drives real React hooks, native disk-backed `File` objects, preload IPC,selection tokens, reference registration, prompt preparation and Composerhistory. A sparse 64 MiB + 1 byte source and a small file outside the project- retain size cards without renderer byte reads or scratch writes. The fixture+ retain size cards without renderer byte reads or scratch writes, while a+ native PNG in the same selection is imported to scratch and prepared as inline+ image data. The fixtureedits the large source before send and verifies refreshed size in model context.A second Electron process recalls the stored metadata and dispatches throughthe persisted reference records. Native clipboard metadata and provider@@ -3335,6 +3341,16 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.Restore the saved selection before focusing the original control so selectionupdates cannot steal its final focus. Stale session/project previews restoreneither focus nor selection (`composer-image-preview-focus.test.mjs`).+- **Native pasteboard coverage (macOS)**: `pnpm test:e2e:composer-paste-image-file`+ runs the built Desktop with a real Host, agent sidecar and preload IPC, writes+ a temporary PNG outside the project to the general pasteboard as a file URL+ (the PixPin/Finder shape from issue #2529), and pastes with a real paste+ command. It asserts an image chip, deletes the source before send, then+ verifies the local vision-capable Chat Completions fixture receives the exact+ PNG as an `image_url` part with no local file reference context, and that the+ transcript stores `attachments/<sha256>`. Only the model endpoint is a local+ fixture. The pasteboard is shared with the desktop session, so the script+ retries a paste only when Chromium saw an empty pasteboard.## E2E-COMPOSER-deep-file-mentions: `@` reaches deep files in a large workspacediff --git a/package.json b/package.jsonindex 62ff1d201..60e28950e 100644--- a/package.json+++ b/package.json@@ -45,6 +45,7 @@"test:e2e:model-discovery-state": "node scripts/e2e-model-discovery-state.mjs","test:e2e:composer-model-selection": "node scripts/e2e-composer-model-selection.mjs","test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs",+ "test:e2e:composer-paste-image-file": "node scripts/e2e-composer-paste-image-file.mjs","test:e2e:transcript": "node scripts/e2e-transcript-render.mjs","test:e2e:gen-ui": "node scripts/e2e-gen-ui.mjs","test:e2e:renderer-responsiveness": "node scripts/e2e-renderer-responsiveness.mjs",diff --git a/scripts/e2e-composer-paste-image-file.mjs b/scripts/e2e-composer-paste-image-file.mjsnew file mode 100644index 000000000..8ba27f9ed--- /dev/null+++ b/scripts/e2e-composer-paste-image-file.mjs@@ -0,0 +1,253 @@+#!/usr/bin/env node+/**+ * Issue #2529: a screenshot tool (PixPin) puts a temporary image *file* on the+ * OS clipboard. Pasting it into the Composer must attach an image that reaches+ * a vision model as image bytes, even after the tool deletes its temp file.+ *+ * Real Desktop, preload, native clipboard, Host SQLite and agent sidecar; only+ * the model is a local Chat Completions fixture. macOS only: the clipboard is+ * written through NSPasteboard exactly like a Finder/PixPin file copy.+ */+import assert from "node:assert/strict";+import { execFileSync, spawn } from "node:child_process";+import { createHash } from "node:crypto";+import { once } from "node:events";+import { createServer } from "node:http";+import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { assertDesktopBuild, resolveElectronBinary } from "./e2e/boot.mjs";+import { Host, resolveHostBinary } from "./e2e/host.mjs";+import { createSession } from "./e2e/session.mjs";+import { waitFor } from "./e2e/wait.mjs";++if (process.platform !== "darwin") {+ console.log("COMPOSER_PASTE_IMAGE_FILE_E2E skipped: native pasteboard fixture requires macOS");+ process.exit(0);+}++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+assertDesktopBuild(root);+const scratch = await realpath(await mkdtemp(join(tmpdir(), "pi-paste-image-file-")));+const dataDir = join(scratch, "data");+const project = join(scratch, "project");+// Outside the project, like %LOCALAPPDATA%\PixPin\Temp.+const screenshotTemp = join(scratch, "PixPin", "Temp");+const screenshot = join(screenshotTemp, "PixPin_2026-11-23_14-37-54.png");+const PNG = Buffer.from(+ "iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAYAAABytg0kAAAAFklEQVR4nGP4z8DwHwyBNBMDAwMDAwBn9Qf+5cS6cAAAAABJRU5ErkJggg==",+ "base64",+);+const requests = [];+const checks = [];+let child;+let ws;+let passed = false;++const provider = createServer(async (request, response) => {+ if (!request.url.endsWith("/chat/completions")) {+ response.writeHead(404); response.end("{}"); return;+ }+ let body = "";+ for await (const chunk of request) body += chunk;+ const payload = JSON.parse(body);+ requests.push(payload);+ const base = { id: `paste-image-${requests.length}`, object: "chat.completion.chunk", created: 1, model: payload.model };+ response.writeHead(200, { "content-type": "text/event-stream" });+ for (const chunk of [+ { ...base, choices: [{ index: 0, delta: { role: "assistant", content: "Screenshot received." }, finish_reason: null }] },+ { ...base, choices: [{ index: 0, delta: {}, finish_reason: "stop" }], usage: { prompt_tokens: 10, completion_tokens: 3, total_tokens: 13 } },+ ]) response.write(`data: ${JSON.stringify(chunk)}\n\n`);+ response.end("data: [DONE]\n\n");+});++/** Write file URLs to the general pasteboard the way Finder and PixPin do. */+function copyFilesToPasteboard(paths) {+ const script = `ObjC.import("AppKit");+const board = $.NSPasteboard.generalPasteboard;+board.clearContents;+const urls = ${JSON.stringify(paths)}.map(path => $.NSURL.fileURLWithPath(path));+if (!board.writeObjects($(urls))) throw new Error("pasteboard write failed");`;+ execFileSync("/usr/bin/osascript", ["-l", "JavaScript", "-e", script]);+}++function clearPasteboard() {+ execFileSync("/usr/bin/osascript", ["-l", "JavaScript", "-e", 'ObjC.import("AppKit"); $.NSPasteboard.generalPasteboard.clearContents;']);+}++try {+ await mkdir(project, { recursive: true });+ await mkdir(screenshotTemp, { recursive: true });+ await writeFile(screenshot, PNG);+ await new Promise((done, fail) => { provider.once("error", fail); provider.listen(0, "127.0.0.1", done); });++ const hostBin = resolveHostBinary();+ const host = new Host(hostBin, dataDir, { quiet: true, env: { PI_DESKTOP_AGENTS_DIR: join(scratch, "agents") } });+ let sessionId;+ await host.start();+ try {+ const created = await host.call("providers.create", {+ name: "Vision fixture", type: "openai_compatible", apiStyle: "chat_completions",+ baseUrl: `http://127.0.0.1:${provider.address().port}/v1`, authKind: "api_key", secretValue: "vision-fixture-key",+ models: [{ id: "vision-fixture", contextWindow: 128000, maxTokens: 4096, thinkingLevels: ["off"], supportsImages: true }],+ defaultModelId: "vision-fixture",+ });+ await host.call("settings.set", {+ defaultProviderId: created.provider.id, defaultModelId: "vision-fixture", defaultMode: "agent", locale: "en",+ });+ sessionId = (await createSession(host, project, "Pasted screenshot file")).id;+ await host.call("session.configure", { id: sessionId, mode: "agent", permissionMode: "auto" });+ } finally { await host.stop(); }++ const { appDir, electronBinary } = resolveElectronBinary(root);+ const port = Number(process.env.PI_PASTE_IMAGE_CDP_PORT || 9391);+ const env = {+ ...process.env, PI_DESKTOP_DATA_DIR: dataDir, PI_DESKTOP_HOST_BIN: hostBin,+ PI_DESKTOP_AGENTS_DIR: join(scratch, "agents"), PI_CODING_AGENT_DIR: join(scratch, "agent"),+ ELECTRON_RENDERER_URL: "", PI_DESKTOP_START_MAXIMIZED: "0",+ };+ delete env.ELECTRON_RUN_AS_NODE;+ child = spawn(electronBinary, [`--remote-debugging-port=${port}`, `--user-data-dir=${join(scratch, "profile")}`, "."], {+ cwd: appDir, env, stdio: ["ignore", "pipe", "pipe"], detached: true,+ });+ let output = "";+ child.stdout.on("data", (data) => { output += data; });+ child.stderr.on("data", (data) => { output += data; });++ let target;+ await waitFor(async () => {+ try {+ target = (await (await fetch(`http://127.0.0.1:${port}/json/list`)).json())+ .find((entry) => entry.type === "page" && entry.url.includes("index.html") && !entry.url.includes("plugin-launcher"));+ return !!target;+ } catch { return false; }+ }, 30_000, "desktop CDP target");+ ws = new WebSocket(target.webSocketDebuggerUrl);+ await once(ws, "open");+ let sequence = 0;+ const pending = new Map();+ ws.onmessage = ({ data }) => {+ const message = JSON.parse(data);+ const entry = pending.get(message.id);+ if (!entry) return;+ pending.delete(message.id);+ if (message.error) entry.reject(new Error(JSON.stringify(message.error)));+ else entry.resolve(message.result);+ };+ const send = (method, params = {}) => new Promise((done, fail) => {+ const id = ++sequence;+ pending.set(id, { resolve: done, reject: fail });+ ws.send(JSON.stringify({ id, method, params }));+ });+ const evaluate = async (expression) => {+ const result = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true });+ if (result.exceptionDetails) throw new Error(result.exceptionDetails.exception?.description ?? JSON.stringify(result.exceptionDetails));+ return result.result.value;+ };+ const key = async (params) => {+ await send("Input.dispatchKeyEvent", { type: "keyDown", ...params });+ await send("Input.dispatchKeyEvent", { type: "keyUp", ...params, commands: undefined, text: undefined });+ };++ await waitFor(() => evaluate("typeof window.__PI_DESKTOP__?.selectSession === 'function' && !!document.querySelector('.app-shell:not(.app-shell-boot):not(.is-booting)')"), 30_000, "desktop shell");+ await evaluate("window.__PI_DESKTOP__.skipStartupOverlays()");+ await evaluate(`window.__PI_DESKTOP__.selectSession(${JSON.stringify(sessionId)})`);+ await waitFor(() => evaluate("!!document.querySelector('.composer-input[contenteditable=\"true\"]')"), 20_000, "composer");+ await evaluate(`(() => {+ window.__pasteProbe = [];+ document.querySelector('.composer-input[contenteditable="true"]').addEventListener("paste", (event) => {+ window.__pasteProbe.push({ types: [...event.clipboardData.types], files: [...event.clipboardData.files].map(file => file.name + ":" + file.type) });+ }, { capture: true });+ })()`);+ const focusComposer = async () => {+ await send("Page.bringToFront");+ await evaluate(`(() => {+ const editor = document.querySelector('.composer-input[contenteditable="true"]');+ editor.focus();+ const range = document.createRange(); range.selectNodeContents(editor); range.collapse(false);+ const selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range);+ })()`);+ };++ // The general pasteboard is shared with the rest of the desktop session; a+ // clipboard manager (for example Clipy) can briefly replace it. Retry only+ // when Chromium saw an empty pasteboard, never when the Composer got a file.+ for (let attempt = 1; ; attempt += 1) {+ copyFilesToPasteboard([screenshot]);+ await new Promise((done) => setTimeout(done, 300 * attempt));+ await focusComposer();+ await key({ key: "v", code: "KeyV", windowsVirtualKeyCode: 86, modifiers: 4, commands: ["paste"] });+ await waitFor(() => evaluate("window.__pasteProbe.length > 0"), 5_000, "paste event");+ const probe = await evaluate("window.__pasteProbe.pop()");+ if (probe.types.includes("Files")) break;+ if (attempt === 3) throw new Error(`paste never carried a file: ${JSON.stringify(probe)}`);+ console.log(`paste attempt ${attempt} saw an empty pasteboard; retrying`);+ }+ await waitFor(() => evaluate(`!!document.querySelector('.composer-chip')`), 15_000, "pasted file chip");+ const chip = await evaluate(`(() => {+ const chip = document.querySelector('.composer-chip');+ return { text: chip.textContent, image: chip.dataset.image !== undefined };+ })()`);+ assert(chip.text.includes("PixPin_2026-11-23_14-37-54.png"), `unexpected chip: ${chip.text}`);+ assert.equal(chip.image, true, "pasted image file must render as an image chip, not a file reference");+ checks.push("native pasteboard image file pastes as an image chip");++ // PixPin clears its temp directory; the draft must not depend on the source.+ await rm(screenshot);+ await send("Input.insertText", { text: "What is in this screenshot?" });+ await key({ key: "Enter", code: "Enter", windowsVirtualKeyCode: 13 });+ await waitFor(() => requests.length > 0, 30_000, "model request");+ const readSession = async () => {+ const result = await evaluate(`window.piDesktop.invoke(window.piDesktop.channels.invoke.sessionGet, ${JSON.stringify(sessionId)})`);+ assert.equal(result.ok, true, JSON.stringify(result.error));+ return result.data.session;+ };+ await waitFor(async () => JSON.stringify((await readSession()).messages.filter((entry) => entry.role === "assistant"))+ .includes("Screenshot received."), 30_000, "persisted assistant reply");++ const user = [...requests[0].messages].reverse().find((message) => message.role === "user");+ const parts = Array.isArray(user.content) ? user.content : [{ type: "text", text: user.content }];+ const images = parts.filter((part) => part.type === "image_url");+ assert.equal(images.length, 1, `vision model must receive one image part: ${JSON.stringify(parts).slice(0, 600)}`);+ assert.equal(images[0].image_url.url, `data:image/png;base64,${PNG.toString("base64")}`);+ const text = parts.filter((part) => part.type === "text").map((part) => part.text).join("\n");+ assert(!text.includes("Local file references"), "image must not be sent as a local file reference");+ assert(!text.includes(screenshot), "deleted temp path must not be the image source");+ checks.push("vision model receives the exact PNG bytes after the temp file was deleted");++ const message = (await readSession()).messages.find((entry) => entry.role === "user");+ assert.equal(message.attachments.length, 1);+ const [attachment] = message.attachments;+ assert.equal(attachment.kind, "image");+ assert.equal(attachment.localReference, undefined);+ const hash = createHash("sha256").update(PNG).digest("hex");+ assert.equal(attachment.ref, `attachments/${hash}`);+ assert.deepEqual(await readFile(join(dataDir, "attachments", hash)), PNG);+ checks.push("transcript stores a durable content-addressed image attachment");++ passed = true;+ console.log("COMPOSER_PASTE_IMAGE_FILE_E2E " + JSON.stringify({ ok: true, checks }));+} catch (error) {+ if (ws?.readyState === WebSocket.OPEN) {+ console.error("SHELL_STATE", await new Promise((done) => {+ const id = 1e9;+ ws.onmessage = ({ data }) => { const message = JSON.parse(data); if (message.id === id) done(message.result?.result?.value); };+ ws.send(JSON.stringify({ id, method: "Runtime.evaluate", params: { expression: "document.body.innerText.slice(-2000)", returnByValue: true } }));+ setTimeout(() => done("<unavailable>"), 3000);+ }));+ }+ throw error;+} finally {+ try { clearPasteboard(); } catch {}+ ws?.close();+ if (child && child.exitCode === null) {+ try { process.kill(-child.pid, "SIGTERM"); } catch {}+ const exited = await Promise.race([once(child, "close").then(() => true), new Promise((done) => setTimeout(() => done(false), 5000))]);+ if (!exited) try { process.kill(-child.pid, "SIGKILL"); } catch {}+ }+ provider.closeAllConnections();+ await new Promise((done) => provider.close(done));+ if (passed && process.env.E2E_KEEP_ARTIFACTS !== "1") await rm(scratch, { recursive: true, force: true });+ else console.log(`Paste image file artifacts: ${scratch}`);+}diff --git a/scripts/e2e-composer-paste.mjs b/scripts/e2e-composer-paste.mjsindex f534964ad..e14a9360d 100644--- a/scripts/e2e-composer-paste.mjs+++ b/scripts/e2e-composer-paste.mjs@@ -97,7 +97,7 @@ const fs = require("node:fs/promises");const assert = require("node:assert/strict");const { saveComposerPasteFiles } = require("./writer.cjs");const { nativeClipboardPaths, readComposerClipboardDirectories } = require("./directories.cjs");-const { referenceComposerFiles } = require("./references.cjs");+const { pasteComposerClipboardFiles } = require("./references.cjs");const { rememberComposerPickerSelection, consumeComposerPickerSelection } = require("./picker.cjs");const { preparePromptAttachments, appendPromptFallbackPaths } = require("./prompt.cjs");const { readOpenableFile, readOpenableImage, resolveRealOpenablePath } = require("./reader.cjs");@@ -113,7 +113,7 @@ let directoryPastePending = true;let referencePrompts = 0;ipcMain.handle("pi-desktop/composer/readClipboardDirectories", async (event) => {if (process.argv.includes("--file-references-only")) {- const paths = ["large reference.bin", "native notes.txt"].map(name => path.join(__dirname, name));+ const paths = ["large reference.bin", "native-image.png", "native notes.txt"].map(name => path.join(__dirname, name));const clipboard = { readBuffer: format => Buffer.from(format === "text/uri-list"? paths.map(source => pathToFileURL(source).href).join("\\r\\n") : "") };const data = await readComposerClipboardDirectories(clipboard,@@ -137,18 +137,24 @@ if (process.argv.includes("--file-references-only") || process.argv.includes("--ipcMain.handle("pi-desktop/composer/importFiles", async (event, input) => {assert.equal(input.reference, true);assert.equal(input.sessionId, "paste-a");- const files = await referenceComposerFiles(__dirname, input.sessionId,+ const files = await pasteComposerClipboardFiles(__dirname, input.sessionId,path.join(__dirname, "reference-project"), consumeComposerPickerSelection(input.token, event.sender.id));assert.equal(files[0].size, 67108865);+ // Native image files are copied like picker imports instead of becoming live references (#2529).+ assert.equal(files[1].kind, "image");+ assert.equal(files[1].localReference, undefined);+ assert(files[1].path.startsWith(path.join(__dirname, "scratch", input.sessionId) + path.sep));// Simulate a source edit after registration, before the user sends the draft.await fs.writeFile(path.join(__dirname, "large reference.bin"), "changed");return { ok: true, data: { files } };});ipcMain.handle("pi-desktop/agent/prompt", async (_event, input) => {- assert.equal(input.attachments.length, 2);+ assert.equal(input.attachments.length, 3);const prepared = await preparePromptAttachments(__dirname, input.sessionId,path.join(__dirname, "reference-project"), input.attachments, true, input.content);- assert(prepared.every(item => item.message.kind === "file" && !item.inlineData));+ const image = prepared.find(item => item.message.name === "native-image.png");+ assert(image?.message.kind === "image" && image.inlineData, "native image file must reach the model as image bytes");+ assert(prepared.filter(item => item !== image).every(item => item.message.kind === "file" && !item.inlineData));const large = prepared.find(item => item.message.name === "large reference.bin");assert.equal(large.message.size, 7);const context = appendPromptFallbackPaths(input.content, prepared);@@ -322,9 +328,9 @@ app.whenReady().then(async () => {window.webContents.debugger.attach("1.3");const { root } = await window.webContents.debugger.sendCommand("DOM.getDocument");const { nodeId } = await window.webContents.debugger.sendCommand("DOM.querySelector", { nodeId: root.nodeId, selector: "#native-files" });- await window.webContents.debugger.sendCommand("DOM.setFileInputFiles", { nodeId, files: [path.join(__dirname,- process.argv.includes("--file-references-only") || process.argv.includes("--file-references-history-check")- ? "large reference.bin" : "native-image.png"), path.join(__dirname, "native notes.txt")] });+ await window.webContents.debugger.sendCommand("DOM.setFileInputFiles", { nodeId, files: (process.argv.includes("--file-references-only") || process.argv.includes("--file-references-history-check")+ ? ["large reference.bin", "native-image.png", "native notes.txt"] : ["native-image.png", "native notes.txt"])+ .map(name => path.join(__dirname, name)) });window.webContents.on("console-message", async (event) => {if (!event.message.startsWith("PI_PREVIEW_KEY:")) return;const key = event.message.slice("PI_PREVIEW_KEY:".length);diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex 1a337ebc6..01ac4d10f 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -282,12 +282,12 @@ globalThis.composerPasteProbe = async (screenshotOnly = false, fileReferencesOnlrender("paste-a", referenceProject);if (referenceHistoryOnly) {const history = loadComposerInputHistory("paste-a")[0];- assert(history?.fileReferences.length === 2, "process restart lost reference history");+ assert(history?.fileReferences.length === 3, "process restart lost reference history");flushSync(() => controller.restoreDraftForKey("paste-a", history));await new Promise(requestAnimationFrame);} else {const files = Array.from((document.getElementById("native-files") as HTMLInputElement).files!);- assert(files.length === 2 && files.every(file => api.getDroppedFilePath(file)), "native reference File paths missing");+ assert(files.length === 3 && files.every(file => api.getDroppedFilePath(file)), "native reference File paths missing");for (const file of files) file.arrayBuffer = () => { throw new Error("disk file bytes were read by the renderer"); };await dispatchPaste(controller.ref.current!, "", files);}@@ -295,10 +295,12 @@ globalThis.composerPasteProbe = async (screenshotOnly = false, fileReferencesOnlconst matchesSnapshot = (candidate: ComposerDraftSnapshot | undefined) => candidate !== undefined &&candidate.text === snapshot.text && candidate.fileReferences.length === snapshot.fileReferences.length &&candidate.fileReferences.every((file, index) => sameDraftFileReference(file, snapshot.fileReferences[index]));- assert(snapshot.fileReferences.length === 2, "native file-only selection did not attach both references");+ assert(snapshot.fileReferences.length === 3, "native file-only selection did not attach every file");const large = snapshot.fileReferences.find(file => file.name === "large reference.bin")!;assert(large?.size === 67108865 && large.localReference && !large.path.includes("/scratch/"), "large file lost its original path, size or selection id");assert(controller.ref.current!.textContent?.includes("64 MiB"), "file card did not display its size");+ const image = snapshot.fileReferences.find(file => file.name === "native-image.png");+ assert(image?.kind === "image" && !image.localReference && /[\\/]scratch[\\/]/.test(image.path), "native image file was not imported as an image attachment");flushSync(() => root.render(null));render("paste-a", referenceProject);await new Promise(requestAnimationFrame);@@ -317,7 +319,7 @@ globalThis.composerPasteProbe = async (screenshotOnly = false, fileReferencesOnlawait new Promise(requestAnimationFrame);assert(matchesSnapshot(controller.draftSnapshot(readEditorValue(controller.ref.current!))), "history recall lost removable references");flushSync(() => controller.ref.current!.querySelector<HTMLButtonElement>(".composer-chip-remove")!.click());- assert(controller.fileReferences.length === 1, "restored reference was not removable");+ assert(controller.fileReferences.length === 2, "restored reference was not removable");} finally { historySendPrompt = previousSend; }return { ok: true, largeFileReference: true, noRendererByteRead: true, metadataHistory: true,refreshedSize: true, processRestartMetadata: referenceHistoryOnly };