Skip to content

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

fix(composer): preserve native metadata and home paste ownership

Linuxdazhaod3f968ce1855
diff --git a/apps/desktop/electron/main/composer-clipboard-directories.ts b/apps/desktop/electron/main/composer-clipboard-directories.ts
index 66a0bb458..b1eb01632 100644
--- a/apps/desktop/electron/main/composer-clipboard-directories.ts
+++ b/apps/desktop/electron/main/composer-clipboard-directories.ts
@@ -1,53 +1,55 @@
import { execFileSync } from "node:child_process";
-import { basename, isAbsolute } from "node:path";
+import { basename, isAbsolute, join, win32 } from "node:path";
import { realpath, stat } from "node:fs/promises";
import { fileURLToPath } from "node:url";
type NativeClipboard = {
- availableFormats(): string[];
readBuffer(format: string): Buffer;
};
const MAX_ITEMS = 20;
const MAX_METADATA_BYTES = 1024 * 1024;
+function windowsClipboardPaths(): string[] {
+ // CF_HDROP is a built-in format, not the custom format named "CF_HDROP".
+ const command = "[Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); Add-Type -AssemblyName System.Windows.Forms; ConvertTo-Json -Compress -InputObject @([System.Windows.Forms.Clipboard]::GetFileDropList())";
+ const executable = join(process.env.SystemRoot || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
+ const value: unknown = JSON.parse(execFileSync(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-STA", "-Command", command], {
+ encoding: "utf8", windowsHide: true, timeout: 2000, maxBuffer: MAX_METADATA_BYTES,
+ }));
+ if (!Array.isArray(value) || !value.every(path => typeof path === "string")) throw new Error("invalid clipboard file list");
+ return value;
+}
+
/** Read native file metadata only during an explicit Composer paste. */
-export function nativeClipboardPaths(clipboard: NativeClipboard): string[] {
- const formats = clipboard.availableFormats();
+export function nativeClipboardPaths(
+ clipboard: NativeClipboard,
+ platform: NodeJS.Platform = process.platform,
+ readWindowsPaths: () => string[] = windowsClipboardPaths,
+): string[] {
const read = (format: string) => {
- if (!formats.includes(format)) return Buffer.alloc(0);
+ // availableFormats exposes normalized MIME names, not native pasteboard types.
const bytes = clipboard.readBuffer(format);
if (bytes.length > MAX_METADATA_BYTES) throw new Error("clipboard file metadata is too large");
return bytes;
};
let paths: string[] = [];
- const macList = read("NSFilenamesPboardType");
- if (macList.length && process.platform === "darwin") {
+ const macList = platform === "darwin" ? read("NSFilenamesPboardType") : Buffer.alloc(0);
+ if (platform === "win32") paths = readWindowsPaths();
+ else if (macList.length) {
const value: unknown = JSON.parse(execFileSync("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", "-"], {
- input: macList, maxBuffer: MAX_METADATA_BYTES,
+ input: macList, maxBuffer: MAX_METADATA_BYTES, timeout: 1000,
}).toString("utf8"));
if (!Array.isArray(value) || !value.every(path => typeof path === "string")) throw new Error("invalid clipboard file list");
paths = value;
} else {
- // DROPFILES contains a 20-byte header followed by a NUL-separated list.
- const drop = read("CF_HDROP");
- if (drop.length) {
- if (drop.length < 20) throw new Error("invalid clipboard file list");
- const offset = drop.readUInt32LE(0);
- if (offset < 20 || offset >= drop.length) throw new Error("invalid clipboard file list");
- paths = drop.subarray(offset).toString(drop.readUInt32LE(16) ? "utf16le" : "latin1").split("\0").filter(Boolean);
- } else {
- const wide = read("FileNameW");
- if (wide.length) paths = wide.toString("utf16le").split("\0").filter(Boolean);
- else {
- const uris = read("text/uri-list").toString("utf8") || read("x-special/gnome-copied-files").toString("utf8") || read("public.file-url").toString("utf8");
- paths = uris.split(/[\r\n\0]+/).filter(line => line.startsWith("file:")).map(uri => fileURLToPath(uri));
- }
- }
+ const uris = read("text/uri-list").toString("utf8") || read("x-special/gnome-copied-files").toString("utf8") || read("public.file-url").toString("utf8");
+ paths = uris.split(/[\r\n\0]+/).filter(line => line.startsWith("file:")).map(uri => fileURLToPath(uri));
}
paths = [...new Set(paths)];
if (paths.length > MAX_ITEMS) throw new Error(`too many pasted items (maximum ${MAX_ITEMS})`);
- if (paths.some(path => !isAbsolute(path) || path.includes("\0"))) throw new Error("invalid clipboard file path");
+ const absolute = platform === "win32" ? win32.isAbsolute : isAbsolute;
+ if (paths.some(path => !absolute(path) || path.includes("\0"))) throw new Error("invalid clipboard file path");
return paths;
}
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
index 9a7dec228..37d75648f 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts
@@ -242,6 +242,7 @@ export function useComposerAttachments({
let sourceValue = readEditorValue(editor);
const sourceSessionId = activeSessionId;
const sourceDraftKey = draftKey;
+ const sourceWorkspacePath = useAppStore.getState().workspace?.path ?? "";
let previousReferences = snapshotReferences(sourceSessionId ?? "");
const sourceRevision = readComposerDraftRevision(sourceDraftKey);
setPasting(true);
@@ -273,6 +274,10 @@ export function useComposerAttachments({
},
];
})();
+ if (!sourceSessionId) {
+ const current = useAppStore.getState();
+ if (current.activeSessionId || (current.workspace?.path ?? "") !== sourceWorkspacePath) return;
+ }
let sessionId = sourceSessionId;
if (!sessionId) sessionId = (await materializeDraftSession()) ?? "";
if (!sessionId) throw new Error("session unavailable");
diff --git a/apps/desktop/test/composer-clipboard-directories.test.mjs b/apps/desktop/test/composer-clipboard-directories.test.mjs
index 357fcd005..72d4ef7a2 100644
--- a/apps/desktop/test/composer-clipboard-directories.test.mjs
+++ b/apps/desktop/test/composer-clipboard-directories.test.mjs
@@ -29,7 +29,19 @@ test("native URI file lists preserve order and decode spaces/unicode without rea
test("native file lists enforce metadata and selection bounds", () => {
assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": "x".repeat(1024 * 1024 + 1) })), /too large/);
assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": Array.from({ length: 21 }, (_, i) => `file:///tmp/${i}`).join("\n") })), /too many/);
- assert.throws(() => nativeClipboardPaths(clipboard({ CF_HDROP: Buffer.alloc(2) })), /invalid/);
+ assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": "file:///tmp/a%00b" })), /null|invalid|encoded/i);
+});
+
+test("Windows uses the complete native FileDropList instead of custom CF_HDROP or one FileNameW", () => {
+ const paths = ["C:\\first folder", "C:\\notes.txt", "D:\\中文"];
+ assert.deepEqual(nativeClipboardPaths({ readBuffer: () => assert.fail("Windows must use its native file list") }, "win32", () => paths), paths);
+ assert.throws(() => nativeClipboardPaths(clipboard({}), "win32", () => ["relative"]), /invalid clipboard file path/);
+});
+
+test("normalized MIME enumeration does not hide raw Finder file URLs", () => {
+ const native = clipboard({ "public.file-url": "file:///tmp/synthetic-folder" });
+ native.availableFormats = () => ["text/uri-list"];
+ assert.deepEqual(nativeClipboardPaths(native), ["/tmp/synthetic-folder"]);
});
test("macOS Finder file-list metadata is decoded in full", { skip: process.platform !== "darwin" }, () => {
diff --git a/apps/desktop/test/composer-directory-paste.test.mjs b/apps/desktop/test/composer-directory-paste.test.mjs
index 3fa32898b..038cc8521 100644
--- a/apps/desktop/test/composer-directory-paste.test.mjs
+++ b/apps/desktop/test/composer-directory-paste.test.mjs
@@ -17,17 +17,18 @@ function extract(source, name) {
return result;
}
-function harness(native, { files = [], text = "", items = [], paused } = {}) {
+function harness(native, { files = [], text = "", items = [], paused, sourceSessionId = "source" } = {}) {
const read = path => readFileSync(new URL(path, import.meta.url), "utf8");
const editor = read("../src/features/chat/composer/editor.ts");
const hook = read("../src/features/chat/composer/hooks/useComposerAttachments.ts");
- const drafts = [], errors = [], writes = [], imported = [], transfers = [];
+ const drafts = [], errors = [], writes = [], imported = [], transfers = [], created = [];
let revision = 0;
- let activeSessionId = "source";
+ let activeSessionId = sourceSessionId;
+ let workspacePath = "/synthetic/project";
const element = { textContent: "before after" };
const context = {
inputBlocked: false, attachmentsAllowed: true, activeSessionId,
- draftKey: "source", largePasteThreshold: 1000,
+ draftKey: sourceSessionId ?? "home", largePasteThreshold: 1000,
ref: { current: element }, valueRef: { current: element.textContent },
previousWorkspacePathRef: { current: "/synthetic/project" },
snapshotReferences: () => [], invalidateComposerTransforms() {},
@@ -62,14 +63,16 @@ function harness(native, { files = [], text = "", items = [], paused } = {}) {
readComposerDraftRevision: () => revision,
readComposerDraft: () => undefined,
deleteComposerDraft() {}, HOME_DRAFT_KEY: "home",
- useAppStore: { getState: () => ({ activeSessionId, sessions: [{ id: "source" }] }) },
+ useAppStore: { getState: () => ({ activeSessionId, workspace: { path: workspacePath }, sessions: [{ id: "source" }, { id: "created" }] }) },
+ materializeDraftSession: async () => { created.push(workspacePath); activeSessionId = "created"; return "created"; },
};
const code = extract(editor, "clipboardFiles") + "\n" + extract(editor, "preferClipboardText") + "\nmodule.exports = " + extract(hook, "pasteClipboardFiles");
vm.runInNewContext(ts.transpileModule(code, { compilerOptions: { target: ts.ScriptTarget.ES2022 } }).outputText, environment);
return {
- drafts, errors, writes, imported, transfers,
+ drafts, errors, writes, imported, transfers, created,
edit(text) { element.textContent = text; revision++; },
switchSession() { activeSessionId = "other"; },
+ switchProject() { workspacePath = "/synthetic/other-project"; },
paste: () => environment.module.exports({ currentTarget: element, preventDefault() {}, clipboardData: { files, items, types: ["Files"], getData: () => text } }),
};
}
@@ -135,3 +138,25 @@ test("ordinary native files keep their existing byte attachment flow", async ()
assert.equal(run.transfers.length, 1);
assert.equal(new TextDecoder().decode(run.transfers[0][0].data), "notes");
});
+
+for (const navigate of ["switchSession", "switchProject"]) {
+ test(`pending home folder paste cannot materialize in a destination after ${navigate}`, async () => {
+ let resume;
+ const paused = new Promise(resolve => { resume = resolve; });
+ const run = harness({ items: [folder], token: null }, { paused, sourceSessionId: null });
+ const pending = run.paste();
+ run[navigate]();
+ resume();
+ await pending;
+ assert.deepEqual(run.created, []);
+ assert.deepEqual(run.writes, []);
+ assert.deepEqual(run.drafts, []);
+ });
+}
+
+test("home folder paste materializes only its original unchanged workspace", async () => {
+ const run = harness({ items: [folder], token: null }, { sourceSessionId: null });
+ await run.paste();
+ assert.deepEqual(run.created, ["/synthetic/project"]);
+ assert.equal(run.drafts[0].references[0].sessionId, "created");
+});
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 8f3d83276..c5a1558e7 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -18,8 +18,10 @@ Each ADR includes:
## Index
+
| ID | Title | Status |
|---|---|---|
+| composer-pasted-directory-references | [Composer pasted directory references](composer-pasted-directory-references.md) | Accepted |
| plugin-projects-list | [Read-only durable project enumeration for plugins](plugin-projects-list.md) | Accepted |
| append-only-review-state | [Append-only review state](append-only-review-state.md) | Implemented candidate |
| lossless-tool-image-storage | [Lossless tool-image storage and bounded history mutations](lossless-tool-image-storage.md) | Implemented candidate |
diff --git a/docs/adr/composer-pasted-directory-references.md b/docs/adr/composer-pasted-directory-references.md
index 4d29ad6f0..6162cd308 100644
--- a/docs/adr/composer-pasted-directory-references.md
+++ b/docs/adr/composer-pasted-directory-references.md
@@ -1,4 +1,4 @@
-# Composer pasted directory references
+# ADR: Composer pasted directory references
- Status: Accepted
- Date: 2026-11-03
@@ -16,7 +16,10 @@ file metadata. Directories become typed draft references and atomic removable
folder cards with a name, localized Folder label and full-path tooltip. Mixed
regular files use the existing sender-bound one-shot import capability. Main
captures the selection before filesystem awaits and accepts no renderer paths.
-The bridge is main-window-only and blocked from MCP/plugin callers.
+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
+complete native FileDropList in a bounded STA PowerShell invocation. Native raw
+formats are not gated on Electron's normalized MIME enumeration.
Directory references serialize as escaped `<dir>absolute/path</dir>` markers plus
one instruction to inspect directory structure and read relevant files as needed
diff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.md
index f407038fa..8bd989c79 100644
--- a/docs/spec/00-baseline.md
+++ b/docs/spec/00-baseline.md
@@ -3,6 +3,7 @@
> [Pasted directory references](../adr/composer-pasted-directory-references.md) add
> folder cards and lazy dir prompt context without copying trees or granting access.
+
- Baseline Version: `0.4.22`
- Date: `2026-10-08`
- Status: `Frozen for implementation details (indefinite local permission approvals + Plan checkpoint artifact + approval/execution startup fence + protocol v11 + schema v16 + host-owned plugin session import/read/update/delete P0/P1 + selectable shell catalog + icon-free composer prompt row + turn-boundary context checkpoint compaction + session-scoped work panel + edge-specific work-panel/chat resize ownership + models.dev chat model catalog + provider/runtime safety + M5 hardening + settings IA + project archive + sidebar organization + app update delivery + three-platform release + Extensions page density and theme-readable actions + custom global UI font + ChatGPT-style logical project groups + categorized plugin providers in Add Service)`
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 6ecce2196..4a52a2e7b 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -5,7 +5,8 @@
Native folder paste inserts atomic folder cards at the captured caret, with a
folder icon, ellipsized name, localized Folder type, full-path tooltip and
accessible remove button. Mixed folders/files preserve native order. The source
-draft/session owns pending results; newer edits survive. Directory-only clipboard
+draft/session owns pending results; newer edits survive. A home paste cancels if
+its workspace/session navigation changes before a durable owner is created. Directory-only clipboard
selections work even when Chromium provides no File object. Ordinary text/image/
file paste and the directory-drop open-project/insert-path choice remain.