Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(open-knowledge): clickable links in the terminal (PRD-7327) (#2573)

serafin-garcia6860de89d15f
diff --git a/.changeset/clickable-terminal-links.md b/.changeset/clickable-terminal-links.md
new file mode 100644
index 000000000..1020e01b7
--- /dev/null
+++ b/.changeset/clickable-terminal-links.md
@@ -0,0 +1,5 @@
+---
+"@inkeep/open-knowledge": minor
+---
+
+Links in the terminal are now clickable. URLs open in your browser (including explicit OSC 8 hyperlinks from tools like `ls --hyperlink`), and file paths in output — absolute, relative, or with a trailing `:line:col` — become clickable when they point to something inside your project: Markdown documents open in the editor, folders open to their overview, and other files open in the OS default app (revealed in Finder when the type can't be opened directly). Only in-project paths that actually exist are highlighted, so there are no dead links. A file path pointing outside your project asks first with a "this file is outside your project — reveal in Finder?" prompt. Links inside a full-screen terminal app that handles its own clicks (like the Claude TUI) are left to that app, so they open exactly once.
diff --git a/packages/app/package.json b/packages/app/package.json
index a01076838..f2acbb7a9 100644
--- a/packages/app/package.json
+++ b/packages/app/package.json
@@ -51,7 +51,7 @@
{
"name": "all JS chunks combined (gzipped)",
"path": "dist/assets/*.js",
- "limit": "3.07 MB",
+ "limit": "3.08 MB",
"gzip": true,
"running": false
},
diff --git a/packages/app/src/components/TerminalPanel.dom.test.tsx b/packages/app/src/components/TerminalPanel.dom.test.tsx
index f7ae6b66a..6f0bfcef0 100644
--- a/packages/app/src/components/TerminalPanel.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.dom.test.tsx
@@ -27,7 +27,14 @@ class MockFitAddon {
}
}
class MockWebglAddon {}
-class MockWebLinksAddon {}
+// Captures the click handler the panel passes to WebLinksAddon so the test can
+// assert URL activation routes through the bridge.
+let lastWebLinksHandler: ((event: MouseEvent, uri: string) => void) | null = null;
+class MockWebLinksAddon {
+ constructor(handler?: (event: MouseEvent, uri: string) => void) {
+ lastWebLinksHandler = handler ?? null;
+ }
+}
class MockUnicode11Addon {}
class MockTerminal {
@@ -61,6 +68,38 @@ class MockTerminal {
// DOM) → the handler's viewport-center fallback; the pointer-mapping test
// assigns a real element.
element: HTMLElement | undefined = undefined;
+ // Text the mocked buffer returns for any row — tests set it, then drive the
+ // captured link provider to exercise file-path detection + click routing.
+ lineText = '';
+ // Optional wrapped-line fixture: each entry is one buffer row; rows after the
+ // first carry `isWrapped` so the provider stitches them into one logical line.
+ lineRows: string[] | null = null;
+ get buffer() {
+ return {
+ active: {
+ getLine: (index: number) => {
+ if (this.lineRows) {
+ const t = this.lineRows[index];
+ if (t === undefined) return undefined;
+ return { translateToString: (_trim?: boolean) => t, isWrapped: index > 0 };
+ }
+ return { translateToString: (_trim?: boolean) => this.lineText, isWrapped: false };
+ },
+ },
+ };
+ }
+ linkProvider: {
+ provideLinks(line: number, cb: (links: unknown[] | undefined) => void): void;
+ } | null = null;
+ linkProviderDispose = mock(() => {});
+ registerLinkProvider = mock(
+ (provider: {
+ provideLinks(line: number, cb: (links: unknown[] | undefined) => void): void;
+ }) => {
+ this.linkProvider = provider;
+ return { dispose: this.linkProviderDispose };
+ },
+ );
onDataCb: ((d: string) => void) | null = null;
keyHandler: ((e: KeyboardEvent) => boolean) | null = null;
wheelHandler: ((e: WheelEvent) => boolean) | null = null;
@@ -173,6 +212,20 @@ function makeBridge(
const unsubData = mock(() => {});
const unsubExit = mock(() => {});
const openExternal = mock(async (_url: string) => {});
+ const openAsset = mock(
+ async (_relPath: string): Promise<{ ok: true } | { ok: false; reason: string }> => ({
+ ok: true,
+ }),
+ );
+ const revealAsset = mock(async (_relPath: string) => ({ ok: true }) as { ok: true });
+ const revealExternal = mock(
+ async (_absPath: string) =>
+ ({ ok: true, outcome: 'revealed' }) as { ok: true; outcome: 'revealed' },
+ );
+ const checkTargetExists = mock(
+ async (_req: { projectPath: string; kind: 'doc' | 'folder'; path: string }) =>
+ 'exists' as const,
+ );
const rewireClaudeMcp = mock(async () => preflight);
const terminal = {
create: mock(async () => createResult),
@@ -196,14 +249,19 @@ function makeBridge(
return {
bridge: {
terminal,
- shell: { openExternal },
- config: { e2eSmoke: false },
+ shell: { openExternal, openAsset, revealAsset, revealExternal },
+ project: { checkTargetExists },
+ config: { e2eSmoke: false, projectPath: '/Users/me/project' },
// Stand in for Electron `webUtils.getPathForFile`: a dropped File resolves
// to a deterministic on-disk path so the drop→input wiring is assertable.
getPathForFile: (file: File) => `/dropped/${file.name}`,
} as unknown as OkDesktopBridge,
terminal,
openExternal,
+ openAsset,
+ revealAsset,
+ revealExternal,
+ checkTargetExists,
rewireClaudeMcp,
unsubData,
unsubExit,
@@ -1251,4 +1309,193 @@ describe('TerminalPanel', () => {
expect(kill).not.toHaveBeenCalledWith('pty-2');
await waitFor(() => expect(screen.queryByRole('alert')).toBeNull());
});
+
+ describe('clickable links', () => {
+ // Drive the captured file-link provider for a buffer row (1-based; defaults
+ // to the first) and resolve with the links it emits (async — snapshot
+ // fast-path or probe). Pass a continuation row to exercise the backward walk.
+ function provide(
+ term: MockTerminal,
+ bufferLine = 1,
+ ): Promise<Array<{ activate: (e: MouseEvent, t: string) => void; text: string }>> {
+ return new Promise((resolve) => {
+ term.linkProvider?.provideLinks(bufferLine, (links) =>
+ resolve(
+ (links ?? []) as Array<{ activate: (e: MouseEvent, t: string) => void; text: string }>,
+ ),
+ );
+ });
+ }
+
+ test('routes URL clicks (WebLinksAddon + OSC 8) through the bridge', async () => {
+ const { bridge, openExternal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm).not.toBeNull());
+
+ // WebLinksAddon received an explicit handler (not the default window.open
+ // bounce); it opens the URL via the scheme-allowlisted bridge call.
+ expect(lastWebLinksHandler).not.toBeNull();
+ lastWebLinksHandler?.({} as MouseEvent, 'https://example.com');
+ expect(openExternal).toHaveBeenCalledWith('https://example.com');
+
+ // OSC 8 explicit hyperlinks route the same way via Terminal.linkHandler.
+ const linkHandler = lastTerm?.options.linkHandler as
+ | { activate: (e: MouseEvent, uri: string) => void }
+ | undefined;
+ linkHandler?.activate({} as MouseEvent, 'https://osc8.example');
+ expect(openExternal).toHaveBeenCalledWith('https://osc8.example');
+ });
+
+ test('registers a file-path link provider once the panel mounts', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ });
+
+ test('clicking a markdown path navigates the editor to the doc', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.lineText = 'edited notes/a.md';
+
+ const [link] = await provide(term);
+ expect(link?.text).toBe('notes/a.md');
+ window.location.hash = '';
+ link?.activate({} as MouseEvent, link.text);
+ expect(window.location.hash).toBe('#/notes/a');
+ });
+
+ test('stitches a path wrapped across buffer rows and navigates it', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.cols = 19;
+ // The path straddles the wrap: row 0 ends mid-path, row 1 (isWrapped)
+ // finishes it. A single-row read would see only `docs/guide/very` and miss.
+ term.lineRows = ['see docs/guide/very', '-long.md'];
+
+ const [link] = await provide(term);
+ expect(link?.text).toBe('docs/guide/very-long.md');
+ window.location.hash = '';
+ link?.activate({} as MouseEvent, link.text);
+ expect(window.location.hash).toBe('#/docs/guide/very-long');
+ });
+
+ test('reconstructs a wrapped path when its continuation row is hovered (backward walk)', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.cols = 19;
+ term.lineRows = ['see docs/guide/very', '-long.md'];
+ // Hover the CONTINUATION row (row 2): readLogicalLine must walk BACK to the
+ // logical start to rebuild the full path, not just read the hovered tail.
+ const [link] = await provide(term, 2);
+ expect(link?.text).toBe('docs/guide/very-long.md');
+ window.location.hash = '';
+ link?.activate({} as MouseEvent, link.text);
+ expect(window.location.hash).toBe('#/docs/guide/very-long');
+ });
+
+ test('clicking a trailing-slash folder navigates the editor to that folder', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ // A trailing slash classifies the path as a folder (not a doc/asset).
+ term.lineText = 'cd packages/app/';
+
+ const [link] = await provide(term);
+ expect(link?.text).toBe('packages/app');
+ window.location.hash = '';
+ link?.activate({} as MouseEvent, link.text);
+ expect(window.location.hash).toBe('#/packages/app/');
+ });
+
+ test('a non-blocked openAsset failure surfaces silently — no reveal fallback', async () => {
+ const { bridge, openAsset, revealAsset } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.lineText = 'wrote data/x.csv';
+
+ const [link] = await provide(term);
+ // Only `extension-blocked` escalates to reveal-in-Finder; a plain miss
+ // (e.g. the file vanished between probe and click) fails silently.
+ openAsset.mockResolvedValueOnce({ ok: false, reason: 'not-found' });
+ link?.activate({} as MouseEvent, link.text);
+ await waitFor(() => expect(openAsset).toHaveBeenCalledWith('data/x.csv'));
+ expect(revealAsset).not.toHaveBeenCalled();
+ });
+
+ test('disposes the file-link provider on unmount', async () => {
+ const { bridge } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ const { unmount } = render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ unmount();
+ expect(term.linkProviderDispose).toHaveBeenCalledTimes(1);
+ });
+
+ test('clicking a non-doc path OS-delegates via openAsset, revealing on block', async () => {
+ const { bridge, openAsset, revealAsset } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.lineText = 'wrote data/x.csv';
+
+ const [link] = await provide(term);
+ expect(link?.text).toBe('data/x.csv');
+ link?.activate({} as MouseEvent, link.text);
+ await waitFor(() => expect(openAsset).toHaveBeenCalledWith('data/x.csv'));
+
+ // An executable-blocked type falls back to reveal-in-Finder.
+ openAsset.mockResolvedValueOnce({ ok: false, reason: 'extension-blocked' });
+ link?.activate({} as MouseEvent, link.text);
+ await waitFor(() => expect(revealAsset).toHaveBeenCalledWith('data/x.csv'));
+ });
+
+ test('clicking an out-of-project absolute path routes the reveal-external dialog', async () => {
+ const { bridge, revealExternal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ // Bridge projectPath is /Users/me/project, so this absolute path is external.
+ term.lineText = 'built /tmp/out/report.pdf';
+ const [link] = await provide(term);
+ expect(link?.text).toBe('/tmp/out/report.pdf');
+ link?.activate({} as MouseEvent, link.text);
+ await waitFor(() => expect(revealExternal).toHaveBeenCalledWith('/tmp/out/report.pdf'));
+ });
+
+ test('defers URL clicks to a mouse-tracking TUI (no double-open with claude)', async () => {
+ const { bridge, openExternal } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm).not.toBeNull());
+ // A full-screen TUI enabled mouse tracking — it owns the click and opens
+ // the link itself, so the terminal must not also open it.
+ (lastTerm as MockTerminal).modes.mouseTrackingMode = 'any';
+ lastWebLinksHandler?.({} as MouseEvent, 'https://example.com');
+ const osc8 = lastTerm?.options.linkHandler as {
+ activate: (e: MouseEvent, u: string) => void;
+ };
+ osc8.activate({} as MouseEvent, 'https://example.com');
+ expect(openExternal).not.toHaveBeenCalled();
+ });
+
+ test('still opens FILE clicks inside a mouse-tracking TUI (only URLs defer)', async () => {
+ const { bridge, openAsset } = makeBridge({ ok: true, ptyId: 'pty-1' });
+ render(<TerminalPanel bridge={bridge} />);
+ await waitFor(() => expect(lastTerm?.linkProvider).toBeTruthy());
+ const term = lastTerm as MockTerminal;
+ term.lineText = 'wrote data/x.csv';
+ const [link] = await provide(term);
+ // A TUI owns the mouse, but it doesn't open file paths — the terminal must.
+ term.modes.mouseTrackingMode = 'any';
+ link?.activate({} as MouseEvent, link.text);
+ await waitFor(() => expect(openAsset).toHaveBeenCalledWith('data/x.csv'));
+ });
+ });
});
diff --git a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
index e7bc96cc9..1aa52aabb 100644
--- a/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
+++ b/packages/app/src/components/TerminalPanel.launch.dom.test.tsx
@@ -60,6 +60,13 @@ class MockTerminal {
// Production attaches a wheel handler at mount; these launch tests never fire
// wheel events, so the no-op presence is all that's needed to avoid throwing.
attachCustomWheelEventHandler = mock(() => {});
+ // The panel registers a file-path link provider at mount; these launch tests
+ // never hover a link, so a disposable-returning stub (plus an empty buffer for
+ // the provider's readLine) is all that's needed to avoid throwing on mount.
+ registerLinkProvider = mock(() => ({ dispose() {} }));
+ get buffer() {
+ return { active: { getLine: () => ({ translateToString: () => '' }) } };
+ }
constructor(options: Record<string, unknown>) {
this.options = options;
}
diff --git a/packages/app/src/components/TerminalPanel.tsx b/packages/app/src/components/TerminalPanel.tsx
index 9590e2476..07506bd39 100644
--- a/packages/app/src/components/TerminalPanel.tsx
+++ b/packages/app/src/components/TerminalPanel.tsx
@@ -16,12 +16,16 @@ import { use, useEffect, useRef, useState } from 'react';
import { ConfigContext } from '@/lib/config-context';
import type { ClaudeReadiness, OkDesktopBridge } from '@/lib/desktop-bridge-types';
import { cn } from '@/lib/utils';
+import { getPageListCache } from '../editor/page-list-cache';
+import { filePathToDocName, hashFromDocName, hashFromFolderPath } from '../lib/doc-hash';
import { ClaudeReadinessBanner } from './ClaudeReadinessBanner';
import type { TerminalLaunchIntent } from './EditorPane';
import { filesFromExternalDrop, isExternalFileDrag } from './file-tree-adapter';
import { TerminalCliMissingBanner } from './TerminalCliMissingBanner';
import { type TerminalExitInfo, TerminalExitNotice } from './TerminalExitNotice';
import { TerminalRefusalNotice } from './TerminalRefusalNotice';
+import { createTerminalFileLinkProvider } from './terminal-link-provider';
+import { createRecentOpenGuard, type TerminalLinkTarget } from './terminal-links';
import { createSameFrameRepaint } from './terminal-render-flush';
import { createResizeThrottle } from './terminal-resize-throttle';
import { xtermThemeForMode } from './terminal-theme';
@@ -224,6 +228,7 @@ function TerminalSession({
let unsubData: (() => void) | undefined;
let unsubExit: (() => void) | undefined;
let titleDisposable: { dispose(): void } | undefined;
+ let linkProviderDisposable: { dispose(): void } | undefined;
let observer: ResizeObserver | undefined;
let canvasPixelObserver: ResizeObserver | undefined;
let ptyResizeThrottle: ReturnType<typeof createResizeThrottle> | undefined;
@@ -237,6 +242,21 @@ function TerminalSession({
// on — its assertions read the .xterm-accessibility tree.
const screenReaderModeAtMount =
bridge.config.e2eSmoke === true || (bridge.accessibility?.isScreenReaderActive() ?? true);
+ const recentOpen = createRecentOpenGuard();
+ const openUrl = (uri: string) => {
+ // Defer while a full-screen TUI owns the mouse: the click is delivered to
+ // the app as a mouse report, so the terminal must not also open the link.
+ // The `claude` TUI additionally opens URLs itself, which is the concrete
+ // double-open this prevents. (Tradeoff: a URL printed inside a mouse-mode
+ // TUI that does NOT open links itself — e.g. `less -R` — isn't
+ // terminal-clickable; that matches how terminals gate clicks on mouse
+ // apps.) `undefined` (pre-mount) also defers — fail closed.
+ if (termRef.current?.modes.mouseTrackingMode !== 'none') return;
+ // Collapse the OSC 8 `linkHandler` + `WebLinksAddon` pair for the same URL
+ // (see createRecentOpenGuard).
+ if (recentOpen(uri, Date.now())) return;
+ void bridge.shell.openExternal(uri);
+ };
const term = new Terminal({
screenReaderMode: screenReaderModeAtMount,
minimumContrastRatio: 4.5,
@@ -258,6 +278,13 @@ function TerminalSession({
// tuned toward native terminals like Ghostty. Mouse-mode TUIs use the
// separate accumulator below, scaled by its own `sensitivity`.
scrollSensitivity: 3,
+ // OSC 8 explicit hyperlinks (`ls --hyperlink`, agent tooling). xterm core
+ // renders them; route activation to the OS browser. `allowNonHttpProtocols`
+ // stays off (default), so only http(s) URIs reach here — nothing untrusted
+ // is handed to `openExternal` beyond what its scheme allowlist permits.
+ linkHandler: {
+ activate: (_event, uri) => openUrl(uri),
+ },
theme: xtermThemeForMode(initialResolvedThemeRef.current),
});
termRef.current = term;
@@ -265,10 +292,98 @@ function TerminalSession({
term.loadAddon(fit);
term.loadAddon(new Unicode11Addon());
term.unicode.activeVersion = '11';
- term.loadAddon(new WebLinksAddon());
+ // Implicit http(s) URL detection. Route clicks explicitly to the OS browser
+ // (scheme-allowlisted in main) instead of relying on xterm's default
+ // window.open → asset-safety-net bounce.
+ term.loadAddon(new WebLinksAddon((_event, uri) => openUrl(uri)));
term.open(container);
+ // Clickable file paths: a custom provider detects POSIX path tokens in
+ // hovered rows, validates them against the project (page-list cache →
+ // checkTargetExists), and routes clicks — OK docs open in the editor, other
+ // files OS-delegate. Disposed on teardown alongside the terminal.
+ const activateFileLink = (target: TerminalLinkTarget) => {
+ // NOTE: unlike `openUrl`, file-path links are NOT gated on mouse tracking.
+ // A TUI like the `claude` TUI opens URLs itself (hence the URL deferral to
+ // avoid a double-open) but does NOT open file paths, so the terminal must
+ // still handle a file-path click even while that TUI owns the mouse.
+ switch (target.kind) {
+ case 'doc':
+ window.location.hash = hashFromDocName(filePathToDocName(target.relPath));
+ return;
+ case 'folder':
+ window.location.hash = hashFromFolderPath(target.relPath);
+ return;
+ case 'external':
+ // A path outside the project — main pops a "reveal in Finder?" dialog
+ // (the confirmation is the security gate for touching an out-of-project
+ // location) and reveals on confirm.
+ void bridge.shell
+ .revealExternal(target.absPath)
+ .catch((err) => console.warn('[terminal] revealExternal failed:', err));
+ return;
+ case 'asset':
+ void bridge.shell
+ .openAsset(target.relPath)
+ .then((result) => {
+ if (result.ok) return;
+ // `extension-blocked` means the file exists but OK refuses to hand a
+ // scripted/executable type to the OS opener — reveal it instead so
+ // the click isn't a silent no-op (mirrors dispatchAssetClick).
+ if (result.reason === 'extension-blocked') {
+ void bridge.shell
+ .revealAsset(target.relPath)
+ .catch((err) => console.warn('[terminal] revealAsset failed:', err));
+ return;
+ }
+ console.warn('[terminal] openAsset refused:', result.reason);
+ })
+ .catch((err) => console.warn('[terminal] openAsset failed:', err));
+ return;
+ default: {
+ // Exhaustiveness: a new TerminalLinkKind must add a case above.
+ const _never: never = target;
+ return _never;
+ }
+ }
+ };
+ linkProviderDisposable = term.registerLinkProvider(
+ createTerminalFileLinkProvider({
+ projectPath: bridge.config.projectPath,
+ readLogicalLine: (bufferLineNumber) => {
+ const buf = term.buffer.active;
+ const idx = bufferLineNumber - 1;
+ if (!buf.getLine(idx)) return undefined;
+ // Stitch the wrapped logical line: a row longer than `term.cols` is
+ // stored across multiple buffer rows, continuations flagged
+ // `isWrapped`. Walk back to the logical start, forward to the end, and
+ // join each row at full width (`translateToString(false)` pads to
+ // `cols`) so the joined offsets map cleanly back to buffer cells. A
+ // single row that reads just the hovered line would split a long path
+ // (an absolute path in a narrow docked terminal) into non-resolving
+ // fragments — the bug this fixes.
+ let start = idx;
+ while (start > 0 && buf.getLine(start)?.isWrapped) start--;
+ let end = idx;
+ while (buf.getLine(end + 1)?.isWrapped) end++;
+ let text = '';
+ for (let row = start; row <= end; row++) {
+ text += buf.getLine(row)?.translateToString(false) ?? '';
+ }
+ return { text, startLine: start + 1, cols: term.cols };
+ },
+ getSnapshot: getPageListCache,
+ checkTargetExists: (kind, path) =>
+ bridge.project.checkTargetExists({
+ projectPath: bridge.config.projectPath,
+ kind,
+ path,
+ }),
+ onActivate: activateFileLink,
+ }),
+ );
+
// Under the Electron smoke suite (main injects `--ok-e2e-smoke=1`, surfaced
// as `config.e2eSmoke`), skip the WebGL canvas renderer and use xterm's DOM
// renderer. The canvas paints to a <canvas> the DOM-based smoke assertions
@@ -752,6 +867,7 @@ function TerminalSession({
unsubData?.();
unsubExit?.();
titleDisposable?.dispose();
+ linkProviderDisposable?.dispose();
term.dispose();
if (ptyId)
void bridge.terminal
diff --git a/packages/app/src/components/terminal-link-provider.test.ts b/packages/app/src/components/terminal-link-provider.test.ts
new file mode 100644
index 000000000..4044f3d58
--- /dev/null
+++ b/packages/app/src/components/terminal-link-provider.test.ts
@@ -0,0 +1,189 @@
+import { describe, expect, mock, test } from 'bun:test';
+import type { ILink, ILinkProvider } from '@xterm/xterm';
+import type { CheckTargetExistsResult } from '@/lib/desktop-bridge-types';
+import type { PageListCacheSnapshot } from '../editor/page-list-cache';
+import {
+ createTerminalFileLinkProvider,
+ type TerminalFileLinkProviderDeps,
+} from './terminal-link-provider';
+import type { TerminalLinkTarget } from './terminal-links';
+
+const PROJECT = '/Users/me/project';
+
+function snapshot(partial: Partial<PageListCacheSnapshot> = {}): PageListCacheSnapshot {
+ return { pages: new Set(), folderPaths: new Set(), pagesBySlug: new Map(), ...partial };
+}
+
+function makeProvider(overrides: Partial<TerminalFileLinkProviderDeps> = {}) {
+ const activated: TerminalLinkTarget[] = [];
+ const checkTargetExists = mock(
+ async (_kind: 'doc' | 'folder', _path: string): Promise<CheckTargetExistsResult> => 'exists',
+ );
+ const deps: TerminalFileLinkProviderDeps = {
+ projectPath: PROJECT,
+ readLogicalLine: () => undefined,
+ getSnapshot: () => null,
+ checkTargetExists,
+ onActivate: (t) => activated.push(t),
+ ...overrides,
+ };
+ return { provider: createTerminalFileLinkProvider(deps), activated, checkTargetExists };
+}
+
+/** A single-row logical line (no wrapping): the whole text sits on `bufferLine`. */
+function row(text: string): TerminalFileLinkProviderDeps['readLogicalLine'] {
+ return (bufferLine: number) => ({ text, startLine: bufferLine, cols: 80 });
+}
+
+/** Drive the pull-model `provideLinks` and resolve with the emitted links. */
+function provide(provider: ILinkProvider, line: number): Promise<ILink[] | undefined> {
+ return new Promise((resolve) => provider.provideLinks(line, resolve));
+}
+
+describe('createTerminalFileLinkProvider', () => {
+ test('returns a link for an existing path with a correct 1-based range', async () => {
+ const { provider } = makeProvider({ readLogicalLine: row('see src/foo.ts here') });
+ const links = await provide(provider, 3);
+ expect(links).toHaveLength(1);
+ const link = links?.[0];
+ expect(link?.text).toBe('src/foo.ts');
+ // "see " = 4 chars → 0-based [4,14) → 1-based start.x=5, end.x=14, y=line.
+ expect(link?.range).toEqual({ start: { x: 5, y: 3 }, end: { x: 14, y: 3 } });
+ });
+
+ test('activating a markdown path routes a doc target', async () => {
+ const { provider, activated } = makeProvider({ readLogicalLine: row('edited notes/a.md') });
+ const links = await provide(provider, 1);
+ links?.[0]?.activate({} as MouseEvent, links[0].text);
+ expect(activated).toEqual([{ kind: 'doc', relPath: 'notes/a.md' }]);
+ });
+
+ test('activating a non-doc path routes an asset target', async () => {
+ const { provider, activated } = makeProvider({ readLogicalLine: row('wrote data/x.csv') });
+ const links = await provide(provider, 1);
+ links?.[0]?.activate({} as MouseEvent, links[0].text);
+ expect(activated[0]).toEqual({ kind: 'asset', relPath: 'data/x.csv' });
+ });
+
+ test('links an out-of-project absolute path as external, without any probe', async () => {
+ const { provider, activated, checkTargetExists } = makeProvider({
+ readLogicalLine: row('built /tmp/out/report.pdf'),
+ });
+ const links = await provide(provider, 1);
+ expect(links).toHaveLength(1);
+ // External paths are optimistic — no project-scoped existence probe fires.
+ expect(checkTargetExists).not.toHaveBeenCalled();
+ links?.[0]?.activate({} as MouseEvent, links[0].text);
+ expect(activated[0]).toEqual({ kind: 'external', absPath: '/tmp/out/report.pdf' });
+ });
+
+ test('does not link a path the probe reports missing', async () => {
+ const { provider } = makeProvider({
+ readLogicalLine: row('missing gone/file.md'),
+ checkTargetExists: async () => 'missing',
+ });
+ expect(await provide(provider, 1)).toBeUndefined();
+ });
+
+ test('does not link a relative path that escapes the project (ambiguous once cd-ed)', async () => {
+ // A relative `..`-escape is ambiguous once the shell cd-s, so it stays
+ // non-clickable — unlike an out-of-project ABSOLUTE path (covered above),
+ // which links as `external`.
+ const { provider, checkTargetExists } = makeProvider({
+ readLogicalLine: row('cat ../../etc/passwd.md'),
+ });
+ expect(await provide(provider, 1)).toBeUndefined();
+ expect(checkTargetExists).not.toHaveBeenCalled();
+ });
+
+ test('resolves known content from the snapshot without any probe', async () => {
+ const { provider, checkTargetExists } = makeProvider({
+ readLogicalLine: row('open guides/setup.md'),
+ getSnapshot: () => snapshot({ pages: new Set(['guides/setup']) }),
+ });
+ const links = await provide(provider, 1);
+ expect(links).toHaveLength(1);
+ expect(checkTargetExists).not.toHaveBeenCalled();
+ });
+
+ test('caches probe results across hovers of the same path', async () => {
+ const { provider, checkTargetExists } = makeProvider({ readLogicalLine: row('x src/a.ts') });
+ await provide(provider, 1);
+ await provide(provider, 1);
+ expect(checkTargetExists).toHaveBeenCalledTimes(1);
+ });
+
+ test('returns undefined for a blank line', async () => {
+ const { provider } = makeProvider({ readLogicalLine: row('') });
+ expect(await provide(provider, 1)).toBeUndefined();
+ });
+
+ test('honors the per-line link cap', async () => {
+ const line = Array.from({ length: 8 }, (_, i) => `dir/f${i}.md`).join(' ');
+ const { provider, checkTargetExists } = makeProvider({
+ readLogicalLine: row(line),
+ maxLinksPerLine: 3,
+ });
+ const links = await provide(provider, 1);
+ expect(links).toHaveLength(3);
+ expect(checkTargetExists).toHaveBeenCalledTimes(3);
+ });
+
+ test('a probe failure fails safe (no link)', async () => {
+ const { provider } = makeProvider({
+ readLogicalLine: row('x src/a.ts'),
+ checkTargetExists: async () => {
+ throw new Error('ipc down');
+ },
+ });
+ expect(await provide(provider, 1)).toBeUndefined();
+ });
+
+ test('maps a path that wraps across rows to a multi-row range', async () => {
+ // A logical line reconstructed from wrapped buffer rows: `cols` is narrow, so
+ // the path crosses the wrap boundary. The emitted range must span rows —
+ // start.y != end.y — which is how a long/absolute path underlines when a
+ // docked terminal wraps it (the single-row read that regressed this before
+ // only ever saw a truncated fragment).
+ const { provider } = makeProvider({
+ readLogicalLine: () => ({ text: 'see docs/guide/very-long.md end', startLine: 1, cols: 20 }),
+ });
+ const links = await provide(provider, 2); // hovered on the continuation row
+ expect(links).toHaveLength(1);
+ expect(links?.[0]?.text).toBe('docs/guide/very-long.md');
+ // path at [4,27): start cell (4 → col 5, row 1); last char idx 26 → col 7, row 2.
+ expect(links?.[0]?.range).toEqual({ start: { x: 5, y: 1 }, end: { x: 7, y: 2 } });
+ });
+
+ test('a slash-bearing directory without a trailing slash falls back to a folder link', async () => {
+ // `packages/app` (no trailing slash, no extension) classifies as an asset, so
+ // the file probe (`checkTargetExists('doc')` → isFile) misses on a real
+ // directory. The provider retries as a folder rather than dropping the link.
+ const checkTargetExists = mock(
+ async (kind: 'doc' | 'folder'): Promise<CheckTargetExistsResult> =>
+ kind === 'folder' ? 'exists' : 'missing',
+ );
+ const { provider, activated } = makeProvider({
+ readLogicalLine: row('cd packages/app now'),
+ checkTargetExists,
+ });
+ const links = await provide(provider, 1);
+ expect(links).toHaveLength(1);
+ links?.[0]?.activate({} as MouseEvent, links[0].text);
+ expect(activated[0]).toEqual({ kind: 'folder', relPath: 'packages/app' });
+ // Probed as a file first, then as a folder — the fallback, not a snapshot hit.
+ expect(checkTargetExists.mock.calls.map((c) => c[0])).toEqual(['doc', 'folder']);
+ });
+
+ test('a missing path WITH an extension does not waste a folder retry', async () => {
+ // The folder fallback is gated on extension-less tokens; `gone/file.md` is a
+ // file by shape, so a miss is final (one probe, no folder retry).
+ const checkTargetExists = mock(async (): Promise<CheckTargetExistsResult> => 'missing');
+ const { provider } = makeProvider({
+ readLogicalLine: row('open gone/file.md'),
+ checkTargetExists,
+ });
+ expect(await provide(provider, 1)).toBeUndefined();
+ expect(checkTargetExists).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/packages/app/src/components/terminal-link-provider.ts b/packages/app/src/components/terminal-link-provider.ts
new file mode 100644
index 000000000..0fcebe13a
--- /dev/null
+++ b/packages/app/src/components/terminal-link-provider.ts
@@ -0,0 +1,184 @@
+/**
+ * xterm `ILinkProvider` for clickable file paths in the terminal.
+ *
+ * `provideLinks` is a PULL model: xterm calls it only for the buffer row under
+ * the mouse on hover, so validating each candidate against the filesystem
+ * (`checkTargetExists`) is affordable here in a way a parse-the-whole-viewport
+ * design never would be. Detection/resolution is delegated to the pure
+ * `terminal-links` module; this factory owns the xterm range mapping, the
+ * existence gate (snapshot fast-path → cached IPC probe), and the click route.
+ *
+ * Decoupled from React + the concrete `Terminal` (it takes a `readLogicalLine`
+ * closure) so it unit-tests without standing up xterm.
+ */
+
+import type { ILink, ILinkProvider } from '@xterm/xterm';
+import type { CheckTargetExistsResult } from '@/lib/desktop-bridge-types';
+import type { PageListCacheSnapshot } from '../editor/page-list-cache';
+import {
+ classifyTarget,
+ detectPathCandidates,
+ hasPathExtension,
+ isKnownInSnapshot,
+ resolveTerminalPath,
+ type TerminalLinkTarget,
+ terminalBufferRange,
+} from './terminal-links';
+
+/** A reconstructed logical line and where it sits in the xterm buffer. */
+interface LogicalLine {
+ /** Full text of the logical line (wrapped continuation rows stitched in). */
+ readonly text: string;
+ /** 1-based buffer row where the logical line begins. */
+ readonly startLine: number;
+ /** Terminal width in columns — how wide each wrapped row is. */
+ readonly cols: number;
+}
+
+export interface TerminalFileLinkProviderDeps {
+ /** PTY cwd — relative paths in output resolve against this. */
+ readonly projectPath: string;
+ /**
+ * Reconstruct the full logical line containing `bufferLineNumber` (xterm's
+ * 1-based row) by stitching wrapped continuation rows. Reading a single row
+ * would split a path longer than the terminal is wide — the reason an
+ * absolute path in a narrow docked terminal never underlined.
+ */
+ readonly readLogicalLine: (bufferLineNumber: number) => LogicalLine | undefined;
+ /** Current page-list cache snapshot (or null before first load). */
+ readonly getSnapshot: () => PageListCacheSnapshot | null;
+ /** Authoritative, project-contained on-disk existence probe. */
+ readonly checkTargetExists: (
+ kind: 'doc' | 'folder',
+ relPath: string,
+ ) => Promise<CheckTargetExistsResult>;
+ /** Route a validated target (editor nav / OS open). */
+ readonly onActivate: (target: TerminalLinkTarget) => void;
+ /** Per-line detection/validation cap. Defaults to 10 (bounds probe work). */
+ readonly maxLinksPerLine?: number;
+}
+
+/** Bounds the existence cache so a long session can't grow it unbounded. */
+const EXISTENCE_CACHE_CAP = 1000;
+
+export function createTerminalFileLinkProvider(deps: TerminalFileLinkProviderDeps): ILinkProvider {
+ const maxLinks = deps.maxLinksPerLine ?? 10;
+ // Memoize probe results per `${kind}:${relPath}`. The click path re-validates
+ // via `openAsset`/nav, so a stale entry can only produce a stale underline,
+ // never a wrong action.
+ const existenceCache = new Map<string, boolean>();
+ // Log a probe failure once — a persistently-broken `checkTargetExists` (bridge
+ // crash, channel deregistration after an Electron upgrade) otherwise silently
+ // stops every file-path link from underlining, indistinguishable from "no
+ // matches". Fail-safe (treat errors as absent) stays; this just adds a signal.
+ let warnedProbeFailure = false;
+ // Same one-time diagnostic for an unexpected throw in the pure mappers
+ // (resolveTerminalPath / classifyTarget) — rare, but otherwise silently
+ // suppresses links with no trace.
+ let warnedComputeError = false;
+
+ async function exists(kind: 'doc' | 'folder', relPath: string): Promise<boolean> {
+ const key = `${kind}:${relPath}`;
+ const cached = existenceCache.get(key);
+ if (cached !== undefined) return cached;
+ let result = false;
+ try {
+ result = (await deps.checkTargetExists(kind, relPath)) === 'exists';
+ } catch (err) {
+ result = false;
+ if (!warnedProbeFailure) {
+ warnedProbeFailure = true;
+ console.warn('[terminal] checkTargetExists probe failed; file-path links suppressed:', err);
+ }
+ }
+ if (existenceCache.size >= EXISTENCE_CACHE_CAP) existenceCache.clear();
+ existenceCache.set(key, result);
+ return result;
+ }
+
+ // Resolve an in-project relative path to a routable target, or null if it
+ // doesn't exist. A snapshot hit skips the probe. The fallback below covers the
+ // bare-directory case: `src` (no slash, no extension) classifies as an asset
+ // and `checkTargetExists('doc')` requires `isFile()`, so a real directory
+ // misses — retry it as a folder before giving up.
+ async function routeInProject(
+ relPath: string,
+ trailingSlash: boolean,
+ snapshot: PageListCacheSnapshot | null,
+ ): Promise<TerminalLinkTarget | null> {
+ const kind = classifyTarget(relPath, trailingSlash, snapshot);
+ if (isKnownInSnapshot(relPath, trailingSlash, snapshot)) return { kind, relPath };
+ if (kind === 'folder') {
+ return (await exists('folder', relPath)) ? { kind, relPath } : null;
+ }
+ if (await exists('doc', relPath)) return { kind, relPath };
+ if (!hasPathExtension(relPath) && (await exists('folder', relPath))) {
+ return { kind: 'folder', relPath };
+ }
+ return null;
+ }
+
+ return {
+ provideLinks(bufferLineNumber, callback) {
+ const logical = deps.readLogicalLine(bufferLineNumber);
+ if (!logical || logical.text.length === 0) {
+ callback(undefined);
+ return;
+ }
+ const { text, startLine, cols } = logical;
+
+ const candidates = detectPathCandidates(text, maxLinks);
+ if (candidates.length === 0) {
+ callback(undefined);
+ return;
+ }
+
+ const snapshot = deps.getSnapshot();
+
+ void Promise.all(
+ candidates.map(async (candidate): Promise<ILink | null> => {
+ const resolved = resolveTerminalPath(candidate.path, deps.projectPath);
+ if (resolved === null) return null;
+
+ let target: TerminalLinkTarget;
+ if (resolved.kind === 'external') {
+ // Out-of-project absolute path. Not existence-gated here: there is no
+ // project-scoped probe for a path outside the project, so it links
+ // optimistically and the reveal handler stats it (a missing path
+ // simply shows no dialog). Clicking offers reveal-in-Finder.
+ target = { kind: 'external', absPath: resolved.absPath };
+ } else {
+ const routed = await routeInProject(
+ resolved.relPath,
+ candidate.trailingSlash,
+ snapshot,
+ );
+ if (routed === null) return null;
+ target = routed;
+ }
+ return {
+ text: candidate.path,
+ // The logical line may span wrapped rows; map the match's string
+ // offsets back to real buffer cells (start.y/end.y can differ).
+ range: terminalBufferRange(candidate.startIndex, candidate.endIndex, startLine, cols),
+ activate: () => deps.onActivate(target),
+ };
+ }),
+ )
+ .then((links) => {
+ const present = links.filter((link): link is ILink => link !== null);
+ callback(present.length > 0 ? present : undefined);
+ })
+ // xterm's ILinkProvider contract requires `callback` to fire on every
+ // call; a rejected chain (an unexpected throw in a candidate mapper)
+ // must still resolve the hover to "no links", never leave it pending.
+ .catch((err) => {
+ if (!warnedComputeError) {
+ warnedComputeError = true;
+ console.warn('[terminal] link provider failed to compute links:', err);
+ }
+ callback(undefined);
+ });
+ },
+ };
+}
diff --git a/packages/app/src/components/terminal-links.test.ts b/packages/app/src/components/terminal-links.test.ts
new file mode 100644
index 000000000..15166ccef
--- /dev/null
+++ b/packages/app/src/components/terminal-links.test.ts
@@ -0,0 +1,290 @@
+import { describe, expect, test } from 'bun:test';
+import type { PageListCacheSnapshot } from '../editor/page-list-cache';
+import {
+ classifyTarget,
+ createRecentOpenGuard,
+ detectPathCandidates,
+ hasPathExtension,
+ isKnownInSnapshot,
+ resolveTerminalPath,
+ terminalBufferRange,
+ toProjectRelative,
+} from './terminal-links';
+
+function snapshot(partial: Partial<PageListCacheSnapshot> = {}): PageListCacheSnapshot {
+ return {
+ pages: new Set(),
+ folderPaths: new Set(),
+ pagesBySlug: new Map(),
+ ...partial,
+ };
+}
+
+describe('detectPathCandidates', () => {
+ test('finds a relative path with a separator', () => {
+ const [c] = detectPathCandidates('see src/foo.ts for details');
+ expect(c?.path).toBe('src/foo.ts');
+ expect('see '.length).toBe(4);
+ expect(c?.startIndex).toBe(4);
+ expect(c?.endIndex).toBe(14);
+ expect(c?.trailingSlash).toBe(false);
+ });
+
+ test('finds dot-relative and parent-relative paths', () => {
+ expect(detectPathCandidates('./a/b.md')[0]?.path).toBe('./a/b.md');
+ expect(detectPathCandidates('../x/y.md')[0]?.path).toBe('../x/y.md');
+ });
+
+ test('finds an absolute path', () => {
+ expect(detectPathCandidates('at /Users/me/notes.md now')[0]?.path).toBe('/Users/me/notes.md');
+ });
+
+ test('finds a bare filename only when it has an extension', () => {
+ expect(detectPathCandidates('open report.md please')[0]?.path).toBe('report.md');
+ expect(detectPathCandidates('the readme was updated')).toHaveLength(0);
+ });
+
+ test('strips a :line:col suffix, keeping it out of the underlined range', () => {
+ const [c] = detectPathCandidates('../x.py:12:5');
+ expect(c?.path).toBe('../x.py');
+ expect(c?.endIndex).toBe('../x.py'.length);
+ });
+
+ test('strips a :line[:col] suffix even when trailing punctuation follows', () => {
+ // A common compiler / ripgrep shape: `error at src/a.ts:12,` — punctuation is
+ // trimmed BEFORE the suffix match so the path still resolves.
+ expect(detectPathCandidates('error at src/a.ts:12,')[0]?.path).toBe('src/a.ts');
+ expect(detectPathCandidates('see src/a.ts:12:5.')[0]?.path).toBe('src/a.ts');
+ });
+
+ test('a trailing-slash folder underline excludes the slash (endIndex over core)', () => {
+ const [c] = detectPathCandidates('cd packages/app/');
+ expect(c?.path).toBe('packages/app');
+ expect(c?.trailingSlash).toBe(true);
+ // 'cd ' = 3; the underlined range is exactly 'packages/app' (no trailing `/`).
+ expect(c?.startIndex).toBe(3);
+ expect(c?.endIndex).toBe(3 + 'packages/app'.length);
+ });
+
+ test('marks a trailing slash as a folder reference', () => {
+ const [c] = detectPathCandidates('cd packages/app/');
+ expect(c?.path).toBe('packages/app');
+ expect(c?.trailingSlash).toBe(true);
+ });
+
+ test('ignores http(s) URLs (WebLinksAddon owns those)', () => {
+ expect(detectPathCandidates('visit https://example.com/path')).toHaveLength(0);
+ expect(detectPathCandidates('file://host/x.md')).toHaveLength(0);
+ });
+
+ test('ignores bare words, numbers, and clock times', () => {
+ expect(detectPathCandidates('the quick brown fox')).toHaveLength(0);
+ expect(detectPathCandidates('elapsed 12:34')).toHaveLength(0);
+ expect(detectPathCandidates('exit code 127')).toHaveLength(0);
+ });
+
+ test('trims trailing sentence punctuation', () => {
+ expect(detectPathCandidates('edited src/a.ts.')[0]?.path).toBe('src/a.ts');
+ expect(detectPathCandidates('files: src/a.ts, src/b.ts')[0]?.path).toBe('src/a.ts');
+ });
+
+ test('strips enclosing brackets (they are token boundaries)', () => {
+ expect(detectPathCandidates('[src/a.ts]')[0]?.path).toBe('src/a.ts');
+ });
+
+ test('rejects ~-home paths (no homedir available renderer-side)', () => {
+ expect(detectPathCandidates('~/notes.md')).toHaveLength(0);
+ });
+
+ test('caps the number of candidates per line', () => {
+ const line = Array.from({ length: 20 }, (_, i) => `dir/file${i}.md`).join(' ');
+ expect(detectPathCandidates(line, 5)).toHaveLength(5);
+ });
+
+ test('ignores empty and pathologically long lines', () => {
+ expect(detectPathCandidates('')).toHaveLength(0);
+ expect(detectPathCandidates(`${'a/'.repeat(2000)}z.md`)).toHaveLength(0);
+ });
+});
+
+describe('toProjectRelative', () => {
+ const root = '/Users/me/project';
+
+ test('passes through a clean relative path', () => {
+ expect(toProjectRelative('src/foo.ts', root)).toBe('src/foo.ts');
+ });
+
+ test('strips a leading ./', () => {
+ expect(toProjectRelative('./src/foo.ts', root)).toBe('src/foo.ts');
+ });
+
+ test('makes an in-project absolute path project-relative', () => {
+ expect(toProjectRelative('/Users/me/project/docs/a.md', root)).toBe('docs/a.md');
+ });
+
+ test('rejects an absolute path outside the project', () => {
+ expect(toProjectRelative('/etc/passwd', root)).toBeNull();
+ expect(toProjectRelative('/Users/me/other/a.md', root)).toBeNull();
+ });
+
+ test('rejects the project root itself', () => {
+ expect(toProjectRelative(root, root)).toBeNull();
+ });
+
+ test('rejects any parent-escape', () => {
+ expect(toProjectRelative('../secrets.md', root)).toBeNull();
+ expect(toProjectRelative('a/../../b.md', root)).toBeNull();
+ });
+
+ test('tolerates a trailing slash on the project root', () => {
+ expect(toProjectRelative('src/a.ts', '/Users/me/project/')).toBe('src/a.ts');
+ });
+
+ test('collapses redundant separators and current-dir segments', () => {
+ expect(toProjectRelative('a//./b.md', root)).toBe('a/b.md');
+ });
+});
+
+describe('resolveTerminalPath', () => {
+ const root = '/Users/me/project';
+
+ test('an in-project relative path resolves in-project', () => {
+ expect(resolveTerminalPath('src/a.ts', root)).toEqual({
+ kind: 'in-project',
+ relPath: 'src/a.ts',
+ });
+ });
+
+ test('an in-project absolute path resolves in-project (made relative)', () => {
+ expect(resolveTerminalPath('/Users/me/project/docs/a.md', root)).toEqual({
+ kind: 'in-project',
+ relPath: 'docs/a.md',
+ });
+ });
+
+ test('an out-of-project absolute path resolves external', () => {
+ expect(resolveTerminalPath('/tmp/out/x.pdf', root)).toEqual({
+ kind: 'external',
+ absPath: '/tmp/out/x.pdf',
+ });
+ expect(resolveTerminalPath('/etc/hosts', root)).toEqual({
+ kind: 'external',
+ absPath: '/etc/hosts',
+ });
+ });
+
+ test('the project root itself is not routable', () => {
+ expect(resolveTerminalPath(root, root)).toBeNull();
+ });
+
+ test('a relative parent-escape stays non-clickable (ambiguous once the shell cd-s)', () => {
+ expect(resolveTerminalPath('../secrets.md', root)).toBeNull();
+ });
+});
+
+describe('classifyTarget', () => {
+ test('markdown extensions classify as docs', () => {
+ expect(classifyTarget('notes/a.md', false, null)).toBe('doc');
+ expect(classifyTarget('notes/a.mdx', false, null)).toBe('doc');
+ });
+
+ test('a docName known to the cache classifies as a doc', () => {
+ const snap = snapshot({ pages: new Set(['guides/setup']) });
+ expect(classifyTarget('guides/setup', false, snap)).toBe('doc');
+ });
+
+ test('trailing slash or a known folder classifies as a folder', () => {
+ expect(classifyTarget('packages/app', true, null)).toBe('folder');
+ const snap = snapshot({ folderPaths: new Set(['packages/app']) });
+ expect(classifyTarget('packages/app', false, snap)).toBe('folder');
+ });
+
+ test('everything else is an asset', () => {
+ expect(classifyTarget('data/example.csv', false, null)).toBe('asset');
+ expect(classifyTarget('img/logo.png', false, null)).toBe('asset');
+ });
+});
+
+describe('isKnownInSnapshot', () => {
+ test('resolves docs, assets, files, and folders from the cache without a probe', () => {
+ const snap = snapshot({
+ pages: new Set(['guides/setup']),
+ folderPaths: new Set(['packages']),
+ assetPaths: new Set(['img/logo.png']),
+ filePaths: new Set(['data/x.csv']),
+ });
+ expect(isKnownInSnapshot('guides/setup.md', false, snap)).toBe(true);
+ expect(isKnownInSnapshot('img/logo.png', false, snap)).toBe(true);
+ expect(isKnownInSnapshot('data/x.csv', false, snap)).toBe(true);
+ expect(isKnownInSnapshot('packages', true, snap)).toBe(true);
+ expect(isKnownInSnapshot('unknown/thing.txt', false, snap)).toBe(false);
+ });
+
+ test('returns false when there is no snapshot', () => {
+ expect(isKnownInSnapshot('a.md', false, null)).toBe(false);
+ });
+});
+
+describe('createRecentOpenGuard', () => {
+ test('suppresses the same URL fired twice within the window (the OSC 8 + WebLinks double)', () => {
+ const guard = createRecentOpenGuard(300);
+ expect(guard('https://x.com', 1000)).toBe(false); // first open proceeds
+ expect(guard('https://x.com', 1000)).toBe(true); // same click, same ms → suppressed
+ expect(guard('https://x.com', 1200)).toBe(true); // still within 300ms window
+ });
+
+ test('allows the same URL again after the window elapses', () => {
+ const guard = createRecentOpenGuard(300);
+ expect(guard('https://x.com', 1000)).toBe(false);
+ expect(guard('https://x.com', 1400)).toBe(false); // 400ms later → a fresh open
+ });
+
+ test('never suppresses a different URL', () => {
+ const guard = createRecentOpenGuard(300);
+ expect(guard('https://a.com', 1000)).toBe(false);
+ expect(guard('https://b.com', 1000)).toBe(false); // different target, same instant
+ });
+});
+
+describe('hasPathExtension', () => {
+ test('true for extensioned leaves, false for extensionless', () => {
+ expect(hasPathExtension('report.md')).toBe(true);
+ expect(hasPathExtension('a/b/c.tsx')).toBe(true);
+ expect(hasPathExtension('packages/app')).toBe(false);
+ expect(hasPathExtension('src')).toBe(false);
+ expect(hasPathExtension('node_modules')).toBe(false);
+ });
+});
+
+describe('terminalBufferRange', () => {
+ test('a span within one row maps to a single-row 1-based range', () => {
+ // "see " (4 chars) then a 10-char path → [4,14); cols wide enough not to wrap.
+ expect(terminalBufferRange(4, 14, 3, 80)).toEqual({
+ start: { x: 5, y: 3 },
+ end: { x: 14, y: 3 },
+ });
+ });
+
+ test('a span crossing the wrap boundary spans rows (start.y != end.y)', () => {
+ // cols=20, path at [4,27): last char is index 26 → row +1, col 7.
+ expect(terminalBufferRange(4, 27, 1, 20)).toEqual({
+ start: { x: 5, y: 1 },
+ end: { x: 7, y: 2 },
+ });
+ });
+
+ test('a span landing exactly on a wrap boundary starts the next row', () => {
+ // index 20 with cols=20 → col 1 of the next row.
+ expect(terminalBufferRange(20, 24, 5, 20)).toEqual({
+ start: { x: 1, y: 6 },
+ end: { x: 4, y: 6 },
+ });
+ });
+
+ test('a non-positive width never wraps (guards divide-by-zero)', () => {
+ expect(terminalBufferRange(2, 8, 1, 0)).toEqual({
+ start: { x: 3, y: 1 },
+ end: { x: 8, y: 1 },
+ });
+ });
+});
diff --git a/packages/app/src/components/terminal-links.ts b/packages/app/src/components/terminal-links.ts
new file mode 100644
index 000000000..c3d304b0e
--- /dev/null
+++ b/packages/app/src/components/terminal-links.ts
@@ -0,0 +1,306 @@
+/**
+ * Pure detection + resolution for clickable file-path links in the terminal.
+ *
+ * The xterm wiring (registerLinkProvider, bridge calls, React lifecycle) lives
+ * in `terminal-link-provider.ts` + `TerminalPanel.tsx`; everything here is
+ * side-effect-free so the heuristics can be unit-tested against a corpus.
+ *
+ * URLs are NOT handled here — `WebLinksAddon` owns implicit `http(s)` detection
+ * (its `strictUrlRegex` + `new URL()` round-trip gate are battle-tested). This
+ * module only finds POSIX file paths (desktop is macOS-only, so no Windows
+ * drive/UNC clauses) and turns them into project-relative targets.
+ *
+ * Philosophy (matching VSCode / iTerm2): parse generously, then gate on
+ * existence at the call site. A generous regex plus a `checkTargetExists` probe
+ * beats a clever regex with no validation — false positives never underline.
+ */
+
+import type { PageListCacheSnapshot } from '../editor/page-list-cache';
+import { filePathToDocName } from '../lib/doc-hash';
+
+/** A path token found in a line of terminal output. */
+export interface PathCandidate {
+ /**
+ * The path portion with any trailing `:line[:col]` suffix and trailing
+ * sentence punctuation removed. This is what gets resolved.
+ */
+ readonly path: string;
+ /** 0-based index of `path`'s first char in the source line. */
+ readonly startIndex: number;
+ /** 0-based index one past `path`'s last char (exclusive). */
+ readonly endIndex: number;
+ /** True when the raw token ended in `/` — a folder reference. */
+ readonly trailingSlash: boolean;
+}
+
+/** How an in-project target opens. */
+export type TerminalLinkKind = 'doc' | 'folder' | 'asset';
+
+/**
+ * A validated, routable terminal link target. In-project targets open in the
+ * editor / OS default app; an `external` target (an existing path outside the
+ * current project) instead offers a reveal-in-Finder dialog on click.
+ */
+export type TerminalLinkTarget =
+ | {
+ readonly kind: TerminalLinkKind;
+ /** contentDir-relative, POSIX-separated, no leading `/`, no trailing `/`. */
+ readonly relPath: string;
+ }
+ | {
+ readonly kind: 'external';
+ /** Absolute on-disk path outside `projectPath`. */
+ readonly absPath: string;
+ };
+
+/** Outcome of resolving a detected path token against the project root. */
+export type ResolvedTerminalPath =
+ | { readonly kind: 'in-project'; readonly relPath: string }
+ | { readonly kind: 'external'; readonly absPath: string };
+
+/**
+ * Resolve a detected path token to either an in-project relative path or an
+ * out-of-project absolute path — or `null` when it isn't routable.
+ *
+ * - In-project (absolute-inside or clean relative) → `{ kind: 'in-project' }`.
+ * - Absolute path outside the project (and not the root itself) →
+ * `{ kind: 'external' }` — clicking offers a reveal-in-Finder dialog.
+ * - A relative `..`-escape stays `null`: once the shell `cd`s the true cwd
+ * diverges from the spawn cwd, so a relative token that escapes the project
+ * is ambiguous and not made clickable. Only absolute paths route external.
+ */
+export function resolveTerminalPath(
+ rawPath: string,
+ projectPath: string,
+): ResolvedTerminalPath | null {
+ const rel = toProjectRelative(rawPath, projectPath);
+ if (rel !== null) return { kind: 'in-project', relPath: rel };
+ // `toProjectRelative` collapses "outside the project" AND "is the root" both to
+ // `null`, so re-distinguish them here: an in-tree absolute would have returned
+ // a relPath above, so a still-absolute path is genuinely external.
+ if (rawPath.startsWith('/')) {
+ if (rawPath === normalizeRoot(projectPath)) return null; // the root isn't a file.
+ return { kind: 'external', absPath: rawPath };
+ }
+ return null;
+}
+
+/** Normalize the project root (drop trailing slashes) for prefix comparison. */
+function normalizeRoot(projectPath: string): string {
+ return projectPath.replace(/\/+$/, '');
+}
+
+const MAX_LINE_LENGTH = 2000;
+
+/**
+ * Runs of non-whitespace, non-delimiter characters. `:` and `.` stay INSIDE a
+ * run so `foo.ts:12` is one token (the suffix is split off afterwards);
+ * brackets, quotes, pipes, angle brackets, and NUL are excluded so they act as
+ * boundaries (they can't appear in a path we would open, and they bound
+ * `(url)` / `[path]` enclosures).
+ */
+const RUN_RE = /[^\s<>"'`|(){}[\]\0]+/g;
+
+/**
+ * Trailing `:line[:col]` suffix (the dominant unix / compiler / ripgrep form),
+ * stripped from the token so it stays out of the underlined range. `(line,col)`
+ * isn't matched: `(` is a run boundary (below), so an enclosing paren already
+ * strips to the bare path.
+ */
+const SUFFIX_RE = /:\d+(?::\d+)?$/;
+
+/** Scheme-prefixed tokens (`https://`, `file://`, …) belong to WebLinksAddon. */
+const SCHEME_RE = /^[a-z][a-z0-9+.-]*:\/\//i;
+
+/** A bare leaf (no `/`) is only a candidate when it carries an extension. */
+const HAS_EXTENSION_RE = /\.[A-Za-z0-9]+$/;
+
+/**
+ * True when the token ends in a file extension (`.md`, `.ts`, `.tar.gz` → yes).
+ * Used to decide whether a slash-less token that missed the file probe is worth
+ * retrying as a directory — extension-less tokens (`src`, `node_modules`) are
+ * the plausible bare-directory case; `report.md` is not.
+ */
+export function hasPathExtension(token: string): boolean {
+ return HAS_EXTENSION_RE.test(token);
+}
+
+/**
+ * Extract path candidates from one line of terminal text. Generous by design —
+ * callers validate existence before decorating. Returns at most `maxCandidates`
+ * results (bounds downstream `stat` work per line).
+ */
+export function detectPathCandidates(line: string, maxCandidates = 10): PathCandidate[] {
+ if (line.length === 0 || line.length > MAX_LINE_LENGTH) return [];
+ const out: PathCandidate[] = [];
+
+ for (const match of line.matchAll(RUN_RE)) {
+ if (out.length >= maxCandidates) break;
+ const run = match[0];
+ const runStart = match.index;
+
+ // URLs are WebLinksAddon's job.
+ if (SCHEME_RE.test(run)) continue;
+
+ // Trim trailing sentence punctuation FIRST (`foo.md.` / `bar,` / `baz:`), so
+ // a `:line[:col]` suffix followed by punctuation (`error at src/a.ts:12,` — a
+ // common compiler / ripgrep shape) still strips to the bare path below.
+ let path = run.replace(/[.,;:!?]+$/, '');
+
+ // Strip a trailing `:line[:col]` suffix so it stays out of the underlined
+ // range — the link resolves to the path, not `path:12`. (Line info isn't
+ // consumed yet; the editor has no line-scroll target.)
+ const suffix = path.match(SUFFIX_RE);
+ if (suffix) path = path.slice(0, suffix.index);
+
+ const trailingSlash = path.endsWith('/');
+ const core = trailingSlash ? path.slice(0, -1) : path;
+ if (!isPathShaped(core)) continue;
+
+ // `endIndex` is one past `core`'s last char — the underlined range is exactly
+ // the emitted path, excluding any stripped suffix / trailing slash.
+ const endIndex = runStart + core.length;
+ out.push({ path: core, startIndex: runStart, endIndex, trailingSlash });
+ }
+
+ return out;
+}
+
+/** An xterm buffer range: 1-based columns, 1-based buffer rows, `end` inclusive. */
+export interface TerminalBufferRange {
+ readonly start: { readonly x: number; readonly y: number };
+ readonly end: { readonly x: number; readonly y: number };
+}
+
+/**
+ * Map a `[startIndex, endIndex)` span of a RECONSTRUCTED logical line back to an
+ * xterm buffer range. A logical line wider than the terminal is stored across
+ * several rows (`cols` chars each); `startLine` is the 1-based buffer row where
+ * it begins. A span that crosses a wrap boundary produces a range whose
+ * `start.y` and `end.y` differ — xterm supports multi-row link ranges, so a
+ * wrapped path underlines and hit-tests correctly across rows. `end` is the
+ * INCLUSIVE cell of the last char (xterm's convention), derived from
+ * `endIndex - 1`.
+ */
+export function terminalBufferRange(
+ startIndex: number,
+ endIndex: number,
+ startLine: number,
+ cols: number,
+): TerminalBufferRange {
+ // A non-positive width can't wrap; keep the whole span on `startLine`.
+ const width = cols > 0 ? cols : Number.MAX_SAFE_INTEGER;
+ const lastIndex = Math.max(startIndex, endIndex - 1);
+ const cell = (i: number) => ({ x: (i % width) + 1, y: startLine + Math.floor(i / width) });
+ return { start: cell(startIndex), end: cell(lastIndex) };
+}
+
+/**
+ * True when `token` looks like a file/folder path worth validating: it either
+ * contains a separator (`src/foo`, `./a`, `/abs`) or is a bare leaf with an
+ * extension (`report.md`). Pure-word and pure-numeric tokens are rejected so we
+ * don't probe every word on the line.
+ */
+function isPathShaped(token: string): boolean {
+ if (token.length < 2) return false;
+ if (token.startsWith('~')) return false; // home paths need a homedir we don't have.
+ if (token.includes('/')) return true;
+ return HAS_EXTENSION_RE.test(token);
+}
+
+/**
+ * Resolve a detected path to a clean, contentDir-relative path — or `null` when
+ * it escapes the project. `projectPath` is the PTY cwd (`bridge.config.projectPath`).
+ *
+ * Rejections (all mean "not a clickable in-project target"):
+ * - absolute paths outside `projectPath`
+ * - any `..` segment (would escape; the PTY cwd is the project root)
+ * - empty / current-dir-only results
+ *
+ * The returned form is what `checkTargetExists` + `openAsset` expect: no leading
+ * `/`, no trailing `/`, no `./` prefix, POSIX separators.
+ */
+export function toProjectRelative(rawPath: string, projectPath: string): string | null {
+ if (!rawPath || !projectPath) return null;
+ const root = normalizeRoot(projectPath);
+
+ let rel: string;
+ if (rawPath.startsWith('/')) {
+ // Absolute — only clickable if it lives inside the project tree.
+ if (rawPath === root) return null; // the root itself is not a doc/asset.
+ const prefix = `${root}/`;
+ if (!rawPath.startsWith(prefix)) return null;
+ rel = rawPath.slice(prefix.length);
+ } else {
+ rel = rawPath.startsWith('./') ? rawPath.slice(2) : rawPath;
+ }
+
+ // Normalize separators; drop empty + current-dir segments; reject escapes.
+ const segments: string[] = [];
+ for (const seg of rel.split('/')) {
+ if (seg === '' || seg === '.') continue;
+ if (seg === '..') return null;
+ segments.push(seg);
+ }
+ if (segments.length === 0) return null;
+ return segments.join('/');
+}
+
+/**
+ * Decide how an existing target opens: docs open in the editor, folders navigate
+ * to their overview, everything else OS-delegates via `openAsset`.
+ *
+ * `snapshot` (the page-list cache) lets tracked content route without any probe;
+ * `trailingSlash` disambiguates a folder reference that isn't yet in the cache.
+ */
+export function classifyTarget(
+ relPath: string,
+ trailingSlash: boolean,
+ snapshot: PageListCacheSnapshot | null,
+): TerminalLinkKind {
+ if (trailingSlash) return 'folder';
+ if (snapshot?.folderPaths.has(relPath)) return 'folder';
+ if (relPath.endsWith('.md') || relPath.endsWith('.mdx')) return 'doc';
+ if (snapshot?.pages.has(filePathToDocName(relPath))) return 'doc';
+ return 'asset';
+}
+
+/**
+ * Guard against opening the same URL twice from a single click. xterm runs two
+ * link layers over the same cells — the core OSC 8 handler (`Terminal.linkHandler`)
+ * and `WebLinksAddon` — and when a URL is emitted as an OSC 8 hyperlink whose
+ * visible text is itself the URL (what the `claude` TUI and many CLIs do), BOTH
+ * match and both fire `activate`, opening the browser twice. Routing both handlers
+ * through this guard collapses the same-URL, same-gesture pair into one open while
+ * leaving OSC 8 links with custom display text (text ≠ target) fully functional.
+ *
+ * `now` is injected so the guard is deterministically testable. Returns `true`
+ * when the caller should SUPPRESS this open (a duplicate within `windowMs`).
+ */
+export function createRecentOpenGuard(windowMs = 300): (uri: string, now: number) => boolean {
+ let last: { uri: string; at: number } | null = null;
+ return (uri, now) => {
+ if (last !== null && last.uri === uri && now - last.at < windowMs) return true;
+ last = { uri, at: now };
+ return false;
+ };
+}
+
+/**
+ * Synchronous existence check against the page-list cache — a fast path that
+ * avoids an IPC round-trip for content the app already tracks. Returns `true`
+ * (known to exist), `false` (unknown — caller must probe), never a false
+ * negative for tracked content.
+ */
+export function isKnownInSnapshot(
+ relPath: string,
+ trailingSlash: boolean,
+ snapshot: PageListCacheSnapshot | null,
+): boolean {
+ if (!snapshot) return false;
+ if (trailingSlash) return snapshot.folderPaths.has(relPath);
+ if (snapshot.pages.has(filePathToDocName(relPath))) return true;
+ if (snapshot.assetPaths?.has(relPath)) return true;
+ if (snapshot.filePaths?.has(relPath)) return true;
+ return snapshot.folderPaths.has(relPath);
+}
diff --git a/packages/app/src/lib/desktop-bridge-types.ts b/packages/app/src/lib/desktop-bridge-types.ts
index e69d54a8b..1f74a432c 100644
--- a/packages/app/src/lib/desktop-bridge-types.ts
+++ b/packages/app/src/lib/desktop-bridge-types.ts
@@ -939,6 +939,19 @@ export interface OkDesktopBridge {
relPath: string,
): Promise<{ ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' }>;
+ /**
+ * Reveal an ABSOLUTE path outside the project (the terminal's out-of-project
+ * clickable-link flow). Main pops a "reveal in Finder?" confirmation naming
+ * the path and reveals on confirm. See canonical JSDoc in
+ * `packages/desktop/src/shared/bridge-contract.ts`.
+ */
+ revealExternal(
+ absPath: string,
+ ): Promise<
+ | { ok: true; outcome: 'revealed' | 'dismissed' }
+ | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' }
+ >;
+
/**
* Display the native right-click context menu for an on-disk reference.
* See canonical JSDoc in `packages/desktop/src/shared/bridge-contract.ts`.
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index c9b8e8145..b2dbd75dc 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -315,6 +315,10 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
},
openAsset: async (): Promise<{ ok: true }> => ({ ok: true }),
revealAsset: async (): Promise<{ ok: true }> => ({ ok: true }),
+ revealExternal: async (): Promise<{ ok: true; outcome: 'revealed' }> => ({
+ ok: true,
+ outcome: 'revealed',
+ }),
showAssetMenu: async (): Promise<void> => {},
showItemInFolder: async (): Promise<void> => {},
// No-op stub — sidebar Delete flow isn't exercised by the handoff
diff --git a/packages/core/src/desktop-bridge.ts b/packages/core/src/desktop-bridge.ts
index 6225d5c8c..45f44f8c2 100644
--- a/packages/core/src/desktop-bridge.ts
+++ b/packages/core/src/desktop-bridge.ts
@@ -1144,6 +1144,20 @@ export interface OkDesktopBridge {
relPath: string,
): Promise<{ ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' }>;
+ /**
+ * Reveal an ABSOLUTE path outside the caller window's project — the
+ * terminal's "this file is outside your project" clickable-link flow.
+ * Deliberately NOT containment-gated (unlike `revealAsset`); main stats the
+ * path and pops a native confirmation dialog, revealing only on confirm. The
+ * dialog is the trust boundary.
+ */
+ revealExternal(
+ absPath: string,
+ ): Promise<
+ | { ok: true; outcome: 'revealed' | 'dismissed' }
+ | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' }
+ >;
+
/**
* Display the native right-click context menu for an on-disk reference
* (`asset`, `wiki-link`, or `image`). Built from `Menu.buildFromTemplate`
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 806f414e7..2a6827251 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -36,6 +36,7 @@ import {
openSync,
readFileSync,
realpathSync,
+ statSync,
writeFileSync,
} from 'node:fs';
import { createServer as createHttpServer } from 'node:http';
@@ -275,6 +276,7 @@ import { removeGitFolder } from './remove-git-folder.ts';
import { attachRendererConsoleCapture } from './renderer-console-capture.ts';
import { resolveDetachedSpawnArgs } from './resolve-detached-spawn-args.ts';
import { resolveShareTarget as resolveShareTargetMain } from './resolve-share-target.ts';
+import { handleRevealExternal } from './reveal-external.ts';
import { startFirstRunHandshake } from './share-handoff.ts';
import { handleShellOpenExternal } from './shell-allowlist.ts';
import { createShowGateRegistry, type ShowGateRegistry } from './show-gate.ts';
@@ -3480,6 +3482,43 @@ function registerIpcHandlers() {
return undefined;
});
+ handle('ok:shell:reveal-external', async (event, absPath) => {
+ // Out-of-project reveal for terminal clickable-links. Uncontained by design;
+ // the confirmation dialog is the trust boundary (see reveal-external.ts).
+ const callerWin = BrowserWindow.fromWebContents(event.sender);
+ const result = await handleRevealExternal(absPath, {
+ // statSync (not existsSync) so a permission error (EACCES/EPERM on a system
+ // path) surfaces as `unreadable` rather than being flattened to `missing`.
+ probe: (p) => {
+ try {
+ statSync(p);
+ return 'exists';
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code === 'ENOENT' ? 'missing' : 'unreadable';
+ }
+ },
+ confirmReveal: async (p) => {
+ const opts: MessageBoxOptions = {
+ type: 'question',
+ buttons: ['Reveal in Finder', 'Cancel'],
+ defaultId: 0,
+ cancelId: 1,
+ message: `"${basename(p)}" is outside your project`,
+ detail: `${p}\n\nReveal it in Finder?`,
+ };
+ const { response } = callerWin
+ ? await dialog.showMessageBox(callerWin, opts)
+ : await dialog.showMessageBox(opts);
+ return response === 0;
+ },
+ showItemInFolder: (p) => shell.showItemInFolder(p),
+ });
+ if (!result.ok) {
+ console.warn('[main] reveal-external refused', { reason: result.reason });
+ }
+ return result;
+ });
+
handle('ok:shell:trash-item', async (event, absPath) => {
const callerWin = BrowserWindow.fromWebContents(event.sender);
const callerProjectPath =
diff --git a/packages/desktop/src/main/reveal-external.test.ts b/packages/desktop/src/main/reveal-external.test.ts
new file mode 100644
index 000000000..f9132b0db
--- /dev/null
+++ b/packages/desktop/src/main/reveal-external.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, mock, test } from 'bun:test';
+import { handleRevealExternal, type RevealExternalDeps } from './reveal-external.ts';
+
+function makeDeps(overrides: Partial<RevealExternalDeps> = {}) {
+ const showItemInFolder = mock((_p: string) => {});
+ const confirmReveal = mock(async (_p: string) => true);
+ const deps: RevealExternalDeps = {
+ probe: () => 'exists',
+ confirmReveal,
+ showItemInFolder,
+ ...overrides,
+ };
+ return { deps, showItemInFolder, confirmReveal };
+}
+
+describe('handleRevealExternal', () => {
+ test('rejects a non-absolute or malformed path before touching disk', async () => {
+ const { deps, showItemInFolder, confirmReveal } = makeDeps();
+ expect(await handleRevealExternal('relative/x.md', deps)).toEqual({
+ ok: false,
+ reason: 'invalid-path',
+ });
+ expect(await handleRevealExternal('', deps)).toEqual({ ok: false, reason: 'invalid-path' });
+ expect(await handleRevealExternal('/a\0b', deps)).toEqual({
+ ok: false,
+ reason: 'invalid-path',
+ });
+ // Other C0 controls (newline/CR/tab) are rejected too — they'd inject extra
+ // lines into the confirmation dialog's interpolated path.
+ expect(await handleRevealExternal('/a\nb', deps)).toEqual({
+ ok: false,
+ reason: 'invalid-path',
+ });
+ expect(await handleRevealExternal('/a\tb', deps)).toEqual({
+ ok: false,
+ reason: 'invalid-path',
+ });
+ expect(await handleRevealExternal(42, deps)).toEqual({ ok: false, reason: 'invalid-path' });
+ expect(confirmReveal).not.toHaveBeenCalled();
+ expect(showItemInFolder).not.toHaveBeenCalled();
+ });
+
+ test('reports not-found for a missing path and shows no dialog', async () => {
+ const { deps, showItemInFolder, confirmReveal } = makeDeps({ probe: () => 'missing' });
+ expect(await handleRevealExternal('/tmp/gone.pdf', deps)).toEqual({
+ ok: false,
+ reason: 'not-found',
+ });
+ expect(confirmReveal).not.toHaveBeenCalled();
+ expect(showItemInFolder).not.toHaveBeenCalled();
+ });
+
+ test('maps an unreadable probe to error', async () => {
+ const { deps } = makeDeps({ probe: () => 'unreadable' });
+ expect(await handleRevealExternal('/root/secret', deps)).toEqual({
+ ok: false,
+ reason: 'error',
+ });
+ });
+
+ test('reveals on confirm', async () => {
+ const { deps, showItemInFolder } = makeDeps({ confirmReveal: async () => true });
+ expect(await handleRevealExternal('/tmp/out/report.pdf', deps)).toEqual({
+ ok: true,
+ outcome: 'revealed',
+ });
+ expect(showItemInFolder).toHaveBeenCalledWith('/tmp/out/report.pdf');
+ });
+
+ test('does not reveal when the user dismisses the dialog', async () => {
+ const { deps, showItemInFolder } = makeDeps({ confirmReveal: async () => false });
+ expect(await handleRevealExternal('/tmp/out/report.pdf', deps)).toEqual({
+ ok: true,
+ outcome: 'dismissed',
+ });
+ expect(showItemInFolder).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/desktop/src/main/reveal-external.ts b/packages/desktop/src/main/reveal-external.ts
new file mode 100644
index 000000000..ef883411f
--- /dev/null
+++ b/packages/desktop/src/main/reveal-external.ts
@@ -0,0 +1,58 @@
+/**
+ * Handler for `ok:shell:reveal-external` — reveal an ABSOLUTE path that lives
+ * outside the caller window's project, the terminal's "this file is outside
+ * your project" clickable-link flow.
+ *
+ * This is the one sanctioned UNCONTAINED reveal: unlike `ok:shell:reveal-asset`
+ * (project-contained via `isPathWithinProject`), the whole point here is to
+ * reveal a path the project boundary would reject. The security control is a
+ * native confirmation dialog — main stats the path and, only if it exists, pops
+ * a dialog naming it; `shell.showItemInFolder` fires solely on confirm. A
+ * compromised renderer can therefore at most surface a dialog the user must
+ * dismiss, never silently steer the file manager at arbitrary locations.
+ *
+ * Pure/deps-injected so the stat → confirm → reveal contract is unit-testable
+ * without an Electron runtime.
+ */
+
+import { isAbsolute } from 'node:path';
+
+export type RevealExternalResult =
+ | { ok: true; outcome: 'revealed' | 'dismissed' }
+ | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' };
+
+export interface RevealExternalDeps {
+ /** Probe the absolute path: exists (any node type) / missing / unreadable. */
+ readonly probe: (absPath: string) => 'exists' | 'missing' | 'unreadable';
+ /** Show the confirmation dialog; resolves true iff the user chose to reveal. */
+ readonly confirmReveal: (absPath: string) => Promise<boolean>;
+ /** Reveal the path in the OS file manager (`shell.showItemInFolder`). */
+ readonly showItemInFolder: (absPath: string) => void;
+}
+
+export async function handleRevealExternal(
+ absPath: unknown,
+ deps: RevealExternalDeps,
+): Promise<RevealExternalResult> {
+ // Absolute, non-empty, and free of C0 control chars — reject anything else
+ // before touching disk. NUL is malformed; other controls (newline/CR/tab)
+ // would inject extra lines into the confirmation dialog's interpolated path.
+ // Codepoint scan (not a regex) so there's no control-char-in-regex to placate.
+ if (typeof absPath !== 'string' || absPath.length === 0) {
+ return { ok: false, reason: 'invalid-path' };
+ }
+ if (Array.from(absPath).some((ch) => ch.charCodeAt(0) < 0x20)) {
+ return { ok: false, reason: 'invalid-path' };
+ }
+ if (!isAbsolute(absPath)) return { ok: false, reason: 'invalid-path' };
+
+ const probed = deps.probe(absPath);
+ if (probed === 'missing') return { ok: false, reason: 'not-found' };
+ if (probed === 'unreadable') return { ok: false, reason: 'error' };
+
+ const confirmed = await deps.confirmReveal(absPath);
+ if (!confirmed) return { ok: true, outcome: 'dismissed' };
+
+ deps.showItemInFolder(absPath);
+ return { ok: true, outcome: 'revealed' };
+}
diff --git a/packages/desktop/src/preload/index.ts b/packages/desktop/src/preload/index.ts
index 5d8681583..440e9ceff 100644
--- a/packages/desktop/src/preload/index.ts
+++ b/packages/desktop/src/preload/index.ts
@@ -406,6 +406,7 @@ const bridge: OkDesktopBridge = {
recordHandoff: (line) => invoke('ok:shell:record-handoff', line),
openAsset: (relPath: string) => invoke('ok:shell:open-asset', relPath),
revealAsset: (relPath: string) => invoke('ok:shell:reveal-asset', relPath),
+ revealExternal: (absPath: string) => invoke('ok:shell:reveal-external', absPath),
showAssetMenu: (params) => invoke('ok:shell:show-asset-menu', params),
showItemInFolder: (path: string) => invoke('ok:shell:show-item-in-folder', path),
trashItem: (absPath: string) => invoke('ok:shell:trash-item', absPath),
diff --git a/packages/desktop/src/shared/bridge-contract.ts b/packages/desktop/src/shared/bridge-contract.ts
index ba47ceb74..49bde737f 100644
--- a/packages/desktop/src/shared/bridge-contract.ts
+++ b/packages/desktop/src/shared/bridge-contract.ts
@@ -1214,6 +1214,24 @@ export interface OkDesktopBridge {
relPath: string,
): Promise<{ ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' }>;
+ /**
+ * Reveal an ABSOLUTE path that lives OUTSIDE the caller window's project —
+ * the terminal's "this file is outside your project" clickable-link flow.
+ * Unlike `revealAsset`, this is deliberately NOT containment-gated (that is
+ * the feature); instead main stats the path and, if it exists, pops a native
+ * confirmation dialog naming it, calling `shell.showItemInFolder` only on
+ * confirm. The dialog is the trust boundary: a compromised renderer can at
+ * most surface a dialog the user must dismiss, never silently steer the file
+ * manager. `not-found` when the path is missing (no dialog shown),
+ * `invalid-path` for a non-absolute / malformed input.
+ */
+ revealExternal(
+ absPath: string,
+ ): Promise<
+ | { ok: true; outcome: 'revealed' | 'dismissed' }
+ | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' }
+ >;
+
/**
* Display the native right-click context menu for an on-disk reference
* (`asset`, `wiki-link`, or `image`). Built from `Menu.buildFromTemplate`
diff --git a/packages/desktop/src/shared/ipc-channels.ts b/packages/desktop/src/shared/ipc-channels.ts
index ee6b10a0f..281d84136 100644
--- a/packages/desktop/src/shared/ipc-channels.ts
+++ b/packages/desktop/src/shared/ipc-channels.ts
@@ -30,7 +30,7 @@
* existing channels is preferred over net-new hand-rolled channels until
* that migration lands.
*
- * Count is 81 (ratchet cap 81). The 74→75 bump reconciled a merge collision:
+ * Count is 82 (ratchet cap 82). The 74→75 bump reconciled a merge collision:
* the worktree selector (`ok:worktree:dispatch`) and the terminal-controls PR
* (`ok:terminal:cli-installed-map`) each landed in the base tree's single free
* slot concurrently. The 75→76 bump then unioned in the desktop
@@ -43,7 +43,10 @@
* (`ok:project-integrations:dispatch`, same status+set fold, scoped to the
* sender window's project). The 79→81 bump added terminal-tab reload-survival
* (`ok:pty:set-meta` + `ok:pty:set-order`) — two slots, following the `ok:pty:*`
- * one-channel-per-operation design rather than a dispatch fold. Full rationale in
+ * one-channel-per-operation design rather than a dispatch fold. The 81→82 bump
+ * added the terminal clickable-links out-of-project reveal
+ * (`ok:shell:reveal-external`): a distinct trust boundary from `reveal-asset`
+ * (uncontained + dialog-gated), so it could not fold onto it. Full rationale in
* the ratchet test header.
*/
@@ -706,6 +709,23 @@ export interface RequestChannels {
args: [relPath: string];
result: { ok: true } | { ok: false; reason: 'path-escape' | 'not-found' | 'resolve-error' };
};
+ /**
+ * Reveal an on-disk ABSOLUTE path that lives OUTSIDE the caller window's
+ * project — the terminal's clickable-links "this file is outside your
+ * project" flow. Deliberately NOT containment-gated like `reveal-asset`
+ * (that is the point): instead main pops a native confirmation dialog naming
+ * the path, and only calls `shell.showItemInFolder` if the user confirms. The
+ * dialog is the security control — a compromised renderer can at most pop a
+ * dialog the user must dismiss, never silently steer the file manager. Main
+ * stats the path first: a missing path shows no dialog (`not-found`). Absolute
+ * paths only; relatives are rejected (`invalid-path`).
+ */
+ 'ok:shell:reveal-external': {
+ args: [absPath: string];
+ result:
+ | { ok: true; outcome: 'revealed' | 'dismissed' }
+ | { ok: false; reason: 'not-found' | 'invalid-path' | 'error' };
+ };
/**
* Pop the native right-click context menu for an on-disk reference
* (`asset`, `wiki-link`, or `image`). Main builds the menu via
diff --git a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
index 0fbcc9eb8..f3f44c605 100644
--- a/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
+++ b/packages/desktop/tests/integration/ipc-channel-count-ratchet.test.ts
@@ -311,8 +311,17 @@ const CHANNELS_SRC = readFileSync(SRC_PATH, 'utf-8');
* full ordering). Folding them into one discriminated channel would wear a
* single channel over two distinct operations against a namespace that
* deliberately keeps each PTY operation on its own channel.
+ *
+ * Bumped from 81 to 82 for the terminal clickable-links out-of-project reveal
+ * (`ok:shell:reveal-external`): when a terminal link points at an existing file
+ * OUTSIDE the window's project, main pops a "reveal in Finder?" confirmation and
+ * reveals on confirm. It is a distinct trust boundary from `ok:shell:reveal-asset`
+ * — deliberately UNCONTAINED (the whole feature) but dialog-gated — so folding it
+ * onto the containment-checked asset reveal would wear one channel over two
+ * opposite security contracts. Single member; the typed-ipc migration remains the
+ * committed end state, with the `ipc-channels.ts` header updated in lock-step.
*/
-const REQUEST_CHANNEL_CAP = 81;
+const REQUEST_CHANNEL_CAP = 82;
/**
* Extract the body of an interface block by name. Returns the substring
diff --git a/packages/desktop/tests/integration/m1-smoke.test.ts b/packages/desktop/tests/integration/m1-smoke.test.ts
index 55496a71b..cb8e2ab4d 100644
--- a/packages/desktop/tests/integration/m1-smoke.test.ts
+++ b/packages/desktop/tests/integration/m1-smoke.test.ts
@@ -248,6 +248,7 @@ describe('M1 smoke', () => {
'shell.recordHandoff', // Open in Agent telemetry
'shell.openAsset', // asset-click dispatcher
'shell.revealAsset', // asset-click dispatcher
+ 'shell.revealExternal', // terminal out-of-project reveal
'shell.showAssetMenu', // right-click context menu
'shell.showItemInFolder', // file-tree reveal-in-finder
'shell.trashItem', // sidebar Trash flow
diff --git a/packages/desktop/tests/smoke/terminal-links.e2e.ts b/packages/desktop/tests/smoke/terminal-links.e2e.ts
new file mode 100644
index 000000000..b9a66ffe9
--- /dev/null
+++ b/packages/desktop/tests/smoke/terminal-links.e2e.ts
@@ -0,0 +1,252 @@
+/**
+ * Clickable-terminal-links live-Electron smoke harness (the `_electron.launch()`
+ * rung). The mocked `TerminalPanel.dom.test.tsx` tests pin the orchestration
+ * against a fake xterm; they CANNOT prove that real xterm actually detects a URL
+ * / file path, calls the registered link provider, and activates on click. This
+ * suite drives the real renderer + real xterm + real PTY + real preload bridge +
+ * real main handlers, and asserts the user-observable outcome:
+ *
+ * - a plain `http(s)` URL printed in the shell → click → `shell.openExternal`
+ * (stubbed in main so no real browser opens) receives the URL;
+ * - an in-project `.md` path printed in the shell → click → the editor
+ * navigates to that doc (hash route).
+ *
+ * Skip gates mirror the sibling terminal smokes: opt-in via OK_DESKTOP_E2E_SMOKE=1,
+ * darwin-only, and the electron-vite build must exist (out/main/index.js).
+ *
+ * QUARANTINED ON CI (test.skip(IS_CI)): same live-Electron terminal surface +
+ * constrained-runner degradation as terminal-dock (shells exit before "running"
+ * after a few launches on the 6-vCPU runner). Allowlisted in the CI no-skip guard
+ * (QUARANTINE_ALLOWLIST); tracked in inkeep/agents-private#2187.
+ */
+
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ realpathSync,
+ rmSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { ElectronApplication, Page } from '@playwright/test';
+import { _electron as electron } from '@playwright/test';
+import { expect, test } from './_helpers/smoke-test';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const MAIN_ENTRY = resolve(__dirname, '..', '..', 'out', 'main', 'index.js');
+
+const SMOKE_ENABLED = process.env.OK_DESKTOP_E2E_SMOKE === '1';
+const DARWIN = process.platform === 'darwin';
+const BUILD_EXISTS = existsSync(MAIN_ENTRY);
+const IS_CI = process.env.CI === 'true' || process.env.GITHUB_ACTIONS === 'true';
+const DESKTOP_PRODUCT_NAME = '@inkeep/open-knowledge-desktop';
+
+interface Seed {
+ tmpHome: string;
+ projectDir: string;
+ pathPrefix: string;
+}
+
+/** Seed a consented project with a `notes.md` doc for the file-path case. */
+function seed(prefix: string): Seed {
+ const tmpHome = realpathSync(mkdtempSync(join(tmpdir(), `ok-termlink-${prefix}-home-`)));
+ const projectDir = realpathSync(mkdtempSync(join(tmpdir(), `ok-termlink-${prefix}-proj-`)));
+ mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
+ writeFileSync(join(projectDir, '.ok', 'config.yml'), "content:\n dir: '.'\n");
+ writeFileSync(join(projectDir, '.ok', 'local', 'config.yml'), 'terminal:\n enabled: true\n');
+ writeFileSync(join(projectDir, 'start.md'), '# Start\n\nSeed document.\n');
+ writeFileSync(join(projectDir, 'notes.md'), '# Notes\n\nClickable link target.\n');
+
+ // A fake `claude` on PATH so the readiness probe resolves deterministically
+ // (mirrors the sibling terminal smokes; the banner isn't under test here).
+ const binDir = join(tmpHome, 'fakebin');
+ mkdirSync(binDir, { recursive: true });
+ writeFileSync(join(binDir, 'claude'), '#!/bin/sh\necho "claude 0.0.0-fake"\n');
+ chmodSync(join(binDir, 'claude'), 0o755);
+
+ const userDataDir = join(tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME);
+ mkdirSync(userDataDir, { recursive: true });
+ writeFileSync(
+ join(userDataDir, 'state.json'),
+ JSON.stringify({
+ recentProjects: [
+ { path: projectDir, name: 'Term Links', lastOpenedAt: new Date().toISOString() },
+ ],
+ lastOpenedProject: projectDir,
+ versionPendingInstall: null,
+ lastSeenVersion: null,
+ lastSuccessfulCheckAt: null,
+ stuckHintShown: false,
+ }),
+ );
+
+ return { tmpHome, projectDir, pathPrefix: binDir };
+}
+
+async function launchApp(s: Seed): Promise<ElectronApplication> {
+ const deepLink = `openknowledge://open?project=${encodeURIComponent(s.projectDir)}&doc=start`;
+ return electron.launch({
+ args: [
+ MAIN_ENTRY,
+ `--user-data-dir=${join(s.tmpHome, 'Library', 'Application Support', DESKTOP_PRODUCT_NAME)}`,
+ deepLink,
+ ],
+ timeout: 30_000,
+ env: {
+ ...process.env,
+ HOME: s.tmpHome,
+ PATH: `${s.pathPrefix}:${process.env.PATH ?? ''}`,
+ OK_DESKTOP_E2E_SMOKE: '1',
+ OK_RECLAIM_DISABLE: '1',
+ },
+ });
+}
+
+async function findEditorWindow(app: ElectronApplication, timeoutMs = 25_000): Promise<Page> {
+ let page: Page | undefined;
+ await expect(async () => {
+ for (const p of app.windows()) {
+ const mode = await p.evaluate(() => window.okDesktop?.config?.mode).catch(() => undefined);
+ if (mode === 'editor') {
+ page = p;
+ return;
+ }
+ }
+ throw new Error('no editor window yet');
+ }).toPass({ timeout: timeoutMs });
+ if (!page) throw new Error('editor window vanished after readiness poll');
+ return page;
+}
+
+/** Open the terminal via the View menu, bottom-dock it, and wait for a live shell. */
+async function openRunningTerminal(app: ElectronApplication, page: Page): Promise<void> {
+ const label = await app.evaluate(async ({ Menu }) => {
+ const view = Menu.getApplicationMenu()?.items.find((i) => i.label === 'View');
+ const item = view?.submenu?.items.find(
+ (i) => i.label === 'Show Terminal' || i.label === 'Hide Terminal',
+ );
+ if (!item) return false;
+ if (item.label === 'Show Terminal') item.click();
+ return item.label;
+ });
+ expect(label).toBeTruthy();
+ await expect(page.locator('section[aria-label="Terminal"]')).toBeVisible({ timeout: 15_000 });
+ // Bottom-dock (default is the right column) so the terminal is wide enough for
+ // a printed URL to render on one row — the link-click assertions need it.
+ const toBottom = page.getByRole('button', { name: 'Dock terminal to the bottom' });
+ if (await toBottom.count()) await toBottom.click();
+ // The status container isn't "visible" to Playwright while right-docked; assert
+ // the attribute value instead (matches the terminal-dock smoke).
+ await expect(page.locator('[data-terminal-status]')).toHaveAttribute(
+ 'data-terminal-status',
+ 'running',
+ { timeout: 25_000 },
+ );
+}
+
+/** Run a command in the focused xterm and wait for `marker` to render. */
+async function runInTerminal(page: Page, command: string, marker: string): Promise<void> {
+ await page.locator('section[aria-label="Terminal"] .xterm').click();
+ await page.keyboard.type(command);
+ await page.keyboard.press('Enter');
+ // The command echoes + its output prints; wait for the marker to appear in the
+ // rendered rows (DOM renderer under OK_DESKTOP_E2E_SMOKE=1).
+ await expect(page.locator('section[aria-label="Terminal"] .xterm-rows')).toContainText(marker, {
+ timeout: 10_000,
+ });
+}
+
+/**
+ * Click the last rendered occurrence of `linkText` in the terminal. xterm's DOM
+ * renderer paints each glyph run as a span; the printed token (URL / path) is a
+ * contiguous run, so clicking that span's box lands on the link's cells and
+ * triggers xterm's link activation.
+ */
+async function clickTerminalLink(page: Page, linkText: string): Promise<void> {
+ const span = page
+ .locator('section[aria-label="Terminal"] .xterm-rows span', { hasText: linkText })
+ .last();
+ await span.scrollIntoViewIfNeeded();
+ await span.hover();
+ await span.click();
+}
+
+/** Replace `shell.openExternal` in main with a recorder (no real browser opens). */
+async function stubOpenExternal(app: ElectronApplication): Promise<void> {
+ await app.evaluate(({ shell }) => {
+ const g = globalThis as unknown as { __openedExternal?: string[] };
+ g.__openedExternal = [];
+ shell.openExternal = async (url: string) => {
+ g.__openedExternal?.push(url);
+ };
+ });
+}
+
+async function readOpenedExternal(app: ElectronApplication): Promise<string[]> {
+ return app.evaluate(
+ () => (globalThis as unknown as { __openedExternal?: string[] }).__openedExternal ?? [],
+ );
+}
+
+const cleanup: string[] = [];
+function track(...paths: string[]): void {
+ cleanup.push(...paths);
+}
+
+test.describe('Terminal clickable links — live Electron', () => {
+ test.skip(
+ !SMOKE_ENABLED || !DARWIN || !BUILD_EXISTS,
+ 'Live-Electron smoke: set OK_DESKTOP_E2E_SMOKE=1 on darwin after `bun run build:desktop`.',
+ );
+ test.skip(
+ IS_CI,
+ 'Quarantined on CI: live-Electron terminal smoke degrades on the constrained runner (see inkeep/agents-private#2187).',
+ );
+
+ test.afterAll(() => {
+ for (const p of cleanup.splice(0)) rmSync(p, { recursive: true, force: true });
+ });
+
+ test('clicking a printed URL opens it via shell.openExternal', async ({ captureStderrFor }) => {
+ const s = seed('url');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ // Bounded auto-close + dir cleanup on teardown (no unbounded `app.close()`).
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await stubOpenExternal(app);
+ await openRunningTerminal(app, page);
+
+ const url = 'https://ok-smoke.example/link';
+ await runInTerminal(page, `echo ${url}`, 'ok-smoke.example');
+ await clickTerminalLink(page, 'ok-smoke.example');
+
+ await expect(async () => {
+ expect(await readOpenedExternal(app)).toContain(url);
+ }).toPass({ timeout: 8_000 });
+ });
+
+ test('clicking an in-project markdown path opens the doc in the editor', async ({
+ captureStderrFor,
+ }) => {
+ const s = seed('doc');
+ track(s.tmpHome, s.projectDir);
+ const app = await launchApp(s);
+ captureStderrFor(app, { cleanupDirs: [s.tmpHome, s.projectDir] });
+ const page = await findEditorWindow(app);
+ await openRunningTerminal(app, page);
+
+ await runInTerminal(page, 'echo notes.md', 'notes.md');
+ await clickTerminalLink(page, 'notes.md');
+
+ // The doc link routes an in-editor hash navigation to `notes`.
+ await expect(async () => {
+ const hash = await page.evaluate(() => window.location.hash);
+ expect(hash).toBe('#/notes');
+ }).toPass({ timeout: 8_000 });
+ });
+});