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(chat): verify file chips and preserve native deletion
zszz3f384375475e4
diff --git a/apps/desktop/src/features/chat/composer/ComposerInput.tsx b/apps/desktop/src/features/chat/composer/ComposerInput.tsxindex 70e2a9d07..3eb5a138e 100644--- a/apps/desktop/src/features/chat/composer/ComposerInput.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerInput.tsx@@ -1,3 +1,5 @@+import { useLayoutEffect } from "react";+import { installComposerDeletionGuard } from "./native-deletion";import type {ClipboardEvent,Dispatch,@@ -57,6 +59,10 @@ export function ComposerInput({onFocus,onBlur,}: ComposerInputProps) {+ useLayoutEffect(() => {+ const editor = inputRef.current;+ return editor ? installComposerDeletionGuard(editor) : undefined;+ }, [inputRef]);return (<div className="composer-input-wrap">{imagePreview ? <ComposerImagePreview controller={imagePreview} /> : null}diff --git a/apps/desktop/src/features/chat/composer/native-deletion.ts b/apps/desktop/src/features/chat/composer/native-deletion.tsnew file mode 100644index 000000000..373d87f38--- /dev/null+++ b/apps/desktop/src/features/chat/composer/native-deletion.ts@@ -0,0 +1,57 @@+import { editorIndexAt, editorSelectionRange, readEditorValue, setEditorCaret } from "./editor";++type DeletionSnapshot = { expected: string; breaks: Set<HTMLBRElement> };++/** Preserve native deletion/undo; remove only a proven extra Chromium placeholder. */+export function installComposerDeletionGuard(editor: HTMLElement): () => void {+ // Chromium reuses its original BR node on redo. Remember only nodes proven+ // spurious, never a string pattern that could also be an intentional newline.+ const placeholders = new WeakSet<HTMLBRElement>();+ let snapshot: DeletionSnapshot | null = null;+ const beforeInput = (event: InputEvent) => {+ snapshot = null;+ if (event.isComposing || !event.inputType.startsWith("delete")) return;+ const range = event.getTargetRanges()[0];+ if (!range || !editor.contains(range.startContainer) || !editor.contains(range.endContainer)) return;+ const before = readEditorValue(editor);+ const start = editorIndexAt(editor, range.startContainer, range.startOffset);+ const end = editorIndexAt(editor, range.endContainer, range.endOffset);+ snapshot = {+ expected: before.slice(0, start) + before.slice(end),+ breaks: new Set(editor.querySelectorAll("br")),+ };+ };+ const input = (event: Event) => {+ const deletion = snapshot;+ snapshot = null;+ if (event instanceof InputEvent && event.inputType === "historyRedo") {+ for (const br of editor.querySelectorAll("br")) {+ if (placeholders.has(br)) br.remove();+ }+ return;+ }+ if (!(event instanceof InputEvent) || !deletion || event.isComposing || !event.inputType.startsWith("delete")) return;+ const current = readEditorValue(editor);+ if (current === deletion.expected) return;+ for (const br of editor.querySelectorAll("br")) {+ if (deletion.breaks.has(br) || !br.parentNode) continue;+ const index = editorIndexAt(editor, br.parentNode, Array.from(br.parentNode.childNodes).indexOf(br));+ if (current.slice(0, index) + current.slice(index + 1) !== deletion.expected) continue;+ const caret = editorSelectionRange(editor).start;+ placeholders.add(br);+ br.remove();+ setEditorCaret(editor, caret > index ? caret - 1 : caret);+ break;+ }+ };+ // Native beforeinput includes deletion target ranges; React's synthetic+ // beforeinput does not consistently expose deletion events. Capture input+ // before React serializes the DOM into the draft.+ editor.addEventListener("beforeinput", beforeInput);+ editor.addEventListener("input", input, true);+ return () => {+ snapshot = null;+ editor.removeEventListener("beforeinput", beforeInput);+ editor.removeEventListener("input", input, true);+ };+}diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex 69fe4f46f..b3dd95038 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -185,7 +185,7 @@ export const MessageRow = memo(function MessageRow({{message.command}</code>) : (- <LinkifiedText text={String(message.content || "")} />+ <LinkifiedText text={String(message.content || "")} attachments={message.attachments} />)}</div>) : null}diff --git a/apps/desktop/src/features/chat/transcript/shared.tsx b/apps/desktop/src/features/chat/transcript/shared.tsxindex bd1319663..debdf1aa5 100644--- a/apps/desktop/src/features/chat/transcript/shared.tsx+++ b/apps/desktop/src/features/chat/transcript/shared.tsx@@ -3,7 +3,6 @@ import {useCallback,useId,useLayoutEffect,- useMemo,useRef,useState,} from "react";@@ -23,7 +22,8 @@ import { useDisclosureAnchorNotifier } from "../../../lib/disclosure-anchor-contimport { isThinkingActive, resolveThinkingDisplayMode } from "../../../lib/turn-process";import { messageThinking as thinkingText } from "../../../lib/assistant-turns";import { useReferencedImageDataUrl } from "../../../lib/use-referenced-image-data-url";-import { isHtmlFilePath, splitChatText } from "../../../lib/chat-links";+import { useVerifiedChatText } from "../../../hooks/use-verified-chat-text";+import { isHtmlFilePath } from "../../../lib/chat-links";import type { SourcePositionProps } from "../../../lib/markdown-source";import { getToolAction, type ToolAction } from "../../../lib/tool-display";import { calculateTokenRate } from "../../../lib/context-usage";@@ -451,12 +451,11 @@ export function MessageAttachmentImage({}/** Plain user text: @paths become composer-like chips; URLs stay text links. */-export function LinkifiedText({ text }: { text: string }) {+export function LinkifiedText({ text, attachments }: { text: string; attachments?: readonly MessageAttachment[] }) {const { t } = useTranslation();- const root = useAppStore((s) => s.workspace?.path);const openTarget = useOpenPreviewTarget();const openFileRef = useOpenChatFileRef();- const segments = useMemo(() => splitChatText(text, root), [text, root]);+ const segments = useVerifiedChatText(text, attachments);let offset = 0;return (<>diff --git a/apps/desktop/src/hooks/use-verified-chat-text.ts b/apps/desktop/src/hooks/use-verified-chat-text.tsnew file mode 100644index 000000000..75636a1df--- /dev/null+++ b/apps/desktop/src/hooks/use-verified-chat-text.ts@@ -0,0 +1,43 @@+import type { MessageAttachment } from "@pi-desktop/shared";+import { useEffect, useMemo, useState } from "react";+import { api } from "../lib/api";+import { splitChatText } from "../lib/chat-links";+import { chatFileCandidates, createChatFileVerificationQueue, verifiedChatSegments, verifyChatFiles } from "../lib/verified-chat-files";+import { useAppStore } from "../stores/app-store";++const scheduleVerification = createChatFileVerificationQueue();+const EMPTY: ReadonlySet<string> = new Set();++/** Confirmation belongs to this text and workspace/session, never the next one. */+export function useVerifiedChatText(text: string, attachments?: readonly MessageAttachment[]) {+ const workspace = useAppStore((s) => s.workspace);+ const sessionId = useAppStore((s) => s.activeSessionId);+ const request = useMemo(() => {+ const segments = splitChatText(text, workspace?.path);+ const trusted = new Set(attachments?.map((attachment) => attachment.ref));+ return { segments, trusted, sessionId, paths: chatFileCandidates(segments, trusted) };+ }, [text, workspace, sessionId, attachments]);+ const [result, setResult] = useState<{+ request: typeof request;+ verified: ReadonlySet<string>;+ } | null>(null);+ useEffect(() => {+ if (request.paths.length === 0) return;+ const controller = new AbortController();+ void verifyChatFiles(+ request.paths,+ (path) => scheduleVerification(+ async () => (await api.fsResolveRef(path, request.sessionId ?? undefined)).match != null,+ controller.signal,+ ),+ controller.signal,+ // Avoid logging the message, path, or an arbitrary IPC error payload.+ () => console.warn("Chat file reference verification failed"),+ ).then((verified) => {+ if (!controller.signal.aborted) setResult({ request, verified });+ });+ return () => controller.abort();+ }, [request]);+ const verified = new Set([...request.trusted, ...(result?.request === request ? result.verified : EMPTY)]);+ return verifiedChatSegments(request.segments, verified);+}diff --git a/apps/desktop/src/lib/verified-chat-files.ts b/apps/desktop/src/lib/verified-chat-files.tsnew file mode 100644index 000000000..54432a52e--- /dev/null+++ b/apps/desktop/src/lib/verified-chat-files.ts@@ -0,0 +1,89 @@+import type { ChatTextSegment } from "./chat-links";++const MAX_MESSAGE_CANDIDATES = 32;+const MAX_CONCURRENT_LOOKUPS = 4;+type FileSegment = Extract<ChatTextSegment, { kind: "target" }> & {+ target: { kind: "file"; path: string };+};++/** Explicit composer refs need no speculative lookup to retain their chip. */+function needsVerification(segment: ChatTextSegment): segment is FileSegment {+ return segment.kind === "target" && segment.target.kind === "file" &&+ !segment.text.startsWith("@");+}++export function verifiedChatSegments(+ segments: ChatTextSegment[],+ verified: ReadonlySet<string>,+): ChatTextSegment[] {+ return segments.map((segment) =>+ needsVerification(segment) && !verified.has(segment.target.path)+ ? { kind: "text", text: segment.text }+ : segment,+ );+}++/** Deduplicate and bound speculative work before starting any IPC. */+export function chatFileCandidates(+ segments: ChatTextSegment[],+ known: ReadonlySet<string> = new Set(),+): string[] {+ const paths = new Set<string>();+ for (const segment of segments) {+ if (needsVerification(segment) && !known.has(segment.target.path)) {+ paths.add(segment.target.path);+ if (paths.size === MAX_MESSAGE_CANDIDATES) break;+ }+ }+ return [...paths];+}++/** Unverified candidates remain readable text on failure or cancellation. */+export async function verifyChatFiles(+ paths: readonly string[],+ resolve: (path: string) => Promise<boolean>,+ signal: AbortSignal,+ onError: () => void,+): Promise<Set<string>> {+ const verified = new Set<string>();+ for (const path of paths) {+ if (signal.aborted) break;+ try {+ const exists = await resolve(path);+ if (signal.aborted) break;+ if (exists) verified.add(path);+ } catch {+ if (!signal.aborted) onError();+ }+ }+ return verified;+}++/** Share a small IPC budget across visible message rows; abort queued work. */+export function createChatFileVerificationQueue() {+ let active = 0;+ const pending: Array<() => void> = [];+ const drain = () => {+ while (active < MAX_CONCURRENT_LOOKUPS && pending.length) pending.shift()?.();+ };+ return (resolve: () => Promise<boolean>, signal: AbortSignal): Promise<boolean> =>+ new Promise((accept, reject) => {+ if (signal.aborted) { accept(false); return; }+ const cancel = () => {+ const index = pending.indexOf(run);+ if (index >= 0) pending.splice(index, 1);+ accept(false);+ };+ const run = () => {+ signal.removeEventListener("abort", cancel);+ active += 1;+ Promise.resolve().then(() => signal.aborted ? false : resolve()).then(accept, reject).finally(() => {+ active -= 1;+ drain();+ });+ };+ signal.addEventListener("abort", cancel, { once: true });+ pending.push(run);+ drain();+ });+}diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex 813750a7e..d8a9c7995 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1597,8 +1597,17 @@ Single message render — either user (plaintext) or assistant (markdown streamithe tooltip and accessible name). Image attachments that are not alreadyinlined as `@path` chips render as bounded thumbnails (data URL from`fs/readImageDataUrl`); unresolved loads keep the chip. Bare path tokens in- message text recognize Unicode letters and digits, so non-ASCII filenames- chip exactly like ASCII ones; absolute and `~/` tokens are matched whole,+ message text recognize Unicode letters and digits. In user-message prose,+ these are candidates only: show a chip after the existing `fs/resolveRef`+ lookup confirms a real file. Pending, missing, or failed lookups preserve+ the exact original text, including `使用llama.cpp`. Explicit `@path` refs+ and structured attachments retain their existing chips without speculative+ lookup. At most 32 unique candidates per message are checked, with four+ concurrent lookups across visible rows; additional candidates remain text.+ Confirmation is scoped to the message text, workspace, and session; changing+ any of these discards old results and cancels queued work. Newly created+ files are reconsidered when the message remounts or its scope changes, not+ by polling. Non-ASCII filenames remain supported. Absolute and `~/` tokens are matched whole,and one outside the workspace (or any home path) stays plain text ratherthan rendering a chip that could never open — containment is unchanged(D322). Clicking a chip@@ -3667,3 +3676,15 @@ Sidebar footer Popover (360px max)panel width (ADR 0151)19. Expanded sidebar session titles, project/group titles, and empty-state copyuse the 13px compact token while primary sidebar actions remain at 14px+++### Native deletion beside composer file chips++Deleting text before an inline file reference must not add a blank line or move+the chip to the next line. Keep native editing and undo/redo. Before a native+deletion, record the browser's target range and existing BR nodes; after input,+remove a newly created BR only when removing that exact node makes the draft+match the requested deletion. Never trim leading newlines or normalize all BRs.+Remember proven placeholder nodes weakly so native redo cannot restore them.+Explicit line breaks, IME composition, file references, and chip deletion retain+their normal behavior. The input owns and disposes the native event listeners.diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 52a6ed084..509962f80 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -2695,3 +2695,26 @@ moves; a failed save shows an error and restores the accepted order. Late cataloresponses cannot restore an earlier order. The default-model picker and Composermodel groups follow the persisted order. Sorting changes neither the selecteddefault nor provider configuration. OAuth accounts remain in their separate section.+++### User-message file candidate verification (#649)++Bare file-like tokens in user prose become chips only after `fs/resolveRef`+confirms a real file. Pending, missing, and failed lookups preserve the original+text. Explicit `@` references and structured attachments retain their existing+chips. Verification checks up to 32 unique candidates per message with four+concurrent lookups across rows. Results belong to the current text, workspace,+and session; stale results are discarded. Files created later are reconsidered+on remount or scope change rather than polled. Assistant Markdown is unchanged.+++### Native deletion beside composer file chips++Deleting text before an inline file reference must not add a blank line or move+the chip to the next line. Keep native editing and undo/redo. Before a native+deletion, record the browser's target range and existing BR nodes; after input,+remove a newly created BR only when removing that exact node makes the draft+match the requested deletion. Never trim leading newlines or normalize all BRs.+Remember proven placeholder nodes weakly so native redo cannot restore them.+Explicit line breaks, IME composition, file references, and chip deletion retain+their normal behavior. The input owns and disposes the native event listeners.