Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(file-links): detect Unicode, bracketed, spaced and bare paths and file:// URIs
review59b4be7cdc1e
diff --git a/CLAUDE.md b/CLAUDE.mdindex fbc453509..a5ef6365e 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1369,7 +1369,22 @@ session.all terminals — harmless in a plain shell). **Cmd (mac) / Ctrl+click** opens links in theoutput: URLs → default browser (`@xterm/addon-web-links`), file paths → editor node anddirectories → Explorer reveal (`terminal/file-links.ts`, existence-verified against the project- fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes). A relative+ fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes). **What counts+ as a path is `terminal/file-link-tokens.ts`**, and it is generous on purpose because existence is+ the arbiter: segments take any Unicode letter/number/mark (`var/otta-aktarım/çıktı.sql`) and+ route-folder brackets (`app/(shop)/[id]/page.tsx`; prose parentheses are dropped only when+ unbalanced); a separator path with SPACES is offered whole, ending at a word with a separator, a+ word completing `name.ext`, or the line end — AND as its space-free pieces, which is what keeps+ `/usr/bin/python failed to start app.py` from costing the `/usr/bin/python` link (tokens may+ overlap; the provider keeps the first that exists in start/longest order, `linkAtCell` carries the+ rest as `alternatives` for the Cmd+click fallback and the link menu); a BARE filename (`README`,+ `foo.ts`) only when `looksLikeBareFilename` says so — versions (`v1.2`), abbreviations (`e.g.`)+ and plain words are never looked up, and a right-click does not claim a bare word; a `file://`+ URI is percent-decoded to its absolute path (local host only; Windows needs a drive). **The scan+ must stay linear** — it runs per hovered row on padded TUI rows; no backtracking regex, and the+ ReDoS guard in `file-link-tokens.test.ts` pins it (the previous regex took 2.2 s on a 30k-char+ word). Hit-tests and underlines go through `Paragraph.cellStart/cellEnd` (xterm cells, not string+ indices), so wide CJK glyphs before or inside a path no longer shift its range. A relativepath is anchored on the node's LAUNCH cwd first, then on the pane's LIVE cwd (`pty:pane-cwd` —tmux `#{pane_current_path}`, local or over the ControlMaster; `findExistingPath`), because anagent prints paths relative to where IT runs; the launch cwd wins a tie so a link never changesdiff --git a/src/renderer/terminal/file-link-tokens.test.ts b/src/renderer/terminal/file-link-tokens.test.tsnew file mode 100644index 000000000..7b82b1339--- /dev/null+++ b/src/renderer/terminal/file-link-tokens.test.ts@@ -0,0 +1,271 @@+// The token matcher (file-link-tokens.ts). Each "measured gap" row names what the matcher before+// this change returned for it, so a revert shows up as a named regression rather than a diff.+// Several cases are taken from Orca's terminal-links tests (MIT, Copyright (c) 2026 Lovecast Inc.).+import { performance } from 'node:perf_hooks'+import { describe, expect, it } from 'vitest'+import { looksLikeBareFilename, matchFileTokens, type FileToken } from './file-link-tokens'+import { resolveFileToken } from './file-links'++const paths = (line: string): string[] => matchFileTokens(line).map((t) => t.path)+/** The span each token claims in `line` — must equal its own `text`. */+const spans = (line: string): string[] =>+ matchFileTokens(line).map((t) => line.slice(t.startIndex, t.startIndex + t.text.length))++describe('the measured gaps', () => {+ it('keeps Turkish letters in a path (was `var/otta-aktar`)', () => {+ expect(paths('› [file] var/otta-aktarım/çıktı.sql (2.8KB)')).toEqual([+ 'var/otta-aktarım/çıktı.sql'+ ])+ })++ it('keeps route-group parentheses and brackets in a segment (was `/page.tsx`)', () => {+ expect(paths('app/(shop)/[id]/page.tsx')).toEqual(['app/(shop)/[id]/page.tsx'])+ })++ it('claims a path with a space as ONE token (was `/Users/me/My` and `Docs/a.md`)', () => {+ const [first] = matchFileTokens('/Users/me/My Docs/a.md')+ expect(first).toEqual({+ text: '/Users/me/My Docs/a.md',+ startIndex: 0,+ path: '/Users/me/My Docs/a.md',+ line: undefined+ })+ })++ it('offers bare filenames (was nothing — no slash, no link)', () => {+ expect(matchFileTokens('see README or Makefile')).toEqual([+ { text: 'README', startIndex: 4, path: 'README', line: undefined, bare: true },+ { text: 'Makefile', startIndex: 14, path: 'Makefile', line: undefined, bare: true }+ ])+ expect(paths('foo.ts')).toEqual(['foo.ts'])+ })++ it('reads a file:// URI as its percent-decoded absolute path (was nothing)', () => {+ expect(matchFileTokens('file:///tmp/a%20b.txt')).toEqual([+ { text: 'file:///tmp/a%20b.txt', startIndex: 0, path: '/tmp/a b.txt', line: undefined }+ ])+ })+})++describe('Unicode path segments', () => {+ it('accepts letters, numbers and marks from any script', () => {+ expect(paths('/tmp/报告.html and docs/café/report.pdf')).toEqual([+ '/tmp/报告.html',+ 'docs/café/report.pdf'+ ])+ // A decomposed é (e + U+0301) is a mark, not a delimiter.+ expect(paths('docs/cafe\u0301/r.md')).toEqual(['docs/cafe\u0301/r.md'])+ expect(paths('~/Документы/отчёт.txt')).toEqual(['~/Документы/отчёт.txt'])+ })++ it('keeps Japanese middle dots and wave dashes, and stops at CJK punctuation', () => {+ expect(paths('/tmp/前・後/a.txt')).toEqual(['/tmp/前・後/a.txt'])+ expect(paths('/tmp/前〜後/a.txt')).toEqual(['/tmp/前〜後/a.txt'])+ expect(paths('/tmp/前後/a.txt,次')).toEqual(['/tmp/前後/a.txt'])+ expect(paths('/tmp/前後/a.txt。')).toEqual(['/tmp/前後/a.txt'])+ })++ it('does not take prose symbols into a path', () => {+ expect(paths('edit · ~/.claude/plans/p.md → done')).toEqual(['~/.claude/plans/p.md'])+ expect(paths('│ src/a.ts │')).toEqual(['src/a.ts'])+ })+})++describe('parentheses and brackets', () => {+ it('drops parentheses that belong to the sentence, keeps those that belong to the path', () => {+ expect(paths('(see src/a.ts)')).toEqual(['src/a.ts'])+ expect(paths('(src/a.ts)')).toEqual(['src/a.ts'])+ expect(paths('[src/a.ts]')).toEqual(['src/a.ts'])+ expect(paths('(app/(shop)/page.tsx)')).toEqual(['app/(shop)/page.tsx'])+ expect(paths('see app/(shop)/page.tsx).')).toEqual(['app/(shop)/page.tsx'])+ expect(paths('src/foo(1).txt, then')).toEqual(['src/foo(1).txt'])+ })++ it('carries a line suffix through the cleanup', () => {+ const [t] = matchFileTokens('Error in app/(shop)/products/[productId]/page.tsx:42:7')+ expect(t).toMatchObject({ path: 'app/(shop)/products/[productId]/page.tsx', line: 42 })+ expect(t.text).toBe('app/(shop)/products/[productId]/page.tsx:42:7')+ expect(matchFileTokens('(src/a.ts:12)')[0]).toMatchObject({+ text: 'src/a.ts:12',+ startIndex: 1,+ line: 12+ })+ })++ it('takes the target of a markdown link', () => {+ expect(paths('[the plan](docs/plan.md)')).toEqual(['docs/plan.md'])+ expect(paths('[src/a.ts](src/a.ts)')).toEqual(['src/a.ts'])+ })++ it('never turns a URL with parentheses into a file token', () => {+ expect(matchFileTokens('https://en.wikipedia.org/wiki/Foo_(bar)/baz')).toEqual([])+ expect(matchFileTokens('see (https://example.com/a/(b)/c.html)')).toEqual([])+ expect(matchFileTokens('[email protected]:org/repo.git http://x.io/(y)/z')).toEqual([+ { text: 'org/repo.git', startIndex: 15, path: 'org/repo.git', line: undefined }+ ])+ })+})++describe('paths with spaces', () => {+ it('stops before trailing prose', () => {+ const [t] = matchFileTokens('Open /Users/Path/FolderName with Space/content.js for details')+ expect(t.path).toBe('/Users/Path/FolderName with Space/content.js')+ })++ it('ends at a word that completes a file name', () => {+ expect(paths('saved /Users/me/Desktop/Screenshot 2026-09-29 at 10.12.33.png ok')[0]).toBe(+ '/Users/me/Desktop/Screenshot 2026-09-29 at 10.12.33.png'+ )+ expect(paths('/Applications/Visual Studio Code.app is open')[0]).toBe(+ '/Applications/Visual Studio Code.app'+ )+ })++ it('takes an extensionless spaced path at the end of the line, padding and all', () => {+ expect(matchFileTokens('/Users/alice/My Folder ')[0]).toMatchObject({+ text: '/Users/alice/My Folder',+ path: '/Users/alice/My Folder'+ })+ expect(paths('cd ./My Folder')[0]).toBe('./My Folder')+ })++ it('keeps the space-free pieces as fallbacks, so prose never costs the real path', () => {+ // The trap from Orca's tests: prose after a path that ends in a file name. The spaced reading is+ // offered, but `/usr/bin/python` stays a candidate — the existence check decides.+ expect(paths('/usr/bin/python failed to start app.py')).toEqual([+ '/usr/bin/python failed to start app.py',+ '/usr/bin/python',+ 'app.py'+ ])+ expect(paths('run /usr/bin/env node')).toEqual(['/usr/bin/env node', '/usr/bin/env'])+ })++ it('does not join a mid-line command argument, or two complete paths', () => {+ expect(paths('run /usr/bin/env node, then continue')).toEqual(['/usr/bin/env'])+ expect(paths('see src/a.ts and lib/b.ts here')).toEqual(['src/a.ts', 'lib/b.ts'])+ expect(paths('cp /tmp/x /tmp/y')).toEqual(['/tmp/x', '/tmp/y'])+ expect(paths('/a/b c/d.ts')).toEqual(['/a/b', 'c/d.ts'])+ })++ it('carries a line suffix on a spaced path', () => {+ expect(matchFileTokens('/Users/me/My Docs/a.ts:12:3 error')[0]).toMatchObject({+ text: '/Users/me/My Docs/a.ts:12:3',+ path: '/Users/me/My Docs/a.ts',+ line: 12+ })+ })++ it('resolves a spaced relative path against the cwd like any other', () => {+ const [t] = matchFileTokens('edited src/My Folder/a.ts')+ expect(t.path).toBe('src/My Folder/a.ts')+ expect(resolveFileToken(t.path, '/repo')).toBe('/repo/src/My Folder/a.ts')+ })+})++describe('bare filenames', () => {+ it('looks like a filename: an extension that starts with a letter, or a known project file', () => {+ const names = ['foo.ts', 'package.json', '.env', '.gitignore', 'archive.tar.gz', 'main.c']+ names.push('Makefile', 'Dockerfile', 'LICENSE', 'çıktı.sql')+ for (const name of names) expect(looksLikeBareFilename(name), name).toBe(true)+ })++ it('refuses versions, abbreviations, numbers and plain words — no lookup storm on prose', () => {+ const words = ['v1.2', '1.2.3', 'e.g', 'i.e', 'U.S', 'a.b', '42', 'readme', 'hello', 'x']+ words.push('...', 'foo.', 'foo.123', '[email protected]')+ for (const word of words) expect(looksLikeBareFilename(word), word).toBe(false)+ expect(matchFileTokens('e.g. version v1.2 of the 1.2.3 build, i.e. done')).toEqual([])+ })++ it('carries a line suffix and trims sentence punctuation', () => {+ expect(matchFileTokens('foo.ts:12:3 failed')).toEqual([+ { text: 'foo.ts:12:3', startIndex: 0, path: 'foo.ts', line: 12, bare: true }+ ])+ expect(paths('See README.')).toEqual(['README'])+ expect(paths('("package.json")')).toEqual(['package.json'])+ })++ it('never takes a piece of something larger', () => {+ // The leaf of a URL, of an assignment, of an email address: none is a bare filename.+ expect(matchFileTokens('--out=dist.js [email protected] http://x.io/a.js')).toEqual([])+ })++ it('resolves against the cwd', () => {+ expect(resolveFileToken('README', '/repo')).toBe('/repo/README')+ expect(resolveFileToken('.env', '/repo')).toBe('/repo/.env')+ })+})++describe('file:// URIs', () => {+ it('decodes, keeps a line suffix, and is never offered twice', () => {+ expect(matchFileTokens('Report: file:///Users/dev/My%20Report/r%C3%A7.html:9.')).toEqual([+ {+ text: 'file:///Users/dev/My%20Report/r%C3%A7.html:9',+ startIndex: 8,+ path: '/Users/dev/My Report/rç.html',+ line: 9+ }+ ])+ expect(matchFileTokens('file:///tmp/a.ts#L42')[0]).toMatchObject({ path: '/tmp/a.ts', line: 42 })+ expect(matchFileTokens('file://localhost/etc/hosts')[0]).toMatchObject({ path: '/etc/hosts' })+ })++ it('refuses another host, a bad escape and the bare root', () => {+ expect(matchFileTokens('file://server/share/a.txt')).toEqual([])+ expect(matchFileTokens('file:///tmp/%E0%A4%A.txt')).toEqual([])+ expect(matchFileTokens('file:///')).toEqual([])+ })++ it('is an absolute path to the resolver', () => {+ const [t] = matchFileTokens('file:///tmp/a%20b.txt')+ expect(resolveFileToken(t.path, '/elsewhere')).toBe('/tmp/a b.txt')+ })+})++describe('every token claims exactly its own text', () => {+ it('for all the kinds at once', () => {+ const line =+ 'at app/(shop)/page.tsx:3 and /Users/me/My Docs/a.md, file:///tmp/x%20y.txt; see README.md or çıktı/ş.sql'+ const toks = matchFileTokens(line)+ expect(spans(line)).toEqual(toks.map((t: FileToken) => t.text))+ expect(toks.map((t) => t.path)).toEqual([+ 'app/(shop)/page.tsx',+ '/Users/me/My Docs/a.md',+ '/Users/me/My',+ 'Docs/a.md',+ '/tmp/x y.txt',+ 'README.md',+ 'çıktı/ş.sql'+ ])+ })+})++describe('ReDoS guard: the scan stays linear on hostile lines', () => {+ // A full-screen TUI paints rows that are mostly alignment padding; a dumped blob can be one+ // unbroken token. Each case is well past anything a terminal row joins to (32 rows × ~300+ // cols ≈ 10k cells) and must finish far inside the budget.+ const BUDGET_MS = 500+ const cases: Array<[string, string]> = [+ ['separator + space padding', `a/${' '.repeat(30_000)}`],+ ['long word, then a path', `${'b'.repeat(30_000)} a/b.ts`],+ ['words separated by single spaces after a path', `/x/y ${'w '.repeat(15_000)}`],+ ['spaced path list', Array.from({ length: 2_000 }, () => '/tmp/Foo Bar/file').join(', ')],+ ['open parentheses', `src/${'('.repeat(30_000)}`],+ ['leading open parentheses', `${'('.repeat(30_000)}src/a.ts`],+ ['nested brackets', `${'('.repeat(15_000)}src/a${')'.repeat(15_000)}`],+ ['many spaced-path starts', 'a/b c '.repeat(5_000)],+ ['alternating separators', 'a/'.repeat(15_000)],+ ['file URI blob', `file:///${'a'.repeat(30_000)}`],+ ['repeated file URIs', 'file:///x '.repeat(3_000)],+ ['dotted prose', 'e.g. '.repeat(6_000)],+ ['Windows-shaped', String.raw`C:\a `.repeat(6_000)]+ ]++ for (const [name, line] of cases) {+ it(`"${name}" (${line.length} chars)`, () => {+ const t0 = performance.now()+ matchFileTokens(line)+ matchFileTokens(line, { windows: true })+ expect(performance.now() - t0).toBeLessThan(BUDGET_MS)+ })+ }+})diff --git a/src/renderer/terminal/file-link-tokens.ts b/src/renderer/terminal/file-link-tokens.tsnew file mode 100644index 000000000..ab96e166f--- /dev/null+++ b/src/renderer/terminal/file-link-tokens.ts@@ -0,0 +1,405 @@+// Path-shaped tokens in a line of terminal output — the MATCHER half of file links. Resolution+// (cwd, existence, activation) lives in file-links.ts; nothing here touches a filesystem.+//+// The existence check downstream is what makes a generous matcher safe: a token that is not a real+// file never becomes a link. So this errs toward offering candidates, including OVERLAPPING ones —+// `/usr/bin/env node` at a line end is offered whole AND as `/usr/bin/env`, and whichever exists+// wins (the longer one when both do). Tokens come back sorted by start, longer first at one start,+// which is the preference order every consumer walks.+//+// What a token may be, in precedence order:+// 1. a `file://` URI — percent-decoded to an absolute path (local host only);+// 2. a separator path whose segments contain SPACES (`/Users/me/My Docs/a.md`), claimed as one+// token, plus its space-free pieces as fallbacks;+// 3. a separator path: absolute, `~/`, dot-relative, or a relative with at least one separator.+// Segments take any Unicode letter, number or mark (`var/otta-aktarım/çıktı.sql`), and the+// parentheses and brackets of framework route folders (`app/(shop)/[id]/page.tsx`);+// 4. a BARE filename (`README`, `Makefile`, `foo.ts`) — only words that look like a filename, so+// prose (`v1.2`, `e.g.`, plain words) never costs a lookup.+// Every kind keeps the optional `:line[:col]` suffix compiler and grep output carries.+//+// LINEAR BY CONSTRUCTION. This runs on every hovered row, and full-screen TUIs paint rows that are+// thousands of cells of padding. No regex here can backtrack: each is a single character class+// repeated (or a bounded quantifier), and the spaced-path logic walks the list of runs with a+// bounded look-ahead instead of asking a regex for "space followed later by a separator" — the+// shape that went quadratic in the reference implementation (Orca, MIT, Copyright (c) 2026+// Lovecast Inc.; its tests supplied many of the cases pinned in file-link-tokens.test.ts).++export interface FileToken {+ /** The raw matched span (drives the underline range), incl. any :line:col suffix. */+ text: string+ /** 0-based index of `text` within the logical line. */+ startIndex: number+ /** The cleaned path portion — for a `file://` URI, the decoded absolute path. */+ path: string+ line?: number+ /** A bare filename (no separator): a link only if it exists, and never worth a right-click menu+ * on its own, since prose is full of words shaped like `name.ext`. */+ bare?: true+}++export interface PathConventionOpts {+ /** Match and resolve Windows-shaped paths. Off by default, so POSIX behaviour is unchanged. */+ windows?: boolean+}++// ── character classes ─────────────────────────────────────────────────────────────────────────+// A "run" is a maximal stretch of characters that may appear inside a path. `:` is deliberately+// NOT one of them (it starts the line suffix, and ends a URL scheme); spaces are not either — a+// spaced path is assembled from runs afterwards. The CJK middle dots and wave dashes appear in+// Japanese folder names and are not prose delimiters.+const PATH_CHARS = String.raw`\p{L}\p{N}\p{M}_.@+%~()\[\]\u30FB\uFF65\u301C\uFF5E\-`+const POSIX_RUN_RE = new RegExp(`[${PATH_CHARS}/]+`, 'gu')+// Windows: both separators, and a drive (`C:`) allowed at the start of a run — after any opening+// brackets, so `(C:\x)` still starts its run at the drive.+const WIN_RUN_RE = new RegExp(`[(\\[]*(?:[A-Za-z]:(?=[\\\\/]))?[${PATH_CHARS}\\\\/]+`, 'gu')+/** A whitespace-delimited word, for the bare-filename pass. Brackets and quotes are trimmed off+ * it afterwards rather than splitting it, so `foo(1).txt` never yields a stray `.txt`. */+const WORD_RE = /\S+/g+/** `file://…` up to whitespace, capped so a dumped blob cannot become one enormous candidate. */+const FILE_URI_RE = /\bfile:\/\/[^\s"'`<>|]{1,2048}/gi+const SUFFIX_AT_RE = /:(\d+)(?::\d+)?/y+const TRAILING_SUFFIX_RE = /:(\d+)(?::\d+)?$/++const OPENERS: Record<string, string> = { '(': ')', '[': ']', '{': '}' }+const CLOSERS: Record<string, string> = { ')': '(', ']': '[', '}': '{' }+/** Trailing characters that belong to the sentence, not the path. */+const TRAILING_PROSE = new Set(['.', ',', ';', ':', '!', '?', "'", '"', '>', '`'])+const LEADING_PROSE = new Set(["'", '"', '`', '<'])++/** A file extension at the end of a name: a dot, then a letter, then a short tail. */+const EXT_END_RE = /[^./\\]\.[\p{L}][\p{L}\p{N}_+-]{0,11}$/u+/** At most this many single spaces inside one spaced path — bounds the look-ahead per run. */+const MAX_SPACED_WORDS = 8++// ── bare filenames ─────────────────────────────────────────────────────────────────────────────+/** Well-known project files without an extension. A bare word must be one of these or have a+ * real-looking extension, or it is prose. */+const EXTENSIONLESS_FILENAMES = new Set([+ 'Makefile',+ 'GNUmakefile',+ 'Dockerfile',+ 'Containerfile',+ 'Jenkinsfile',+ 'Vagrantfile',+ 'Rakefile',+ 'Gemfile',+ 'Procfile',+ 'Brewfile',+ 'Justfile',+ 'justfile',+ 'LICENSE',+ 'LICENCE',+ 'COPYING',+ 'README',+ 'CHANGELOG',+ 'AUTHORS',+ 'NOTICE',+ 'CONTRIBUTING',+ 'CODEOWNERS'+])+const BARE_NAME_RE = /^\.?[\p{L}\p{N}_][\p{L}\p{N}\p{M}_.+-]*$/u+const MAX_BARE_LEN = 100++/**+ * Does a separator-free word look like a filename worth one existence lookup? A name with an+ * extension that starts with a letter (`foo.ts`, `.env`, `archive.tar.gz`), or a known+ * extensionless project file. Rejects version numbers (`v1.2`, `1.2.3` — the extension starts with+ * a digit), abbreviations (`e.g`, `i.e` — every dotted piece is one letter) and ordinary words.+ */+export function looksLikeBareFilename(name: string): boolean {+ if (name.length < 3 || name.length > MAX_BARE_LEN) return false+ if (EXTENSIONLESS_FILENAMES.has(name)) return true+ if (!BARE_NAME_RE.test(name) || name.endsWith('.')) return false+ const dot = name.lastIndexOf('.')+ if (dot < 0) return false+ if (!/^[\p{L}][\p{L}\p{N}_+-]{0,11}$/u.test(name.slice(dot + 1))) return false+ const pieces = name.split('.').filter(Boolean)+ return !pieces.every((p) => [...p].length === 1)+}++// ── cleanup ────────────────────────────────────────────────────────────────────────────────────+/** Prose wraps a path in a bracket pair or two, never more; bounds the unwrapping. */+const MAX_WRAPS = 3++/** Does the opener at 0 close exactly at the last character (the pair wraps the whole text)? */+function wrapsWhole(text: string): boolean {+ const open = text[0]+ const close = OPENERS[open]+ if (!close || text[text.length - 1] !== close) return false+ let depth = 0+ for (let i = 0; i < text.length; i++) {+ if (text[i] === open) depth+++ else if (text[i] === close) {+ depth--+ if (depth === 0 && i < text.length - 1) return false+ }+ }+ return depth === 0+}++/**+ * Trim what surrounds a path in prose, keeping brackets that belong to it. A trailing `)` is+ * dropped only when it has no `(` to close inside the token (`see src/a.ts)`), so a route folder+ * like `app/(shop)/page.tsx` survives whole — the balance check Orca's `trimTrailingProse` does.+ * A markdown link `[label](target)` keeps only its target.+ */+function cleanSpan(text: string, start: number): { text: string; start: number } | null {+ const md = text.indexOf('](')+ if (md >= 0) {+ start += md + 2+ text = text.slice(md + 2)+ }+ // Bracket counts are kept incrementally and the span is narrowed by index, so a token that is+ // thousands of brackets long is still trimmed in linear time.+ const counts: Record<string, number> = { '(': 0, ')': 0, '[': 0, ']': 0, '{': 0, '}': 0 }+ for (const c of text) if (c in counts) counts[c]+++ const drop = (c: string): void => {+ if (c in counts) counts[c]--+ }+ let i = 0+ let j = text.length+ let wraps = 0+ while (i < j) {+ const first = text[i]+ const last = text[j - 1]+ if (LEADING_PROSE.has(first) || (OPENERS[first] && counts[first] > counts[OPENERS[first]])) {+ drop(first)+ i+++ } else if (+ TRAILING_PROSE.has(last) ||+ OPENERS[last] ||+ (CLOSERS[last] && counts[last] > counts[CLOSERS[last]])+ ) {+ drop(last)+ j--+ } else if (wraps < MAX_WRAPS && wrapsWhole(text.slice(i, j))) {+ drop(first)+ drop(last)+ i+++ j--+ wraps+++ } else break+ }+ return i < j ? { text: text.slice(i, j), start: start + i } : null+}++// ── runs and the separator pass ────────────────────────────────────────────────────────────────+interface Run {+ /** Raw run bounds in the line. */+ start: number+ end: number+}++interface Dialect {+ windows: boolean+ run: RegExp+ sep: RegExp+ /** Starts a new path: an absolute, home, dot-relative or drive prefix. */+ anchor: RegExp+}++const POSIX: Dialect = {+ windows: false,+ run: POSIX_RUN_RE,+ sep: /\//,+ anchor: /^(?:\/|~\/|\.{1,2}\/)/+}+const WINDOWS: Dialect = {+ windows: true,+ run: WIN_RUN_RE,+ sep: /[\\/]/,+ anchor: /^(?:[\\/]|\.{1,2}[\\/]|[A-Za-z]:[\\/])/+}++/** Strip opening brackets/quotes so an anchor test sees the path itself. */+function stripOpeners(text: string): string {+ let i = 0+ while (i < text.length && (OPENERS[text[i]] || LEADING_PROSE.has(text[i]))) i+++ return text.slice(i)+}++/** The `:line[:col]` right after `end`, if any. */+function suffixAt(line: string, end: number): { len: number; line: number } | null {+ SUFFIX_AT_RE.lastIndex = end+ const m = SUFFIX_AT_RE.exec(line)+ return m ? { len: m[0].length, line: parseInt(m[1], 10) } : null+}++/**+ * Turn a span into a token, or null when it is not a usable path. `requireSep` is false only for+ * the bare pass. Shared by the plain and spaced passes so both apply the same refusals.+ */+function toToken(+ lineText: string,+ rawStart: number,+ rawEnd: number,+ d: Dialect,+ requireSep: boolean+): FileToken | null {+ const suffix = suffixAt(lineText, rawEnd)+ const cleaned = cleanSpan(lineText.slice(rawStart, rawEnd), rawStart)+ if (!cleaned) return null+ let { text: path, start } = cleaned+ // A suffix belongs to the path only when nothing was trimmed off the path's end before it.+ const touching = suffix && start + path.length === rawEnd ? suffix : null+ if (d.windows) {+ // A UNC path is refused WHOLE: starting two characters in would turn `server\share\a.ts` into a+ // cwd-relative path and bypass the resolver's UNC refusal.+ if (/^(?:\\\\|\/\/)/.test(path)) return null+ // A lone leading separator is root-relative on the current drive; the old matcher took the+ // path from its first segment, and so does this.+ while (/^[\\/]/.test(path)) {+ path = path.slice(1)+ start+++ }+ }+ // Trailing separators: `dir/` names the directory; the lookup wants `dir`.+ const trailingSep = d.windows ? /[\\/]$/ : /\/$/+ while (path.length > 1 && trailingSep.test(path) && !/^[A-Za-z]:[\\/]$/.test(path)) {+ path = path.slice(0, -1)+ }+ if (path.includes('//') || (d.windows && path.includes('\\\\'))) return null+ // `~` is only ever a whole first segment (a home path, POSIX only). `backup~/x` and `~user/x`+ // are not home paths, and on Windows `~` cannot start one either.+ const firstSeg = path.split(d.sep)[0]+ if (firstSeg.includes('~') && (d.windows ? firstSeg.startsWith('~') : firstSeg !== '~')) return null+ if (requireSep && !d.sep.test(path)) return null+ if (d.windows && /^[A-Za-z]:$/.test(path)) return null+ const text = touching+ ? lineText.slice(start, rawEnd + touching.len)+ : lineText.slice(start, start + path.length)+ if (text.length < 3 || !path) return null+ return { text, startIndex: start, path, line: touching?.line }+}++/** A separator path whose last segment is a complete `name.ext` — a space after it is prose. */+function endsWithFileName(text: string): boolean {+ return EXT_END_RE.test(text)+}++function spacedTokens(lineText: string, runs: Run[], d: Dialect): FileToken[] {+ const out: FileToken[] = []+ const adjacent = (a: Run, b: Run): boolean => b.start === a.end + 1 && lineText[a.end] === ' '+ const clean = (r: Run): string => stripOpeners(lineText.slice(r.start, r.end))+ // Everything after this index is whitespace; computed once so the line-end test is O(1).+ const lastInk = lineText.trimEnd().length+ for (let i = 0; i < runs.length; i++) {+ const r0 = clean(runs[i])+ if (!d.sep.test(r0) || endsWithFileName(r0) || suffixAt(lineText, runs[i].end)) continue+ let best = -1+ for (let j = i + 1; j < runs.length && j - i <= MAX_SPACED_WORDS; j++) {+ if (!adjacent(runs[j - 1], runs[j])) break+ const w = clean(runs[j])+ if (d.anchor.test(w)) break // a second path begins here+ const hasSep = d.sep.test(w)+ const fileEnd = endsWithFileName(w.replace(/[.,;:!?)\]]+$/, ''))+ const lineEnd = runs[j].end >= lastInk+ const suffixed = !!suffixAt(lineText, runs[j].end)+ // A candidate ends at a word that carries a separator (`… Docs/a.md`), completes a file+ // name (`… final report.pdf`), or ends the line (`/Users/me/My Folder`).+ if (hasSep || fileEnd || lineEnd) best = j+ if (fileEnd || suffixed) break+ }+ if (best < 0) continue+ const tok = toToken(lineText, runs[i].start, runs[best].end, d, true)+ if (tok && tok.path.includes(' ')) out.push(tok)+ }+ return out+}++// ── file:// URIs ───────────────────────────────────────────────────────────────────────────────+/**+ * A printed `file://` URI as a token whose path is the decoded absolute path. Local host only: a+ * `file://server/…` names another machine, and the existence check would look on this one. On+ * Windows the path must carry a drive (`file:///C:/…`); a POSIX-rooted one cannot resolve there.+ */+function fileUriTokens(lineText: string, d: Dialect): FileToken[] {+ const out: FileToken[] = []+ for (const m of lineText.matchAll(FILE_URI_RE)) {+ const cleaned = cleanSpan(m[0], m.index)+ if (!cleaned || !/^file:\/\//i.test(cleaned.text)) continue+ let rest = cleaned.text.slice('file://'.length)+ const slash = rest.indexOf('/')+ if (slash < 0) continue+ const host = rest.slice(0, slash)+ if (host && host.toLowerCase() !== 'localhost') continue+ rest = rest.slice(slash)+ let line: number | undefined+ const hash = rest.indexOf('#')+ if (hash >= 0) {+ const l = /^#L(\d+)(?:C\d+)?$/i.exec(rest.slice(hash))+ if (l) line = parseInt(l[1], 10)+ rest = rest.slice(0, hash)+ }+ const query = rest.indexOf('?')+ if (query >= 0) rest = rest.slice(0, query)+ const suffix = TRAILING_SUFFIX_RE.exec(rest)+ if (suffix) {+ line = parseInt(suffix[1], 10)+ rest = rest.slice(0, suffix.index)+ }+ let path: string+ try {+ path = decodeURIComponent(rest)+ } catch {+ continue+ }+ if (!path || path === '/' || path.includes('\0')) continue+ if (d.windows) {+ if (!/^\/[A-Za-z]:\//.test(path)) continue+ path = path.slice(1)+ }+ out.push({ text: cleaned.text, startIndex: cleaned.start, path, line })+ }+ return out+}++// ── bare filenames ─────────────────────────────────────────────────────────────────────────────+function bareTokens(lineText: string, d: Dialect): FileToken[] {+ const out: FileToken[] = []+ for (const m of lineText.matchAll(WORD_RE)) {+ const word = m[0]+ if (word.length > MAX_BARE_LEN + 12 || /[\\/]/.test(word)) continue+ const cleaned = cleanSpan(word.replace(/:\d+(?::\d+)?[.,;:!?]*$/, ''), m.index)+ if (!cleaned || !looksLikeBareFilename(cleaned.text)) continue+ const tok = toToken(lineText, cleaned.start, cleaned.start + cleaned.text.length, d, false)+ if (tok && tok.path === cleaned.text) out.push({ ...tok, bare: true })+ }+ return out+}++// ── the matcher ────────────────────────────────────────────────────────────────────────────────+function overlaps(a: FileToken, b: FileToken): boolean {+ return a.startIndex < b.startIndex + b.text.length && b.startIndex < a.startIndex + a.text.length+}++/**+ * Every file-path candidate in a logical line, sorted by start and, at one start, longer first —+ * the order in which to prefer them. Candidates may OVERLAP (a spaced path and its pieces); a+ * `file://` URI claims its span outright, and nothing else is offered inside it.+ */+export function matchFileTokens(lineText: string, opts: PathConventionOpts = {}): FileToken[] {+ const d = opts.windows ? WINDOWS : POSIX+ const uris = fileUriTokens(lineText, d)+ const runs: Run[] = []+ for (const m of lineText.matchAll(d.run)) runs.push({ start: m.index, end: m.index + m[0].length })+ const plain: FileToken[] = []+ for (const r of runs) {+ const tok = toToken(lineText, r.start, r.end, d, true)+ if (tok) plain.push(tok)+ }+ const rest = [...spacedTokens(lineText, runs, d), ...plain, ...bareTokens(lineText, d)].filter(+ (t) => !uris.some((u) => overlaps(u, t))+ )+ const all = [...uris, ...rest]+ const seen = new Set<string>()+ return all+ .filter((t) => {+ const key = `${t.startIndex}:${t.text.length}`+ if (seen.has(key)) return false+ seen.add(key)+ return true+ })+ .sort((a, b) => a.startIndex - b.startIndex || b.text.length - a.text.length)+}diff --git a/src/renderer/terminal/file-links.cells.test.ts b/src/renderer/terminal/file-links.cells.test.tsnew file mode 100644index 000000000..17cab43e0--- /dev/null+++ b/src/renderer/terminal/file-links.cells.test.ts@@ -0,0 +1,249 @@+// @vitest-environment jsdom+// Hit-testing and underline ranges for the new token kinds, against a buffer that reports CELLS the+// way xterm does: a wide (CJK) glyph is one character over two cells, the second a width-0+// placeholder. Before the cell map, string index = cell index was assumed everywhere, so any wide+// glyph before a path shifted its underline and its click target left by one cell per glyph.+import { describe, expect, it } from 'vitest'+import type { ILink, Terminal } from '@xterm/xterm'+import {+ createFileLinkProvider,+ installLinkClickFallback,+ installLinkContextMenu,+ linkAtCell,+ type LinkHit,+ type LinkHitDeps+} from './file-links'+import { resolveLinkTarget } from './link-menu'++const CELL_W = 10+const CELL_H = 20+const WIDE = /[ᄀ-ᅟ⺀-가-힣豈--⦆]/u++interface FakeCell {+ chars: string+ width: number+}++function toCells(row: string, cols: number): FakeCell[] {+ const out: FakeCell[] = []+ for (const ch of row) {+ if (WIDE.test(ch)) out.push({ chars: ch, width: 2 }, { chars: '', width: 0 })+ else out.push({ chars: ch, width: 1 })+ }+ while (out.length < cols) out.push({ chars: '', width: 1 })+ return out.slice(0, cols)+}++/** A terminal whose buffer answers per cell (getChars/getWidth), plus the DOM the listeners use. */+function fakeTerm(rows: string[], cols = 40) {+ const cellRows = rows.map((r) => toCells(r, cols))+ const host = document.createElement('div')+ const screen = document.createElement('div')+ screen.className = 'xterm-screen'+ screen.getBoundingClientRect = () =>+ ({ left: 0, top: 0, width: cols * CELL_W, height: rows.length * CELL_H }) as DOMRect+ host.appendChild(screen)+ document.body.appendChild(host)+ const term = {+ cols,+ rows: rows.length,+ element: host,+ modes: { mouseTrackingMode: 'vt200' },+ clearSelection: () => {},+ buffer: {+ active: {+ viewportY: 0,+ length: rows.length,+ getLine: (r: number) => {+ const cells = cellRows[r]+ if (!cells) return undefined+ const str = cells+ .filter((c) => c.width !== 0)+ .map((c) => c.chars || ' ')+ .join('')+ return {+ isWrapped: false,+ length: cols,+ translateToString: (trim: boolean) => (trim ? str.replace(/ +$/, '') : str),+ getCell: (x: number) => {+ const c = cells[x]+ return c && { getChars: () => c.chars, getWidth: () => c.width }+ }+ }+ }+ }+ },+ _core: { _oscLinkService: { getLinkData: () => undefined } }+ } as unknown as Terminal+ return { term, host, screen }+}++const deps = (over: Partial<LinkHitDeps> = {}): LinkHitDeps => ({+ getCwd: () => '/home/me/proj',+ convention: () => ({}),+ fileEnabled: () => true,+ ...over+})++const provide = (term: Terminal, row: number, exists: (abs: string) => boolean): Promise<ILink[]> =>+ new Promise((resolve) => {+ createFileLinkProvider(term, {+ getCwd: () => '/home/me/proj',+ lookup: async (abs) => ({ exists: exists(abs), dir: false }),+ activate: () => {}+ }).provideLinks(row, (links) => resolve(links ?? []))+ })++describe('wide glyphs before a path', () => {+ // cells: 日0-1 本2-3 語4-5 ␠6 s7 r8 c9 /10 a11 .12 t13 s14+ const { term } = fakeTerm(['日本語 src/a.ts done'])++ it('hit-tests the path at its real cells', () => {+ const hit = { kind: 'path', token: 'src/a.ts', abs: '/home/me/proj/src/a.ts' }+ expect(linkAtCell(term, 0, 7, deps())).toEqual(hit)+ expect(linkAtCell(term, 0, 14, deps())).toEqual(hit) // the last `s`+ expect(linkAtCell(term, 0, 15, deps())).toBeNull() // the space after it+ expect(linkAtCell(term, 0, 4, deps())).toBeNull() // 語, not the path+ })++ it('underlines exactly the path cells', async () => {+ const links = await provide(term, 1, () => true)+ expect(links.map((l) => l.range)).toEqual([{ start: { x: 8, y: 1 }, end: { x: 15, y: 1 } }])+ })++ it('underlines a wide glyph inside the path through its second cell', async () => {+ // cells: s0 r1 c2 /3 報4-5 告6-7 .8 m9 d10+ const { term: t } = fakeTerm(['src/報告.md'])+ const links = await provide(t, 1, () => true)+ expect(links[0].range).toEqual({ start: { x: 1, y: 1 }, end: { x: 11, y: 1 } })+ expect(linkAtCell(t, 0, 5, deps())).toMatchObject({ token: 'src/報告.md' })+ })++ it('joins a hard-wrapped row that ends in a wide glyph', async () => {+ // Row 0 is full: `abc/` (4 cells) + 日本語 (6 cells) = 10. The old text read was 7 characters+ // long, so the row never counted as full and the path was cut at the seam.+ const { term: t } = fakeTerm(['abc/日本語', 'x.txt'], 10)+ const links = await provide(t, 2, () => true)+ expect(links.map((l) => [l.text, l.range])).toEqual([+ ['abc/日本語x.txt', { start: { x: 1, y: 1 }, end: { x: 5, y: 2 } }]+ ])+ expect(linkAtCell(t, 1, 2, deps())).toMatchObject({ token: 'abc/日本語x.txt' })+ })+})++describe('the new token kinds under the pointer', () => {+ it('a spaced path is one hit, with its pieces as alternatives', () => {+ const { term } = fakeTerm(['open /Users/me/My Docs/a.md'])+ for (const col of [5, 16, 20, 26]) {+ expect(linkAtCell(term, 0, col, deps())).toEqual({+ kind: 'path',+ token: '/Users/me/My Docs/a.md',+ abs: '/Users/me/My Docs/a.md',+ alternatives: col < 17 ? ['/Users/me/My'] : ['Docs/a.md']+ })+ }+ })++ it('a Unicode path is hit on any of its letters', () => {+ const { term } = fakeTerm(['wrote var/otta-aktarım/çıktı.sql'])+ expect(linkAtCell(term, 0, 25, deps())).toMatchObject({ token: 'var/otta-aktarım/çıktı.sql' })+ expect(linkAtCell(term, 0, 31, deps())).toMatchObject({ token: 'var/otta-aktarım/çıktı.sql' })+ })++ it('the provider links the longest reading that exists, and never its overlapping pieces', async () => {+ const { term } = fakeTerm(['run /usr/bin/env node'])+ const onlyEnv = await provide(term, 1, (abs) => abs === '/usr/bin/env')+ expect(onlyEnv.map((l) => l.text)).toEqual(['/usr/bin/env'])+ const both = await provide(term, 1, () => true)+ expect(both.map((l) => l.text)).toEqual(['/usr/bin/env node'])+ })++ it('a bare filename links only when it exists', async () => {+ const { term } = fakeTerm(['edit README.md and notes.txt'])+ const links = await provide(term, 1, (abs) => abs === '/home/me/proj/README.md')+ expect(links.map((l) => [l.text, l.range])).toEqual([+ ['README.md', { start: { x: 6, y: 1 }, end: { x: 14, y: 1 } }]+ ])+ })++ it('a file URI underlines the URI and resolves to its decoded path', async () => {+ const { term } = fakeTerm(['see file:///tmp/a%20b.txt'])+ const seen: string[] = []+ const links = await provide(term, 1, (abs) => (seen.push(abs), true))+ expect(links.map((l) => l.text)).toEqual(['file:///tmp/a%20b.txt'])+ expect(seen).toEqual(['/tmp/a b.txt'])+ })+})++/** A left or right click at buffer cell (row, col) on the screen element. */+function fire(target: HTMLElement, type: string, row: number, col: number, button: number, mod = false) {+ const ev = new MouseEvent(type, {+ bubbles: true,+ cancelable: true,+ button,+ metaKey: mod,+ clientX: col * CELL_W + 2,+ clientY: row * CELL_H + 2+ })+ target.dispatchEvent(ev)+ return ev+}++describe('the Cmd+click fallback walks the alternatives', () => {+ const setup = (rows: string[], exists: (abs: string) => boolean) => {+ const { term, host, screen } = fakeTerm(rows)+ const opened: string[] = []+ const missing: Array<[string, string[]]> = []+ installLinkClickFallback(term, host, {+ ...deps(),+ lookup: async (abs) => ({ exists: exists(abs), dir: false }),+ activateFile: (abs) => opened.push(abs),+ openUrl: () => {},+ onMissing: (token, miss) => missing.push([token, miss.tried])+ })+ return { screen, opened, missing }+ }+ const settle = () => new Promise((r) => setTimeout(r, 0))++ it('opens the piece that exists when the spaced reading does not', async () => {+ const { screen, opened } = setup(['run /usr/bin/env node'], (abs) => abs === '/usr/bin/env')+ fire(screen, 'mouseup', 0, 6, 0, true)+ await settle()+ expect(opened).toEqual(['/usr/bin/env'])+ })++ it('reports every place it looked when nothing exists', async () => {+ const { screen, opened, missing } = setup(['open /Users/me/My Docs/a.md'], () => false)+ fire(screen, 'mouseup', 0, 20, 0, true)+ await settle()+ expect(opened).toEqual([])+ expect(missing).toEqual([+ ['/Users/me/My Docs/a.md', ['/Users/me/My Docs/a.md', '/home/me/proj/Docs/a.md']]+ ])+ })+})++describe('the right-click menu', () => {+ it('does not claim a bare filename, which is most likely prose', () => {+ const { term, host, screen } = fakeTerm(['see README.md or src/a.ts'])+ const opened: LinkHit[] = []+ let reached = 0+ screen.addEventListener('mousedown', () => reached++)+ installLinkContextMenu(term, host, { ...deps(), openMenu: (hit) => opened.push(hit) })+ fire(screen, 'mousedown', 0, 6, 2)+ fire(screen, 'contextmenu', 0, 6, 2)+ expect(opened).toEqual([])+ expect(reached).toBe(1)+ fire(screen, 'mousedown', 0, 19, 2)+ fire(screen, 'contextmenu', 0, 19, 2)+ expect(opened).toEqual([{ kind: 'path', token: 'src/a.ts', abs: '/home/me/proj/src/a.ts' }])+ })++ it('resolves a spaced hit to the piece that exists', async () => {+ const hit: LinkHit = { kind: 'path', token: '/a/My Docs', abs: '/a/My Docs', alternatives: ['/a/My'] }+ const target = await resolveLinkTarget(hit, async (token) =>+ token === '/a/My' ? { found: true, abs: '/a/My', dir: true } : { found: false, tried: [token] }+ )+ expect(target).toEqual({ kind: 'file', abs: '/a/My', dir: true })+ })+})diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.tsindex b1a0ef7df..c8621c00c 100644--- a/src/renderer/terminal/file-links.ts+++ b/src/renderer/terminal/file-links.ts@@ -1,7 +1,7 @@// Cmd/Ctrl+click links in terminal output. `createUrlLinkProvider` handles http(s) URLs;-// `createFileLinkProvider` handles path-like tokens: absolute (`/x/y`), dot-relative-// (`./x`, `../x`) and bare relatives with at least one slash (`src/a.ts`), with optional-// `:line[:col]` suffixes (compiler/grep output), and home-relative `~/x` paths. A `~` path stays+// `createFileLinkProvider` handles path-like tokens — what counts as one (separator paths with+// Unicode, bracketed and spaced segments, bare filenames, `file://` URIs, `:line[:col]` suffixes,+// home-relative `~/x`) is file-link-tokens.ts. A `~` path stays// `~`-rooted all the way to the filesystem call: the core that owns the filesystem expands it// against ITS home (`expandHomePath` in core/fs-handlers.ts; an SSH project's remote shell does it// for `sshFs`) — the renderer does not know that home, and on the Server Edition it is another@@ -36,133 +36,20 @@ export interface LinkHoverSink {leave(): void}-export interface FileToken {- /** The raw matched span (drives the underline range), incl. any :line:col suffix. */- text: string- /** 0-based index of `text` within the logical line. */- startIndex: number- /** The cleaned path portion. */- path: string- line?: number-}+import {+ matchFileTokens,+ type FileToken,+ type PathConventionOpts+} from './file-link-tokens'-// Path-ish token: an optional ./ ../ / prefix, then segments of path-safe chars with at-// least one internal slash — OR a prefixed single-segment (/tmp, ./x) — with an optional-// trailing :line[:col]. Trailing punctuation is cleaned afterwards, not in the regex.-const TOKEN_RE =- /(?:(?:\.{1,2}\/|\/)?[\w.@+-]+(?:\/[\w.@+~-]+)+|(?:\.{1,2}\/|\/)[\w.@+-]+)(?::\d+(?::\d+)?)?/g+// The matcher (what counts as a path in a line of output) lives in file-link-tokens.ts.+export { looksLikeBareFilename, matchFileTokens } from './file-link-tokens'+export type { FileToken, PathConventionOpts } from './file-link-tokens'-/**- * The same shape with Windows separators, plus drive and UNC prefixes. Used ONLY when the- * filesystem-owning core reports Windows — never just because the viewing browser is on Windows,- * and never for an SSH project, whose paths are POSIX however the viewer is spelled.- *- * A SEPARATE regex rather than widening TOKEN_RE's separator class, deliberately: the POSIX path- * is what every existing user runs, and it stays byte-identical. Widening it would also start- * matching Windows-shaped text inside a POSIX session, where it can only ever be wrong.- *- * Four alternatives, in order: a UNC path (consumed whole so it can be refused), a drive-absolute- * path, a dot-prefixed relative, or a plain multi-segment relative. Both separators are accepted,- * because Windows tools emit both. A bare single word is deliberately not a token — `readme` in a- * sentence is not a path, and TOKEN_RE takes the same position for POSIX.- *- * SPACES ARE NOT PART OF A SEGMENT, even though `C:\Program Files\…` is everywhere on Windows.- * An unquoted path in terminal output gives no way to tell where it ends, so allowing spaces made- * `C:\Users\me\src\a.ts for detail` match as one token — it swallowed the rest of the sentence.- * The existence check would have rejected that, which means a path with a space would simply never- * have linked while quietly breaking the ones around it. The POSIX matcher takes the same- * position, so this is parity rather than a Windows-specific shortfall.- */-const WIN_TOKEN_RE =- /(?:(?:\\\\|\/\/)[\w.@+~-]+[\\/][\w.@+~-]+(?:[\\/][\w.@+~-]+)*|[A-Za-z]:[\\/][\w.@+~-]*(?:[\\/][\w.@+~-]+)*|\.{1,2}[\\/][\w.@+~-]+(?:[\\/][\w.@+~-]+)*|[\w.@+-]+(?:[\\/][\w.@+~-]+)+)(?::\d+(?::\d+)?)?/g-const SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/const TRAILING_PUNCT = /[.,;:!?'")\]}>]+$//** `C:\…`, `C:/…`, or a UNC `\\host\share` / `//host/share`. */const WIN_ABSOLUTE_RE = /^(?:[A-Za-z]:[\\/]|\\\\|\/\/)/-export interface PathConventionOpts {- /** Match and resolve Windows-shaped paths. Off by default, so POSIX behaviour is unchanged. */- windows?: boolean-}--/** Characters that, right before a `~`, mean it is not the start of a home path (`a~/x`). */-const HOME_LEAD_BLOCK_RE = /[\w.@+~\/-]/--export function matchFileTokens(lineText: string, opts: PathConventionOpts = {}): FileToken[] {- const out: FileToken[] = []- if (opts.windows) return matchWindowsFileTokens(lineText)- for (const m of lineText.matchAll(TOKEN_RE)) {- let text = m[0]- let start = m.index- // URLs (and protocol-ish tokens) belong to the web-links addon.- const before = lineText.slice(Math.max(0, m.index - 8), m.index)- // `\w+:\/{1,2}$` (not just `://`): the optional leading-`/` in TOKEN_RE can swallow the- // second slash of `://`, so a URL's token starts at that slash and `before` ends `https:/`.- if (/\w+:\/{1,2}$/.test(before) || text.includes('//')) continue- // A token preceded by `~` is a home-relative path minus its tilde. Re-attach the tilde when it- // stands at a word start (`~/x`, ` ~/x`, `(~/x`) so it never mis-resolves as the absolute `/x`.- // Anything else before the `~` (`a~/x`, `~user/x`) is not a home path — skip it, as before.- if (m.index > 0 && lineText[m.index - 1] === '~') {- const lead = m.index > 1 ? lineText[m.index - 2] : ''- if (!text.startsWith('/') || HOME_LEAD_BLOCK_RE.test(lead)) continue- text = '~' + text- start = m.index - 1- }- text = text.replace(TRAILING_PUNCT, '')- if (text.length < 3) continue- let path = text- let line: number | undefined- const suffix = SUFFIX_RE.exec(text)- if (suffix) {- path = suffix[1]- line = parseInt(suffix[2], 10)- }- if (!path || !path.includes('/')) continue- out.push({ text, startIndex: start, path, line })- }- return out-}--/**- * The Windows half of `matchFileTokens`. Kept separate so the POSIX path above is untouched.- *- * The existence check downstream (`makeDirListingLookup`) is what makes a slightly generous- * matcher safe: a token that is not a real file simply never becomes a link. So this errs toward- * matching, and lets the filesystem decide — the opposite trade from the traversal guards- * elsewhere in this codebase, where guessing wrong has a cost.- */-function matchWindowsFileTokens(lineText: string): FileToken[] {- const out: FileToken[] = []- for (const m of lineText.matchAll(WIN_TOKEN_RE)) {- let text = m[0]- const before = lineText.slice(Math.max(0, m.index - 8), m.index)- // A URL's token can begin at the second slash of `://` — same guard as the POSIX branch.- if (/\w+:\/{1,2}$/.test(before) || text.includes('//')) continue- text = text.replace(TRAILING_PUNCT, '')- if (text.length < 3) continue- let path = text- // Refuse the WHOLE UNC token here. Without the explicit UNC alternative in WIN_TOKEN_RE the- // matcher started two characters in (`server\share\a.ts`), turning the network path into a- // relative path under cwd and bypassing resolveWindowsFileToken's UNC refusal.- if (/^(?:\\\\|\/\/)/.test(path)) continue- let line: number | undefined- const suffix = SUFFIX_RE.exec(text)- // `C:\src\a.ts:12` splits correctly because SUFFIX_RE anchors the digits at the END — the- // drive's own colon is not followed by digits-then-end. `C:12` would split into path `C`,- // which the separator requirement below then rejects.- if (suffix) {- path = suffix[1]- line = parseInt(suffix[2], 10)- }- if (!path) continue- // Must look like a path, not a bare word: either drive/UNC-qualified, or containing a- // separator. Without this a `:line` suffix on any word would produce a token.- if (!WIN_ABSOLUTE_RE.test(path) && !/[\\/]/.test(path)) continue- out.push({ text, startIndex: m.index, path, line })- }- return out-}-// http(s) URLs. Shared by createUrlLinkProvider (hover underline + click outside tmux) and// the mouse-up click fallback (below), which hit-tests URLs and file paths in one pass —// under tmux/agent mouse-reporting a provider's own click never fires (see@@ -487,22 +374,54 @@ export interface FileLinkDeps extends CwdSources {}/** The minimal buffer slice paragraph joining needs — unit tests drive a fake. */+/** One buffer cell: its text (`''` for a never-written cell) and its width — 2 for a wide (CJK,+ * emoji) glyph, 0 for the placeholder cell that follows one. */+export interface BufferCell {+ chars: string+ width: number+}+export interface BufferView {cols: numberlength: number- line(row: number): { isWrapped: boolean; text(trimRight: boolean): string } | undefined+ line(+ row: number+ ):+ | {+ isWrapped: boolean+ text(trimRight: boolean): string+ /** Per-cell content, when the buffer can say. Without it every UTF-16 unit is taken to be+ * one cell — true for ASCII, wrong after a wide glyph. */+ cells?(): BufferCell[] | undefined+ }+ | undefined}export function bufferView(term: Terminal): BufferView {const buf = term.buffer.active+ const cols = term.colsreturn {- cols: term.cols,+ cols,length: buf.length,line: (row) => {const l = buf.getLine(row)- return l- ? { isWrapped: l.isWrapped, text: (trim: boolean) => l.translateToString(trim) }- : undefined+ if (!l) return undefined+ return {+ isWrapped: l.isWrapped,+ text: (trim: boolean) => l.translateToString(trim),+ cells: () => {+ const out: BufferCell[] = []+ let cell = l.getCell?.(0)+ if (!cell || typeof cell.getChars !== 'function') return undefined+ const n = Math.min(l.length ?? cols, cols)+ for (let x = 0; x < n; x++) {+ cell = l.getCell(x, cell)+ if (!cell) break+ out.push({ chars: cell.getChars(), width: cell.getWidth() })+ }+ return out+ }+ }}}}@@ -511,61 +430,136 @@ export function bufferView(term: Terminal): BufferView {* full-width walls of text; a wrapped OAuth URL is ~7 rows at 80 cols. */const MAX_JOIN_ROWS = 32+/** A row as cells: from the buffer when it can say, else one cell per UTF-16 unit of its text. */+function rowCells(view: BufferView, row: number): BufferCell[] | null {+ const l = view.line(row)+ if (!l) return null+ const cells = l.cells?.()+ if (cells) return cells+ return [...l.text(false).padEnd(view.cols)].slice(0, view.cols).map((chars) => ({ chars, width: 1 }))+}++const isBlank = (c: BufferCell | undefined): boolean => !c || c.chars === '' || c.chars === ' '+// Whether `row` runs into `row + 1`: the successor carries xterm's soft-wrap flag, OR the-// hard-wrap heuristic holds — `row` is full to its last column (untrimmed non-space in the-// final cell) and the successor starts at column 0 with a non-space. See the header comment.+// hard-wrap heuristic holds — `row` is full to its last column (a non-space in the final cell, or+// the placeholder half of a wide glyph there) and the successor starts at column 0 with a+// non-space. See the header comment.function continuesOnNextRow(view: BufferView, row: number): boolean {const next = view.line(row + 1)if (!next) return falseif (next.isWrapped) return trueconst cur = view.line(row)if (!cur) return false- const raw = cur.text(false)- if (raw.length < view.cols || raw[view.cols - 1] === ' ') return false- const nextRaw = next.text(false)- return nextRaw.length > 0 && nextRaw[0] !== ' '+ const cells = cur.cells?.()+ if (!cells) {+ // Text-only view: the original check, unit for unit.+ const raw = cur.text(false)+ if (raw.length < view.cols || raw[view.cols - 1] === ' ') return false+ const nextRaw = next.text(false)+ return nextRaw.length > 0 && nextRaw[0] !== ' '+ }+ const last = cells[view.cols - 1]+ const full = last && (last.width === 0 ? !isBlank(cells[view.cols - 2]) : !isBlank(last))+ if (!full) return false+ return !isBlank(rowCells(view, row + 1)?.[0])+}++/** A logical paragraph, with the buffer cell of every UTF-16 unit of its text. */+export interface Paragraph {+ text: string+ startRow: number+ rows: number+ /** Paragraph-relative cell index (`rowOffset * cols + col`) where each unit of `text` starts. */+ cellStart: number[]+ /** …and the last cell it occupies (one further for a wide glyph). */+ cellEnd: number[]}/*** The logical paragraph containing `row` (0-based): walks up to the paragraph's first row,- * then joins downward across soft AND hard wraps. Every row that continues contributes- * EXACTLY `cols` characters (padded/truncated untrimmed read), so an index into `text` maps- * back to the buffer as `(startRow + idx / cols, idx % cols)`; the final row is right-trimmed.+ * then joins downward across soft AND hard wraps. Every row that continues contributes all its+ * cells (untrimmed); the final row is right-trimmed. Text and cells are NOT one-to-one — a wide+ * glyph is one character over two cells, an astral one two units in one cell — so `cellStart` /+ * `cellEnd` carry the mapping, and every hit-test and underline range goes through them.*/-export function paragraphContaining(- view: BufferView,- row: number-): { text: string; startRow: number; rows: number } | null {+export function paragraphContaining(view: BufferView, row: number): Paragraph | null {if (!view.line(row)) return nulllet start = rowwhile (start > 0 && row - start < MAX_JOIN_ROWS && continuesOnNextRow(view, start - 1)) start--let text = ''+ const cellStart: number[] = []+ const cellEnd: number[] = []let r = startfor (;;) {const joins = r - start + 1 < MAX_JOIN_ROWS && continuesOnNextRow(view, r)- const lineText = view.line(r)!.text(!joins)- // Continuing rows must contribute exactly `cols` chars so the index math above holds.- text += joins ? lineText.padEnd(view.cols).slice(0, view.cols) : lineText- if (!joins) break+ const base = (r - start) * view.cols+ const cells = rowCells(view, r)!+ let n = Math.min(cells.length, view.cols)+ // A wide glyph that did not fit leaves the last cell of a soft-wrapped row empty; it is not+ // a space in the text, or it would split a token across the seam.+ if (joins && view.line(r + 1)?.isWrapped && cells[n - 1]?.chars === '' && cells[n - 1]?.width === 1)+ n--+ const rowStartLen = text.length+ for (let x = 0; x < n; x++) {+ const c = cells[x]+ if (c.width === 0) continue+ const chars = c.chars || ' '+ for (let u = 0; u < chars.length; u++) {+ cellStart.push(base + x)+ cellEnd.push(base + x + Math.max(c.width, 1) - 1)+ }+ text += chars+ }+ if (!joins) {+ // Right-trim the final row only.+ let end = text.length+ while (end > rowStartLen && text[end - 1] === ' ') end--+ text = text.slice(0, end)+ cellStart.length = end+ cellEnd.length = end+ break+ }r++}- return { text, startRow: start, rows: r - start + 1 }+ return { text, startRow: start, rows: r - start + 1, cellStart, cellEnd }}/** ILink range (1-based, inclusive) for a token at `startIndex..+len` of a paragraph. */function tokenRange(- startRow: number,+ p: Paragraph,cols: number,startIndex: number,len: number): ILink['range'] {- const endIndex = startIndex + len - 1+ const first = p.cellStart[startIndex]+ const last = p.cellEnd[startIndex + len - 1]return {- start: { x: (startIndex % cols) + 1, y: startRow + Math.floor(startIndex / cols) + 1 },- end: { x: (endIndex % cols) + 1, y: startRow + Math.floor(endIndex / cols) + 1 }+ start: { x: (first % cols) + 1, y: p.startRow + Math.floor(first / cols) + 1 },+ end: { x: (last % cols) + 1, y: p.startRow + Math.floor(last / cols) + 1 }}}+/** Does paragraph cell `cell` fall inside the token at `startIndex..+len`? */+function tokenCovers(p: Paragraph, startIndex: number, len: number, cell: number): boolean {+ return len > 0 && cell >= p.cellStart[startIndex] && cell <= p.cellEnd[startIndex + len - 1]+}++/**+ * Among links resolved from OVERLAPPING candidates (a spaced path and its pieces), keep the first+ * in preference order and drop any later one that overlaps a kept one. Candidates arrive sorted by+ * start, longer first, so a spaced path that exists wins over its fragments.+ */+function dropShadowed<T extends { startIndex: number; len: number }>(found: T[]): T[] {+ const kept: T[] = []+ for (const f of found) {+ if (kept.some((k) => f.startIndex < k.startIndex + k.len && k.startIndex < f.startIndex + f.len))+ continue+ kept.push(f)+ }+ return kept+}+/** xterm link provider for file paths. Register once per terminal with a reachable filesystem. */export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILinkProvider {return {@@ -589,14 +583,16 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin}const cols = term.colsvoid Promise.all(- tokens.map(async (t): Promise<ILink | null> => {+ tokens.map(async (t): Promise<(ILink & { startIndex: number; len: number }) | null> => {const found = await findExistingPath(t.path, convention, deps)if (!found.found) return nullconst { abs, dir } = foundconst sink = deps.hoverSinkreturn {+ startIndex: t.startIndex,+ len: t.text.length,text: t.text,- range: tokenRange(logical.startRow, cols, t.startIndex, t.text.length),+ range: tokenRange(logical, cols, t.startIndex, t.text.length),activate: (event: MouseEvent) => {const intent = linkOpenIntent(event)if (intent === 'none') return@@ -619,7 +615,9 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin}})).then((links) => {- const real = links.filter((l): l is ILink => !!l)+ const real = dropShadowed(links.filter((l) => !!l)).map(+ ({ startIndex: _s, len: _l, ...link }): ILink => link+ )callback(real.length ? real : undefined)})}@@ -647,7 +645,7 @@ export function createUrlLinkProvider(const links = matchUrlTokens(logical.text).map((u): ILink => ({text: u.text,- range: tokenRange(logical.startRow, term.cols, u.startIndex, u.text.length),+ range: tokenRange(logical, term.cols, u.startIndex, u.text.length),activate: (event: MouseEvent) => {if (!(event.metaKey || event.ctrlKey)) returnhoverSink?.leave()@@ -763,7 +761,17 @@ export type LinkHit =| { kind: 'url'; url: string }/** `token` is the path as printed; `abs` its resolution against the LAUNCH cwd (null when that* cannot anchor it — a relative token on a cwd-less node — which the live cwd may still). */- | { kind: 'path'; token: string; abs: string | null }+ | {+ kind: 'path'+ token: string+ abs: string | null+ /** Shorter readings of the same span, to try in order when `token` does not exist — a spaced+ * path's pieces (`/usr/bin/env node` → `/usr/bin/env`). Absent when there are none. */+ alternatives?: string[]+ /** `token` is a bare filename (`foo.ts`): Cmd+click tries it, a right-click does not claim+ * it, since prose is full of words shaped like a filename. */+ bare?: true+ }/** What `linkAtCell` needs to turn text into a path: the cwd and dialect the file providers use. */export interface LinkHitDeps extends CwdSources {@@ -793,7 +801,7 @@ export function linkAtCell(if (!logical) return nullconst idx = (row - logical.startRow) * term.cols + colconst inRange = (startIndex: number, len: number): boolean =>- idx >= startIndex && idx < startIndex + len+ tokenCovers(logical, startIndex, len, idx)for (const u of matchUrlTokens(logical.text)) {if (inRange(u.startIndex, u.text.length)) return { kind: 'url', url: u.url }@@ -801,14 +809,39 @@ export function linkAtCell(if (!deps.fileEnabled()) return nullconst convention = deps.convention ? deps.convention() : { windows: deps.windows }if (!convention) return null- for (const t of matchFileTokens(logical.text, convention)) {- if (inRange(t.startIndex, t.text.length)) {- const abs = resolveFileToken(t.path, deps.getCwd(), convention)- // Unanchorable against the launch cwd is still a hit when a live cwd can be asked.- return abs || deps.getLiveCwd ? { kind: 'path', token: t.path, abs } : null- }+ // Every candidate under the cell, in preference order: the first is the hit, the rest its+ // fallbacks (the pieces of a spaced path that may not exist).+ const under = matchFileTokens(logical.text, convention).filter((t) =>+ inRange(t.startIndex, t.text.length)+ )+ const [t, ...others] = under+ if (!t) return null+ const abs = resolveFileToken(t.path, deps.getCwd(), convention)+ // Unanchorable against the launch cwd is still a hit when a live cwd can be asked.+ if (!abs && !deps.getLiveCwd) return null+ const hit: LinkHit = { kind: 'path', token: t.path, abs }+ if (others.length) hit.alternatives = others.map((o) => o.path)+ if (t.bare) hit.bare = true+ return hit+}++/** Try a hit's token, then its alternatives; the first that exists wins. `tried` accumulates+ * every absolute path looked at, for the not-found toast. */+export async function findExistingForHit(+ tokens: string[],+ find: (token: string) => Promise<PathResolution>+): Promise<PathResolution> {+ const tried: string[] = []+ const unverified: UnverifiedPath[] = []+ for (const token of tokens) {+ const r = await find(token)+ if (r.found) return r+ for (const p of r.tried) if (!tried.includes(p)) tried.push(p)+ // An unchecked reading of ANY alternative keeps the whole miss unverified: the host must not+ // say "not found" about a token one of whose readings could not be looked at.+ for (const u of r.unverified ?? []) if (!unverified.some((x) => x.abs === u.abs)) unverified.push(u)}- return null+ return unverified.length ? { found: false, tried, unverified } : { found: false, tried }}export interface LinkClickDeps extends LinkHitDeps {@@ -878,7 +911,9 @@ export function installLinkClickFallback(const convention = (deps.convention ? deps.convention() : { windows: deps.windows }) ?? {}const open =intent === 'system' ? (deps.openFileWithSystem ?? deps.activateFile) : deps.activateFile- void findExistingPath(hit.token, convention, deps).then((r) => {+ void findExistingForHit([hit.token, ...(hit.alternatives ?? [])], (token) =>+ findExistingPath(token, convention, deps)+ ).then((r) => {if (r.found) open(r.abs, r.dir)else deps.onMissing?.(hit.token, r)})@@ -929,6 +964,9 @@ export function installLinkContextMenu(if (ev.button !== 2) returnconst pos = bufferPosFromEvent(term, ev)pending = pos ? linkAtCell(term, pos.row, pos.col, deps) : null+ // A bare filename is not claimed: the press would be taken from tmux for a word that is most+ // likely prose, and the menu could only say "Not found".+ if (pending?.kind === 'path' && pending.bare) pending = nullif (pending) swallow(ev)}const onMouseUp = (ev: MouseEvent): void => {diff --git a/src/renderer/terminal/file-links.unverifiable.test.ts b/src/renderer/terminal/file-links.unverifiable.test.tsindex 802dd4e03..34bf63fae 100644--- a/src/renderer/terminal/file-links.unverifiable.test.ts+++ b/src/renderer/terminal/file-links.unverifiable.test.ts@@ -4,11 +4,13 @@import { describe, expect, it } from 'vitest'import {fileMissMessage,+ findExistingForHit,findExistingPath,makeDirListingLookup,missingFileMessage,unverifiableFileMessage,- type PathLookup+ type PathLookup,+ type PathResolution} from './file-links'type Entry = { name: string; dir: boolean }@@ -167,3 +169,22 @@ describe('the Cmd/Ctrl+click toast', () => {)})})++describe('findExistingForHit keeps an unchecked alternative unverified', () => {+ it('a miss where one reading could not be looked at is not a plain "not found"', async () => {+ const find = async (token: string): Promise<PathResolution> =>+ token === 'a b/c.ts'+ ? { found: false, tried: ['/p/a b/c.ts'], unverified: [{ abs: '/p/a b/c.ts', reason: 'ssh down' }] }+ : { found: false, tried: ['/p/' + token] }+ expect(await findExistingForHit(['a b/c.ts', 'b/c.ts'], find)).toEqual({+ found: false,+ tried: ['/p/a b/c.ts', '/p/b/c.ts'],+ unverified: [{ abs: '/p/a b/c.ts', reason: 'ssh down' }]+ })+ })++ it('a verified miss on every reading stays a plain miss', async () => {+ const find = async (token: string): Promise<PathResolution> => ({ found: false, tried: ['/p/' + token] })+ expect(await findExistingForHit(['x', 'y'], find)).toEqual({ found: false, tried: ['/p/x', '/p/y'] })+ })+})diff --git a/src/renderer/terminal/file-links.windows.test.ts b/src/renderer/terminal/file-links.windows.test.tsindex bd1410487..c755c4ff9 100644--- a/src/renderer/terminal/file-links.windows.test.ts+++ b/src/renderer/terminal/file-links.windows.test.ts@@ -136,14 +136,47 @@ describe('resolving Windows tokens', () => {})})-describe('a path containing a space, which is not supported', () => {- it('matches only up to the space, rather than swallowing the sentence', () => {- // `C:\Program Files\...` is everywhere on Windows, but an unquoted path in terminal output- // gives no way to tell where it ends. Allowing spaces made the matcher take the rest of the- // line; the existence check would then reject it, so a spaced path would never have linked- // while quietly breaking the tokens around it. Documented parity with the POSIX matcher.+describe('a path containing a space', () => {+ it('is offered whole, with its space-free pieces as fallbacks, and stops before the sentence', () => {+ // `C:\Program Files\...` is everywhere on Windows. The spaced reading ends at the word that+ // completes a file name (`a.exe`), so `crashed` is never swallowed; the pieces stay candidates+ // because only the existence check can say which reading is real.const got = matchFileTokens(String.raw`C:\Program Files\app\a.exe crashed`, WIN)- expect(got.map((t) => t.path)).toEqual([String.raw`C:\Program`, String.raw`Files\app\a.exe`])+ expect(got.map((t) => t.path)).toEqual([+ String.raw`C:\Program Files\app\a.exe`,+ String.raw`C:\Program`,+ String.raw`Files\app\a.exe`+ ])+ })++ it('keeps a parenthesised segment inside a spaced path', () => {+ const got = matchFileTokens(String.raw`at C:\Program Files (x86)\tool\run.exe:4`, WIN)+ expect(got[0]).toMatchObject({+ path: String.raw`C:\Program Files (x86)\tool\run.exe`,+ line: 4+ })+ })+})++describe('Unicode, brackets, bare names and file URIs in the Windows dialect', () => {+ it('keeps Unicode letters and route brackets in a segment', () => {+ expect(paths(String.raw`wrote C:\veri\çıktı\aktarım.sql`)).toEqual([+ String.raw`C:\veri\çıktı\aktarım.sql`+ ])+ expect(paths(String.raw`app\(shop)\[id]\page.tsx`)).toEqual([String.raw`app\(shop)\[id]\page.tsx`])+ })++ it('offers a bare filename, and not the leaf of a Windows path read as POSIX', () => {+ expect(matchFileTokens('see README.md', WIN)).toEqual([+ { text: 'README.md', startIndex: 4, path: 'README.md', line: undefined, bare: true }+ ])+ expect(matchFileTokens(String.raw`C:\Users\me\a.ts`)).toEqual([])+ })++ it('decodes a drive-qualified file URI and refuses a POSIX-rooted one', () => {+ expect(paths('open file:///C:/Users/me/My%20Docs/a.md now')).toEqual(['C:/Users/me/My Docs/a.md'])+ expect(paths('open file:///home/me/a.md')).toEqual([])+ expect(resolveFileToken('C:/Users/me/My Docs/a.md', CWD, WIN)).toBe('C:/Users/me/My Docs/a.md')})})diff --git a/src/renderer/terminal/link-menu.ts b/src/renderer/terminal/link-menu.tsindex 4eabd2f7f..7a3afc80e 100644--- a/src/renderer/terminal/link-menu.ts+++ b/src/renderer/terminal/link-menu.ts@@ -15,7 +15,7 @@ import type { MenuItem } from '../components/ContextMenu'import type { DownloadRoute } from '../lib/download'import { downloadMenuEntries } from '../lib/filesNode'import { tidySeparators } from '../lib/tidySeparators'-import type { LinkHit, PathResolution } from './file-links'+import { findExistingForHit, type LinkHit, type PathResolution } from './file-links'/** What a right-click resolved to, once a path's existence is known. */export type LinkMenuTarget =@@ -82,7 +82,7 @@ export async function resolveLinkTarget(if (hit.kind === 'url') return { kind: 'url', url: hit.url }const missing: LinkMenuTarget = { kind: 'missing', abs: hit.abs ?? hit.token }try {- const r = await find(hit.token)+ const r = await findExistingForHit([hit.token, ...(hit.alternatives ?? [])], find)if (r.found) return { kind: 'file', abs: r.abs, dir: r.dir }const u = r.unverified?.[0]return u ? { kind: 'unverified', abs: u.abs, reason: u.reason } : missing