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): pin file-chip verification to workspace path
vastsaa1db7e99f8aa
diff --git a/apps/desktop/src/hooks/use-verified-chat-text.ts b/apps/desktop/src/hooks/use-verified-chat-text.tsindex 75636a1df..038696c5d 100644--- a/apps/desktop/src/hooks/use-verified-chat-text.ts+++ b/apps/desktop/src/hooks/use-verified-chat-text.ts@@ -8,15 +8,15 @@ 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. */+/** Confirmation belongs to this text and workspace path/session, never the next one. */export function useVerifiedChatText(text: string, attachments?: readonly MessageAttachment[]) {- const workspace = useAppStore((s) => s.workspace);+ const workspacePath = useAppStore((s) => s.workspace?.path);const sessionId = useAppStore((s) => s.activeSessionId);const request = useMemo(() => {- const segments = splitChatText(text, workspace?.path);+ const segments = splitChatText(text, workspacePath);const trusted = new Set(attachments?.map((attachment) => attachment.ref));return { segments, trusted, sessionId, paths: chatFileCandidates(segments, trusted) };- }, [text, workspace, sessionId, attachments]);+ }, [text, workspacePath, sessionId, attachments]);const [result, setResult] = useState<{request: typeof request;verified: ReadonlySet<string>;diff --git a/apps/desktop/test/composer-native-deletion.test.mjs b/apps/desktop/test/composer-native-deletion.test.mjsnew file mode 100644index 000000000..9b0b8bed3--- /dev/null+++ b/apps/desktop/test/composer-native-deletion.test.mjs@@ -0,0 +1,19 @@+import { readComposerModule } from "./helpers/source-contracts.mjs";+import assert from "node:assert/strict";+import test from "node:test";++const [inputSource, deletionSource] = await Promise.all([+ readComposerModule("ComposerInput.tsx"),+ readComposerModule("native-deletion.ts"),+]);++test("composer input owns the native deletion guard", () => {+ assert.match(inputSource, /installComposerDeletionGuard\(editor\)/);+ assert.match(inputSource, /useLayoutEffect\(\(\) => \{/);+ assert.match(deletionSource, /event\.inputType\.startsWith\("delete"\)/);+ assert.match(deletionSource, /event\.getTargetRanges\(\)/);+ assert.match(deletionSource, /historyRedo/);+ assert.match(deletionSource, /event\.isComposing/);+ assert.match(deletionSource, /placeholders\.has\(br\)/);+ assert.doesNotMatch(deletionSource, /trim\(\)/);+});diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjsindex c1a0ab2ac..66c4712d5 100644--- a/apps/desktop/test/transcript-file-chips.test.mjs+++ b/apps/desktop/test/transcript-file-chips.test.mjs@@ -79,3 +79,18 @@ test("a tool row and a tool result row open a file where the message body does",);assert.doesNotMatch(toolDetails, /openFileInWorkPanel/);});++test("user-message bare paths wait for fs/resolveRef before becoming chips", async () => {+ const [verified, files] = await Promise.all([+ read("../src/hooks/use-verified-chat-text.ts"),+ read("../src/lib/verified-chat-files.ts"),+ ]);+ assert.match(transcript, /useVerifiedChatText\(text, attachments\)/);+ assert.match(transcript, /attachments=\{message\.attachments\}/);+ assert.match(verified, /useAppStore\(\(s\) => s\.workspace\?\.path\)/);+ assert.doesNotMatch(verified, /useAppStore\(\(s\) => s\.workspace\)(?!\?)/);+ assert.match(verified, /api\.fsResolveRef\(/);+ assert.match(files, /MAX_MESSAGE_CANDIDATES = 32/);+ assert.match(files, /MAX_CONCURRENT_LOOKUPS = 4/);+ assert.match(files, /!segment\.text\.startsWith\("@\"\)/);+});diff --git a/apps/desktop/test/verified-chat-files.test.mjs b/apps/desktop/test/verified-chat-files.test.mjsnew file mode 100644index 000000000..152a7199b--- /dev/null+++ b/apps/desktop/test/verified-chat-files.test.mjs@@ -0,0 +1,144 @@+import assert from "node:assert/strict";+import test from "node:test";+import { splitChatText } from "../src/lib/chat-links.ts";+import {+ chatFileCandidates,+ createChatFileVerificationQueue,+ verifiedChatSegments,+ verifyChatFiles,+} from "../src/lib/verified-chat-files.ts";++const ROOT = "/Users/dev/project";+const ISSUE_PROSE = "使用llama.cpp,给我迁移步骤,只读。";++function deferred() {+ let resolve;+ const promise = new Promise((settle) => {+ resolve = settle;+ });+ return { promise, resolve };+}++test("dotted prose stays text until a lookup confirms the file", () => {+ const segments = splitChatText(ISSUE_PROSE, ROOT);+ assert.deepEqual(+ segments+ .filter((segment) => segment.kind === "target" && segment.target.kind === "file")+ .map((segment) => segment.target.path),+ ["使用llama.cpp"],+ );+ assert.deepEqual(chatFileCandidates(segments), ["使用llama.cpp"]);++ const pending = verifiedChatSegments(segments, new Set());+ assert.ok(pending.every((segment) => segment.kind === "text"));+ assert.equal(pending.map((segment) => segment.text).join(""), ISSUE_PROSE);++ const confirmed = verifiedChatSegments(segments, new Set(["使用llama.cpp"]));+ assert.equal(+ confirmed.find((segment) => segment.kind === "target")?.target.path,+ "使用llama.cpp",+ );+});++test("explicit @ refs and URLs skip speculative lookup", () => {+ const segments = splitChatText(+ "Open @src/App.tsx and https://example.com now.",+ ROOT,+ );+ assert.deepEqual(chatFileCandidates(segments), []);+ const pending = verifiedChatSegments(segments, new Set());+ assert.deepEqual(+ pending+ .filter((segment) => segment.kind === "target")+ .map((segment) => segment.target),+ [+ { kind: "file", path: "src/App.tsx" },+ { kind: "url", url: "https://example.com" },+ ],+ );+});++test("structured attachment refs keep their chip without a lookup", () => {+ const segments = splitChatText("see App.tsx please", ROOT);+ const trusted = new Set(["App.tsx"]);+ assert.deepEqual(chatFileCandidates(segments, trusted), []);+ assert.ok(+ verifiedChatSegments(segments, trusted).some(+ (segment) => segment.kind === "target" && segment.target.path === "App.tsx",+ ),+ );+});++test("candidate lookup is unique and capped at 32", () => {+ const text = Array.from({ length: 40 }, (_, index) => `file${index}.ts`).join(" ");+ const segments = splitChatText(text, ROOT);+ const paths = chatFileCandidates(segments);+ assert.equal(paths.length, 32);+ assert.equal(paths[0], "file0.ts");+ assert.equal(paths[31], "file31.ts");+ assert.equal(chatFileCandidates(splitChatText("a.ts and a.ts again", ROOT)).length, 1);+});++test("verifyChatFiles keeps hits, skips misses, and survives a thrown lookup", async () => {+ const errors = [];+ const verified = await verifyChatFiles(+ ["hit.ts", "miss.ts", "boom.ts", "after.ts"],+ async (path) => {+ if (path === "boom.ts") throw new Error("lookup failed");+ return path === "hit.ts" || path === "after.ts";+ },+ new AbortController().signal,+ () => errors.push("lookup"),+ );+ assert.deepEqual([...verified], ["hit.ts", "after.ts"]);+ assert.deepEqual(errors, ["lookup"]);+});++test("verifyChatFiles drops in-flight hits after abort and does not warn", async () => {+ const controller = new AbortController();+ const errors = [];+ const verified = await verifyChatFiles(+ ["a.ts", "b.ts"],+ async (path) => {+ if (path === "a.ts") {+ controller.abort();+ throw new Error("cancelled");+ }+ return true;+ },+ controller.signal,+ () => errors.push("lookup"),+ );+ assert.deepEqual([...verified], []);+ assert.deepEqual(errors, []);+});++test("the shared queue caps concurrency and aborts work still waiting", async () => {+ const queue = createChatFileVerificationQueue();+ const gate = deferred();+ let running = 0;+ let peak = 0;+ const blockers = Array.from({ length: 4 }, () =>+ queue(async () => {+ running += 1;+ peak = Math.max(peak, running);+ await gate.promise;+ running -= 1;+ return true;+ }, new AbortController().signal),+ );++ let started = false;+ const waiting = new AbortController();+ const queued = queue(async () => {+ started = true;+ return true;+ }, waiting.signal);+ waiting.abort();+ assert.equal(await queued, false);+ assert.equal(started, false);++ gate.resolve();+ assert.deepEqual(await Promise.all(blockers), [true, true, true, true]);+ assert.equal(peak, 4);+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex d8a9c7995..7a48c401e 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1604,7 +1604,7 @@ Single message render — either user (plaintext) or assistant (markdown streamiand structured attachments retain their existing chips without speculativelookup. At most 32 unique candidates per message are checked, with fourconcurrent lookups across visible rows; additional candidates remain text.- Confirmation is scoped to the message text, workspace, and session; changing+ Confirmation is scoped to the message text, workspace path, and session; changingany of these discards old results and cancels queued work. Newly createdfiles are reconsidered when the message remounts or its scope changes, notby polling. Non-ASCII filenames remain supported. Absolute and `~/` tokens are matched whole,diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 259e811e4..1e016d205 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -6382,6 +6382,8 @@ identify the platform validation still needed.attachment format and leaves work-panel tabs unchanged. Closing/unmountingreleases modal/native-view blocking.- Deleting the session removes the pasted files with the rest of scratch.+ - Deleting text immediately before an inline file chip must not insert a+ blank line or move the chip to the next line; native undo/redo stay intact.- **Specs linked**: `04-ux/08-component-spec.md` §11.7–11.8,`03-runtime/01-ipc-protocol.md` §13c,`03-runtime/03-tools-and-permissions.md` §4b,@@ -6391,7 +6393,7 @@ identify the platform validation still needed.F (persistence), Quality- **Milestone**: M5- **Status**: Unit-covered (`composer-paste-files.test.mjs`,- `composer-clipboard.test.mjs`); `pnpm test:e2e:composer-paste` mounts the real+ `composer-clipboard.test.mjs`, `composer-native-deletion.test.mjs`); `pnpm test:e2e:composer-paste` mounts the realComposerInput, draft/paste hooks, file viewer, production CSS and sandboxedpreload. It dispatches Chromium ClipboardEvents with synthetic mixed dataand native File objects, exercises the real scratch writer and contained@@ -10623,6 +10625,9 @@ are withdrawn with ADR 0165.file in the work-panel files viewer and click a `../spec/00-baseline.md` link.5) Include an absolute path under the workspace, an outside absolute path,and a `~/` path in chat; confirm only the under-root path becomes a target.+ 6) Send a user message `使用llama.cpp,给我迁移步骤,只读。`, then a user+ message that names the real `apps/desktop/src/App.tsx` as a bare path and as+ `@apps/desktop/src/App.tsx`.- **Expected**:- Opening the session paints the transcript without throwing.- Each chat path opens `apps/desktop/src/App.tsx` in the File Manager@@ -10635,11 +10640,16 @@ are withdrawn with ADR 0165.- The markdown-file `../` link opens `docs/spec/00-baseline.md`, not aworkspace-root `spec/00-baseline.md`.- A `../../../outside.ts` link from `docs/adr` stays inert.+ - The user sentence containing `使用llama.cpp` stays exact original text, not+ a file chip, when that path does not exist.+ - A user-message bare path becomes a chip only after `fs/resolveRef` confirms+ a real file; an explicit `@path` chips immediately.- **Specs linked**: `04-ux/08-component-spec.md` §8.3,`08-meta/decisions-log.md` (D322)- **Acceptance**: C (conversation & stream), D (workspace), Quality- **Milestone**: M5- **Status**: Unit-covered (`chat-links.test.mjs`,+ `verified-chat-files.test.mjs`, `transcript-file-chips.test.mjs`,`markdown-prose-style.test.mjs`); full UI journey Draft (run only in a capable environment when this surface changes)#### E2E-185: External URL opens stay on http(s) and mailtodiff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 509962f80..fc87763e3 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1166,7 +1166,7 @@ row 而不是在转录本中添加树镶边。聊天轮流而不是全角块。气泡按提示的 max-content 收缩,而不是撑到该上限;内联文件芯片使用确定的 240px 名称上限,因此粘贴文件加上短提示仍保持紧凑。用户正文是明文保留硬换行符(`white-space: pre-wrap`);仅应用 trailing/leading 输入框修剪,从不应用内部换行符- 崩溃。序列化的 `@path` 文件引用画成与输入框一致的叶子名芯片(图标 + 省略号文件名;规范路径放在工具提示和无障碍名称里)。未内联成 `@path` 芯片的图片附件渲染为有界缩略图(`fs/readImageDataUrl` 的 data URL);无法解析时保留芯片。消息正文里的裸路径 token 识别 Unicode 字母与数字,非 ASCII 文件名与 ASCII 一样成为芯片;绝对路径与 `~/` 整体匹配,工作区之外(以及一切家目录路径)保持纯文本,而不是渲染一个永远打不开的芯片——包含边界不变(D322)。点击芯片先经 `pi-desktop/fs/resolveRef` 补全引用——该通道搜索整个打开的项目,按项目组文件夹顺序、主文件夹优先(ADR 0263)——再按解析结果打开:项目文件在随应用打包的 `pi.file-manager` 工作面板视图中打开(该视图不可用时退回宿主 `file:` 选项卡),会话临时目录或附件文件在宿主 `file:` 选项卡中打开,主文件夹中的 `.html`/`.htm` 仍由侧边浏览器打开。交给该视图的地址跟随应答的文件夹:主文件夹中的文件用项目内相对路径传递,同一项目的同级文件夹中的文件用绝对路径传递,与会话临时目录和附件文件一致。已解析的图片缩略图按同样规则打开。什么都没匹配到的芯片不打开任何东西,而是自己报告出来;系统默认应用不再由这次点击触发。HTTP(S) URL 仍是内联文本链接,在侧边浏览器打开;长 URL 在板内换行并保持逻辑开始对齐,而不是继承浏览器的居中按钮文本。+ 崩溃。序列化的 `@path` 文件引用画成与输入框一致的叶子名芯片(图标 + 省略号文件名;规范路径放在工具提示和无障碍名称里)。未内联成 `@path` 芯片的图片附件渲染为有界缩略图(`fs/readImageDataUrl` 的 data URL);无法解析时保留芯片。消息正文里的裸路径 token 识别 Unicode 字母与数字。在用户消息正文中,它们只是候选:现有的 `fs/resolveRef` 查找确认是真实文件后才显示芯片。等待、未找到或失败的查找保留原文,包括 `使用llama.cpp`。显式 `@path` 引用和结构化附件保留现有芯片,不做猜测查询。每条消息最多检查 32 个唯一候选,可见行之间最多 4 个并发查找;其余候选保持纯文本。确认结果绑定到当前消息文本、工作区路径和会话;任一变化都会丢弃旧结果并取消排队的工作。之后新建的文件在消息重新挂载或作用域变化时再考虑,不轮询。非 ASCII 文件名仍受支持。绝对路径与 `~/` 整体匹配,工作区之外(以及一切家目录路径)保持纯文本,而不是渲染一个永远打不开的芯片——包含边界不变(D322)。点击芯片先经 `pi-desktop/fs/resolveRef` 补全引用——该通道搜索整个打开的项目,按项目组文件夹顺序、主文件夹优先(ADR 0263)——再按解析结果打开:项目文件在随应用打包的 `pi.file-manager` 工作面板视图中打开(该视图不可用时退回宿主 `file:` 选项卡),会话临时目录或附件文件在宿主 `file:` 选项卡中打开,主文件夹中的 `.html`/`.htm` 仍由侧边浏览器打开。交给该视图的地址跟随应答的文件夹:主文件夹中的文件用项目内相对路径传递,同一项目的同级文件夹中的文件用绝对路径传递,与会话临时目录和附件文件一致。已解析的图片缩略图按同样规则打开。什么都没匹配到的芯片不打开任何东西,而是自己报告出来;系统默认应用不再由这次点击触发。HTTP(S) URL 仍是内联文本链接,在侧边浏览器打开;长 URL 在板内换行并保持逻辑开始对齐,而不是继承浏览器的居中按钮文本。- Assistant:透明表面,左对齐,Markdown 完全渲染内容宽度。该 Markdown 里的工作区文件路径可预览:行内代码、Markdown 链接与裸路径token(带已知扩展名)都像芯片一样,在打开项目的每个文件夹里先补全再打开(ADR 0263)——@@ -2697,24 +2697,6 @@ model 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.+删除内联文件引用前面的文字时,不得插入空行或把芯片挤到下一行。保留原生编辑与撤销/重做。原生删除前记录浏览器的目标范围和已有 BR 节点;输入之后,仅当去掉那颗新出现的 BR 后草稿恰好等于这次删除的目标时才移除它。绝不裁掉前导换行,也不整批规范化所有 BR。用弱引用记住已证实的占位节点,避免原生重做把它们恢复回来。显式换行、输入法合成、文件引用和芯片删除保持原有行为。由输入框安装并卸载这些原生事件监听。