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): show pasted folders above prompt text
Linuxdazhao4a60a62dff11
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.tsindex 35627a0e4..e70fbc3b7 100644--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts@@ -998,8 +998,18 @@ handleWithEvent(},);- handle(IPC.invoke.fsReveal, async (input: { path?: string; sessionId?: string } = {}) => {+ handleWithEvent(IPC.invoke.fsReveal, async (event, input: { path?: string; sessionId?: string; directory?: boolean } = {}) => {+ if (input.directory === true) assertMainWindowSender(event);const remote = await remoteFileWorkspace(input.sessionId);+ if (input.directory === true) {+ if (remote || !input.sessionId || typeof input.path !== "string" || !isAbsolute(input.path)) {+ throw new Error("A local session and an absolute directory path are required");+ }+ const directory = await realpath(input.path);+ if (!(await stat(directory)).isDirectory()) throw new Error("Path is not a directory");+ shell.showItemInFolder(stripWinLongPrefix(directory));+ return { ok: true };+ }if (remote && !(await isLocalStoredFile(String(input.path ?? "")))) throw Object.assign(new Error("remote paths cannot be revealed on this computer"), { errorCode: ErrorCodes.INVALID_ARGUMENT });const requested = String(input.path ?? "").trim();let workspaceRoot: string | null = null;diff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex 2850fbda0..33b4ebd52 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -580,6 +580,8 @@ export function Composer({) : null}<ComposerInputimagePreview={draft.imagePreview}+ directoryReferences={activeFileReferences.filter((reference) => reference.kind === "directory")}+ onRemoveDirectory={draft.removeDirectoryReference}inputRef={ref}value={value}placeholderText={placeholderText}diff --git a/apps/desktop/src/features/chat/DirectoryReferenceCard.tsx b/apps/desktop/src/features/chat/DirectoryReferenceCard.tsxnew file mode 100644index 000000000..a04f9fd6a--- /dev/null+++ b/apps/desktop/src/features/chat/DirectoryReferenceCard.tsx@@ -0,0 +1,60 @@+import { useTranslation } from "react-i18next";+import { fileReferenceLabel } from "@pi-desktop/shared";+import { IconFolder, IconX } from "../../components/icons";+import { Button } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";++export function DirectoryReferenceCard({+ path,+ name = fileReferenceLabel(path),+ sessionId,+ onRemove,+ disabled,+}: {+ path: string;+ name?: string;+ sessionId?: string;+ onRemove?: () => void;+ disabled?: boolean;+}) {+ const { t } = useTranslation();+ const details = (+ <>+ <IconFolder size={20} />+ <span className="directory-reference-details">+ <span className="directory-reference-name">{name}</span>+ <span className="directory-reference-type">{t("chat.directoryReference")}</span>+ </span>+ </>+ );+ return (+ <span className="directory-reference-card" title={path}>+ {sessionId ? (+ <Button+ type="button"+ variant="ghost"+ className="directory-reference-main"+ onClick={() => void api.fsRevealDirectory(path, sessionId).catch((error: unknown) => {+ useAppStore.getState().showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ })}+ >+ {details}+ </Button>+ ) : <span className="directory-reference-main">{details}</span>}+ {onRemove ? (+ <Button+ type="button"+ variant="ghost"+ className="directory-reference-remove"+ aria-label={t("chat.removeFileReference", { name })}+ disabled={disabled}+ onMouseDown={(event) => event.preventDefault()}+ onClick={onRemove}+ >+ <IconX size={13} />+ </Button>+ ) : null}+ </span>+ );+}diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex 973d50edf..c690200fa 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -11,6 +11,8 @@ import type {import { editorSelectionRange, readEditorValue } from "./editor";import { ComposerImagePreview } from "./ComposerImagePreview";import { ComposerImageHover } from "./ComposerImageHoverPreview";+import { DirectoryReferenceCard } from "../DirectoryReferenceCard";+import type { ComposerFileReference } from "./model";import { composerSuggestionKeyAction } from "./plugins/suggestion-keys";import type { ComposerSuggestionView } from "./hooks/useComposerSuggestion";import type { CompletionController } from "./hooks/useComposerCompletions";@@ -18,6 +20,8 @@ import type { ComposerImagePreviewController } from "./hooks/useComposerImagePreexport type ComposerInputProps = {imagePreview?: ComposerImagePreviewController;+ directoryReferences?: ComposerFileReference[];+ onRemoveDirectory?: (id: string) => void;inputRef: RefObject<HTMLDivElement | null>;value: string;placeholderText: string;@@ -56,6 +60,8 @@ export type ComposerInputProps = {/** Rich contenteditable input; draft state and async operations stay outside. */export function ComposerInput({imagePreview,+ directoryReferences = [],+ onRemoveDirectory,inputRef,value,placeholderText,@@ -86,6 +92,19 @@ export function ComposerInput({<div className="composer-input-wrap">{imagePreview ? <ComposerImagePreview controller={imagePreview} /> : null}{imagePreview ? <ComposerImageHover controller={imagePreview} editorRef={inputRef} /> : null}+ {directoryReferences.length > 0 ? (+ <div className="directory-reference-list">+ {directoryReferences.map((reference) => (+ <DirectoryReferenceCard+ key={reference.id}+ path={reference.path}+ name={reference.name}+ disabled={inputBlocked}+ onRemove={() => onRemoveDirectory?.(reference.id)}+ />+ ))}+ </div>+ ) : null}<div className="composer-input-stage">{/* React does not render children into this node; the editor modulepaints atomic attachment chips imperatively. */}diff --git a/apps/desktop/src/features/chat/composer/directory-attachments.ts b/apps/desktop/src/features/chat/composer/directory-attachments.tsnew file mode 100644index 000000000..305cee40b--- /dev/null+++ b/apps/desktop/src/features/chat/composer/directory-attachments.ts@@ -0,0 +1,16 @@+import type { ComposerFileReference } from "./model";++/** Restore older input-history and queued drafts with inline directory tokens. */+export function detachDirectoryTokens(+ text: string,+ references: ComposerFileReference[],+): { text: string; references: ComposerFileReference[] } {+ const nextReferences = references.flatMap((reference) => {+ if (reference.kind !== "directory" || !reference.token) return [reference];+ if (!text.includes(reference.token)) return [];+ text = text.replaceAll(reference.token, "");+ const { token: _token, ...directory } = reference;+ return [directory];+ });+ return { text, references: nextReferences };+}diff --git a/apps/desktop/src/features/chat/composer/editor.ts b/apps/desktop/src/features/chat/composer/editor.tsindex c6e5322bb..8734a474e 100644--- a/apps/desktop/src/features/chat/composer/editor.ts+++ b/apps/desktop/src/features/chat/composer/editor.ts@@ -293,7 +293,6 @@ 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";@@ -303,8 +302,6 @@ 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";@@ -342,7 +339,7 @@ function buildChipElement(const icon = document.createElement("span");icon.className = "composer-chip-icon";- icon.innerHTML = chipSvg(chipIconKey(reference), directory ? 26 : 13);+ icon.innerHTML = chipSvg(chipIconKey(reference), 13);const nameSpan = document.createElement("span");nameSpan.className = "composer-chip-name";@@ -365,15 +362,7 @@ function buildChipElement(onRemove(token);});- 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);+ chip.append(icon, nameSpan, remove);return chip;}@@ -387,7 +376,6 @@ export function paintEditorValue(onExpandText: (token: string) => void,onOpenImage: (token: string) => void,onOpenSession: (token: string) => void,- directoryLabel?: string,): void {el.replaceChildren();let textBuffer = "";@@ -411,7 +399,6 @@ 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 48df11308..29ed1f8f2 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@ -309,7 +309,7 @@ export function useComposerAttachments({}if (native && sourceSessionId && !useAppStore.getState().sessions.some(session => session.id === sourceSessionId)) return;const chips = result.files.map((file) => {- const token = nextChipToken();+ const token = file.kind === "directory" ? undefined : nextChipToken();return {token,reference: createFileReference(file.path, file.name, sessionId, {@@ -321,9 +321,9 @@ export function useComposerAttachments({});const inserted = chips.map((chip) => chip.token).join("");const nextText =- sourceValue.slice(0, selectionStart) +- inserted +- sourceValue.slice(selectionEnd);+ inserted+ ? sourceValue.slice(0, selectionStart) + inserted + sourceValue.slice(selectionEnd)+ : sourceValue;const nextReferences = [...previousReferences.map((reference) =>createFileReference(reference.path, reference.name, sessionId!, reference),diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 9cd84e27a..50a45ad4b 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -48,6 +48,12 @@ import type { ComposerPrefill } from "../model";import { useComposerImagePreview, type ComposerImagePreviewController } from "./useComposerImagePreview";import { attachImageTokens } from "../image-attachments";+import { detachDirectoryTokens } from "../directory-attachments";++function restoreDraftAttachments(text: string, references: ComposerFileReference[]) {+ const draft = detachDirectoryTokens(text, references);+ return attachImageTokens(draft.text, draft.references, nextChipToken);+}type ComposerSession = { id: string };@@ -81,6 +87,7 @@ export type ComposerDraftController = {paintCurrentDraft: (element: HTMLElement, nextValue: string) => void;commitEditorDom: () => void;insertNewlineInEditor: () => void;+ removeDirectoryReference: (id: string) => void;/** Set the draft; `focus` false leaves focus where it is (plugin writes). */applyEditorDraft: (nextText: string,@@ -142,7 +149,7 @@ export function useComposerDraft({const references = (initialDraft?.fileReferences ?? []).map((fileReference) =>createFileReferenceFromSnapshot(fileReference, referenceSessionId),);- return attachImageTokens(initialDraft?.text ?? "", references, nextChipToken);+ return restoreDraftAttachments(initialDraft?.text ?? "", references);});const [value, setValue] = useState(initialDraftState.text);const [fileReferences, setFileReferences] = useState<ComposerFileReference[]>(@@ -294,7 +301,6 @@ export function useComposerDraft({(token) => expandTextReferenceRef.current(token),(token) => openImageReferenceRef.current(token),(token) => openSessionReferenceRef.current(token),- t("chat.directoryReference"),);editorValueRef.current = nextValue;};@@ -423,7 +429,7 @@ export function useComposerDraft({const nextReferences = (nextDraft?.fileReferences ?? []).map((fileReference) =>createFileReferenceFromSnapshot(fileReference, referenceSessionId),);- const nextDraftState = attachImageTokens(nextDraft?.text ?? "", nextReferences, nextChipToken);+ const nextDraftState = restoreDraftAttachments(nextDraft?.text ?? "", nextReferences);setValue(nextDraftState.text);setFileReferences(nextDraftState.references);setCursor(nextDraftState.text.length);@@ -539,7 +545,7 @@ export function useComposerDraft({const prefilledReferences = composerPrefill.fileReferences.map((fileReference) =>createFileReferenceFromSnapshot(fileReference, composerPrefill.sessionId),);- const prefilled = attachImageTokens(composerPrefill.text, prefilledReferences, nextChipToken);+ const prefilled = restoreDraftAttachments(composerPrefill.text, prefilledReferences);setValue(prefilled.text);setFileReferences((current) => [...current.filter(@@ -577,7 +583,7 @@ export function useComposerDraft({focus = true,) => {compositionRef.current = null;- const entered = attachImageTokens(nextText, nextReferences, nextChipToken);+ const entered = restoreDraftAttachments(nextText, nextReferences);nextText = entered.text;nextReferences = entered.references;markComposerDraftEdited(draftKeyRef.current);@@ -705,7 +711,7 @@ export function useComposerDraft({const restoredReferences = snapshot.fileReferences.map((fileReference) =>createFileReferenceFromSnapshot(fileReference, sessionId),);- const restored = attachImageTokens(snapshot.text, restoredReferences, nextChipToken);+ const restored = restoreDraftAttachments(snapshot.text, restoredReferences);setValue(restored.text);setFileReferences((current) => [...current.filter((fileReference) => fileReference.sessionId !== sessionId),@@ -759,6 +765,8 @@ export function useComposerDraft({paintCurrentDraft,commitEditorDom,insertNewlineInEditor,+ removeDirectoryReference: (id) => setDraftFileReferences((current) =>+ current.filter((reference) => reference.id !== id || reference.kind !== "directory")),applyEditorDraft,snapshotReferences,draftSnapshot,diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex ca9d24c63..2528f4bc0 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -9,7 +9,8 @@ import {} from "react";import { useTranslation } from "react-i18next";import type { UiMessage } from "@pi-desktop/shared";-import { splitInlineContent } from "@pi-desktop/shared";+import { splitComposerDirectoryPrompt, splitInlineContent } from "@pi-desktop/shared";+import { DirectoryReferenceCard } from "../DirectoryReferenceCard";import { useOpenChatFileRef } from "../../../hooks/use-preview-target";import { sessionAllows } from "../../../lib/remote-session-safety";import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";@@ -111,6 +112,12 @@ export const MessageRow = memo(function MessageRow({// Runtime chunks are already progressive. Rendering that source directly// avoids a second per-frame state loop while Markdown memoizes stable blocks.const displayed = message.content || "";+ const directories = useMemo(+ () => isUser ? splitComposerDirectoryPrompt(displayed) : { text: displayed, paths: [] },+ [isUser, displayed],+ );+ const folderSessionId = sessionAllows(session ?? { id: paneSessionId }, "canUseLocalTools")+ ? paneSessionId : undefined;const hasAnswer = Boolean((message.content || "").trim());const revisionCount = message.revisionCount ?? 0;const activeRevision = message.activeRevision ?? revisionCount;@@ -125,8 +132,8 @@ export const MessageRow = memo(function MessageRow({// The user's own order: an image chip the draft named inline renders between// the text runs it sat between, exactly where the Composer showed it.const userContentParts = useMemo(- () => splitInlineContent(String(message.content || ""), message.attachments ?? []).parts,- [message.attachments, message.content],+ () => splitInlineContent(directories.text, message.attachments ?? []).parts,+ [message.attachments, directories.text],);const renderContentPart = (part: (typeof userContentParts)[number],@@ -310,7 +317,14 @@ export const MessageRow = memo(function MessageRow({</form>) : isUser ? (<>- {message.content ? (+ {directories.paths.length ? (+ <div className="directory-reference-list">+ {directories.paths.map((path, index) => (+ <DirectoryReferenceCard key={`${index}:${path}`} path={path} sessionId={folderSessionId} />+ ))}+ </div>+ ) : null}+ {directories.text || message.command ? (<div className="message-user-text selectable">{editableUserMessage && message.command ? (<>@@ -322,7 +336,7 @@ export const MessageRow = memo(function MessageRow({className="chat-command-chip"data-source-start={0}data-source-end={message.content.length}- title={String(message.content || "")}+ title={directories.text}>{message.command}</code>diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex b641325f9..512c7a777 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -1735,6 +1735,8 @@ export const api = {...(sessionId ? { sessionId } : {}),}),fsReveal: (path: string, sessionId?: string) => invoke(IPC.invoke.fsReveal, { path, ...(sessionId ? { sessionId } : {}) }),+ fsRevealDirectory: (path: string, sessionId: string) =>+ invoke(IPC.invoke.fsReveal, { path, sessionId, directory: true }),fsOpen: (path: string, mimeType?: string, sessionId?: string) =>invoke(IPC.invoke.fsOpen, { path, mimeType, ...(sessionId ? { sessionId } : {}) }),fsIndex: (sessionId?: string) => invoke<FsIndexResult>(IPC.invoke.fsIndex, { ...(sessionId ? { sessionId } : {}) }),diff --git a/apps/desktop/src/styles/composer.css b/apps/desktop/src/styles/composer.cssindex 167e4dd93..8f9bb0e0b 100644--- a/apps/desktop/src/styles/composer.css+++ b/apps/desktop/src/styles/composer.css@@ -1405,34 +1405,66 @@}}-.composer-directory-card {- width: 240px;+.directory-reference-list {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;max-width: 100%;- height: 64px;- gap: 12px;- margin: 4px 2px;- padding: 10px 12px;+ margin-bottom: 6px;+}++.directory-reference-list + .composer-input-stage .composer-input {+ min-height: 1lh;+}++.directory-reference-card {+ display: inline-flex;+ align-items: flex-start;+ max-width: min(100%, 240px);border: 1px solid var(--ds-border-default);border-radius: var(--radius-lg);color: var(--ds-text-primary);}-.composer-directory-details {+.directory-reference-main,+.directory-reference-main.btn {+ display: flex;+ align-items: center;+ min-width: 0;+ gap: 8px;+ padding: 6px 8px;+ color: inherit;+ text-align: start;+}++.directory-reference-main > svg {+ flex: none;+}++.directory-reference-details {display: flex;min-width: 0;- flex: 1;flex-direction: column;- gap: 4px;font-size: var(--text-sm);+ line-height: var(--leading-compact);}-.composer-directory-type {+.directory-reference-name {+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.directory-reference-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;+.directory-reference-remove.btn {+ flex: none;+ width: 22px;+ height: 22px;+ min-height: 0;+ padding: 0;+ margin: 2px 2px 0 0;}diff --git a/apps/desktop/test/composer-clipboard-directories.test.mjs b/apps/desktop/test/composer-clipboard-directories.test.mjsindex ea4d6a503..8e62b5bc5 100644--- a/apps/desktop/test/composer-clipboard-directories.test.mjs+++ b/apps/desktop/test/composer-clipboard-directories.test.mjs@@ -79,40 +79,13 @@ test("both send serializers include one directory instruction and escaped path m}});-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");+test("restore moves older folder chips out of the editable without changing file tokens", () => {+ const { detachDirectoryTokens } = load("../src/features/chat/composer/directory-attachments.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");+ const file = { path: "/tmp/file.txt", name: "file.txt", kind: "file", token: "\ue002" };+ assert.deepEqual(detachDirectoryTokens("before \ue001after \ue002", [reference, file]), {+ text: "before after \ue002",+ references: [{ path: reference.path, name: reference.name, kind: "directory" }, file],+ });+ assert.deepEqual(detachDirectoryTokens("removed", [reference]), { text: "removed", references: [] });});diff --git a/apps/desktop/test/composer-directory-paste.test.mjs b/apps/desktop/test/composer-directory-paste.test.mjsindex 590ec73bb..717f14e0b 100644--- a/apps/desktop/test/composer-directory-paste.test.mjs+++ b/apps/desktop/test/composer-directory-paste.test.mjs@@ -88,7 +88,8 @@ test("paste uses native directory paths even when Chromium exposes no File", asyassert.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.drafts[0].text, "before after");+ assert.equal(run.drafts[0].references[0].token, undefined);assert.equal(run.imported.length, 0);assert.equal(run.transfers.length, 0);assert.deepEqual(run.errors, []);@@ -99,6 +100,7 @@ test("mixed native folders and files preserve their order and use the existing iawait run.paste();assert.equal(run.drafts.length, 1);assert.deepEqual(Array.from(run.drafts[0].references, reference => reference.kind), ["directory", "file"]);+ assert.equal(run.drafts[0].text, "before \ue001after");assert.deepEqual(run.imported, [{ session: "source", token: "native-selection" }]);});@@ -123,7 +125,7 @@ test("directory paste preserves edits made while native metadata is pending", asrun.edit("newer edits remain");resume();await pending;- assert.equal(run.drafts[0].text, "newer e\ue001dits remain");+ assert.equal(run.drafts[0].text, "newer edits remain");});test("native directory paste never reads browser directory bytes", async () => {diff --git a/apps/desktop/test/composer-draft-cache.test.mjs b/apps/desktop/test/composer-draft-cache.test.mjsindex 183021922..14ac1b1a3 100644--- a/apps/desktop/test/composer-draft-cache.test.mjs+++ b/apps/desktop/test/composer-draft-cache.test.mjs@@ -149,11 +149,10 @@ test("flushing a scheduled adopt uses the Composer persist that rewrote home", (test("composer hydrates from the shared cache and persists across unmount and hidden windows", () => {assert.match(draftHook, /composer-draft-cache/);assert.match(composer, /readComposerDraft\(draftKey\)/);- // A cached draft hydrates through the image attach helper so inline image- // chips come back together with their draft.+ // Cached references are restored with their current presentation.assert.match(composer,- /return attachImageTokens\(initialDraft\?\.text \?\? "", references, nextChipToken\)/,+ /return restoreDraftAttachments\(initialDraft\?\.text \?\? "", references\)/,);assert.match(composer, /persistDraft\(draftKeyRef\.current\)/);assert.match(composer, /document\.visibilityState === "hidden"/);diff --git a/docs/adr/composer-pasted-directory-references.md b/docs/adr/composer-pasted-directory-references.mdindex 6162cd308..b9a8e92aa 100644--- a/docs/adr/composer-pasted-directory-references.md+++ b/docs/adr/composer-pasted-directory-references.md@@ -12,9 +12,10 @@ Copying its tree into scratch would create an expensive and stale snapshot.## DecisionOn 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+file metadata. Directories become typed draft references and removable folder+cards above the editable text, with a name, localized Folder label and full-path+tooltip. Mixed regular files use the existing sender-bound one-shot import+capability. Maincaptures the selection before filesystem awaits and accepts no renderer paths.The bridge is main-window-only and blocked from MCP/plugin callers. macOS readsraw pasteboard types, Linux reads native file URI lists, and Windows reads the@@ -26,6 +27,9 @@ one instruction to inspect directory structure and read relevant files as neededfor 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.+The user bubble displays the references as folder cards. Its local reveal action+is restricted to the main renderer and an existing absolute directory. The+action reveals the directory in the system file manager and returns no contents.## Consequencesdiff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 1ddd71640..84a6bbd20 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -2,10 +2,13 @@### 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. A home paste cancels if+Native folder paste adds compact cards in a wrapping row above the editable+text. Each card shows a folder icon, ellipsized name, localized Folder type,+full-path tooltip and accessible remove button. Short names use their natural+width. In mixed pastes, folders keep their selection order in the row and+regular files remain inline at the caret. A folder-only paste preserves the+selected text. The source draft/session owns pending results and newer edits+survive. A home paste cancels ifits workspace/session navigation changes before a durable owner is created. Directory-only clipboardselections work even when Chromium provides no File object. Ordinary text/image/file paste and the directory-drop open-project/insert-path choice remain.@@ -13,8 +16,11 @@ file paste and the directory-drop open-project/insert-path choice remain.Normal send and steering include escaped `<dir>absolute/path</dir>` markers andone 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).+The user message shows folder cards above the text and omits those generated+markers and guidance. Clicking a card in a local session reveals the directory+in the system file manager. Removing a draft 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)diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex c140c8fb5..3c32f4220 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -4,18 +4,24 @@- **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+ session composers with text on both sides of the caret. Remove cards by+ mouse/keyboard and restore draftsfrom 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+ Send and steer with folder cards, then activate a card in the sent message.+ Repeat ordinary text/image/file pastes.+- **Expected**: Folder cards wrap above the text, fit short names and expose+ full paths and removal. The sent user bubble shows the directory cards and+ only the user text. Local cards reveal the referenced directory in the+ system file manager. Selectionorder and source ownership survive, preserving newer edits. Removed cards sendno hint. Both send paths carry escaped dir markers and one inspect/read-as-neededinstruction. No directory arrayBuffer, traversal, recursive copy, Project changeor filesystem grant occurs. Unavailable paths fail without partial references.- **Status**: Parser/handler/editor/serialization tests cover deterministic cases.`pnpm test:e2e:composer-paste` uses synthetic file-list metadata to verify- folder insertion and removal across the Electron preload bridge. Native OS- clipboard verification remains a manual scenario.+ folder placement, removal, transcript rendering and reveal IPC across the+ Electron preload bridge. Native OS clipboard and file-manager display are+ manual scenarios.> Scope: MVP acceptance scenarios plus current shipped product increments for PI-Desktopdiff --git a/packages/shared/src/composer-trigger.test.ts b/packages/shared/src/composer-trigger.test.tsindex 51ec8142f..67928f537 100644--- a/packages/shared/src/composer-trigger.test.ts+++ b/packages/shared/src/composer-trigger.test.ts@@ -10,9 +10,31 @@ import {rewriteIdeographicCommaTrigger,serializeComposerFileReferences,serializeInlineComposerFileReferences,+ splitComposerDirectoryPrompt,stripInlineComposerFileReferenceTokens,} from "./composer-trigger.js";+describe("splitComposerDirectoryPrompt", () => {+ const path = "/tmp/a & <b> <";++ it("removes generated markers and guidance from old and current user messages", () => {+ const reference = { path, kind: "directory" };+ for (const content of [+ serializeInlineComposerFileReferences("before after", [reference]),+ serializeInlineComposerFileReferences("before \ue001after", [{ ...reference, token: "\ue001" }]),+ ]) {+ expect(splitComposerDirectoryPrompt(content)).toEqual({ text: "before after", paths: [path] });+ }+ expect(splitComposerDirectoryPrompt(serializeInlineComposerFileReferences("", [reference]))).toEqual({ text: "", paths: [path] });+ });++ it("keeps literal markup in the prompt body when the generated folder block is present", () => {+ const text = "Explain <dir>/tmp/example</dir>";+ expect(splitComposerDirectoryPrompt(text)).toEqual({ text, paths: [] });+ expect(splitComposerDirectoryPrompt(serializeInlineComposerFileReferences(text, [{ path, kind: "directory" }]))).toEqual({ text, paths: [path] });+ });+});+describe("detectTrigger — slash mode", () => {it("triggers on a bare slash at position 0", () => {expect(detectTrigger("/", 1)).toEqual({diff --git a/packages/shared/src/composer-trigger.ts b/packages/shared/src/composer-trigger.tsindex 8cd8a4dfc..f790a494d 100644--- a/packages/shared/src/composer-trigger.ts+++ b/packages/shared/src/composer-trigger.ts@@ -193,6 +193,39 @@ export function serializeComposerFileReferences(return [content, paths].filter(Boolean).join("\n");}+const DIRECTORY_PROMPT_GUIDANCE =+ "The user provided these local directories for the current task.\nInspect their structure and read relevant files as needed to fulfill the request.";++/** Separate pasted folders from the user-facing text of a serialized prompt. */+export function splitComposerDirectoryPrompt(content: string): { text: string; paths: string[] } {+ const guidanceStart = content.lastIndexOf(DIRECTORY_PROMPT_GUIDANCE);+ if (guidanceStart < 0 || (guidanceStart > 0 && content[guidanceStart - 1] !== "\n")) {+ return { text: content, paths: [] };+ }+ const body = content.slice(0, guidanceStart).trimEnd();+ const trailer = content.slice(guidanceStart + DIRECTORY_PROMPT_GUIDANCE.length);+ const marker = /<dir>([^<>]+)<\/dir>/g;+ const paths: string[] = [];+ const decodePath = (escaped: string) => escaped.replace(/&(amp|lt|gt);/g, (entity) =>+ entity === "&" ? "&" : entity === "<" ? "<" : ">");+ const absolute = /^(?:\/|[A-Za-z]:[\\/]|\\\\)/;+ if (trailer) {+ // Current drafts append a block of directory references after the guidance.+ const markers = [...trailer.matchAll(marker)];+ if (trailer !== markers.map(([tag]) => "\n" + tag).join("")) return { text: content, paths };+ for (const [, escaped] of markers) paths.push(decodePath(escaped));+ return paths.every((path) => absolute.test(path)) ? { text: body, paths } : { text: content, paths: [] };+ }+ // Older drafts stored the markers inline before the guidance.+ const text = body.replace(/<dir>([^<>]+)<\/dir>([ \t]?)/g, (tag, escaped: string, space: string, offset: number) => {+ const path = decodePath(escaped);+ if (!absolute.test(path)) return tag;+ paths.push(path);+ return offset > 0 && /[ \t]/.test(body[offset - 1]) ? "" : space;+ }).trim();+ return paths.length ? { text, paths } : { text: content, paths };+}+/** 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, ">");@@ -237,7 +270,7 @@ export function serializeInlineComposerFileReferences(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."+ ? DIRECTORY_PROMPT_GUIDANCE: "";const unpositioned = directories.filter(reference => !reference.token).map(reference => directoryPromptReference(reference.path)).join("\n");return [content.trim(), guidance, unpositioned].filter(Boolean).join("\n");diff --git a/scripts/e2e-composer-paste.mjs b/scripts/e2e-composer-paste.mjsindex 67adfc5a8..323d56b08 100644--- a/scripts/e2e-composer-paste.mjs+++ b/scripts/e2e-composer-paste.mjs@@ -93,6 +93,7 @@ app.setPath("userData", path.join(__dirname, "profile"));const saved = [];const history = [];const opened = [];+const revealedFolders = [];let completeOpens;const opensDone = new Promise(resolve => { completeOpens = resolve; });let directoryPastePending = true;@@ -158,6 +159,10 @@ ipcMain.handle("pi-desktop/fs/open", async (_event, input) => {if (opened.length === 3) completeOpens();return { ok: true, data: { ok: true } };});+ipcMain.handle("pi-desktop/fs/reveal", async (_event, input) => {+ revealedFolders.push(input);+ return { ok: true, data: { ok: true } };+});ipcMain.handle("pi-desktop/clipboard/recordPaste", (_event, input) => {history.push(input.text);return { ok: true, data: null };@@ -296,6 +301,7 @@ app.whenReady().then(async () => {const result = await window.webContents.executeJavaScript("globalThis.composerPasteProbe()");assert.equal(result.ok, true, JSON.stringify(result));await opensDone;+ assert.deepEqual(revealedFolders, [{ path: path.join(__dirname, "copied folder"), sessionId: "paste-a", directory: true }]);assert.deepEqual(opened.map(path.extname), [".mp4", ".mp4", ".mp4"]);assert.equal(await fs.realpath(opened[0]), await fs.realpath(path.join(__dirname, "attachments", "a".repeat(64))));assert.equal(await fs.realpath(opened[1]), await fs.realpath(path.join(__dirname, "attachments", "b".repeat(64))));diff --git a/scripts/e2e/composer-paste.tsx b/scripts/e2e/composer-paste.tsxindex 1dad3a27c..c50fd2642 100644--- a/scripts/e2e/composer-paste.tsx+++ b/scripts/e2e/composer-paste.tsx@@ -31,6 +31,8 @@ import {import { api } from "../../apps/desktop/src/lib/api";import { FilesTab } from "../../apps/desktop/src/components/workpanel/FilesTab";import { FileRefChip, MessageAttachmentImage } from "../../apps/desktop/src/features/chat/transcript/shared";+import { MessageRow } from "../../apps/desktop/src/features/chat/transcript/MessageRow";+import { SlotSessionProvider } from "../../apps/desktop/src/plugins/renderer-slots/use-slots";import { useOpenChatFileRef } from "../../apps/desktop/src/hooks/use-preview-target";import {readComposerDraft,@@ -102,6 +104,8 @@ function Fixture({ sessionId, t, workspacePath }: { sessionId: string; t: TFunct<div className="composer-shell"><ComposerInputimagePreview={draft.imagePreview}+ directoryReferences={draft.activeFileReferences.filter((reference) => reference.kind === "directory")}+ onRemoveDirectory={draft.removeDirectoryReference}inputRef={draft.ref}value={draft.value}placeholderText=""@@ -242,12 +246,30 @@ globalThis.composerPasteProbe = async () => {permissionMode: "inherit", thinkingLevel: "off", messageCount: 0,createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z",}] });- const directoryEditor = await paste("", [], true);- const directoryChip = directoryEditor.querySelector(".composer-chip");+ const directoryEditor = await dispatchPaste(await reset("before after", 0, 6), "", []);+ const directoryChip = directoryEditor.closest(".composer-input-wrap")?.querySelector(".directory-reference-card");assert(directoryChip?.textContent?.includes("copied folder"), "native folder metadata did not render a chip");+ assert(directoryChip!.getBoundingClientRect().bottom <= directoryEditor.getBoundingClientRect().top,+ "folder card must be above the editable text");+ assert(directoryChip!.getBoundingClientRect().width < 200, "short folder name leaves too much blank card width");+ assert(directoryEditor.getBoundingClientRect().height < 40, "a short prompt leaves excess blank space below the card");+ assert(readEditorValue(directoryEditor) === "before after", "folder paste changed the editable text");assert(controller.fileReferences[0]?.kind === "directory", "folder chip must own a directory reference");- flushSync(() => directoryChip?.querySelector<HTMLButtonElement>(".composer-chip-remove")?.click());+ const content = serializeInlineComposerFileReferences(readEditorValue(directoryEditor), controller.activeFileReferences);+ assert(content.includes("<dir>") && content.includes("Inspect their structure"), "model prompt lost directory context");+ flushSync(() => directoryChip?.querySelector<HTMLButtonElement>(".directory-reference-remove")?.click());assert(controller.fileReferences.length === 0, "folder chip could not be removed");+ flushSync(() => root.render(+ <I18nextProvider i18n={i18n}>+ <SlotSessionProvider sessionId="paste-a">+ <MessageRow message={{ id: "directory-message", role: "user", content, createdAt: "2026-01-01T00:00:00Z" }} isRunning={false} />+ </SlotSessionProvider>+ </I18nextProvider>,+ ));+ assert(host.querySelector(".message-user-text")?.textContent === "before after", "user bubble leaked the model prompt");+ const sentFolder = host.querySelector<HTMLButtonElement>(".message-bubble .directory-reference-main");+ assert(sentFolder?.textContent?.includes("copied folder"), "user bubble lost the clickable folder");+ sentFolder!.click();// Settings replaces ChatSurface, then remounts the composer in the same// workspace. Exercise the real draft hook and DOM across that lifecycle.