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): paste folders as lazy directory references
Linuxdazhaoee51582b9264
diff --git a/apps/desktop/electron/main/composer-clipboard-directories.ts b/apps/desktop/electron/main/composer-clipboard-directories.tsnew file mode 100644index 000000000..66a0bb458--- /dev/null+++ b/apps/desktop/electron/main/composer-clipboard-directories.ts@@ -0,0 +1,78 @@+import { execFileSync } from "node:child_process";+import { basename, isAbsolute } 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;++/** Read native file metadata only during an explicit Composer paste. */+export function nativeClipboardPaths(clipboard: NativeClipboard): string[] {+ const formats = clipboard.availableFormats();+ const read = (format: string) => {+ if (!formats.includes(format)) return Buffer.alloc(0);+ 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 value: unknown = JSON.parse(execFileSync("/usr/bin/plutil", ["-convert", "json", "-o", "-", "--", "-"], {+ input: macList, maxBuffer: MAX_METADATA_BYTES,+ }).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));+ }+ }+ }+ 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");+ return paths;+}++/** Directories stay path references; regular files use the existing picker capability. */+export async function readComposerClipboardDirectories(+ clipboard: NativeClipboard,+ rememberFiles: (paths: string[]) => string,+): 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 = nativeClipboardPaths(clipboard);+ const entries = await Promise.all(paths.map(async path => {+ const canonical = await realpath(path);+ const metadata = await stat(canonical);+ 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;+ const files = entries.filter(entry => !entry.directory).map(entry => entry.path);+ return {+ items: entries.map(entry => entry.directory+ ? { kind: "directory", path: entry.path, name: entry.name }+ : { kind: "file", name: entry.name }),+ token: files.length ? rememberFiles(files) : null,+ };+}diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 0c4526614..6432df849 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -1,3 +1,5 @@+import { clipboard } from "electron";+import { readComposerClipboardDirectories } from "../composer-clipboard-directories";import { BrowserWindow, dialog, shell, type OpenDialogOptions } from "electron";import { dirname } from "node:path";import { homedir } from "node:os";@@ -632,7 +634,12 @@ export function registerWorkspaceIpc({},);- handleWithEvent(+ handleWithEvent(IPC.invoke.composerReadClipboardDirectories, async (event) => {+ assertMainWindowSender(event);+ return readComposerClipboardDirectories(clipboard, paths => rememberComposerPickerSelection(paths, event.sender.id));+});++handleWithEvent(IPC.invoke.composerPasteFiles,async (event, input: { sessionId?: unknown; files?: unknown } = {}) => {assertMainWindowSender(event);diff --git a/apps/desktop/electron/main/mcp-control.ts b/apps/desktop/electron/main/mcp-control.tsindex 8bfc20a6f..301abd96e 100644--- a/apps/desktop/electron/main/mcp-control.ts+++ b/apps/desktop/electron/main/mcp-control.ts@@ -461,6 +461,7 @@ export const MCP_CONTROL_BLOCKED_CHANNEL_KEYS = ["composerPickPhotos","composerImportFiles","composerPasteFiles",+ "composerReadClipboardDirectories","clipboardRecordPaste","menuRendererReady","traySetSessionPreferences",diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex 584747a20..c6e5322bb 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -39,7 +39,7 @@ export function createFileReference(preferredName?: string,sessionId = "",metadata?: {- kind?: "image" | "file" | "session";+ kind?: "image" | "file" | "session" | "directory";mimeType?: string;token?: string;plugin?: ComposerPluginPart;@@ -237,6 +237,7 @@ export function setEditorCaret(el: HTMLElement, index: number): void {/** One glyph per file family on attachment chips, as inline SVG strings. */const CHIP_ICON_SVG: Record<string, string> = {+ dir: '<path d="M3 7V5a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z"/><path d="M3 9h18"/>',image:'<rect width="18" height="18" x="3" y="3" rx="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/>',code: '<path d="m18 16 4-4-4-4"/><path d="m6 8-4 4 4 4"/><path d="M14.5 4 9.5 20"/>',@@ -260,6 +261,7 @@ function chipIconKey(reference: ComposerFileReference): string {if (reference.plugin?.kind === "mark") return "plugin";if (reference.plugin?.kind === "fold") return "fold";if (reference.kind === "session") return "session";+ if (reference.kind === "directory") return "dir";const mime = reference.mimeType ?? "";if (reference.kind === "image" || mime.startsWith("image/")) return "image";const name = reference.name;@@ -278,7 +280,7 @@ function chipSvg(key: string, size = 13): string {}export function isEditableTextReference(reference: ComposerFileReference): boolean {- if (isPluginMark(reference)) return false;+ if (isPluginMark(reference) || reference.kind === "directory") return false;return reference.mimeType?.toLowerCase() === "text/plain" || /\.txt$/i.test(reference.name);}@@ -291,6 +293,7 @@ function buildChipElement(onExpandText: (token: string) => void,onOpenImage: (token: string) => void,onOpenSession: (token: string) => void,+ directoryLabel?: string,): HTMLElement {const chip = document.createElement("span");chip.className = "composer-chip";@@ -300,6 +303,8 @@ function buildChipElement(const origin = isPluginMark(reference) ? (reference.plugin?.pluginId ?? "") : reference.path;if (isPluginMark(reference)) chip.dataset.pluginMark = reference.plugin?.kind;chip.title = origin;+ const directory = reference.kind === "directory";+ if (directory) chip.classList.add("composer-directory-card");// 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";@@ -337,7 +342,7 @@ function buildChipElement(const icon = document.createElement("span");icon.className = "composer-chip-icon";- icon.innerHTML = chipSvg(chipIconKey(reference));+ icon.innerHTML = chipSvg(chipIconKey(reference), directory ? 26 : 13);const nameSpan = document.createElement("span");nameSpan.className = "composer-chip-name";@@ -360,7 +365,15 @@ function buildChipElement(onRemove(token);});- chip.append(icon, nameSpan, remove);+ if (directory) {+ const details = document.createElement("span");+ details.className = "composer-directory-details";+ const label = document.createElement("span");+ label.className = "composer-directory-type";+ label.textContent = directoryLabel ?? "";+ details.append(nameSpan, label);+ chip.append(icon, details, remove);+ } else chip.append(icon, nameSpan, remove);return chip;}@@ -374,6 +387,7 @@ export function paintEditorValue(onExpandText: (token: string) => void,onOpenImage: (token: string) => void,onOpenSession: (token: string) => void,+ directoryLabel?: string,): void {el.replaceChildren();let textBuffer = "";@@ -397,6 +411,7 @@ export function paintEditorValue(onExpandText,onOpenImage,onOpenSession,+ directoryLabel,),);continue;diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.tsindex 5feede94d..9a7dec228 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@ -1,3 +1,4 @@+import { readComposerDraft, readComposerDraftRevision } from "../../../../lib/composer-draft-cache";import {useState,useRef,@@ -230,19 +231,27 @@ export function useComposerAttachments({const files = preferClipboardText(text, pastedFiles, api.getDroppedFilePath)? []: pastedFiles;+ const hasNativeFileTypes = event.clipboardData.types?.includes("Files");+ const nativeFilePaste = hasNativeFileTypes || !text;const textLength = Array.from(text).length;const isLargeTextPaste = !files.length && textLength > largePasteThreshold;- if (isLargeTextPaste || files.length) {+ if (isLargeTextPaste || files.length || nativeFilePaste) {event.preventDefault();const editor = event.currentTarget;- const { start: selectionStart, end: selectionEnd } = editorSelectionRange(editor);- const sourceValue = readEditorValue(editor);+ let { start: selectionStart, end: selectionEnd } = editorSelectionRange(editor);+ let sourceValue = readEditorValue(editor);const sourceSessionId = activeSessionId;const sourceDraftKey = draftKey;- const previousReferences = snapshotReferences(sourceSessionId ?? "");+ let previousReferences = snapshotReferences(sourceSessionId ?? "");+ const sourceRevision = readComposerDraftRevision(sourceDraftKey);setPasting(true);try {- const payload = files.length+ const native = !isLargeTextPaste ? await api.readClipboardDirectories() : null;+ if (!native && !files.length && !isLargeTextPaste) {+ if (hasNativeFileTypes) throw new Error(t("chat.directoryPasteUnavailable"));+ return;+ }+ const payload = native ? [] : files.length? await Promise.all(files.map(async (file) => ({name: file.name || undefined,@@ -268,7 +277,31 @@ export function useComposerAttachments({if (!sessionId) sessionId = (await materializeDraftSession()) ?? "";if (!sessionId) throw new Error("session unavailable");- const result = await api.pasteFiles(sessionId, payload);+ let result;+ if (native) {+ const imported = native.token ? await api.importFiles(sessionId, native.token) : { 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 }+ : imported.files[index++]) };+ } else {+ result = await api.pasteFiles(sessionId, payload);+ }+ if (native && readComposerDraftRevision(sourceDraftKey) !== sourceRevision) {+ if (useAppStore.getState().activeSessionId === sourceSessionId) {+ sourceValue = readEditorValue(editor);+ const selection = editorSelectionRange(editor);+ selectionStart = selection.start;+ selectionEnd = selection.end;+ previousReferences = snapshotReferences(sourceSessionId ?? "");+ } else {+ const latest = readComposerDraft(sourceDraftKey);+ sourceValue = latest?.text ?? sourceValue;+ selectionStart = selectionEnd = sourceValue.length;+ previousReferences = latest?.fileReferences ?? previousReferences;+ }+ }+ if (native && sourceSessionId && !useAppStore.getState().sessions.some(session => session.id === sourceSessionId)) return;const chips = result.files.map((file) => {const token = nextChipToken();return {@@ -304,7 +337,7 @@ export function useComposerAttachments({} else if (sourceDraftKey === HOME_DRAFT_KEY) {deleteComposerDraft(HOME_DRAFT_KEY);}- showToast(+ if (!native) showToast(t,files.length ? "chat.filesPasted" : "chat.largeTextPasted",files.lengthdiff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 2961744f0..9cd84e27a 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -294,6 +294,7 @@ export function useComposerDraft({(token) => expandTextReferenceRef.current(token),(token) => openImageReferenceRef.current(token),(token) => openSessionReferenceRef.current(token),+ t("chat.directoryReference"),);editorValueRef.current = nextValue;};diff --git a/apps/desktop/src/features/chat/composer/model.ts b/apps/desktop/src/features/chat/composer/model.tsindex 787283b91..b56bce388 100644--- a/apps/desktop/src/features/chat/composer/model.ts+++ b/apps/desktop/src/features/chat/composer/model.ts@@ -61,7 +61,7 @@ export type ComposerFileReference = {sessionId: string;path: string;name: string;- kind: "image" | "file" | "session";+ kind: "image" | "file" | "session" | "directory";mimeType?: string;token?: string;plugin?: ComposerPluginPart;diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex cb003fc31..d3b130de3 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1,3 +1,7 @@+type ClipboardDirectoryPaste = {+ items: Array<{ kind: "directory"; path: string; name: string } | { kind: "file"; name: string }>;+ token: string | null;+};import { projectPlanHistory } from "./plan-history";import { guardRemoteInvocation } from "./remote-ipc-safety";import { isRemoteSession, safeSessionSummary } from "./remote-session-safety";@@ -1090,6 +1094,7 @@ export const api = {}),pickFiles: () =>invoke<{ token: string | null; canceled?: boolean }>(IPC.invoke.composerPickFiles),+ readClipboardDirectories: () => invoke<ClipboardDirectoryPaste | null>(IPC.invoke.composerReadClipboardDirectories),getDroppedFilePath: (file: File) =>window.piDesktop?.getDroppedFilePath?.(file) ?? null,pickPhotos: () =>diff --git a/apps/desktop/src/lib/composer-draft-cache.ts b/apps/desktop/src/lib/composer-draft-cache.tsindex 69a0d09f9..8362b10ca 100644--- a/apps/desktop/src/lib/composer-draft-cache.ts+++ b/apps/desktop/src/lib/composer-draft-cache.ts@@ -24,7 +24,7 @@ export type ComposerDraftFileInput = {sessionId?: string;path: string;name: string;- kind?: "image" | "file" | "session";+ kind?: "image" | "file" | "session" | "directory";mimeType?: string;token?: string;plugin?: ComposerPluginPart;diff --git a/apps/desktop/src/lib/composer-input-history.ts b/apps/desktop/src/lib/composer-input-history.tsindex 9b5205ec5..893c15d4f 100644--- a/apps/desktop/src/lib/composer-input-history.ts+++ b/apps/desktop/src/lib/composer-input-history.ts@@ -39,7 +39,7 @@ function readReference(value: unknown): HistoryReference | null {if (!value || typeof value !== "object") return null;const row = value as Record<string, unknown>;if (typeof row.path !== "string" || !row.path || typeof row.name !== "string") return null;- const kind = row.kind === "image" || row.kind === "file" ? row.kind : undefined;+ const kind = row.kind === "image" || row.kind === "file" || row.kind === "directory" ? row.kind : undefined;return {path: row.path,name: row.name,diff --git a/apps/desktop/src/lib/composer-smart-stop.ts b/apps/desktop/src/lib/composer-smart-stop.tsindex f984205d4..24d5becfc 100644--- a/apps/desktop/src/lib/composer-smart-stop.ts+++ b/apps/desktop/src/lib/composer-smart-stop.ts@@ -25,7 +25,7 @@ export type ComposerPluginPart =export type ComposerDraftFileReference = {path: string;name: string;- kind?: "image" | "file" | "session";+ kind?: "image" | "file" | "session" | "directory";mimeType?: string;/** Visible inline token for a generated large-text paste reference. */token?: string;diff --git a/apps/desktop/src/lib/session-transcript.ts b/apps/desktop/src/lib/session-transcript.tsindex a69ec2b9d..a13984106 100644--- a/apps/desktop/src/lib/session-transcript.ts+++ b/apps/desktop/src/lib/session-transcript.ts@@ -11,7 +11,7 @@ import {type OptimisticFileReference = {path: string;name: string;- kind?: "image" | "file" | "session";+ kind?: "image" | "file" | "session" | "directory";mimeType?: string;/** Large-text paste tokens travel inline in the text, not as attachments. */token?: string;@@ -37,6 +37,7 @@ export function optimisticUserMessage(// an image chip is one: it also records where its path sits, so the row shows// the image in place before the durable echo arrives (D288).const rendered = fileReferences.flatMap((reference) => {+ if (reference.kind === "directory") return [];const kind =reference.kind ??(IMAGE_PATH_PATTERN.test(reference.path) ? ("image" as const) : ("file" as const));diff --git a/apps/desktop/src/stores/helpers/store-helpers.ts b/apps/desktop/src/stores/helpers/store-helpers.tsindex 957139296..b9dc108ee 100644--- a/apps/desktop/src/stores/helpers/store-helpers.ts+++ b/apps/desktop/src/stores/helpers/store-helpers.ts@@ -27,7 +27,7 @@ export function promptAttachmentsFromDraft(return references.flatMap((reference) => {// A session link is prompt text: main resolves it into a conversation// reference, and it never travels as a structured attachment.- if (reference.kind === "session") return [];+ if (reference.kind === "session" || reference.kind === "directory") return [];const kind =reference.kind ??(/\.(avif|bmp|gif|heic|jpe?g|png|tiff?|webp)$/i.test(reference.path)diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.cssindex ad89dc03c..167e4dd93 100644--- a/apps/desktop/src/styles/composer.css+++ b/apps/desktop/src/styles/composer.css@@ -1404,3 +1404,35 @@transition: none;}}++.composer-directory-card {+ width: 240px;+ max-width: 100%;+ height: 64px;+ gap: 12px;+ margin: 4px 2px;+ padding: 10px 12px;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-lg);+ color: var(--ds-text-primary);+}++.composer-directory-details {+ display: flex;+ min-width: 0;+ flex: 1;+ flex-direction: column;+ gap: 4px;+ font-size: var(--text-sm);+}++.composer-directory-type {+ color: var(--ds-text-muted);+ font-size: var(--text-xs-plus);+}++.composer-directory-card .composer-chip-remove {+ align-self: flex-start;+ width: 20px;+ height: 20px;+}diff --git a/apps/desktop/test/composer-clipboard-directories.test.mjs b/apps/desktop/test/composer-clipboard-directories.test.mjsnew file mode 100644index 000000000..357fcd005--- /dev/null+++ b/apps/desktop/test/composer-clipboard-directories.test.mjs@@ -0,0 +1,106 @@+import assert from "node:assert/strict";+import { mkdtemp, mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { pathToFileURL, fileURLToPath } from "node:url";+import { createRequire } from "node:module";+import test from "node:test";+import { buildSync } from "esbuild";++const require = createRequire(import.meta.url);+function load(path) {+ const result = buildSync({ entryPoints: [fileURLToPath(new URL(path, import.meta.url))], bundle: true, write: false, platform: "node", format: "cjs" });+ const module = { exports: {} };+ new Function("require", "module", "exports", result.outputFiles[0].text)(require, module, module.exports);+ return module.exports;+}+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] ?? "") });++test("native URI file lists preserve order and decode spaces/unicode without reading clipboard text", () => {+ assert.deepEqual(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",+ })), ["/tmp/one folder", "/tmp/中文"]);+ assert.deepEqual(nativeClipboardPaths(clipboard({ "x-special/gnome-copied-files": "copy\nfile:///tmp/a\nfile:///tmp/a" })), ["/tmp/a"]);+});++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/);+});++test("macOS Finder file-list metadata is decoded in full", { skip: process.platform !== "darwin" }, () => {+ 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 })), ["/tmp/first folder", "/tmp/second"]);+});++test("directory metadata never copies a tree and mixed files use the existing import capability", async t => {+ const root = await mkdtemp(join(tmpdir(), "composer-folders-"));+ t.after(() => rm(root, { recursive: true, force: true }));+ const folder = join(root, "folder & 中文"), file = join(root, "notes.txt");+ await mkdir(folder);+ await writeFile(join(folder, "keep.txt"), "original");+ await writeFile(file, "notes");+ let captured;+ const result = await readComposerClipboardDirectories(clipboard({ "text/uri-list": [folder, file].map(path => pathToFileURL(path).href).join("\n") }), paths => { captured = paths; return "selection"; });+ assert.deepEqual(result.items.map(item => item.kind), ["directory", "file"]);+ assert.equal(result.items[0].name, "folder & 中文");+ assert.equal(result.token, "selection");+ 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({ "public.file-url": pathToFileURL(file).href }), () => assert.fail("regular-only paste keeps its current flow")), null);+});++test("both send serializers include one directory instruction and escaped path markers", () => {+ const refs = [{ path: "/tmp/a & <b>", kind: "directory", token: "\ue001" }, { path: "/tmp/two", kind: "directory", token: "\ue002" }];+ for (const serialize of [serializeComposerFileReferences, serializeInlineComposerFileReferences]) {+ const result = serialize("Inspect \ue001 and \ue002", refs);+ assert.ok(result.includes("<dir>/tmp/a & <b></dir>"));+ assert.ok(result.includes("<dir>/tmp/two</dir>"));+ assert.equal(result.match(/Inspect their structure/g)?.length, 1);+ assert.equal(serialize("Removed both", refs), "Removed both");+ assert.equal(serialize("", [{ path: "/tmp/without-token", kind: "directory" }]).includes("<dir>/tmp/without-token</dir>"), true);+ }+});++test("the real editor paints an atomic folder card with a localized type, full path and remove action", t => {+ const originalDocument = globalThis.document, originalNode = globalThis.Node;+ t.after(() => { globalThis.document = originalDocument; globalThis.Node = originalNode; });+ function element(tag) {+ const node = { nodeType: 1, tagName: tag.toUpperCase(), className: "", dataset: {}, childNodes: [], attributes: {}, listeners: {},+ setAttribute(key, value) { this.attributes[key] = value; },+ addEventListener(key, value) { this.listeners[key] = value; },+ append(...nodes) { this.childNodes.push(...nodes); },+ appendChild(child) { this.childNodes.push(child); return child; },+ replaceChildren() { this.childNodes = []; },+ };+ node.classList = { contains: key => node.className.split(" ").includes(key), add: key => { node.className += ` ${key}`; } };+ return node;+ }+ globalThis.document = { createElement: element, createTextNode: value => ({ nodeType: 3, nodeValue: value }) };+ globalThis.Node = { ELEMENT_NODE: 1, TEXT_NODE: 3 };+ const editor = load("../src/features/chat/composer/editor.ts");+ const reference = { path: "/tmp/folder.txt", name: "folder.txt", kind: "directory", token: "\ue001" };+ const container = element("div");+ let removed;+ const args = [container, "\ue001", new Map([["\ue001", reference]]), () => "Remove folder", token => { removed = token; }];+ if (editor.paintEditorValue.length >= 10) args.push(undefined, undefined, () => {}, () => {}, () => {}, "Folder");+ else args.push(() => {}, () => {}, () => {}, "Folder");+ editor.paintEditorValue(...args);+ const card = container.childNodes[0];+ assert.equal(card.classList.contains("composer-directory-card"), true);+ assert.equal(card.title, reference.path);+ assert.equal(card.contentEditable, "false");+ assert.equal(card.childNodes[1].childNodes[0].textContent, "folder.txt");+ assert.equal(card.childNodes[1].childNodes[1].textContent, "Folder");+ assert.equal(editor.readEditorValue(container), "\ue001");+ const remove = card.childNodes.at(-1);+ assert.equal(remove.attributes["aria-label"], "Remove folder");+ remove.listeners.click({ stopPropagation() {} });+ assert.equal(removed, "\ue001");+ assert.equal(editor.isEditableTextReference(reference), false, "a directory named .txt must not expand as a text file");+});diff --git a/apps/desktop/test/composer-directory-paste.test.mjs b/apps/desktop/test/composer-directory-paste.test.mjsnew file mode 100644index 000000000..3fa32898b--- /dev/null+++ b/apps/desktop/test/composer-directory-paste.test.mjs@@ -0,0 +1,137 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";+import vm from "node:vm";+import ts from "typescript";++function extract(source, name) {+ const tree = ts.createSourceFile("module.ts", source, ts.ScriptTarget.Latest, true);+ let result;+ function visit(node) {+ if (ts.isFunctionDeclaration(node) && node.name?.text === name) result = node.getText(tree).replace(/^export\s+/, "");+ if (ts.isVariableDeclaration(node) && node.name.getText(tree) === name) result = node.initializer?.getText(tree);+ ts.forEachChild(node, visit);+ }+ visit(tree);+ assert.ok(result, name);+ return result;+}++function harness(native, { files = [], text = "", items = [], paused } = {}) {+ 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 = [];+ let revision = 0;+ let activeSessionId = "source";+ const element = { textContent: "before after" };+ const context = {+ inputBlocked: false, attachmentsAllowed: true, activeSessionId,+ draftKey: "source", largePasteThreshold: 1000,+ ref: { current: element }, valueRef: { current: element.textContent },+ previousWorkspacePathRef: { current: "/synthetic/project" },+ snapshotReferences: () => [], invalidateComposerTransforms() {},+ applyEditorDraft: (text, references) => drafts.push({ text, references }),+ showToast(message, options) { if (options?.variant === "error") errors.push(message); },+ t: key => key,+ };+ let sequence = 0;+ const environment = {+ module: { exports: {} }, Array, TextEncoder, crypto,+ context: () => context, ...context, draft: context, isInputBlocked: false,+ setPasting() {}, readEditorValue: editor => editor.textContent,+ editorSelectionRange: () => ({ start: 7, end: 7 }),+ pasteSessionLinks: () => false, parseSessionLinks: () => [],+ showErrorToast: error => errors.push(error.message),+ api: {+ getDroppedFilePath: () => null,+ readClipboardDirectories: async () => { if (paused) await paused; return native; },+ importFiles: async (session, token) => {+ imported.push({ session, token });+ return { files: [{ path: "/synthetic/scratch/notes.txt", name: "notes.txt", kind: "file" }] };+ },+ pasteFiles: async (_session, payload) => {+ transfers.push(payload);+ return { files: payload.map(file => ({ path: "/synthetic/scratch/" + file.name, name: file.name, kind: "file", mimeType: file.mimeType })) };+ },+ },+ nextChipToken: () => String.fromCodePoint(0xe001 + sequence++),+ createFileReference: (path, name, sessionId, metadata) => ({ path, name, sessionId, ...metadata }),+ draftFileReference: reference => reference,+ writeComposerDraft: (key, snapshot) => writes.push({ key, snapshot }),+ readComposerDraftRevision: () => revision,+ readComposerDraft: () => undefined,+ deleteComposerDraft() {}, HOME_DRAFT_KEY: "home",+ useAppStore: { getState: () => ({ activeSessionId, sessions: [{ id: "source" }] }) },+ };+ 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,+ edit(text) { element.textContent = text; revision++; },+ switchSession() { activeSessionId = "other"; },+ paste: () => environment.module.exports({ currentTarget: element, preventDefault() {}, clipboardData: { files, items, types: ["Files"], getData: () => text } }),+ };+}++const folder = { kind: "directory", path: "/synthetic/copied folder", name: "copied folder" };+test("paste uses native directory paths even when Chromium exposes no File", async () => {+ const run = harness({ items: [folder], token: null });+ await run.paste();+ assert.equal(run.drafts.length, 1);+ assert.equal(run.drafts[0].references[0].kind, "directory");+ assert.equal(run.drafts[0].references[0].path, folder.path);+ assert.equal(run.drafts[0].text, "before \ue001after");+ assert.equal(run.imported.length, 0);+ assert.equal(run.transfers.length, 0);+ assert.deepEqual(run.errors, []);+});++test("mixed native folders and files preserve their order and use the existing import token", async () => {+ const run = harness({ items: [folder, { kind: "file", name: "notes.txt" }], token: "native-selection" });+ await run.paste();+ assert.equal(run.drafts.length, 1);+ assert.deepEqual(Array.from(run.drafts[0].references, reference => reference.kind), ["directory", "file"]);+ assert.deepEqual(run.imported, [{ session: "source", token: "native-selection" }]);+});++test("pending directory paste stays with its captured session", async () => {+ let resume;+ const paused = new Promise(resolve => { resume = resolve; });+ const run = harness({ items: [folder], token: null }, { paused });+ const pending = run.paste();+ run.switchSession();+ resume();+ await pending;+ assert.equal(run.drafts.length, 0);+ assert.equal(run.writes[0].key, "source");+ assert.equal(run.writes[0].snapshot.fileReferences[0].path, folder.path);+});++test("directory paste preserves edits made while native metadata is pending", async () => {+ let resume;+ const paused = new Promise(resolve => { resume = resolve; });+ const run = harness({ items: [folder], token: null }, { paused });+ const pending = run.paste();+ run.edit("newer edits remain");+ resume();+ await pending;+ assert.equal(run.drafts[0].text, "newer e\ue001dits remain");+});++test("native directory paste never reads browser directory bytes", async () => {+ const directory = new File([], "copied folder", { type: "application/x-directory" });+ directory.arrayBuffer = () => assert.fail("directory bytes were read");+ const run = harness({ items: [folder], token: null }, { files: [directory] });+ await run.paste();+ assert.equal(run.drafts[0].references[0].kind, "directory");+ assert.equal(run.transfers.length, 0);+});++test("ordinary native files keep their existing byte attachment flow", async () => {+ const run = harness(null, { files: [new File(["notes"], "notes.txt", { type: "text/plain" })] });+ await run.paste();+ assert.equal(run.drafts[0].references[0].kind, "file");+ assert.equal(run.transfers.length, 1);+ assert.equal(new TextDecoder().decode(run.transfers[0][0].data), "notes");+});diff --git a/apps/desktop/test/composer-paste-files.test.mjs b/apps/desktop/test/composer-paste-files.test.mjsindex 3e94257c3..72622d8d6 100644--- a/apps/desktop/test/composer-paste-files.test.mjs+++ b/apps/desktop/test/composer-paste-files.test.mjs@@ -34,7 +34,7 @@ test("composer converts oversized text paste and materializes clipboard files",assert.doesNotMatch(composer, /const token = `@\$\{displayName\}`/);assert.match(composer, /sourceValue\.slice\(0, selectionStart\) \+/);assert.match(composer, /writeComposerDraft\(sessionId, \{/);- assert.match(composer, /if \(isLargeTextPaste \|\| files\.length\) \{/);+ assert.match(composer, /if \(isLargeTextPaste \|\| files\.length \|\| nativeFilePaste\) \{/);assert.match(composer, /file\.arrayBuffer\(\)/);assert.match(composer,diff --git a/docs/adr/0059-composer-clipboard-files-in-session-scratch.md b/docs/adr/0059-composer-clipboard-files-in-session-scratch.mdindex 81e4015e6..e72b75442 100644--- a/docs/adr/0059-composer-clipboard-files-in-session-scratch.md+++ b/docs/adr/0059-composer-clipboard-files-in-session-scratch.md@@ -17,6 +17,10 @@ ownership rules.## Decision+The [directory-reference amendment](composer-pasted-directory-references.md) keeps+native directories as path references. This regular-file byte contract continues+to apply to files and images only.+1. The renderer intercepts paste only when the clipboard contains one or more`File` objects. Text-only paste remains native textarea behavior.2. The renderer transfers bounded file bytes plus the browser-provided name anddiff --git a/docs/adr/composer-pasted-directory-references.md b/docs/adr/composer-pasted-directory-references.mdnew file mode 100644index 000000000..4d29ad6f0--- /dev/null+++ b/docs/adr/composer-pasted-directory-references.md@@ -0,0 +1,34 @@+# Composer pasted directory references++- Status: Accepted+- Date: 2026-11-03+- Related: ADR 0059, ADR 0070++## Context++A directory has no regular-file bytes, and Chromium can omit its clipboard File.+Copying its tree into scratch would create an expensive and stale snapshot.++## Decision++On an explicit native-file paste, Electron main captures bounded native clipboard+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.++Directory references serialize as escaped `<dir>absolute/path</dir>` markers plus+one instruction to inspect directory structure and read relevant files as needed+for the current request. They never enter binary attachment transport, previews,+recursive copies or file snapshots. References grant no new filesystem access;+existing tool permission checks apply. Removing a card removes its prompt hint.++## Consequences++Normal file/image/text paste and the existing directory-drop choice remain.+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+reference shape gains the additive directory kind; Host protocol and database+schema versions remain unchanged.diff --git a/docs/spec/00-baseline.md b/docs/spec/00-baseline.mdindex a6c502e63..f407038fa 100644--- a/docs/spec/00-baseline.md+++ b/docs/spec/00-baseline.md@@ -1,5 +1,8 @@# PI-Desktop Baseline Freeze+> [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/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex c6a1811f7..99d35be2e 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1,5 +1,18 @@# 01. IPC Protocol+### composer/readClipboardDirectories++An additive main-window-only Electron channel accepting no source paths. During+an explicit native file paste, main captures at most 20 paths / 1 MiB of native+metadata, resolves file/directory metadata and returns null if no directory is+present. Otherwise it returns ordered items (`{kind: "directory", path, name}` or+`{kind: "file", name}`) and an optional sender-bound one-shot token for regular+files through `composer/importFiles`. MCP/plugin callers cannot invoke it.+Directories remain prompt/draft metadata, never binary attachments, file previews+or recursive snapshots. History retains their absolute paths without reading+contents or granting access. Other clipboard text is never read by this channel.++## 1. GoalDefine a stable contract between the renderer and main.diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 0e83a4709..6ecce2196 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1,5 +1,21 @@# 08. Component Spec+### Copied directory references++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+selections work even when Chromium provides no File object. Ordinary text/image/+file paste and the directory-drop open-project/insert-path choice remain.++Normal send and steering include escaped `<dir>absolute/path</dir>` markers and+one instruction: "The user provided these local directories for the current task.+Inspect their structure and read relevant files as needed to fulfill the request."+Removing a card removes its hint. Pasting neither reads/copies a directory tree nor+changes tool permissions. See [directory reference ADR](../../adr/composer-pasted-directory-references.md).++> Layout and IA reference: [01-ui-ia.md](01-ui-ia.md)> Design tokens and foundations: [07-ui-design-system.md](07-ui-design-system.md)> Interaction behavior: [09-interaction-patterns.md](09-interaction-patterns.md)diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 0d7e3406f..ab66990b6 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -1,5 +1,21 @@# 04. E2E Test Plan+## E2E-COMPOSER-DIRECTORY-PASTE: Native folder cards and lazy context++- **Preconditions**: Synthetic folders/files with spaces, Unicode and XML-significant names.+- **Steps**: Copy and paste single/multiple folders and mixed files in home and+ session composers. Remove cards by mouse/keyboard, undo/redo and restore drafts+ from history. Edit or switch sessions while metadata resolves; delete the owner.+ Send and steer with folder cards. Repeat ordinary text/image/file pastes.+- **Expected**: Localized folder cards expose full paths and removal. Selection+ order and source ownership survive, preserving newer edits. Removed cards send+ no hint. Both send paths carry escaped dir markers and one inspect/read-as-needed+ instruction. No directory arrayBuffer, traversal, recursive copy, Project change+ or filesystem grant occurs. Unavailable paths fail without partial references.+- **Status**: Parser/handler/editor/serialization tests cover deterministic cases.+ Native OS clipboard E2E has not been run in this request.++> Scope: MVP acceptance scenarios plus current shipped product increments for PI-Desktop> Status: Accepted (protocol/Electron automation is active; full desktop Playwright remains planned)> Cross-references: [acceptance-criteria](02-acceptance-criteria.md) · [milestones](01-mvp-milestones.md) · [ai-development-workflow](03-ai-development-workflow.md) · [change-checklist](05-change-checklist.md)diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 07d3f3ddc..d476150ca 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -367,6 +367,8 @@ export const de = {"sessionTranscriptEmpty": "Der Verlauf dieser Sitzung konnte nicht gelesen werden. Bitte die Sitzung erneut öffnen.","fileMenu": "Dateiverweise","removeFileReference": "Dateiverweis {{name}} entfernen",+ directoryReference: "Ordner",+ directoryPasteUnavailable: "Der vollständige Pfad des kopierten Ordners ist nicht verfügbar. Ziehen Sie den Ordner in das Eingabefeld.","removePluginMark": "{{name}} entfernen","pluginTriggerMenu": "Plugin-Vorschläge","messageAttachments": "Anhänge in dieser Nachricht",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 615a82399..b5fe75cde 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -374,6 +374,8 @@ export const en = {sessionTranscriptEmpty: "This session's history could not be read. Reopen the session to try again.",fileMenu: "File references",removeFileReference: "Remove file reference {{name}}",+ directoryReference: "Folder",+ directoryPasteUnavailable: "The copied folder's full path is unavailable. Drag the folder into the composer instead.",removePluginMark: "Remove {{name}}",pluginTriggerMenu: "Plugin suggestions",messageAttachments: "Attachments in this message",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 364aaa259..1f1c2ce5f 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -367,6 +367,8 @@ export const es = {"sessionTranscriptEmpty": "No se pudo leer el historial de esta sesión. Vuelve a abrirla para intentarlo de nuevo.","fileMenu": "Referencias de archivos","removeFileReference": "Eliminar referencia de archivo {{name}}",+ directoryReference: "Carpeta",+ directoryPasteUnavailable: "No se puede obtener la ruta completa de la carpeta copiada. Arrastra la carpeta al cuadro de entrada.","removePluginMark": "Eliminar {{name}}","pluginTriggerMenu": "Sugerencias de plugins","messageAttachments": "Archivos adjuntos en este mensaje",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 9f6c303e5..8364e6379 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -367,6 +367,8 @@ export const fr = {"sessionTranscriptEmpty": "L'historique de cette session n'a pas pu être lu. Rouvrez la session pour réessayer.","fileMenu": "Références de fichiers","removeFileReference": "Supprimer la référence de fichier {{name}}",+ directoryReference: "Dossier",+ directoryPasteUnavailable: "Le chemin complet du dossier copié est indisponible. Faites glisser le dossier dans la zone de saisie.","removePluginMark": "Supprimer {{name}}","pluginTriggerMenu": "Suggestions de plugins","messageAttachments": "Pièces jointes à ce message",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 62cb57500..94072a891 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -376,6 +376,8 @@ export const ko = {sessionTranscriptEmpty: "이 세션의 기록을 읽지 못했습니다. 세션을 다시 열어 시도하세요.",fileMenu: "파일 참조",removeFileReference: "파일 참조 {{name}} 제거",+ directoryReference: "폴더",+ directoryPasteUnavailable: "복사한 폴더의 전체 경로를 가져올 수 없습니다. 폴더를 입력란으로 드래그하세요.",removePluginMark: "{{name}} 제거",pluginTriggerMenu: "플러그인 제안",messageAttachments: "이 메시지의 첨부 파일",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex 81a32b845..d97295c14 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -366,6 +366,8 @@ export const ptBR = {sessionTranscriptEmpty: "Não foi possível ler o histórico desta sessão. Reabra-a para tentar novamente.",fileMenu: "Referências a arquivos",removeFileReference: "Remover referência de arquivo {{name}}",+ directoryReference: "Pasta",+ directoryPasteUnavailable: "O caminho completo da pasta copiada não está disponível. Arraste a pasta para o campo de entrada.",removePluginMark: "Remover {{name}}",pluginTriggerMenu: "Sugestões de plugins",messageAttachments: "Anexos desta mensagem",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex ec4f6b65c..7d0827b17 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -376,6 +376,8 @@ export const tr = {sessionTranscriptEmpty: "Bu oturumun geçmişi okunamadı. Yeniden denemek için oturumu tekrar açın.",fileMenu: "Dosya başvuruları",removeFileReference: "{{name}} dosya başvurusunu kaldır",+ directoryReference: "Klasör",+ directoryPasteUnavailable: "Kopyalanan klasörün tam yolu alınamıyor. Klasörü giriş alanına sürükleyin.",removePluginMark: "{{name}} öğesini kaldır",pluginTriggerMenu: "Eklenti önerileri",messageAttachments: "Bu iletideki ekler",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 6d72b69c5..b89341acc 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -369,6 +369,8 @@ export const zhCN = {sessionTranscriptEmpty: "无法读取该会话的记录,请重新打开会话后重试。",fileMenu: "引用文件",removeFileReference: "移除文件引用 {{name}}",+ directoryReference: "文件夹",+ directoryPasteUnavailable: "无法获取所复制文件夹的完整路径,请将文件夹拖入输入框。",removePluginMark: "移除 {{name}}",pluginTriggerMenu: "插件建议",messageAttachments: "此消息中的附件",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 4a5e77068..1f1312a9f 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -369,6 +369,8 @@ export const zhTW = {sessionTranscriptEmpty: "無法讀取此工作階段的記錄,請重新開啟後再試一次。",fileMenu: "引用檔案",removeFileReference: "移除檔案引用 {{name}}",+ directoryReference: "資料夾",+ directoryPasteUnavailable: "無法取得所複製資料夾的完整路徑,請將資料夾拖入輸入框。",removePluginMark: "移除 {{name}}",pluginTriggerMenu: "外掛建議",messageAttachments: "此訊息中的附件",diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex 32160a1ad..8cd8a4dfc 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -186,13 +186,17 @@ export function serializeComposerFileReferences(): string {const content = serializeInlineComposerFileReferences(draft, references);const paths = references- .filter((reference) => !reference.token && reference.kind !== "session")+ .filter((reference) => !reference.token && reference.kind !== "session" && reference.kind !== "directory").map((reference) => formatFileInsert(reference.path, "file")).join("").trim();- if (!content) return paths;- if (!paths) return content;- return `${content}\n${paths}`;+ return [content, paths].filter(Boolean).join("\n");+}++/** XML escaping keeps directory names from breaking out of their data marker. */+function directoryPromptReference(path: string): string {+ const escaped = path.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");+ return `<dir>${escaped}</dir>`;}/**@@ -215,7 +219,9 @@ export function serializeInlineComposerFileReferences(? send: reference.kind === "session"? formatSessionLink(reference.path)- : formatFileInsert(reference.path, "file").trim();+ : reference.kind === "directory"+ ? directoryPromptReference(reference.path)+ : formatFileInsert(reference.path, "file").trim();let index = content.indexOf(token);while (index !== -1) {const nextChar = content[index + token.length];@@ -228,7 +234,13 @@ export function serializeInlineComposerFileReferences(index = content.indexOf(token, index + insert.length + separator.length);}}- return content.trim();+ const directories = references.filter(reference => reference.kind === "directory" &&+ (!reference.token || draft.includes(reference.token)));+ const guidance = directories.length+ ? "The user provided these local directories for the current task.\nInspect their structure and read relevant files as needed to fulfill the request."+ : "";+ const unpositioned = directories.filter(reference => !reference.token).map(reference => directoryPromptReference(reference.path)).join("\n");+ return [content.trim(), guidance, unpositioned].filter(Boolean).join("\n");}/** Remove renderer-only inline reference tokens before a text transform. */diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex bbdea6855..9fbc9fc7a 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -420,6 +420,7 @@ export const IPC = {composerPickPhotos: "pi-desktop/composer/pickPhotos",composerImportFiles: "pi-desktop/composer/importFiles",composerPasteFiles: "pi-desktop/composer/pasteFiles",+ composerReadClipboardDirectories: "pi-desktop/composer/readClipboardDirectories",clipboardRecordPaste: "pi-desktop/clipboard/recordPaste",composerCommands: "pi-desktop/composer/commands",workspaceDiff: "pi-desktop/workspace/diff",