Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(terminal): Cmd/Ctrl+click opens URLs in the browser and file paths as editor nodes
enes57974dab3a30
diff --git a/package-lock.json b/package-lock.jsonindex 1de6239f5..a419a7ea0 100644--- a/package-lock.json+++ b/package-lock.json@@ -11,6 +11,7 @@"license": "BUSL-1.1","dependencies": {"@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@xterm/addon-web-links": "^0.11.0","dompurify": "^3.4.11","electron-updater": "^6.8.9","marked": "^12.0.2",@@ -3003,6 +3004,15 @@"@xterm/xterm": "^5.0.0"}},+ "node_modules/@xterm/addon-web-links": {+ "version": "0.11.0",+ "resolved": "https://registry.npmjs.org/@xterm/addon-web-links/-/addon-web-links-0.11.0.tgz",+ "integrity": "sha512-nIHQ38pQI+a5kXnRaTgwqSHnX7KE6+4SVoceompgHL26unAxdfP6IPqUTSYPQgSwM56hsElfoNrrW5V7BUED/Q==",+ "license": "MIT",+ "peerDependencies": {+ "@xterm/xterm": "^5.0.0"+ }+ },"node_modules/@xterm/addon-webgl": {"version": "0.18.0","resolved": "https://registry.npmjs.org/@xterm/addon-webgl/-/addon-webgl-0.18.0.tgz",@@ -3017,7 +3027,6 @@"version": "5.5.0","resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-5.5.0.tgz","integrity": "sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==",- "dev": true,"license": "MIT"},"node_modules/@xyflow/react": {diff --git a/package.json b/package.jsonindex c2bf741b6..3a55cb37a 100644--- a/package.json+++ b/package.json@@ -70,6 +70,7 @@},"dependencies": {"@anthropic-ai/claude-agent-sdk": "^0.3.201",+ "@xterm/addon-web-links": "^0.11.0","dompurify": "^3.4.11","electron-updater": "^6.8.9","marked": "^12.0.2",diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 216e30337..499d4b0c8 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -1598,6 +1598,25 @@ export function Canvas() {setReveal((r) => ({ path: relPath, nonce: (r?.nonce ?? 0) + 1 }))}, [])+ // Cmd+click file links inside terminal output (TerminalNode dispatches these — it has no+ // direct line to the canvas). Files open as editor nodes; directories reveal in Explorer.+ useEffect(() => {+ const onOpen = (e: Event): void => {+ const d = (e as CustomEvent<{ path: string; ssh?: boolean }>).detail+ if (d?.path) openFile(d.path, undefined, d.ssh)+ }+ const onReveal = (e: Event): void => {+ const d = (e as CustomEvent<{ path: string }>).detail+ if (d?.path) revealProjectFile(d.path)+ }+ window.addEventListener('nodeterm:open-file', onOpen)+ window.addEventListener('nodeterm:reveal-file', onReveal)+ return () => {+ window.removeEventListener('nodeterm:open-file', onOpen)+ window.removeEventListener('nodeterm:reveal-file', onReveal)+ }+ }, [openFile, revealProjectFile])+/** Open a git diff editor node for a changed file (from Source Control). */const openDiff = useCallback((relPath: string, staged: boolean) => {diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 5c0e8a5ea..a3145b405 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -11,6 +11,7 @@ import { Terminal } from '@xterm/xterm'import { FitAddon } from '@xterm/addon-fit'import { SearchAddon } from '@xterm/addon-search'import { WebglAddon } from '@xterm/addon-webgl'+import { WebLinksAddon } from '@xterm/addon-web-links'import { renderMarkdown } from '../lib/markdown'import { ChatPanel } from './ChatPanel'import { transport as localTransport } from '../terminal/local-transport'@@ -18,6 +19,9 @@ import { RemoteTransport } from '../terminal/remote-transport'import type { TerminalTransport } from '../terminal/transport'import { patchTerminalScale } from '../terminal/scale-fix'import { parseOsc52 } from '../terminal/osc52'+import { createFileLinkProvider, makeDirListingLookup } from '../terminal/file-links'+import { sshFs } from '../terminal/ssh-fs'+import type { FsApi } from '@shared/types'import {attachReplay,closedByLabel,@@ -604,6 +608,36 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasNif (text !== null) window.nodeTerminal.clipboard.writeText(text)return true})+ // Cmd (mac) / Ctrl+click link opening. URLs → default browser via the WebLinksAddon;+ // file paths → editor node / Explorer reveal via the custom provider. Both are+ // modifier-gated inside their activate handlers, so plain clicks stay selections.+ term.loadAddon(+ new WebLinksAddon((event, uri) => {+ if (event.metaKey || event.ctrlKey) window.nodeTerminal.shell.openExternal(uri)+ })+ )+ // Relay-remote nodes have no client-side fs to verify paths against — URLs only.+ if (!data.remote) {+ const projectFs = (): { fs: FsApi; ssh: boolean } => {+ const st = useProjects.getState()+ const project = st.projects.find((p) => p.id === st.activeProjectId)+ return project?.ssh ? { fs: sshFs(project.id), ssh: true } : { fs: window.nodeTerminal.fs, ssh: false }+ }+ const lookup = makeDirListingLookup(async (dir) => projectFs().fs.list(dir))+ term.registerLinkProvider(+ createFileLinkProvider(term, {+ getCwd: () => (data.cwd as string | undefined) || undefined,+ lookup,+ activate: (abs, isDir) => {+ if (isDir) window.dispatchEvent(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } }))+ else+ window.dispatchEvent(+ new CustomEvent('nodeterm:open-file', { detail: { path: abs, ssh: projectFs().ssh } })+ )+ }+ })+ )+ }}// Cmd+C (mac) / Ctrl+Shift+C (Linux, Windows) / Ctrl+Insert copy the terminal selection — xtermdiff --git a/src/renderer/terminal/file-links.test.ts b/src/renderer/terminal/file-links.test.tsnew file mode 100644index 000000000..36f29af23--- /dev/null+++ b/src/renderer/terminal/file-links.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from 'vitest'+import { matchFileTokens, resolveFileToken } from './file-links'++describe('matchFileTokens', () => {+ it('finds absolute, dot-relative and bare relative paths', () => {+ const t = matchFileTokens('see /etc/hosts and ./src/a.ts plus src/lib/b.tsx here')+ expect(t.map((x) => x.path)).toEqual(['/etc/hosts', './src/a.ts', 'src/lib/b.tsx'])+ expect(t[0].startIndex).toBe(4)+ })++ it('parses :line and :line:col suffixes into path + line', () => {+ const [t] = matchFileTokens('src/renderer/App.tsx:42:7 - error TS2551')+ expect(t.path).toBe('src/renderer/App.tsx')+ expect(t.line).toBe(42)+ expect(t.text).toBe('src/renderer/App.tsx:42:7')+ })++ it('strips trailing punctuation', () => {+ expect(matchFileTokens('(see src/a.ts, then src/b.ts.)').map((x) => x.path)).toEqual([+ 'src/a.ts',+ 'src/b.ts'+ ])+ })++ it('skips URLs and lone words', () => {+ expect(matchFileTokens('https://example.com/a/b plain word')).toEqual([])+ })++ it('skips ~ paths (no home resolution in v1)', () => {+ expect(matchFileTokens('~/notes.md')).toEqual([])+ })+})++describe('resolveFileToken', () => {+ it('passes absolutes through and resolves relatives against cwd', () => {+ expect(resolveFileToken('/etc/hosts', '/repo')).toBe('/etc/hosts')+ expect(resolveFileToken('src/a.ts', '/repo')).toBe('/repo/src/a.ts')+ expect(resolveFileToken('./src/a.ts', '/repo/')).toBe('/repo/src/a.ts')+ expect(resolveFileToken('../other/x.ts', '/repo/sub')).toBe('/repo/other/x.ts')+ })++ it('returns null without a cwd for relatives, and for root-escaping paths', () => {+ expect(resolveFileToken('src/a.ts', undefined)).toBeNull()+ expect(resolveFileToken('../../../../etc/passwd', '/a')).toBeNull()+ })+})diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.tsnew file mode 100644index 000000000..0b698d6b1--- /dev/null+++ b/src/renderer/terminal/file-links.ts@@ -0,0 +1,161 @@+// Cmd/Ctrl+click file-path links in terminal output. URLs are the WebLinksAddon's job;+// this provider handles path-like tokens: absolute (`/x/y`), dot-relative (`./x`, `../x`)+// and bare relatives with at least one slash (`src/a.ts`), with optional `:line[:col]`+// suffixes (compiler/grep output). `~` paths are skipped in v1 (no home resolution).+//+// Existence (and dir-ness) is verified before a link is offered, via a short-TTL cache of+// parent-directory listings — one fs.list covers every sibling on a compiler-error screen.+// Wrapped rows are joined into one logical line so long paths still match; the provider+// only fires from a logical line's FIRST row (continuation rows resolve to the same links).+import type { IBufferLine, ILink, ILinkProvider, Terminal } from '@xterm/xterm'++export interface FileToken {+ /** The raw matched span (drives the underline range), incl. any :line:col suffix. */+ text: string+ /** 0-based index of `text` within the logical line. */+ startIndex: number+ /** The cleaned path portion. */+ path: string+ line?: number+}++// Path-ish token: an optional ./ ../ / prefix, then segments of path-safe chars with at+// least one internal slash — OR a prefixed single-segment (/tmp, ./x) — with an optional+// trailing :line[:col]. Trailing punctuation is cleaned afterwards, not in the regex.+const TOKEN_RE =+ /(?:(?:\.{1,2}\/|\/)?[\w.@+-]+(?:\/[\w.@+~-]+)+|(?:\.{1,2}\/|\/)[\w.@+-]+)(?::\d+(?::\d+)?)?/g+const SUFFIX_RE = /^(.*?):(\d+)(?::\d+)?$/+const TRAILING_PUNCT = /[.,;:!?'")\]}>]+$/++export function matchFileTokens(lineText: string): FileToken[] {+ const out: FileToken[] = []+ for (const m of lineText.matchAll(TOKEN_RE)) {+ let text = m[0]+ // URLs (and protocol-ish tokens) belong to the web-links addon. A token preceded by+ // `~` is a home-relative path minus its tilde (no home resolution in v1) — skip it+ // rather than mis-resolve `~/x` as the absolute `/x`.+ const before = lineText.slice(Math.max(0, m.index - 8), m.index)+ // `\w+:\/{1,2}$` (not just `://`): the optional leading-`/` in TOKEN_RE can swallow the+ // second slash of `://`, so a URL's token starts at that slash and `before` ends `https:/`.+ if (/\w+:\/{1,2}$/.test(before) || text.includes('//')) continue+ if (m.index > 0 && lineText[m.index - 1] === '~') continue+ text = text.replace(TRAILING_PUNCT, '')+ if (text.length < 3) continue+ let path = text+ let line: number | undefined+ const suffix = SUFFIX_RE.exec(text)+ if (suffix) {+ path = suffix[1]+ line = parseInt(suffix[2], 10)+ }+ if (!path || !path.includes('/')) continue+ out.push({ text, startIndex: m.index, path, line })+ }+ return out+}++/** Absolute path for a token: absolutes pass through, relatives resolve against cwd,+ * `.`/`..` segments normalized. Null when unresolvable or when `..` escapes the root. */+export function resolveFileToken(path: string, cwd: string | undefined): string | null {+ const raw = path.startsWith('/') ? path : cwd ? `${cwd.replace(/\/+$/, '')}/${path}` : null+ if (!raw) return null+ const out: string[] = []+ for (const seg of raw.split('/')) {+ if (!seg || seg === '.') continue+ if (seg === '..') {+ if (!out.length) return null+ out.pop()+ } else out.push(seg)+ }+ return '/' + out.join('/')+}++export interface FileLinkDeps {+ getCwd(): string | undefined+ lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>+ activate(abs: string, dir: boolean): void+}++// Join a logical (soft-wrapped) line starting at row `startRow` (0-based). Rows that have a+// wrapped successor are read untrimmed (they are exactly `cols` wide, keeping index math+// exact); the last row is right-trimmed.+function logicalLine(term: Terminal, startRow: number): { text: string; rows: number } | null {+ const buf = term.buffer.active+ const first = buf.getLine(startRow)+ if (!first || first.isWrapped) return null // continuation rows are the first row's job+ let text = ''+ let rows = 0+ let cur: IBufferLine | undefined = first+ while (cur) {+ const next = buf.getLine(startRow + rows + 1)+ const wrappedNext = !!next?.isWrapped+ text += cur.translateToString(!wrappedNext)+ rows += 1+ if (!wrappedNext) break+ cur = next+ }+ return { text, rows }+}++/** xterm link provider for file paths. Register once per (non-relay) terminal. */+export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILinkProvider {+ return {+ provideLinks(bufferLineNumber: number, callback: (links: ILink[] | undefined) => void): void {+ const startRow = bufferLineNumber - 1 // provider y is 1-based+ const logical = logicalLine(term, startRow)+ if (!logical) {+ callback(undefined)+ return+ }+ const tokens = matchFileTokens(logical.text)+ if (!tokens.length) {+ callback(undefined)+ return+ }+ const cols = term.cols+ void Promise.all(+ tokens.map(async (t): Promise<ILink | null> => {+ const abs = resolveFileToken(t.path, deps.getCwd())+ if (!abs) return null+ const found = await deps.lookup(abs)+ if (!found.exists) return null+ const endIndex = t.startIndex + t.text.length - 1+ return {+ text: t.text,+ range: {+ // ILink range coords are 1-based, inclusive.+ start: { x: (t.startIndex % cols) + 1, y: startRow + Math.floor(t.startIndex / cols) + 1 },+ end: { x: (endIndex % cols) + 1, y: startRow + Math.floor(endIndex / cols) + 1 }+ },+ activate: (event: MouseEvent) => {+ if (!(event.metaKey || event.ctrlKey)) return+ deps.activate(abs, found.dir)+ }+ }+ })+ ).then((links) => {+ const real = links.filter((l): l is ILink => !!l)+ callback(real.length ? real : undefined)+ })+ }+ }+}++/** Existence+dir-ness via cached parent-dir listings (one list covers all siblings). */+export function makeDirListingLookup(+ list: (dir: string) => Promise<Array<{ name: string; dir: boolean }>>,+ ttlMs = 3000+): (abs: string) => Promise<{ exists: boolean; dir: boolean }> {+ const cache = new Map<string, { at: number; entries: Array<{ name: string; dir: boolean }> }>()+ return async (abs) => {+ const i = abs.lastIndexOf('/')+ const dir = i <= 0 ? '/' : abs.slice(0, i)+ const name = abs.slice(i + 1)+ const hit = cache.get(dir)+ const entries =+ hit && Date.now() - hit.at < ttlMs ? hit.entries : await list(dir).catch(() => [])+ if (!hit || Date.now() - (hit?.at ?? 0) >= ttlMs) cache.set(dir, { at: Date.now(), entries })+ const e = entries.find((x) => x.name === name)+ return { exists: !!e, dir: !!e?.dir }+ }+}