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): replace execFileSync with async execFile to prevent main-process hang
贾湘君c870341daf5d
diff --git a/apps/desktop/electron/main/composer-clipboard-directories.ts b/apps/desktop/electron/main/composer-clipboard-directories.tsindex 1e3a45517..7b8849b7a 100644--- a/apps/desktop/electron/main/composer-clipboard-directories.ts+++ b/apps/desktop/electron/main/composer-clipboard-directories.ts@@ -1,4 +1,4 @@-import { execFileSync } from "node:child_process";+import { execFile, type ExecFileException } from "node:child_process";import { basename, join, posix, win32 } from "node:path";import { realpath, stat } from "node:fs/promises";import { fileURLToPath } from "node:url";@@ -10,23 +10,48 @@ type NativeClipboard = {const MAX_ITEMS = 20;const MAX_METADATA_BYTES = 1024 * 1024;-function windowsClipboardPaths(): string[] {+async function execFileAsync(+ command: string,+ args: string[],+ options: { timeout?: number; maxBuffer?: number; [key: string]: unknown },+): Promise<Buffer> {+ const child = execFile(command, args, options);+ return new Promise<Buffer>((resolve, reject) => {+ let stdout = Buffer.alloc(0);+ child.stdout?.on("data", (chunk: Buffer) => {+ stdout = Buffer.concat([stdout, chunk]);+ });+ child.on("error", (error: ExecFileException) => {+ reject(new Error(error.message || "clipboard file list read failed"));+ });+ child.on("close", (code) => {+ if (code === 0) resolve(stdout);+ else reject(new Error("clipboard file list read failed"));+ });+ });+}++async function windowsClipboardPaths(): Promise<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,- }));+ const value: unknown = JSON.parse(+ (+ await execFileAsync(executable, ["-NoLogo", "-NoProfile", "-NonInteractive", "-STA", "-Command", command], {+ windowsHide: true, timeout: 10000, maxBuffer: MAX_METADATA_BYTES,+ })+ ).toString("utf8"),+ );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(+export async function nativeClipboardPaths(clipboard: NativeClipboard,platform: NodeJS.Platform = process.platform,- readWindowsPaths: () => string[] = windowsClipboardPaths,-): string[] {+ readWindowsPaths: () => Promise<string[]> = windowsClipboardPaths,+): Promise<string[]> {const read = (format: string) => {// availableFormats exposes normalized MIME names, not native pasteboard types.const bytes = clipboard.readBuffer(format);@@ -35,11 +60,26 @@ export function nativeClipboardPaths(};let paths: string[] = [];const macList = platform === "darwin" ? read("NSFilenamesPboardType") : Buffer.alloc(0);- if (platform === "win32") paths = readWindowsPaths();+ if (platform === "win32") paths = await readWindowsPaths();else if (macList.length) {- const value: unknown = JSON.parse(execFileSync("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", "-"], {- input: macList, maxBuffer: MAX_METADATA_BYTES, timeout: 1000,- }).toString("utf8"));+ const child = execFile("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", "-"], {+ input: macList, maxBuffer: MAX_METADATA_BYTES, timeout: 10000,+ } as any);+ const value: unknown = JSON.parse(+ (+ await new Promise<Buffer>((resolve, reject) => {+ let buf = Buffer.alloc(0);+ child.stdout?.on("data", (chunk: Buffer) => {+ buf = Buffer.concat([buf, chunk]);+ });+ child.on("error", reject);+ child.on("close", (code) => {+ if (code === 0) resolve(buf);+ else reject(new Error("invalid clipboard file list"));+ });+ })+ ).toString("utf8"),+ );if (!Array.isArray(value) || !value.every(path => typeof path === "string")) throw new Error("invalid clipboard file list");paths = value;} else {@@ -57,13 +97,13 @@ export function nativeClipboardPaths(export async function readComposerClipboardDirectories(clipboard: NativeClipboard,rememberFiles: (paths: string[]) => string,- capturePaths: () => string[] = () => nativeClipboardPaths(clipboard),+ capturePaths: () => Promise<string[]> = async () => nativeClipboardPaths(clipboard),): Promise<{items: Array<{ kind: "directory"; path: string; name: string } | { kind: "file"; name: string }>;token: string | null;} | null> {// Capture before yielding so later clipboard changes cannot replace this selection.- const paths = capturePaths();+ const paths = await capturePaths();const entries = await Promise.all(paths.map(async path => {const canonical = await realpath(path);const metadata = await stat(canonical);diff --git a/apps/desktop/test/composer-clipboard-directories.test.mjs b/apps/desktop/test/composer-clipboard-directories.test.mjsindex 8e62b5bc5..4c2371802 100644--- a/apps/desktop/test/composer-clipboard-directories.test.mjs+++ b/apps/desktop/test/composer-clipboard-directories.test.mjs@@ -17,36 +17,59 @@ function load(path) {const { nativeClipboardPaths, readComposerClipboardDirectories } = load("../electron/main/composer-clipboard-directories.ts");const { serializeComposerFileReferences, serializeInlineComposerFileReferences } = load("../../../packages/shared/src/composer-trigger.ts");const clipboard = values => ({ availableFormats: () => Object.keys(values), readBuffer: format => Buffer.from(values[format] ?? "") });+const silentWindowsClipboard = () => ({ readBuffer: () => assert.fail("Windows must use its native file list") });-test("native URI file lists preserve order and decode spaces/unicode without reading clipboard text", () => {- assert.deepEqual(nativeClipboardPaths(clipboard({+test("native URI file lists preserve order and decode spaces/unicode without reading clipboard text", async () => {+ assert.deepEqual(await nativeClipboardPaths(clipboard({"text/uri-list": "# comment\r\nfile:///tmp/one%20folder\r\nfile:///tmp/%E4%B8%AD%E6%96%87\r\nhttps://example.com/ignored","text/plain": "unrelated clipboard text",}), "linux"), ["/tmp/one folder", "/tmp/中文"]);- assert.deepEqual(nativeClipboardPaths(clipboard({ "x-special/gnome-copied-files": "copy\nfile:///tmp/a\nfile:///tmp/a" }), "linux"), ["/tmp/a"]);+ assert.deepEqual(await nativeClipboardPaths(clipboard({ "x-special/gnome-copied-files": "copy\nfile:///tmp/a\nfile:///tmp/a" }), "linux"), ["/tmp/a"]);});-test("native file lists enforce metadata and selection bounds", () => {- assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": "x".repeat(1024 * 1024 + 1) }), "linux"), /too large/);- assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": Array.from({ length: 21 }, (_, i) => `file:///tmp/${i}`).join("\n") }), "linux"), /too many/);- assert.throws(() => nativeClipboardPaths(clipboard({ "text/uri-list": "file:///tmp/a%00b" }), "linux"), /null|invalid|encoded/i);+test("native file lists enforce metadata and selection bounds", async () => {+ await assert.rejects(() => nativeClipboardPaths(clipboard({ "text/uri-list": "x".repeat(1024 * 1024 + 1) }), "linux"), /too large/);+ await assert.rejects(() => nativeClipboardPaths(clipboard({ "text/uri-list": Array.from({ length: 21 }, (_, i) => `file:///tmp/${i}`).join("\n") }), "linux"), /too many/);+ await assert.rejects(() => nativeClipboardPaths(clipboard({ "text/uri-list": "file:///tmp/a%00b" }), "linux"), /null|invalid|encoded/i);});-test("Windows uses the complete native FileDropList instead of custom CF_HDROP or one FileNameW", () => {+test("Windows uses the complete native FileDropList instead of custom CF_HDROP or one FileNameW", async () => {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/);+ assert.deepEqual(await nativeClipboardPaths(silentWindowsClipboard(), "win32", () => paths), paths);+ await assert.rejects(() => nativeClipboardPaths(clipboard({}), "win32", () => ["relative"]), /invalid clipboard file path/);});-test("normalized MIME enumeration does not hide raw Finder file URLs", () => {+test("normalized MIME enumeration does not hide raw Finder file URLs", async () => {const native = clipboard({ "public.file-url": "file:///tmp/synthetic-folder" });native.availableFormats = () => ["text/uri-list"];- assert.deepEqual(nativeClipboardPaths(native, "darwin"), ["/tmp/synthetic-folder"]);+ assert.deepEqual(await nativeClipboardPaths(native, "darwin"), ["/tmp/synthetic-folder"]);});-test("macOS Finder file-list metadata is decoded in full", { skip: process.platform !== "darwin" }, () => {+test("macOS Finder file-list metadata is decoded in full", { skip: process.platform !== "darwin" }, async () => {const xml = '<?xml version="1.0"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"><plist version="1.0"><array><string>/tmp/first folder</string><string>/tmp/second</string></array></plist>';- assert.deepEqual(nativeClipboardPaths(clipboard({ NSFilenamesPboardType: xml }), "darwin"), ["/tmp/first folder", "/tmp/second"]);+ assert.deepEqual(await nativeClipboardPaths(clipboard({ NSFilenamesPboardType: xml }), "darwin"), ["/tmp/first folder", "/tmp/second"]);+});++test("a Windows clipboard probe slower than the former 2s timeout no longer aborts the paste", async () => {+ // The former spawnSync bound was 2000ms; a machine whose PowerShell starts slower used to+ // surface spawnSync ETIMEDOUT and fail image paste outright.+ const paths = ["C:\\slow folder"];+ const slowProbe = () => new Promise(resolve => setTimeout(() => resolve(paths), 50));+ let ticks = 0;+ const spin = setInterval(() => ticks++, 5);+ try {+ assert.deepEqual(await nativeClipboardPaths(silentWindowsClipboard(), "win32", slowProbe), paths);+ } finally {+ clearInterval(spin);+ }+ assert.ok(ticks >= 3, "the event loop must keep running while the clipboard probe is pending");+});++test("a Windows clipboard probe failure rejects without blocking the main process", async () => {+ // A hung or killed shell must surface as a rejection the caller can report, never as a+ // synchronous throw that leaves the main process frozen.+ const failed = () => new Promise((_resolve, reject) => setTimeout(() => reject(new Error("clipboard file list read failed")), 20));+ await assert.rejects(() => nativeClipboardPaths(silentWindowsClipboard(), "win32", failed), /clipboard file list read failed/);});test("directory metadata never copies a tree and mixed files use the existing import capability", async t => {