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
fix(terminal): follow a link across hard-wrapped rows (tmux repaint / TUI)
enesbf55ade9477b
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsxindex 265fb71e9..5831b0ca7 100644--- a/src/renderer/nodes/TerminalNode.tsx+++ b/src/renderer/nodes/TerminalNode.tsx@@ -11,7 +11,6 @@ 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 { LocalTransport } from '../terminal/local-transport'@@ -20,6 +19,7 @@ import { patchTerminalScale } from '../terminal/scale-fix'import { parseOsc52 } from '../terminal/osc52'import {createFileLinkProvider,+ createUrlLinkProvider,installLinkClickFallback,makeDirListingLookup} from '../terminal/file-links'@@ -701,13 +701,13 @@ 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)- })+ // Cmd (mac) / Ctrl+click link opening. URLs → default browser via createUrlLinkProvider+ // (NOT the WebLinksAddon — the addon can't join the hard-wrapped rows a tmux repaint /+ // agent TUI paints, so a long OAuth URL matched only its first row's fragment); file+ // paths → editor node / Explorer reveal via the file provider. Both are modifier-gated+ // inside their activate handlers, so plain clicks stay selections.+ term.registerLinkProvider(+ createUrlLinkProvider(term, (uri) => window.nodeTerminal.shell.openExternal(uri)))const projectFs = (): { fs: FsApi; ssh: boolean } => {const st = useProjects.getState()@@ -730,7 +730,7 @@ export function TerminalNode({ id, data, selected, parentId }: NodeProps<CanvasN)}term.registerLinkProvider(createFileLinkProvider(term, { getCwd, lookup, activate: openFile }))- // The provider above (and the WebLinksAddon) rely on xterm's own click handling, which+ // Both providers above rely on xterm's own click handling, which// tmux/agent mouse-reporting swallows. This capture-phase mouse-up fallback restores// Cmd/Ctrl+click for both URLs and file paths in that mode. Attached to `term.element` so// it travels with the terminal across park/adopt; it dies with the terminal on dispose.diff --git a/src/renderer/terminal/file-links.test.ts b/src/renderer/terminal/file-links.test.tsindex b4663f0c4..dda924e8d 100644--- a/src/renderer/terminal/file-links.test.ts+++ b/src/renderer/terminal/file-links.test.ts@@ -1,5 +1,11 @@import { describe, expect, it } from 'vitest'-import { matchFileTokens, matchUrlTokens, resolveFileToken } from './file-links'+import {+ matchFileTokens,+ matchUrlTokens,+ paragraphContaining,+ resolveFileToken,+ type BufferView+} from './file-links'describe('matchFileTokens', () => {it('finds absolute, dot-relative and bare relative paths', () => {@@ -53,6 +59,77 @@ describe('resolveFileToken', () => {})})+/** Fake buffer: each entry is a row's content; `w:` prefix marks it soft-wrapped. Rows are+ * stored untrimmed exactly as given (pad to `cols` yourself to simulate a full row). */+function view(cols: number, rows: string[]): BufferView {+ const parsed = rows.map((r) =>+ r.startsWith('w:') ? { wrapped: true, text: r.slice(2) } : { wrapped: false, text: r }+ )+ return {+ cols,+ length: parsed.length,+ line: (row) => {+ const p = parsed[row]+ return p+ ? { isWrapped: p.wrapped, text: (trim) => (trim ? p.text.replace(/\s+$/, '') : p.text) }+ : undefined+ }+ }+}++describe('paragraphContaining', () => {+ it('joins soft-wrapped rows from any row of the paragraph', () => {+ const v = view(10, ['prompt> ', 'https://x.', 'w:io/abc'])+ for (const row of [1, 2]) {+ const p = paragraphContaining(v, row)!+ expect(p.startRow).toBe(1)+ expect(p.text).toBe('https://x.io/abc')+ expect(p.rows).toBe(2)+ }+ // row 0 does not run into row 1 (it has trailing spaces) — separate paragraph+ expect(paragraphContaining(v, 0)!.text).toBe('prompt>')+ })++ it('joins HARD-wrapped rows (tmux repaint / TUI): full last column + non-space next start', () => {+ // 10-col screen painting "https://claude.com/oauth?x=1" as three hard rows+ const v = view(10, ['https://cl', 'aude.com/o', 'auth?x=1'])+ for (const row of [0, 1, 2]) {+ const p = paragraphContaining(v, row)!+ expect(p.startRow).toBe(0)+ expect(p.text).toBe('https://claude.com/oauth?x=1')+ }+ expect(matchUrlTokens(paragraphContaining(v, 1)!.text)[0].url).toBe(+ 'https://claude.com/oauth?x=1'+ )+ })++ it('does NOT join when the row is not full to the last column', () => {+ const v = view(10, ['https://x ', 'unrelated'])+ expect(paragraphContaining(v, 0)!.text).toBe('https://x')+ })++ it('does NOT join when the next row starts with a space', () => {+ const v = view(10, ['aaaaaaaaaa', ' indented'])+ expect(paragraphContaining(v, 0)!.text).toBe('aaaaaaaaaa')+ })++ it('index math holds across hard rows (every joined row contributes exactly cols chars)', () => {+ const v = view(10, ['see https:', '//x.io/abc', 'd now'])+ const p = paragraphContaining(v, 0)!+ const [u] = matchUrlTokens(p.text)+ expect(u.url).toBe('https://x.io/abcd')+ // token starts at index 4 → row 0 col 4; ends at index 20 → row 2 col 0+ expect(Math.floor(u.startIndex / 10)).toBe(0)+ expect(Math.floor((u.startIndex + u.text.length - 1) / 10)).toBe(2)+ })++ it('caps runaway joins at MAX_JOIN_ROWS', () => {+ const wall = Array.from({ length: 80 }, () => 'x'.repeat(10))+ const p = paragraphContaining(view(10, wall), 0)!+ expect(p.rows).toBeLessThanOrEqual(32)+ })+})+describe('matchUrlTokens', () => {it('finds http(s) URLs with their start index', () => {const t = matchUrlTokens('open https://example.com/a/b and http://x.io/p here')diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.tsindex bfe58b716..5a4af4759 100644--- a/src/renderer/terminal/file-links.ts+++ b/src/renderer/terminal/file-links.ts@@ -1,15 +1,26 @@-// 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).+// Cmd/Ctrl+click links in terminal output. `createUrlLinkProvider` handles http(s) URLs;+// `createFileLinkProvider` handles path-like tokens: absolute (`/x/y`), dot-relative+// (`./x`, `../x`) and bare relatives with at least one slash (`src/a.ts`), with optional+// `:line[:col]` suffixes (compiler/grep output). `~` 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, whose link ranges span the wrapped rows.-// A continuation row resolves to NO links of its own (the provider returns undefined for it),-// so hovering a wrapped tail directly is a known non-clickable v1 limitation.-import type { IBufferLine, ILink, ILinkProvider, Terminal } from '@xterm/xterm'+// Existence (and dir-ness) is verified before a file link is offered, via a short-TTL cache+// of parent-directory listings — one fs.list covers every sibling on a compiler-error screen.+//+// Long tokens span rows two different ways, and BOTH are joined into one logical paragraph+// (`paragraphContaining`) before matching:+// - SOFT wrap — xterm wrapped a long streamed line itself; the continuation row carries+// `isWrapped`. The easy, always-joined case.+// - HARD wrap — tmux repaints (attach, resize, refresh) and an agent's fullscreen TUI PAINT+// the screen row by row with explicit cursor moves, so a long line lands as separate+// full-width rows with NO wrapped flags. This is what a `claude /login` OAuth URL looks+// like in practice; matching per-row opened just the clicked row's fragment (a truncated,+// wrong URL). A row is treated as continuing onto the next when it is full to the LAST+// column and the next row starts at column 0 with a non-space — a heuristic (the buffer+// genuinely cannot distinguish a repainted wrap from prose that exactly fills the row),+// gated tightly and capped at MAX_JOIN_ROWS, and the regex still has to match across the+// seam for a link to result.+import type { ILink, ILinkProvider, Terminal } from '@xterm/xterm'export interface FileToken {/** The raw matched span (drives the underline range), incl. any :line:col suffix. */@@ -56,9 +67,10 @@ export function matchFileTokens(lineText: string): FileToken[] {return out}-// http(s) URLs, matched the way the WebLinksAddon's click path would see them. Kept here so-// the mouse-up click fallback (below) can hit-test URLs and file paths in one pass — under-// tmux/agent mouse-reporting the addon's own click never fires (see installLinkClickFallback).+// http(s) URLs. Shared by createUrlLinkProvider (hover underline + click outside tmux) and+// the mouse-up click fallback (below), which hit-tests URLs and file paths in one pass —+// under tmux/agent mouse-reporting a provider's own click never fires (see+// installLinkClickFallback).const URL_RE = /\bhttps?:\/\/[^\s"'`<>()[\]{}|\\^]+/giexport interface UrlToken {@@ -110,33 +122,93 @@ export interface FileLinkDeps {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 {+/** The minimal buffer slice paragraph joining needs — unit tests drive a fake. */+export interface BufferView {+ cols: number+ length: number+ line(row: number): { isWrapped: boolean; text(trimRight: boolean): string } | undefined+}++export function bufferView(term: Terminal): BufferView {const buf = term.buffer.active- const first = buf.getLine(startRow)- if (!first || first.isWrapped) return null // continuation rows are the first row's job+ return {+ cols: term.cols,+ length: buf.length,+ line: (row) => {+ const l = buf.getLine(row)+ return l+ ? { isWrapped: l.isWrapped, text: (trim: boolean) => l.translateToString(trim) }+ : undefined+ }+ }+}++/** Upper bound on rows joined in each direction — bounds hover work on pathological+ * full-width walls of text; a wrapped OAuth URL is ~7 rows at 80 cols. */+const MAX_JOIN_ROWS = 32++// Whether `row` runs into `row + 1`: the successor carries xterm's soft-wrap flag, OR the+// hard-wrap heuristic holds — `row` is full to its last column (untrimmed non-space in the+// final cell) and the successor starts at column 0 with a non-space. See the header comment.+function continuesOnNextRow(view: BufferView, row: number): boolean {+ const next = view.line(row + 1)+ if (!next) return false+ if (next.isWrapped) return true+ const cur = view.line(row)+ if (!cur) return false+ const raw = cur.text(false)+ if (raw.length < view.cols || raw[view.cols - 1] === ' ') return false+ const nextRaw = next.text(false)+ return nextRaw.length > 0 && nextRaw[0] !== ' '+}++/**+ * The logical paragraph containing `row` (0-based): walks up to the paragraph's first row,+ * then joins downward across soft AND hard wraps. Every row that continues contributes+ * EXACTLY `cols` characters (padded/truncated untrimmed read), so an index into `text` maps+ * back to the buffer as `(startRow + idx / cols, idx % cols)`; the final row is right-trimmed.+ */+export function paragraphContaining(+ view: BufferView,+ row: number+): { text: string; startRow: number; rows: number } | null {+ if (!view.line(row)) return null+ let start = row+ while (start > 0 && row - start < MAX_JOIN_ROWS && continuesOnNextRow(view, start - 1)) start--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+ let r = start+ for (;;) {+ const joins = r - start + 1 < MAX_JOIN_ROWS && continuesOnNextRow(view, r)+ const lineText = view.line(r)!.text(!joins)+ // Continuing rows must contribute exactly `cols` chars so the index math above holds.+ text += joins ? lineText.padEnd(view.cols).slice(0, view.cols) : lineText+ if (!joins) break+ r+++ }+ return { text, startRow: start, rows: r - start + 1 }+}++/** ILink range (1-based, inclusive) for a token at `startIndex..+len` of a paragraph. */+function tokenRange(+ startRow: number,+ cols: number,+ startIndex: number,+ len: number+): ILink['range'] {+ const endIndex = startIndex + len - 1+ return {+ start: { x: (startIndex % cols) + 1, y: startRow + Math.floor(startIndex / cols) + 1 },+ end: { x: (endIndex % cols) + 1, y: startRow + Math.floor(endIndex / cols) + 1 }}- 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)+ // Resolve the paragraph CONTAINING the hovered row (not just one starting at it), so+ // hovering any wrapped tail row of a long path underlines and activates the whole token.+ const logical = paragraphContaining(bufferView(term), bufferLineNumber - 1)if (!logical) {callback(undefined)return@@ -153,14 +225,9 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILinif (!abs) return nullconst found = await deps.lookup(abs)if (!found.exists) return null- const endIndex = t.startIndex + t.text.length - 1return {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 }- },+ range: tokenRange(logical.startRow, cols, t.startIndex, t.text.length),activate: (event: MouseEvent) => {if (!(event.metaKey || event.ctrlKey)) returndeps.activate(abs, found.dir)@@ -175,6 +242,34 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin}}+/**+ * xterm link provider for http(s) URLs — replaces the WebLinksAddon, which joined soft-wrapped+ * rows but not the hard-wrapped rows a tmux repaint / fullscreen TUI paints (the addon+ * underlined and opened just the first row's fragment of a long OAuth URL). Modifier-gated in+ * activate like the file provider, so plain clicks stay selections.+ */+export function createUrlLinkProvider(term: Terminal, openUrl: (url: string) => void): ILinkProvider {+ return {+ provideLinks(bufferLineNumber: number, callback: (links: ILink[] | undefined) => void): void {+ const logical = paragraphContaining(bufferView(term), bufferLineNumber - 1)+ if (!logical) {+ callback(undefined)+ return+ }+ const links = matchUrlTokens(logical.text).map(+ (u): ILink => ({+ text: u.text,+ range: tokenRange(logical.startRow, term.cols, u.startIndex, u.text.length),+ activate: (event: MouseEvent) => {+ if (event.metaKey || event.ctrlKey) openUrl(u.url)+ }+ })+ )+ callback(links.length ? links : 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 }>>,@@ -194,17 +289,6 @@ export function makeDirListingLookup(}}-// Walk up from an arbitrary buffer row to the first non-wrapped row, then join the whole-// soft-wrapped logical line from there. Lets a click on ANY wrapped row of a long path resolve-// to the same logical string the hover provider builds from the line's first row.-function logicalLineContaining(term: Terminal, row: number): { text: string; startRow: number } | null {- const buf = term.buffer.active- let start = row- while (start > 0 && buf.getLine(start)?.isWrapped) start -= 1- const l = logicalLine(term, start)- return l ? { text: l.text, startRow: start } : null-}-// Cell (0-based col, 0-based buffer row) under a mouse event. The canvas applies zoom as a CSS// transform, so getBoundingClientRect() is already the on-screen (scaled) size — dividing the// scaled offset by the scaled cell size cancels the zoom, keeping cols/rows constant.@@ -252,12 +336,12 @@ export function installLinkClickFallback(if (ev.button !== 0 || !(ev.metaKey || ev.ctrlKey)) return// Only take over when the app has mouse-reporting on (tmux mouse / agent TUI) — that is the// exact case where xterm's own link `activate` never fires. With reporting OFF (a plain shell- // when tmux is unavailable) xterm's provider + WebLinksAddon handle the click, so stepping in+ // when tmux is unavailable) the registered providers handle the click, so stepping in// here would open the link twice.if (term.modes.mouseTrackingMode === 'none') returnconst pos = bufferPosFromEvent(term, ev)if (!pos) return- const logical = logicalLineContaining(term, pos.row)+ const logical = paragraphContaining(bufferView(term), pos.row)if (!logical) returnconst idx = (pos.row - logical.startRow) * term.cols + pos.colconst inRange = (startIndex: number, len: number): boolean =>