Skip to content

an open-source alternative to the dots, bots and muses of the world, run an office of claude code/codex like agents on your laptop, sandboxes or anywhere, uses your existing subscriptions

feat(terminal): every path is clickable, not just markdown

Chaitanya Girid15056e6aeaf
diff --git a/src/main/index.ts b/src/main/index.ts
index 5b1df90b..5944af45 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -3194,6 +3194,32 @@ ipcMain.handle('fs:statAbs', (_evt, p: unknown) => {
return statAbs(p);
});
+/** Reveal a path in the OS file browser — Finder, Explorer, or whatever the
+ * Linux desktop registers. Backs ⌘-click on a terminal path we cannot open
+ * ourselves (an image, an archive, an unknown extension).
+ *
+ * `showItemInFolder`, NEVER `shell.openPath`, for a file. The path arrives
+ * from agent output, and openPath hands an arbitrary file to its default
+ * application: a printed `installer.dmg` or `.desktop` would be one click from
+ * executing. Revealing only ever opens a file browser, so the worst an agent
+ * can achieve by printing a path is a window at a folder the user could
+ * already open themselves.
+ *
+ * openPath IS used for a directory, and only after statAbs has confirmed it is
+ * one — a directory has no default application to launch, so the execution
+ * argument above does not apply, and revealing a folder inside its parent is
+ * not what "open this folder" means to anyone. */
+ipcMain.handle('fs:revealPath', async (_evt, p: unknown) => {
+ if (typeof p !== 'string' || !p.length || p.length > 4096 || p.includes('\0')) {
+ return { ok: false, error: 'bad request' };
+ }
+ const st = await statAbs(p);
+ if (!st.exists) return { ok: false, error: 'not found' };
+ if (st.isFile) { shell.showItemInFolder(st.path); return { ok: true }; }
+ const err = await shell.openPath(st.path);
+ return err ? { ok: false, error: err } : { ok: true };
+});
+
// ─── IPC: git ───────────────────────────────────────────────────────────────
ipcMain.handle('git:isRepo', (_evt, cwd: unknown) => {
if (typeof cwd !== 'string') return false;
diff --git a/src/preload/index.ts b/src/preload/index.ts
index d7214d28..32d65078 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -685,6 +685,12 @@ const api = {
* terminal ⌘-click markdown flow. Metadata only, never contents. */
statAbs: (p: string): Promise<{ exists: boolean; isFile: boolean; path: string }> =>
ipcRenderer.invoke('fs:statAbs', p),
+ /** Show a path in the OS file browser (Finder / Explorer / the Linux default).
+ * Backs ⌘-click on a terminal path we have no viewer for. Reveals only — main
+ * never launches a file's default application, because the path came from
+ * agent output. */
+ revealPath: (p: string): Promise<{ ok: boolean; error?: string }> =>
+ ipcRenderer.invoke('fs:revealPath', p),
// ─── Git ─────────────────────────────────────────────────────────────────
gitIsRepo: (cwd: string): Promise<boolean> => ipcRenderer.invoke('git:isRepo', cwd),
diff --git a/src/renderer/src/components/terminalPool.ts b/src/renderer/src/components/terminalPool.ts
index 64fcde59..1e2e5295 100644
--- a/src/renderer/src/components/terminalPool.ts
+++ b/src/renderer/src/components/terminalPool.ts
@@ -18,6 +18,9 @@ import { Terminal } from '@xterm/xterm';
import { FitAddon } from '@xterm/addon-fit';
import { WebglAddon } from '@xterm/addon-webgl';
import { Unicode11Addon } from '@xterm/addon-unicode11';
+import {
+ classifyPathToken, isPathToken, pathTokenMatcher, stripPathToken, type PathAction
+} from '@shared/terminalPaths';
import {
createTerminalRecoveryState,
normalizePtyChunk,
@@ -742,23 +745,26 @@ export function disposeTerminal(ptyId: string): void {
pool.delete(ptyId);
}
-// ─── v0.3.4: ⌘-click a markdown path in terminal output → rendered preview ───
+// ─── v0.3.4: ⌘-click a path in terminal output ──────────────────────────────
// A custom ILinkProvider (NOT WebLinksAddon, which only matches URLs): detects
-// *.md tokens in the visible buffer line, resolves relative ones against the
+// path tokens in the visible buffer line, resolves relative ones against the
// owning agent's cwd, and on Cmd/Ctrl+click verifies existence via the
-// metadata-only fs:statAbs IPC before opening the fullscreen preview overlay.
+// metadata-only fs:statAbs IPC before acting.
// Plain click stays with the TUI (matches VS Code's terminal convention).
// The path string is agent output — treated as hostile: it flows only into a
-// read-only stat + the existing read pipeline, and only on an explicit
-// modifier-click.
-const MD_TOKEN_RE = /[A-Za-z0-9_@.~/+-]+\.(?:md|markdown)\b(?::\d+)?/g;
+// read-only stat, the existing read pipeline, or a REVEAL (never an "open with
+// the default app", which would turn a printed path into an execution), and
+// only on an explicit modifier-click.
+//
+// v0.4.5 widened this from markdown-only to every path token. What each type
+// does lives in @shared/terminalPaths, not here — this file only knows how to
+// find tokens on a line and how to run the three verdicts.
const mdStatCache = new Map<string, { isFile: boolean; path: string }>();
-function resolveMdCandidate(ptyId: string, raw: string): string | null {
- // strip wrapping quotes/backticks/parens + trailing punctuation + :line
- const p = raw.replace(/^["'`(]+/, '').replace(/["'`),.;:]+$/, '').replace(/:(\d+)$/, '');
- if (!/\.(md|markdown)$/i.test(p)) return null;
- if (p.startsWith('~/') || p.startsWith('/')) return p;
+function resolvePathCandidate(ptyId: string, raw: string): string | null {
+ const p = stripPathToken(raw);
+ if (!isPathToken(p)) return null;
+ if (p.startsWith('~/') || p.startsWith('/') || /^[A-Za-z]:[\\/]/.test(p)) return p;
// relative → resolve against the owning agent's cwd. Async store import keeps
// this module usable in the node test harness (no zustand/react at load).
const cwd = storeApi?.getState().agents.find((a) => a.ptyId === ptyId)?.cwd ?? null;
@@ -780,17 +786,23 @@ void import('@/store/store')
.then((m) => { storeApi = (m as unknown as { useStore: MdStoreShape }).useStore; })
.catch(() => { /* store unavailable (tests) — link provider stays inert */ });
-async function openMdPreview(abs: string): Promise<void> {
+/** Act on a verified path. `reveal` is the only branch that accepts a directory:
+ * the other two need a file to put in the editor. A miss is silent by design —
+ * the token is agent output and may simply not exist. */
+async function activatePath(abs: string, action: PathAction): Promise<void> {
let hit = mdStatCache.get(abs);
if (!hit) {
const res = await window.cth.statAbs(abs).catch(() => null);
- if (!res) return;
- hit = { isFile: res.exists && res.isFile, path: res.path };
+ if (!res || !res.exists) return;
+ hit = { isFile: res.isFile, path: res.path };
if (mdStatCache.size > 500) mdStatCache.clear();
mdStatCache.set(abs, hit);
}
- if (!hit.isFile) return;
- storeApi?.getState().setFullscreenFile(hit.path, 'preview');
+ if (action === 'reveal' || !hit.isFile) {
+ void window.cth.revealPath(hit.path).catch(() => { /* file browser refused */ });
+ return;
+ }
+ storeApi?.getState().setFullscreenFile(hit.path, action === 'preview' ? 'preview' : 'edit');
}
function registerMarkdownLinkProvider(term: Terminal, ptyId: string): void {
@@ -799,14 +811,15 @@ function registerMarkdownLinkProvider(term: Terminal, ptyId: string): void {
provideLinks(bufferLineNumber, callback) {
const line = term.buffer.active.getLine(bufferLineNumber - 1);
const text = line ? line.translateToString(true) : '';
- if (!text || !/\.(md|markdown)\b/i.test(text)) { callback(undefined); return; }
+ if (!text || !text.includes('.')) { callback(undefined); return; }
const links: Parameters<typeof callback>[0] = [];
- const re = new RegExp(MD_TOKEN_RE.source, 'g');
+ const re = pathTokenMatcher();
let m: RegExpExecArray | null;
while ((m = re.exec(text)) !== null) {
const raw = m[0];
- const abs = resolveMdCandidate(ptyId, raw);
+ const abs = resolvePathCandidate(ptyId, raw);
if (!abs) continue;
+ const action = classifyPathToken(stripPathToken(raw));
links!.push({
range: {
start: { x: m.index + 1, y: bufferLineNumber },
@@ -817,7 +830,7 @@ function registerMarkdownLinkProvider(term: Terminal, ptyId: string): void {
activate: (event: MouseEvent | undefined) => {
// ⌘/Ctrl+click only — a plain click must keep going to the TUI.
if (event && !(event.metaKey || event.ctrlKey)) return;
- void openMdPreview(abs);
+ void activatePath(abs, action);
}
});
}
diff --git a/src/shared/terminalPaths.ts b/src/shared/terminalPaths.ts
new file mode 100644
index 00000000..0358d568
--- /dev/null
+++ b/src/shared/terminalPaths.ts
@@ -0,0 +1,137 @@
+/**
+ * What a ⌘-clicked path token in terminal output should DO.
+ *
+ * v0.3.4 shipped this for markdown only: `*.md` in agent output became a link
+ * that opened the rendered preview. Everything else in the same line stayed
+ * dead text, so a printed `src/main/updater.ts` was something you had to
+ * retype into the file tree by hand.
+ *
+ * Three outcomes, and the split is about what we can HONESTLY do with the file:
+ *
+ * preview → markdown. There is a renderer for it, and reading is the point.
+ * edit → source and config we can put in Monaco without lying about it.
+ * reveal → everything else: images, archives, binaries, PDFs, unknown
+ * extensions, directories. We open the OS file browser at the
+ * file's parent instead of pretending to understand the bytes.
+ *
+ * WHY REVEAL RATHER THAN OPEN. The token comes from AGENT OUTPUT, which is
+ * hostile input. Handing an arbitrary path to the OS "open with default app"
+ * call would let a line of terminal text become an execution: a printed
+ * `installer.dmg`, `payload.app`, or `.desktop` file is one ⌘-click from
+ * running. Revealing only ever opens a file browser, so the worst an agent can
+ * do by printing a path is show you a folder you could already reach yourself.
+ * That is why this module never returns an "open" verdict for an unknown type.
+ *
+ * MATCHING IS THE HARD PART, not classifying. Anchoring on a known extension
+ * (what the markdown version did) cannot see `report.pdf` — and `report.pdf` is
+ * exactly the case that needs reveal. Opening the match up to ANY extension
+ * instead drags in every version string and decimal on the line: `v0.4.5`,
+ * `1.5`, `electron 43.0`. The rule that separates them is below.
+ */
+
+import { isImagePath } from './imageTypes';
+
+/** Extensions that open in the markdown preview. */
+const PREVIEW_EXTS = new Set(['md', 'markdown']);
+
+/**
+ * Extensions we are willing to put in the editor. Deliberately a list rather
+ * than "anything that isn't binary": a wrong guess here opens a font or a
+ * sqlite file as mojibake, and the reveal fallback is a strictly better answer
+ * for anything we are not sure about.
+ */
+const EDIT_EXTS = new Set([
+ // source
+ 'ts', 'tsx', 'js', 'jsx', 'mjs', 'cjs', 'mts', 'cts',
+ 'py', 'rb', 'go', 'rs', 'java', 'kt', 'kts', 'swift', 'c', 'h', 'cc', 'cpp',
+ 'hpp', 'cs', 'php', 'lua', 'pl', 'r', 'scala', 'clj', 'ex', 'exs', 'erl',
+ 'dart', 'zig', 'hs', 'ml', 'vue', 'svelte', 'astro',
+ // shell
+ 'sh', 'bash', 'zsh', 'fish', 'ps1', 'bat', 'cmd',
+ // markup and style
+ 'html', 'htm', 'css', 'scss', 'sass', 'less', 'xml', 'xsl',
+ // data and config
+ 'json', 'jsonc', 'json5', 'yaml', 'yml', 'toml', 'ini', 'cfg', 'conf',
+ 'env', 'properties', 'lock', 'gradle', 'tf', 'tfvars', 'graphql', 'gql',
+ 'proto', 'sql', 'csv', 'tsv',
+ // plain text
+ 'txt', 'text', 'log', 'diff', 'patch', 'gitignore', 'dockerignore',
+ 'editorconfig', 'npmrc', 'nvmrc'
+]);
+
+export type PathAction = 'preview' | 'edit' | 'reveal';
+
+/**
+ * Lower-cased extension of the last path segment, or '' when there is none.
+ * Local rather than imported from imageTypes so a `?query` suffix cannot reach
+ * a filesystem call: terminal tokens are filesystem paths, and a literal `?` in
+ * a filename is legal on every platform we ship.
+ */
+function extOf(token: string): string {
+ const base = token.split(/[/\\]/).pop() ?? '';
+ const dot = base.lastIndexOf('.');
+ if (dot <= 0 || dot === base.length - 1) return '';
+ return base.slice(dot + 1).toLowerCase();
+}
+
+/**
+ * Candidate path tokens in one line of terminal output.
+ *
+ * The extension must START WITH A LETTER and run 1-8 more alphanumerics. That
+ * single constraint is what keeps `v0.4.5`, `1.5`, and `0.92` out: their
+ * "extension" is digits. `node_modules/.bin` has no extension and is caught by
+ * the separator rule in `isPathToken` instead.
+ *
+ * The leading `X:\` group exists because `:` cannot be in the body class (it
+ * would swallow the `:line` suffix). Without the group the match on
+ * `C:\Users\x\a.ts` starts at the backslash, and a drive-less `\Users\x\a.ts`
+ * then looks RELATIVE and gets joined onto the agent's cwd.
+ */
+const PATH_TOKEN_RE = /(?:[A-Za-z]:[\\/])?[A-Za-z0-9_@.~/\\+-]*[A-Za-z0-9_@~/\\+-]\.[A-Za-z][A-Za-z0-9]{0,7}(?::\d+)?/g;
+
+/** A fresh matcher. The regex is stateful (`g`), so callers must never share one. */
+export function pathTokenMatcher(): RegExp {
+ return new RegExp(PATH_TOKEN_RE.source, 'g');
+}
+
+/** Strip shell/prose wrapping and any trailing `:line` from a raw match. */
+export function stripPathToken(raw: string): string {
+ return raw
+ .replace(/^["'`([<]+/, '')
+ .replace(/["'`)\]>,.;:]+$/, '')
+ .replace(/:(\d+)$/, '');
+}
+
+/**
+ * Is this token worth underlining at all?
+ *
+ * A token qualifies when it carries an extension we KNOW, or when it contains a
+ * path separator. The separator clause is what lets `docs/report.pdf` and
+ * `/tmp/dump.bin` reach the reveal branch while a bare `electron.43` on a prose
+ * line stays dead text. It is a heuristic and it is meant to be: the cost of a
+ * false positive is one underline that stats to nothing and does nothing.
+ */
+export function isPathToken(token: string): boolean {
+ const ext = extOf(token);
+ if (!ext) return false;
+ if (PREVIEW_EXTS.has(ext) || EDIT_EXTS.has(ext) || isImagePath(token)) return true;
+ return /[/\\]/.test(token);
+}
+
+/**
+ * What ⌘-click should do with `token`.
+ *
+ * Images resolve to `reveal` on purpose. The app HAS an image viewer (the IDE
+ * routes there), but a terminal click is a navigation gesture: you clicked a
+ * path because you want to get to the file, and Finder is where you can then
+ * drag, rename, or open it with the tool you actually wanted. Change this to
+ * 'preview' if that reading turns out to be wrong; the classifier is the only
+ * place that decides.
+ */
+export function classifyPathToken(token: string): PathAction {
+ const ext = extOf(token);
+ if (PREVIEW_EXTS.has(ext)) return 'preview';
+ if (isImagePath(token)) return 'reveal';
+ if (EDIT_EXTS.has(ext)) return 'edit';
+ return 'reveal';
+}
diff --git a/test/terminal-paths.test.cjs b/test/terminal-paths.test.cjs
new file mode 100644
index 00000000..54d6774d
--- /dev/null
+++ b/test/terminal-paths.test.cjs
@@ -0,0 +1,115 @@
+'use strict';
+
+/**
+ * ⌘-click on a path in terminal output. Two jobs, and the matcher is the one
+ * that actually breaks: agent output is full of version strings and decimals
+ * that look like filenames if the extension rule is loose.
+ */
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const loadTs = require('./load-ts.cjs');
+
+const {
+ classifyPathToken, isPathToken, pathTokenMatcher, stripPathToken
+} = loadTs('src/shared/terminalPaths.ts');
+
+/** Every token the provider would underline on one line of output. */
+function tokensIn(line) {
+ const re = pathTokenMatcher();
+ const out = [];
+ let m;
+ while ((m = re.exec(line)) !== null) {
+ const p = stripPathToken(m[0]);
+ if (isPathToken(p)) out.push(p);
+ }
+ return out;
+}
+
+/* ---------------------------------------------------------------- *
+ * classification
+ * ---------------------------------------------------------------- */
+
+test('markdown previews, source edits — the v0.3.4 behaviour is unchanged', () => {
+ assert.equal(classifyPathToken('RELEASE.md'), 'preview');
+ assert.equal(classifyPathToken('docs/drops/v0.4.5.markdown'), 'preview');
+ assert.equal(classifyPathToken('src/main/updater.ts'), 'edit');
+ assert.equal(classifyPathToken('tools/copy-main-assets.cjs'), 'edit');
+ assert.equal(classifyPathToken('electron-builder.yml'), 'edit');
+ assert.equal(classifyPathToken('.github/workflows/release.yml'), 'edit');
+});
+
+test('images reveal rather than open — a click on a path is a navigation gesture', () => {
+ for (const p of ['build/icon.png', 'shot.JPEG', 'a/b/logo.svg', 'anim.webp']) {
+ assert.equal(classifyPathToken(p), 'reveal', p);
+ }
+});
+
+test('anything we cannot honestly render reveals instead of guessing', () => {
+ for (const p of ['report.pdf', 'dump.bin', 'archive.zip', 'db.sqlite', 'font.woff2']) {
+ assert.equal(classifyPathToken(p), 'reveal', p);
+ }
+});
+
+test('an executable never classifies as anything but reveal', () => {
+ // The whole safety argument: reveal opens a file browser, it never launches.
+ for (const p of ['installer.dmg', 'Payload.app', 'setup.exe', 'run.desktop']) {
+ assert.equal(classifyPathToken(p), 'reveal', p);
+ }
+});
+
+/* ---------------------------------------------------------------- *
+ * matching — the part that goes wrong
+ * ---------------------------------------------------------------- */
+
+test('version strings and decimals are not files', () => {
+ assert.deepEqual(tokensIn('bumped to v0.4.5 after 1.5 hours, cost $0.92'), []);
+ assert.deepEqual(tokensIn('electron 43.0 and vite 7.1.2'), []);
+});
+
+test('a bare unknown extension needs a separator to count as a path', () => {
+ // No separator and an extension we do not know: could be prose. Left alone.
+ assert.deepEqual(tokensIn('the release is codenamed spring.thaw'), []);
+ // Same extension, now unambiguously a path.
+ assert.deepEqual(tokensIn('wrote out/spring.thaw'), ['out/spring.thaw']);
+});
+
+test('a known extension is a path with or without a separator', () => {
+ assert.deepEqual(tokensIn('see RELEASE.md'), ['RELEASE.md']);
+ assert.deepEqual(tokensIn('edited package.json'), ['package.json']);
+});
+
+test('several tokens on one line all resolve independently', () => {
+ assert.deepEqual(
+ tokensIn('moved src/main/updater.ts and build/icon.png, see RELEASE.md'),
+ ['src/main/updater.ts', 'build/icon.png', 'RELEASE.md']
+ );
+});
+
+test('shell and prose wrapping comes off, and so does :line', () => {
+ assert.equal(stripPathToken('`src/main/index.ts`'), 'src/main/index.ts');
+ assert.equal(stripPathToken('"docs/a.md",'), 'docs/a.md');
+ assert.equal(stripPathToken('(build/icon.png)'), 'build/icon.png');
+ assert.equal(stripPathToken('src/main/updater.ts:165'), 'src/main/updater.ts');
+});
+
+test('a :line suffix survives matching and still classifies by extension', () => {
+ assert.deepEqual(tokensIn('fails at src/main/updater.ts:165'), ['src/main/updater.ts']);
+ assert.equal(classifyPathToken('src/main/updater.ts'), 'edit');
+});
+
+test('absolute, home, and Windows paths are all recognised', () => {
+ assert.deepEqual(tokensIn('at /Users/x/notes.md'), ['/Users/x/notes.md']);
+ assert.deepEqual(tokensIn('at ~/HarnessAgents/board.md'), ['~/HarnessAgents/board.md']);
+ assert.deepEqual(tokensIn('at C:\\Users\\x\\a.ts'), ['C:\\Users\\x\\a.ts']);
+});
+
+test('a dotted directory name cannot masquerade as an extension', () => {
+ // extOf looks at the LAST segment only, so v1.2 here is not the extension.
+ assert.equal(classifyPathToken('reports/v1.2/summary.md'), 'preview');
+});
+
+test('case does not decide the verdict', () => {
+ assert.equal(classifyPathToken('README.MD'), 'preview');
+ assert.equal(classifyPathToken('src/App.TSX'), 'edit');
+});