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): parse positioned and ambiguous file references safely
xieqiyingfb81b1fc8360
diff --git a/apps/desktop/src/lib/chat-link-scanner.ts b/apps/desktop/src/lib/chat-link-scanner.tsindex 7bca4529e..55d033f60 100644--- a/apps/desktop/src/lib/chat-link-scanner.ts+++ b/apps/desktop/src/lib/chat-link-scanner.ts@@ -55,7 +55,7 @@ export type ChatLinkCandidateDispositionResolver = () => ChatLinkCandidateDisposition;const PATH_WORD_RE = /^[\p{L}\p{N}_@+./\\-]$/u;-const TERMINAL_FILE_RE = /\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+)?)?$/u;+const TERMINAL_FILE_RE = /\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)?$/u;const PROSE_BOUNDARIES = new Set(["a", "an", "and", "against", "because", "but", "change", "check","copy", "create", "created", "delete", "edit", "find", "fix", "for",@@ -603,7 +603,7 @@ export function scanChatLinkCandidates<T>(const PATH_WORD = String.raw`[\p{L}\p{N}_@+.-]+`;const PATH_SEGMENT = String.raw`[\p{L}\p{N}_@+. -]+`;const PATH_CONTINUATION = String.raw`[\p{L}\p{N}_@+.-]*[\\/]`;-const FILE_END = String.raw`\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+)?)?(?![A-Za-z0-9_@+-]|\.[A-Za-z0-9]|${PATH_CONTINUATION})`;+const FILE_END = String.raw`\.[A-Za-z0-9]{1,8}(?:[+@-][\p{L}\p{N}_@+-]*)?(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)?(?![A-Za-z0-9_@+-]|\.[A-Za-z0-9]|${PATH_CONTINUATION})`;const BARE_FILE_END = String.raw`(?:${[...KNOWN_BARE_CHAT_FILES].join("|")})(?![\p{L}\p{N}_@+.-]|${PATH_CONTINUATION})`;const FILE_NAME = String.raw`(?:${PATH_SEGMENT}?${FILE_END}|${BARE_FILE_END})`;const UNC_PREFIX = String.raw`(?:\\\\[^\\/\s]+[\\/]|\/\/[^/\s]+\/)`;@@ -615,8 +615,8 @@ const FILE_SCAN_SOURCE = [String.raw`${SPACED_START}[\\/](?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,String.raw`${SPACED_START}(?:\.[A-Za-z0-9_-]+)*${FILE_END}`,String.raw`(?:${PATH_WORD}[\\/])+(?:${PATH_SEGMENT}[\\/])*?${FILE_NAME}`,- String.raw`(?:~[\\/])?\/?\.{1,2}[\\/](?:${PATH_WORD}\/)*${PATH_WORD}(?::\d+(?::\d+)?)?`,- String.raw`(?:~[\\/])?\/?(?:${PATH_WORD}\/)+${PATH_WORD}(?::\d+(?::\d+)?)?`,+ String.raw`(?:~[\\/])?\/?\.{1,2}[\\/](?:${PATH_WORD}\/)*${PATH_WORD}(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)?`,+ String.raw`(?:~[\\/])?\/?(?:${PATH_WORD}\/)+${PATH_WORD}(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)?`,String.raw`[\p{L}\p{N}_@+-][\p{L}\p{N}_@+.-]*${FILE_END}`,].join("|");const FILE_SCAN_RE = new RegExp(FILE_SCAN_SOURCE, "uy");diff --git a/apps/desktop/src/lib/chat-links.ts b/apps/desktop/src/lib/chat-links.tsindex 7e89f4f5c..83496ee92 100644--- a/apps/desktop/src/lib/chat-links.ts+++ b/apps/desktop/src/lib/chat-links.ts@@ -39,7 +39,7 @@ const KNOWN_EXTS = new Set([]);const FILE_TOKEN_RE =- /^(?:(?:[A-Za-z]:[\\/]|~[\\/]|\\\\|\/\/|[\\/])|(?:\.{1,2}[\\/])?)[\p{L}\p{N}_@+. -]+(?:[\\/][\p{L}\p{N}_@+. -]+)*(?::\d+(?::\d+)?)?$/u;+ /^(?:(?:[A-Za-z]:[\\/]|~[\\/]|\\\\|\/\/|[\\/])|(?:\.{1,2}[\\/])?)[\p{L}\p{N}_@+. -]+(?:[\\/][\p{L}\p{N}_@+. -]+)*(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)?$/u;const AT_QUOTED_RE = /^@"([^"\n]+)"$/;const AT_UNQUOTED_RE = /^@(\/?[^\s]+)$/;@@ -53,22 +53,23 @@ export function isHtmlFilePath(path: string): boolean {}function stripLineRef(path: string): string {- return path.replace(/:\d+(?::\d+)?$/, "");+ return path.replace(/(?::\d+(?::\d+|-\d+)?|#[lL]\d+(?:-[lL]?\d+)?)$/u, "");}-/** Trailing `:line[:col]` on a file token, if any. */+/** Trailing line, column, range, or GitHub line anchor on a file token. */export function parseFileRefPosition(text: string,): { line: number; column?: number } | null {const token = text.trim().replace(/[.,!?;:,。!?;:]+$/u, "");- const match = token.match(/:(\d+)(?::(\d+))?$/);+ const match = token.match(/(?::(\d+)(?::(\d+)|-(\d+))?|#L(\d+)(?:-L?(\d+))?)$/iu);if (!match) return null;- const line = Number(match[1]);+ const line = Number(match[1] ?? match[4]);if (!Number.isFinite(line) || line < 1) return null;- const column = match[2] !== undefined ? Number(match[2]) : undefined;- return column !== undefined && Number.isFinite(column) && column >= 1- ? { line, column }- : { line };+ const column = match[2] ? Number(match[2]) : undefined;+ if (column !== undefined && (!Number.isFinite(column) || column < 1)) return null;+ const rangeEnd = match[3] ?? match[5];+ if (rangeEnd !== undefined && (!Number.isFinite(Number(rangeEnd)) || Number(rangeEnd) < line)) return null;+ return { line, ...(column !== undefined ? { column } : {}) };}function leafName(path: string): string {diff --git a/apps/desktop/test/chat-links.test.mjs b/apps/desktop/test/chat-links.test.mjsindex 3f6ab9dbb..ea04b6db6 100644--- a/apps/desktop/test/chat-links.test.mjs+++ b/apps/desktop/test/chat-links.test.mjs@@ -155,6 +155,9 @@ test("parseFileRef accepts pathy tokens and strips line refs", () => {assert.equal(parseFileRef("apps/desktop/src/App.tsx"), "apps/desktop/src/App.tsx");assert.equal(parseFileRef("src/main.rs:42"), "src/main.rs");assert.equal(parseFileRef("src/main.rs:42:7"), "src/main.rs");+ assert.equal(parseFileRef("src/main.rs:42-44"), "src/main.rs");+ assert.equal(parseFileRef("src/main.rs#L42"), "src/main.rs");+ assert.equal(parseFileRef("src/main.rs#L42-L44"), "src/main.rs");assert.equal(parseFileRef("./scripts/build.sh"), "./scripts/build.sh");assert.equal(parseFileRef("/abs/path/file.ts"), "/abs/path/file.ts");assert.equal(parseFileRef("docs/Makefile"), "docs/Makefile");@@ -879,13 +882,27 @@ test("URL link creation is capped per conversion without changing source text",);});-test("parseFileRefPosition keeps :line[:col] that parseFileRef strips", () => {+test("parseFileRefPosition handles line, column, range, and GitHub anchors", () => {assert.deepEqual(parseFileRefPosition("src/main.rs:42"), { line: 42 });assert.deepEqual(parseFileRefPosition("src/main.rs:42:7"), { line: 42, column: 7 });+ assert.deepEqual(parseFileRefPosition("src/main.rs:42-44"), { line: 42 });+ assert.deepEqual(parseFileRefPosition("src/main.rs#L42"), { line: 42 });+ assert.deepEqual(parseFileRefPosition("src/main.rs#L42-L44"), { line: 42 });assert.deepEqual(parseFileRefPosition("src/main.rs:42."), { line: 42 });assert.deepEqual(parseFileRefPosition("src/main.rs:42:7,"), { line: 42, column: 7 });assert.equal(parseFileRefPosition("src/main.rs"), null);assert.equal(parseFileRefPosition("src/main.rs:0"), null);+ assert.equal(parseFileRefPosition("src/main.rs:42-41"), null);+});++test("splitChatText preserves common line-reference formats as positioned file chips", () => {+ for (const [suffix, line] of [[":42-44", 42], ["#L43", 43], ["#L44-L48", 44]]) {+ const source = `See src/main.rs${suffix}.`;+ const segments = splitChatText(source, ROOT);+ const target = segments.find((segment) => segment.kind === "target");+ assert.deepEqual(target?.target, { kind: "file", path: "src/main.rs", line }, source);+ assert.equal(segments.map((segment) => segment.text).join(""), source);+ }});test("resolvePreviewTarget carries line/col on file chips (#681)", () => {@@ -900,6 +917,16 @@ test("resolvePreviewTarget carries line/col on file chips (#681)", () => {line: 42,column: 7,});+ assert.deepEqual(resolvePreviewTarget("src/a.ts:42-48", ROOT), {+ kind: "file",+ path: "src/a.ts",+ line: 42,+ });+ assert.deepEqual(resolvePreviewTarget("src/a.ts#L43-L48", ROOT), {+ kind: "file",+ path: "src/a.ts",+ line: 43,+ });assert.deepEqual(resolvePreviewTarget("src/a.ts:42:7.", ROOT), {kind: "file",path: "src/a.ts",diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjsindex 9fe164405..33044757a 100644--- a/apps/desktop/test/chat-ref-resolve.test.mjs+++ b/apps/desktop/test/chat-ref-resolve.test.mjs@@ -37,8 +37,8 @@ const resolve = (ref, options) => resolveChatFileRef(ref, roots(options));* but names only `openimage.js` in its reply, so the click resolved to a* workspace-root path that does not exist and the panel opened blank. The* contract under test is the product priority — the open project answers- * first, the session scratch store second — plus the "best" rule inside one- * root: longest matching tail, then shallowest path.+ * first, the session scratch store second — plus safe matching inside one+ * root: an exact path or unique complete suffix only.*/function tempTree(name, files) {@@ -150,7 +150,7 @@ test("an exact relative link within its root remains resolvable", async () => {test("a stale fuzzy index skips escaped and missing candidates in priority order", async () => {const workspace = tempTree("stale-index", ["a/page.md", "b/page.md", "c/page.md"]);- assert.equal((await resolve("page.md", { workspace }))?.relativePath, "a/page.md");+ assert.equal(await resolve("page.md", { workspace }), null);renameSync(join(workspace, "a"), join(workspace, "old-a"));renameSync(join(workspace, "b"), join(workspace, "old-b"));const outside = tempTree("stale-outside", ["page.md"]);@@ -172,19 +172,50 @@ test("a dangling relative link, including a middle directory, does not fall backassert.equal(await resolve("linked/page.md", { scratch }), null);});-test("a longer matching tail beats a bare leaf name", async () => {+test("a unique complete path suffix resolves", async () => {const workspace = tempTree("ws", ["deep/openimage.js", "src/dir/openimage.js"]);const match = await resolve("dir/openimage.js", { workspace });assert.equal(match?.matchedBy, "path-suffix");assert.equal(match?.relativePath, "src/dir/openimage.js");});-test("the shallowest candidate wins when the tail length ties", async () => {+test("an exact root-level path wins even when shorthand matches are ambiguous", async () => {const workspace = tempTree("ws", ["a/b/openimage.js", "openimage.js"]);const match = await resolve("openimage.js", { workspace });+ assert.equal(match?.matchedBy, "exact-relative");assert.equal(match?.relativePath, "openimage.js");});+test("ambiguous basename and directory suffix references do not guess", async () => {+ const workspace = tempTree("ambiguous", [+ "crates/host-core/src/main.rs",+ "crates/agent/src/main.rs",+ "src/deep/file.ts",+ "other/deep/file.ts",+ ]);+ assert.equal(await resolve("main.rs", { workspace }), null);+ assert.equal(await resolve("deep/file.ts", { workspace }), null);+});++test("a partial path never degrades to a matching basename", async () => {+ const workspace = tempTree("partial-path", ["crates/host-core/src/main.rs"]);+ assert.equal(await resolve("acp-server/src/main.rs", { workspace }), null);+});++test("an ambiguous project match does not fall through to a different root", async () => {+ const workspace = tempTree("ambiguous-priority", ["a/page.md", "b/page.md"]);+ const scratch = tempTree("unique-scratch", ["page.md"]);+ assert.equal(await resolve("page.md", { workspace, scratch }), null);+});++test("line suffixes are stripped before host-side file resolution", async () => {+ const workspace = tempTree("line-ref", ["src/main.rs"]);+ for (const reference of ["src/main.rs:42-44", "src/main.rs#L42", "src/main.rs#L42-L44"]) {+ const match = await resolve(reference, { workspace });+ assert.equal(match?.relativePath, "src/main.rs", reference);+ }+});+test("the project answers before the session scratch store", async () => {const workspace = tempTree("ws", ["notes/openimage.js"]);const scratch = tempTree("scratch", ["openimage.js"]);diff --git a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md b/docs/adr/0262-chat-file-refs-open-in-the-file-view.mdindex 3369e5893..2dd41f3c0 100644--- a/docs/adr/0262-chat-file-refs-open-in-the-file-view.md+++ b/docs/adr/0262-chat-file-refs-open-in-the-file-view.md@@ -40,16 +40,18 @@ work-panel tab already carries was honoured by main for `pi.browser` only.first, the session scratch store second, the attachment store last** — andthe first root that answers wins, so the project is searched to exhaustionbefore the scratch store is considered;- - inside one root, an exact path beats a shorthand; among shorthands the- longest matching tail wins, then the shallowest path, so `src/dir/a.ts`- beats a second `dir/a.ts` buried deeper;+ - inside one root, an exact path beats a shorthand; a shorthand resolves+ only when its complete supplied suffix uniquely identifies one safe file.+ It never degrades to a shorter suffix, and ambiguous matches resolve to+ nothing;- the files panel's ignore set applies, so a dependency tree is neversearched;- a reference that matches nothing opens **nothing** and reports itself. Noempty panel, no blank browser page.2. **The destination follows where the reference resolved.** A project file- opens in the `pi.file-manager` view, except a `path:line` reference, which- opens in the host's read-only `file:` tab so the requested source line can+ opens in the `pi.file-manager` view, except a positioned reference (`:line`,+ `:line:column`, `:line-range` or `#Lline[-Lend]`), which opens in the host's+ read-only `file:` tab so the requested source line canbe brought into view. The bundled view accepts opaque path locations and hasno line-navigation contract; this keeps the path unchanged and uses thehost viewer's existing scroll support. A file in the session scratch ordiff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex 8eea0bc40..1abc005b8 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -1952,9 +1952,10 @@ Renderer IPC kept for the Plan-safe preview facade and URL fallback:other folders, which are then searched in the group's own order (ADR 0263),so a shorthand resolves in a sibling folder as readily as in the primary one,and the match names the folder that answered. Inside one root an exact path- beats a shorthand; among shorthands the longest matching tail wins, then the- shallowest path. Relative and indexed candidates must resolve to regular files- whose real paths remain inside their answering root; an exact path through an+ beats a shorthand; a shorthand matches only when its complete supplied suffix+ identifies one safe file. It never degrades to a shorter suffix, and an+ ambiguous match returns `match: null`. Relative and indexed candidates must+ resolve to regular files whose real paths remain inside their answering root; an exact path through anescaping or dangling link cannot fall back to a same-name indexed file. Thefiles-panel ignore set applies. An absolute reference may also name a storethe app reads without searching it: the whole scratch storediff --git a/docs/spec/04-ux/09-interaction-patterns.md b/docs/spec/04-ux/09-interaction-patterns.mdindex 78bca6941..4e38d5ae9 100644--- a/docs/spec/04-ux/09-interaction-patterns.md+++ b/docs/spec/04-ux/09-interaction-patterns.md@@ -1400,9 +1400,11 @@ Project drag/drop follows these patterns:No project is required to open a scratch artifact. Missing workspace stateis normalized consistently across asynchronous session-change guards.Local `file:` Markdown URLs are converted to file references before- sanitization, not admitted as native links. `path:line[:column]` retains- source navigation in plain text, inline code and Markdown links, including- HTML; unavailable browser views report an error without auto-enabling.+ sanitization, not admitted as native links. `path:line[:column]`,+ `path:line-range` and GitHub `path#Lline[-Lend]` retain source navigation+ from plain text, inline code and Markdown links, including HTML; ranges open+ at their starting line. Ambiguous shorthand paths do not resolve. Unavailable+ browser views report an error without auto-enabling.The address handed tothe work panel follows the folder that answered: a file of the primary foldertravels as a project-relative path, a file of a sibling folder of the samediff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex ced0b4975..4d0281b1a 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -13498,10 +13498,9 @@ are withdrawn with ADR 0165.- Clicking `openimage.js` opens the project's `img/openimage.js`, although thescratch store holds a file with that same leaf name: the project issearched to exhaustion before the scratch store is considered at all.- - `dir/a.ts` opens `src/dir/a.ts`: an exact path beats a shorthand, a longer- matching tail beats a bare leaf name, and the shallowest candidate wins a- tail-length tie, so the deeper `packages/app/dir/a.ts` is never the one- that opens.+ - `dir/a.ts` matches both `src/dir/a.ts` and+ `packages/app/dir/a.ts`, so the shorthand is ambiguous and opens nothing.+ The exact reference `src/dir/a.ts` opens that path.- A reference the project cannot answer resolves in the session scratchstore; one that neither answers resolves in the attachment store, and an`attachments/<sha256>` ref opens that stored blob.@@ -18074,18 +18073,19 @@ renderer's durable transcript reads. No real model or provider is contacted.closure behavior. Covered by the parameterized runtime overflow user-path test.-#### E2E-262: Transcript path:line opens and scrolls the host file viewer+#### E2E-262: Transcript positioned file references open and scroll the host file viewer- **Preconditions:** Isolated Electron/Chromium, an active workspace and session,the bundled file-manager view available, and deterministic filesystem IPCfixtures.-- **Steps:** Render a real transcript `path:line:column` reference followed by+- **Steps:** Render a real transcript `path:line-range` reference followed bysentence punctuation; click its verified file chip and wait for the host file- viewer to load.+ viewer to load. Unit coverage also exercises `path:line:column` and GitHub+ `path#Lline[-Lend]` references.- **Expected:** Despite the bundled file-manager view being available, thepositioned reference opens in the host's read-only file tab. The file request- retains its line and column, and the viewer scrolls the requested line into- the visible center area. The path and file contents remain the same as the+ retains the range's starting line, and the viewer scrolls that line into the+ visible center area. The path and file contents remain the same as thereference target.- **Specs:** `04-ux/08` §11.8; ADR 0262.- **Status:** `node scripts/e2e-file-ref-line-scroll.mjs` mounts productiondiff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex fc0cc4b8e..c50577bac 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -377,6 +377,9 @@ describe("custom system prompt files (issue #542)", () => {// Operational rules from the default prompt must survive the replacement.expect(prompt).toContain("Complete the requested work and relevant checks");expect(prompt).toContain("Before each tool batch, briefly state its purpose");+ expect(prompt).toContain("File references: when citing a real local file, use a Markdown link");+ expect(prompt).toContain("do not use ranges or GitHub #L anchors");+ expect(prompt).toContain("Do not wrap links in backticks or use file://, vscode://, or https://");expect(prompt).toContain("Editing workflow: inside the advertised workspace");expect(prompt).toContain("You are operating in Agent mode.");@@ -423,6 +426,7 @@ describe("custom system prompt files (issue #542)", () => {const prompt = promptOf(runtime);expect(prompt).toContain("You are PI-Desktop");+ expect(prompt).toContain("File references: when citing a real local file, use a Markdown link");expect(prompt).not.toContain("MARKER-XYZ-123");await runtime.dispose();diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 7249de152..966ca3eae 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -2077,6 +2077,8 @@ export class DesktopAgentRuntime {"Complete the requested work and relevant checks without expanding scope. Preserve unrelated user changes. Resolve recoverable blockers yourself.",// Visibility rules."Before each tool batch, briefly state its purpose. Keep the user informed during long work. The final response must state the outcome, verification, and remaining blockers. Never claim actions or checks you did not perform.",+ // File-reference formatting.+ "File references: when citing a real local file, use a Markdown link with a short label and the exact absolute path as its target, e.g. [file.ts](/workspace/src/file.ts:42). Add only a starting line (:line or :line:column) when useful; do not use ranges or GitHub #L anchors. Wrap destinations containing spaces in angle brackets. Do not wrap links in backticks or use file://, vscode://, or https:// for local files. Link only to existing files in the accessible workspace; mention unavailable or other-repository files as code text.",// Delegation steering (ADR 0089)....(this.subagents.length? [diff --git a/packages/host-runtime/src/chat-ref-resolve.ts b/packages/host-runtime/src/chat-ref-resolve.tsindex 9803053eb..54ace884d 100644--- a/packages/host-runtime/src/chat-ref-resolve.ts+++ b/packages/host-runtime/src/chat-ref-resolve.ts@@ -26,9 +26,9 @@ import { getWorkspaceFileIndex } from "./fs-index.js";* first, the session's own scratch store second, the attachment blob* store last — and the first root that answers wins, so the project is* searched to exhaustion before the scratch store is considered;- * 4. inside one root an exact path beats a shorthand, and among shorthands- * the longest matching tail wins, then the shallowest path, so- * `src/dir/a.ts` beats a second `dir/a.ts` buried deeper.+ * 4. inside one root an exact path wins; a shorthand resolves only when the+ * complete supplied suffix matches one safe file. Ambiguous or shortened+ * suffixes remain unresolved.*/export type ChatRefRoots = {@@ -69,8 +69,6 @@ type CanonicalChatRefRoot = ChatRefRootEntry & { realPath: string | null };const MAX_REF_LENGTH = 512;const ATTACHMENT_HASH_PATTERN = /^[0-9a-f]{64}$/i;-/** A tail longer than this is a user quoting a full path, not a shorthand. */-const MAX_FUZZY_TAIL_SEGMENTS = 6;/** Bound for the scratch/attachment walk; those trees are small by design. */const MAX_ROOT_WALK_ENTRIES = 4000;@@ -90,11 +88,11 @@ function matchesSegment(candidate: string, wanted: string): boolean {return CASE_INSENSITIVE_FS && candidate.toLowerCase() === wanted.toLowerCase();}-/** Strip the composer sigil, optional quotes, and a `:line[:col]` reference. */+/** Strip the composer sigil, optional quotes, and a file line reference. */function cleanRef(raw: string): string {let value = stripRefDecorations(String(raw ?? ""));if (value.includes("\0")) return "";- value = value.replace(/:\d+(?::\d+)?$/, "");+ value = value.replace(/(?::\d+(?::\d+|-\d+)?|#L\d+(?:-L?\d+)?)$/i, "");return value;}@@ -250,14 +248,7 @@ function segmentsOf(path: string): string[] {return toPosix(path).split("/").filter(Boolean);}-/** Fewer segments first, then a stable lexicographic order. */-function compareCandidates(a: string, b: string): number {- const depthDelta = segmentsOf(a).length - segmentsOf(b).length;- if (depthDelta !== 0) return depthDelta;- return a.localeCompare(b);-}--function endsWithTail(fileSegments: string[], tail: string[]): boolean {+function endsWithTail(fileSegments: readonly string[], tail: readonly string[]): boolean {if (fileSegments.length < tail.length) return false;const offset = fileSegments.length - tail.length;for (let index = 0; index < tail.length; index += 1) {@@ -268,35 +259,17 @@ function endsWithTail(fileSegments: string[], tail: string[]): boolean {type FuzzyCandidate = { relativePath: string; matchedBy: FsChatRefMatchKind };-/**- * Longest tail first, so a two-segment shorthand beats a bare leaf name.- * Within one tail the shallowest file wins.- */+/** Only a unique candidate matching the complete supplied suffix is safe. */function fuzzyCandidates(files: readonly string[],- tails: readonly string[][],+ segments: readonly string[],): FuzzyCandidate[] {- const parsedFiles = files.map((file) => ({- file,- segments: segmentsOf(file),- }));- const candidates: FuzzyCandidate[] = [];- const seen = new Set<string>();- for (const tail of tails) {- const matches = parsedFiles- .filter((entry) => endsWithTail(entry.segments, tail))- .map((entry) => entry.file)- .sort(compareCandidates);- for (const file of matches) {- if (seen.has(file)) continue;- seen.add(file);- candidates.push({- relativePath: file,- matchedBy: tail.length === 1 ? "basename" : "path-suffix",- });- }- }- return candidates;+ return files+ .filter((file) => endsWithTail(segmentsOf(file), segments))+ .map((relativePath) => ({+ relativePath,+ matchedBy: segments.length === 1 ? "basename" : "path-suffix",+ }));}async function isContainedRegularFile(root: string, relativePath: string): Promise<boolean> {@@ -444,11 +417,6 @@ export async function resolveChatFileRef(// outright: the open project is searched to exhaustion before the session// scratch store is considered at all. Inside one root the reference read// as a path verbatim outranks a tail match.- const tails: string[][] = [];- const longestTail = Math.min(parsed.segments.length, MAX_FUZZY_TAIL_SEGMENTS);- for (let length = longestTail; length >= 1; length -= 1) {- tails.push(parsed.segments.slice(parsed.segments.length - length));- }for (const root of rootList) {const absolutePath = join(root.path, ...parsed.segments);if (await isRegularFile(absolutePath)) {@@ -465,10 +433,17 @@ export async function resolveChatFileRef(if (await hasInvalidLinkAncestor(root.path, parsed.segments)) return null;const candidates = fuzzyCandidates(await listRootFiles(root.kind, root.path),- tails,+ parsed.segments,);+ const safeCandidates: FuzzyCandidate[] = [];for (const candidate of candidates) {- if (!(await isContainedRegularFile(root.path, candidate.relativePath))) continue;+ if (await isContainedRegularFile(root.path, candidate.relativePath)) {+ safeCandidates.push(candidate);+ if (safeCandidates.length > 1) return null;+ }+ }+ const candidate = safeCandidates[0];+ if (candidate) {return {root: root.kind,relativePath: candidate.relativePath,diff --git a/scripts/e2e-file-ref-line-scroll.mjs b/scripts/e2e-file-ref-line-scroll.mjsindex 8238b6d29..c95c31b37 100644--- a/scripts/e2e-file-ref-line-scroll.mjs+++ b/scripts/e2e-file-ref-line-scroll.mjs@@ -90,7 +90,7 @@ app.whenReady().then(async () => {assert.deepEqual(result.resolveRefs, ["src/scroll-target.txt", "核查报告.md", "src/scroll-target.txt"]);assert.deepEqual(result.readPaths, ["src/scroll-target.txt"]);assert.equal(result.selectedPath, "src/scroll-target.txt");- assert.deepEqual(result.request, { path: "src/scroll-target.txt", seq: 1, line: 65, column: 4 });+ assert.deepEqual(result.request, { path: "src/scroll-target.txt", seq: 1, line: 65 });assert.deepEqual(result.scrollCall, { line: "65", block: "center" });assert.ok(result.scrollTop > 0, "host file viewer did not scroll away from the top");assert.equal(result.targetLineVisible, true, "requested line is outside the visible viewer area");diff --git a/scripts/e2e/file-ref-line-scroll.tsx b/scripts/e2e/file-ref-line-scroll.tsxindex daf189fb8..2e08c0e2c 100644--- a/scripts/e2e/file-ref-line-scroll.tsx+++ b/scripts/e2e/file-ref-line-scroll.tsx@@ -110,7 +110,7 @@ void i18nroot.render(<I18nextProvider i18n={i18n}><div className="fixture-chat">- <LinkifiedText text={`Review ${targetPath}:${targetLine}:4.`} />+ <LinkifiedText text={`Review ${targetPath}:${targetLine}-70.`} /></div><div className="fixture-markdown"><Markdown source="[核查报告.md](核查报告.md)" renderDiagrams={false} />@@ -178,7 +178,7 @@ void i18npluginEnableCalls,fileManagerLocation: fileManagerTab?.location ?? null,selectedPath: document.querySelector(".file-viewer-path")?.textContent,- segments: splitChatText(`Review ${targetPath}:${targetLine}:4.`, "/workspace"),+ segments: splitChatText(`Review ${targetPath}:${targetLine}-70.`, "/workspace"),resolveRefs,readPaths,request,