Skip to content

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.

feat(terminal): right-click menu on links in terminal output

review4608cb6c0e61
diff --git a/CLAUDE.md b/CLAUDE.md
index 0e9b67ed6..237c97112 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1377,6 +1377,19 @@ session.
have no remote fs API with which to verify a token; relay tabs do have a core-bound, jailed fs
API and therefore support file links. Windows existence matching is case-insensitive and accepts
both separators; UNC tokens are refused whole before they can be reinterpreted as cwd-relative.
+ **Right-click on a link** opens a link menu (pure `terminal/link-menu.ts`; the listener is
+ `installLinkContextMenu`, beside the Cmd+click fallback and sharing its `linkAtCell` hit-test):
+ Open / Reveal in Explorer / Download / Copy path for a file, Open in browser / canvas browser /
+ Copy link for a URL. The gates are the Explorer's, reused not restated — Download only where
+ `downloadRoute` ≠ `none` (SSH project → scp to this machine, Server Edition → HTTP), never on a
+ desktop LOCAL project; the OS reveal only under `canUseLocalShell`. **The decision is made on the
+ right PRESS, not on `contextmenu`:** tmux 3.x binds `MouseDown3Pane` to its own `display-menu`, so
+ the press is what must be swallowed; a right-click OFF a link stays byte-identical (tmux menu,
+ agent TUI, node menu). A path-shaped token that turns out not to exist still gets a menu ("Not
+ found" + Copy path) — its press was already swallowed, and a silent swallow reads as broken.
+ Downloads report in a `DownloadStrip` floated over the terminal, not in a drawer that may be
+ shut. The kanban card modal gets URL rows only (no file links there) and no "Open in canvas
+ browser" (the node would land under the board).
**Home-relative `~/x` tokens** (Claude Code prints its plan file as `~/.claude/plans/<name>.md`)
stay `~`-rooted all the way to the fs call and are expanded by the core that OWNS the filesystem
— `expandHomePath` in `core/fs-handlers.ts` for desktop/Server Edition, the remote shell for
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a0d93ddc6..53c2c20da 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -99,6 +99,7 @@ import { withNodeBoundary } from '../components/NodeBoundary'
import { Dock } from '../components/Dock'
import { TabBar } from '../components/TabBar'
import { ContextMenu, type MenuItem } from '../components/ContextMenu'
+import { tidySeparators } from '../lib/tidySeparators'
import { CommandPalette, type Command } from '../components/CommandPalette'
import { Tooltip } from '../components/Tooltip'
import {
@@ -946,19 +947,6 @@ const restartAgentIdOf = (n: Node | undefined): AgentId | undefined =>
/** Stable empty card list, so the closed board's memo never churns array identity. */
const NO_KANBAN_SESSIONS: KanbanSession[] = []
-/** Drop the separators a hidden row leaves dangling: the menu's rules are written between blocks,
- * so hiding every row of a block would otherwise emit two rules in a row (or one hanging at the
- * top / bottom). Also drops a rule directly under a section label, which reads as a double line.
- * Cheap and total, so the builders can stay plain array literals instead of tracking what is left. */
-const tidySeparators = (items: MenuItem[]): MenuItem[] =>
- items
- .filter((item, i, all) => {
- if (item.type !== 'separator') return true
- const prev = all[i - 1]
- return !!prev && prev.type !== 'separator' && prev.type !== 'label'
- })
- .filter((item, i, all) => item.type !== 'separator' || i < all.length - 1)
-
// The minimap subscribes to agent status HERE, in its own tiny component — not in Canvas.
// Canvas must not subscribe to the whole status map (every working/waiting flip would re-render
// the entire canvas), but the minimap's working/attention/unread strokes DO need to track those
@@ -9864,22 +9852,11 @@ export function Canvas() {
// A browser guest's new-window (target=_blank / window.open) request → open another browser node
// (never a real popup; main denies the real one) roped below/right of the source. Reads the
// latest nodes via nodesRef so the deps stay []. Rope is display-only lineage (controlEdges, persisted as `ropes`).
+ // The same placement serves a terminal link's right-click "Open in canvas browser"
+ // (terminal/link-menu.ts): a node's output opening a page beside the node that printed it.
useEffect(() => {
- return window.nodeTerminal.browser.onBrowserNewWindow(({ url, sourceNodeId }) => {
- const src = nodesRef.current.find((n) => n.id === sourceNodeId)
- if (!src) return
- // Guard against a hostile/careless page flooding the canvas with real Chromium nodes
- // (ad loops, setInterval(window.open)). Prune old records, then dedup + rate-cap.
- const now = Date.now()
- const recent = browserPopupSpawnsRef.current.filter((r) => now - r.t < 10000)
- const isDup = recent.some((r) => r.url === url && r.source === sourceNodeId && now - r.t < 2000)
- if (isDup || recent.length >= 8) {
- browserPopupSpawnsRef.current = recent
- console.warn('[browser] popup spawn blocked (dedup/rate cap):', url)
- return
- }
- recent.push({ url, source: sourceNodeId, t: now })
- browserPopupSpawnsRef.current = recent
+ const spawnBelow = (src: Node, url: string): void => {
+ const sourceNodeId = src.id
const srcW = src.measured?.width ?? (src.width as number) ?? 800
const srcH = src.measured?.height ?? (src.height as number) ?? 560
// src.position is group-relative when the opener sits in a group frame: place in absolute
@@ -9894,7 +9871,36 @@ export function Canvas() {
setNodes((ns) => [...ns, placed])
setControlEdges((es) => [...es, ropeEdge(`ctrl-${sourceNodeId}-${placed.id}`, sourceNodeId, placed.id)])
markDirty()
+ }
+ // A user's own click, one node per gesture — the popup flood guard below is not for this.
+ const onOpenUrlNode = (e: Event): void => {
+ const d = (e as CustomEvent<{ url?: string; sourceNodeId?: string }>).detail
+ if (!d?.url || !/^https?:\/\//i.test(d.url)) return
+ const src = nodesRef.current.find((n) => n.id === d.sourceNodeId)
+ if (src) spawnBelow(src, d.url)
+ }
+ window.addEventListener('nodeterm:open-url-node', onOpenUrlNode)
+ const offNewWindow = window.nodeTerminal.browser.onBrowserNewWindow(({ url, sourceNodeId }) => {
+ const src = nodesRef.current.find((n) => n.id === sourceNodeId)
+ if (!src) return
+ // Guard against a hostile/careless page flooding the canvas with real Chromium nodes
+ // (ad loops, setInterval(window.open)). Prune old records, then dedup + rate-cap.
+ const now = Date.now()
+ const recent = browserPopupSpawnsRef.current.filter((r) => now - r.t < 10000)
+ const isDup = recent.some((r) => r.url === url && r.source === sourceNodeId && now - r.t < 2000)
+ if (isDup || recent.length >= 8) {
+ browserPopupSpawnsRef.current = recent
+ console.warn('[browser] popup spawn blocked (dedup/rate cap):', url)
+ return
+ }
+ recent.push({ url, source: sourceNodeId, t: now })
+ browserPopupSpawnsRef.current = recent
+ spawnBelow(src, url)
})
+ return () => {
+ offNewWindow()
+ window.removeEventListener('nodeterm:open-url-node', onOpenUrlNode)
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index e5d168529..9bd0e93de 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -28,8 +28,11 @@ import { guardMiddleClickPaste } from '../../terminal/middle-click'
import {
createOsc8LinkHandler,
createUrlLinkProvider,
- installLinkClickFallback
+ installLinkClickFallback,
+ installLinkContextMenu
} from '../../terminal/file-links'
+import { urlLinkMenuItems } from '../../terminal/link-menu'
+import { ContextMenu } from '../ContextMenu'
import { parseOsc52 } from '../../terminal/osc52'
import { activateUnicode11 } from '../../terminal/unicode-width'
import { useCopyFeedback } from '../../terminal/useCopyFeedback'
@@ -152,6 +155,9 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
hasSelection: () => !!termRef.current?.hasSelection(),
enabled: !reportsOwnCopy(spawn.agentId as AgentId | undefined)
})
+ // Right-click on a URL → the canvas node's link menu, URL rows only (no file links here — see the
+ // link wiring in the lifecycle effect).
+ const [linkMenu, setLinkMenu] = useState<{ x: number; y: number; url: string } | null>(null)
// Same search machinery as the canvas node: capture-indexed matches + xterm highlight.
const readBuffer = useCallback((): string => {
@@ -246,6 +252,15 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
fileEnabled: () => false
}).dispose
)
+ cleanups.push(
+ installLinkContextMenu(term, term.element, {
+ getCwd: () => undefined,
+ fileEnabled: () => false,
+ openMenu: (hit, x, y) => {
+ if (hit.kind === 'url') setLinkMenu({ x, y, url: hit.url })
+ }
+ }).dispose
+ )
}
// MIRROR TerminalNode "WRITE-ONLY — `parseOsc52` returns null" — the OSC 52 clipboard-write path.
@@ -559,6 +574,20 @@ export function ModalTerminal({ nodeId, spawn, searchOpen, onCloseSearch, covere
/>
)}
<div ref={hostRef} className="kanban-modal__term" />
+ {linkMenu && (
+ <ContextMenu
+ x={linkMenu.x}
+ y={linkMenu.y}
+ zIndex={60}
+ // No "Open in canvas browser": the node would open on the canvas UNDER the board,
+ // out of sight of the click that asked for it.
+ items={urlLinkMenuItems(linkMenu.url, {
+ openUrl: (url) => window.nodeTerminal.shell.openExternal(url),
+ copy: (text) => window.nodeTerminal.clipboard.writeText(text)
+ })}
+ onClose={() => setLinkMenu(null)}
+ />
+ )}
</div>
)
}
diff --git a/src/renderer/lib/tidySeparators.ts b/src/renderer/lib/tidySeparators.ts
new file mode 100644
index 000000000..6a81a4466
--- /dev/null
+++ b/src/renderer/lib/tidySeparators.ts
@@ -0,0 +1,14 @@
+import type { MenuItem } from '../components/ContextMenu'
+
+/** Drop the separators a hidden row leaves dangling: the menu's rules are written between blocks,
+ * so hiding every row of a block would otherwise emit two rules in a row (or one hanging at the
+ * top / bottom). Also drops a rule directly under a section label, which reads as a double line.
+ * Cheap and total, so the builders can stay plain array literals instead of tracking what is left. */
+export const tidySeparators = (items: MenuItem[]): MenuItem[] =>
+ items
+ .filter((item, i, all) => {
+ if (item.type !== 'separator') return true
+ const prev = all[i - 1]
+ return !!prev && prev.type !== 'separator' && prev.type !== 'label'
+ })
+ .filter((item, i, all) => item.type !== 'separator' || i < all.length - 1)
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index a56095395..767d85323 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -45,8 +45,14 @@ import {
createOsc8LinkHandler,
createUrlLinkProvider,
installLinkClickFallback,
+ installLinkContextMenu,
makeDirListingLookup
} from '../terminal/file-links'
+import { linkMenuItems, resolveLinkTarget, type LinkMenuTarget } from '../terminal/link-menu'
+import { ContextMenu } from '../components/ContextMenu'
+import { DownloadStrip } from '../components/DownloadStrip'
+import { canUseLocalShell, downloadRoute } from '../lib/download'
+import { useDownloads } from '../lib/useDownloads'
import { fileLinkDialect } from '../terminal/file-link-dialect'
import { hostPlatformFor } from '../terminal/host-platform'
import { sshFs } from '../terminal/ssh-fs'
@@ -1138,6 +1144,10 @@ export function wakeHibernatedNode(nodeId: string): void {
*/
const copySubs = new Map<string, (text: string) => void>()
+/** The right-click link menu's sink, published for the same reason as `copySubs`: the listener
+ * (`installLinkContextMenu`) is installed once per xterm instance and survives a park. */
+const linkMenuSubs = new Map<string, (target: LinkMenuTarget, x: number, y: number) => void>()
+
function getCo(key: string): CoState {
return coStates.get(key) ?? NO_CO
}
@@ -1332,6 +1342,66 @@ export function TerminalNode({
if (copySubs.get(termKey) === copy.notifyCopy) copySubs.delete(termKey)
}
}, [termKey, copy.notifyCopy])
+ // Right-click on a link in the output → open / reveal / download / copy (terminal/link-menu.ts).
+ // The listener lives in the lifecycle effect and reaches this state through `linkMenuSubs`.
+ const [linkMenu, setLinkMenu] = useState<{ x: number; y: number; target: LinkMenuTarget } | null>(
+ null
+ )
+ useEffect(() => {
+ const sink = (target: LinkMenuTarget, x: number, y: number): void => setLinkMenu({ x, y, target })
+ linkMenuSubs.set(termKey, sink)
+ return () => {
+ if (linkMenuSubs.get(termKey) === sink) linkMenuSubs.delete(termKey)
+ }
+ }, [termKey])
+ // The file links resolve against the ACTIVE project's filesystem (see `projectFs` in the
+ // lifecycle effect), so Download follows it too: an SSH project's file comes down over scp. Two
+ // primitive selectors, not the project object — that is rebuilt on every node serialization.
+ const activeProjectId = useProjects((s) => s.activeProjectId)
+ const activeIsSsh = useProjects((s) => !!s.projects.find((p) => p.id === s.activeProjectId)?.ssh)
+ const linkDlCtx = { browser: isBrowserRuntime(), ssh: activeIsSsh, source: session.source }
+ const linkDownloads = useDownloads({
+ route: downloadRoute(linkDlCtx),
+ projectId: activeProjectId || undefined,
+ files: api.files
+ })
+ /** The link menu's rows, read against the project as it is when the menu opens. Every action
+ * reuses the channel Cmd+click, the Explorer or the file-manager node already goes through. */
+ const linkMenuRows = (target: LinkMenuTarget) => {
+ const project = useProjects.getState().getProject(activeProjectId ?? '')
+ // Literal event names on purpose: nodeterm-events.test.ts pairs every dispatch with its
+ // listener by reading `new CustomEvent('nodeterm:…'` out of the source.
+ const send = (ev: CustomEvent): void => void window.dispatchEvent(ev)
+ return linkMenuItems(
+ target,
+ {
+ route: downloadRoute(linkDlCtx),
+ localShell: canUseLocalShell(linkDlCtx),
+ // The Explorer drawer's own root (ExplorerPanel: `ssh ? ssh.remoteCwd : project.cwd`).
+ explorerRoot: project?.ssh ? project.ssh.remoteCwd : project?.cwd,
+ terminals: session.source !== 'relay',
+ downloading: (p) => linkDownloads.rowDl[p] === 'running'
+ },
+ {
+ openUrl: (url) => window.nodeTerminal.shell.openExternal(url),
+ // A browser node is an Electron `<webview>`; in a browser tab it would render nothing.
+ openUrlInNode: linkDlCtx.browser
+ ? undefined
+ : (url) =>
+ send(new CustomEvent('nodeterm:open-url-node', { detail: { url, sourceNodeId: id } })),
+ copy: (text) => window.nodeTerminal.clipboard.writeText(text),
+ openFile: (abs) =>
+ send(new CustomEvent('nodeterm:open-file', { detail: { path: abs, ssh: activeIsSsh } })),
+ revealInExplorer: (abs) =>
+ send(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } })),
+ revealInOs: (abs) => window.nodeTerminal.shell.reveal(abs),
+ openTerminal: (dir) =>
+ send(new CustomEvent('nodeterm:open-terminal', { detail: { cwd: dir } })),
+ download: (abs, dir, pickFolder) =>
+ void (pickFolder ? linkDownloads.downloadTo(abs, dir) : linkDownloads.download(abs, dir))
+ }
+ )
+ }
const fitRef = useRef<FitAddon | null>(null)
const searchAddonRef = useRef<SearchAddon | null>(null)
// The live session's "measure my grid, render it, report it" routine (set by the lifecycle
@@ -2990,6 +3060,17 @@ export function TerminalNode({
fileEnabled: () => pathConvention() !== null,
convention: pathConvention
})
+ // Right-click on the same links → a menu (open / reveal / download / copy). Same hit-test,
+ // same routed lookup; the menu itself is state on whichever instance is mounted now.
+ installLinkContextMenu(term, term.element, {
+ getCwd,
+ fileEnabled: () => pathConvention() !== null,
+ convention: pathConvention,
+ openMenu: (hit, x, y) =>
+ void resolveLinkTarget(hit, lookup).then((target) =>
+ linkMenuSubs.get(termKey)?.(target, x, y)
+ )
+ })
}
}
@@ -5936,6 +6017,21 @@ export function TerminalNode({
{copy.feedback.label}
</div>
)}
+ {/* Downloads started from a link's right-click menu, reported on the terminal they were
+ clicked in (the same corner as the copy receipt) — not in a drawer that may be shut. */}
+ <DownloadStrip
+ downloads={linkDownloads.downloads}
+ onDismiss={linkDownloads.dismiss}
+ className="term-node__dls nodrag nowheel"
+ />
+ {linkMenu && (
+ <ContextMenu
+ x={linkMenu.x}
+ y={linkMenu.y}
+ items={linkMenuRows(linkMenu.target)}
+ onClose={() => setLinkMenu(null)}
+ />
+ )}
{/* Offscreen-disposed: the xterm and the PTY client are gone, the tmux session is not.
Deliberately above the overlays below it in the DOM but the least insistent of them —
it states a resting state, not a failure. Nobody is ever looking at it as it appears
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index a53c23230..f1d6fa952 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2611,6 +2611,22 @@ body,
border-color: var(--border);
}
+/* Downloads started from a terminal link's right-click menu (terminal/link-menu.ts): the shared
+ `.ex-dls` strip, floated over the terminal's bottom-right like the copy receipt above — one
+ notch higher so the two never cover each other — instead of docked under a file tree. */
+.ex-dls.term-node__dls {
+ position: absolute;
+ right: 10px;
+ bottom: 34px;
+ z-index: 6;
+ max-width: min(320px, 70%);
+ max-height: 40%;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ background: color-mix(in srgb, var(--bg) 92%, transparent);
+ box-shadow: 0 4px 14px rgb(0 0 0 / 35%);
+}
+
@keyframes nt-copy-pill-in {
from {
opacity: 0;
diff --git a/src/renderer/terminal/file-links.context-menu.test.ts b/src/renderer/terminal/file-links.context-menu.test.ts
new file mode 100644
index 000000000..c2be55875
--- /dev/null
+++ b/src/renderer/terminal/file-links.context-menu.test.ts
@@ -0,0 +1,180 @@
+// @vitest-environment jsdom
+import { describe, expect, it, vi } from 'vitest'
+import type { Terminal } from '@xterm/xterm'
+import { installLinkContextMenu, linkAtCell, type LinkHit, type LinkHitDeps } from './file-links'
+
+const COLS = 40
+const CELL_W = 10
+const CELL_H = 20
+
+/**
+ * The slice of xterm the hit-test and the listener read: a buffer of plain rows (no wraps), the
+ * `.xterm-screen` box the pointer maps against, and an optional OSC 8 cell. `host` stands in for
+ * `term.element`; a child plays xterm's own element, whose listeners must never see a swallowed
+ * event.
+ */
+function fakeTerm(rows: string[], osc8?: { row: number; col: number; uri: string }) {
+ const host = document.createElement('div')
+ const screen = document.createElement('div')
+ screen.className = 'xterm-screen'
+ screen.getBoundingClientRect = () =>
+ ({ left: 0, top: 0, width: COLS * CELL_W, height: rows.length * CELL_H }) as DOMRect
+ host.appendChild(screen)
+ document.body.appendChild(host)
+ const term = {
+ cols: COLS,
+ rows: rows.length,
+ element: host,
+ modes: { mouseTrackingMode: 'vt200' },
+ buffer: {
+ active: {
+ viewportY: 0,
+ length: rows.length,
+ getLine: (r: number) =>
+ r < rows.length
+ ? {
+ isWrapped: false,
+ translateToString: (trim: boolean) => (trim ? rows[r].trimEnd() : rows[r].padEnd(COLS)),
+ getCell: (c: number) => ({
+ extended: { urlId: osc8 && osc8.row === r && osc8.col === c ? 7 : 0 }
+ })
+ }
+ : undefined
+ }
+ },
+ _core: { _oscLinkService: { getLinkData: () => (osc8 ? { uri: osc8.uri } : undefined) } }
+ } as unknown as Terminal
+ return { term, host, screen }
+}
+
+const deps = (over: Partial<LinkHitDeps> = {}): LinkHitDeps => ({
+ getCwd: () => '/home/me/proj',
+ convention: () => ({}),
+ fileEnabled: () => true,
+ ...over
+})
+
+describe('linkAtCell', () => {
+ const { term } = fakeTerm([
+ 'see https://example.com/docs now',
+ 'wrote out/report.csv ok',
+ 'plain words only'
+ ])
+
+ it('finds a URL under the cell', () => {
+ expect(linkAtCell(term, 0, 6, deps())).toEqual({ kind: 'url', url: 'https://example.com/docs' })
+ })
+
+ it('finds a path and resolves it against cwd', () => {
+ expect(linkAtCell(term, 1, 8, deps())).toEqual({ kind: 'path', abs: '/home/me/proj/out/report.csv' })
+ })
+
+ it('is null off a link, and for paths while file links are disabled', () => {
+ expect(linkAtCell(term, 2, 3, deps())).toBeNull()
+ expect(linkAtCell(term, 0, 1, deps())).toBeNull()
+ expect(linkAtCell(term, 1, 8, deps({ fileEnabled: () => false }))).toBeNull()
+ expect(linkAtCell(term, 1, 8, deps({ convention: () => null }))).toBeNull()
+ })
+
+ it('prefers an OSC 8 link, whose URL the visible text does not show', () => {
+ const t = fakeTerm(['click here'], { row: 0, col: 2, uri: 'https://pr.example/1' }).term
+ expect(linkAtCell(t, 0, 2, deps())).toEqual({ kind: 'url', url: 'https://pr.example/1' })
+ })
+})
+
+/** Dispatch a mouse event at buffer cell (row, col), targeting the screen like a real click. */
+function fire(target: HTMLElement, type: string, row: number, col: number, button = 2): MouseEvent {
+ const ev = new MouseEvent(type, {
+ bubbles: true,
+ cancelable: true,
+ button,
+ clientX: col * CELL_W + 2,
+ clientY: row * CELL_H + 2
+ })
+ target.dispatchEvent(ev)
+ return ev
+}
+
+describe('installLinkContextMenu', () => {
+ function setup(over: Partial<LinkHitDeps> = {}) {
+ const { term, host, screen } = fakeTerm(['wrote out/report.csv ok', 'plain words only'])
+ const opened: Array<{ hit: LinkHit; x: number; y: number }> = []
+ const reached = { mousedown: 0, mouseup: 0, contextmenu: 0 }
+ // Stand-ins for the listeners BEHIND ours: xterm's mouse reporting (on its element) and React
+ // Flow's node context menu (bubbling up the tree).
+ for (const type of Object.keys(reached) as Array<keyof typeof reached>) {
+ screen.addEventListener(type, () => reached[type]++)
+ }
+ const handle = installLinkContextMenu(term, host, {
+ ...deps(over),
+ openMenu: (hit, x, y) => opened.push({ hit, x, y })
+ })
+ return { host, screen, opened, reached, handle }
+ }
+
+ it('a right-click on a link opens the menu and never reaches the terminal or the node', () => {
+ const { screen, opened, reached } = setup()
+ const down = fire(screen, 'mousedown', 0, 8)
+ const up = fire(screen, 'mouseup', 0, 8)
+ const menu = fire(screen, 'contextmenu', 0, 8)
+ expect(opened).toEqual([
+ { hit: { kind: 'path', abs: '/home/me/proj/out/report.csv' }, x: 82, y: 2 }
+ ])
+ expect(reached).toEqual({ mousedown: 0, mouseup: 0, contextmenu: 0 })
+ expect(down.defaultPrevented && up.defaultPrevented && menu.defaultPrevented).toBe(true)
+ })
+
+ it('a right-click off a link is left exactly as it was', () => {
+ const { screen, opened, reached } = setup()
+ const down = fire(screen, 'mousedown', 1, 3)
+ fire(screen, 'mouseup', 1, 3)
+ const menu = fire(screen, 'contextmenu', 1, 3)
+ expect(opened).toEqual([])
+ expect(reached).toEqual({ mousedown: 1, mouseup: 1, contextmenu: 1 })
+ expect(down.defaultPrevented || menu.defaultPrevented).toBe(false)
+ })
+
+ it('leaves the left button alone, even on a link (selection, Cmd+click)', () => {
+ const { screen, opened, reached } = setup()
+ fire(screen, 'mousedown', 0, 8, 0)
+ fire(screen, 'mouseup', 0, 8, 0)
+ expect(opened).toEqual([])
+ expect(reached.mousedown).toBe(1)
+ expect(reached.mouseup).toBe(1)
+ })
+
+ it('a keyboard context menu (no right press before it) passes through', () => {
+ const { screen, opened, reached } = setup()
+ fire(screen, 'mousedown', 0, 8) // right press on a link, menu shown…
+ fire(screen, 'contextmenu', 0, 8)
+ fire(screen, 'contextmenu', 0, 8) // …then Shift+F10: not ours
+ expect(opened).toHaveLength(1)
+ expect(reached.contextmenu).toBe(1)
+ })
+
+ it('stops listening once disposed', () => {
+ const { screen, opened, handle } = setup()
+ handle.dispose()
+ fire(screen, 'mousedown', 0, 8)
+ fire(screen, 'contextmenu', 0, 8)
+ expect(opened).toEqual([])
+ })
+
+ it('does not swallow a path while file links are off (the modal terminal, a standalone ssh node)', () => {
+ const { screen, opened, reached } = setup({ fileEnabled: () => false })
+ fire(screen, 'mousedown', 0, 8)
+ fire(screen, 'contextmenu', 0, 8)
+ expect(opened).toEqual([])
+ expect(reached).toMatchObject({ mousedown: 1, contextmenu: 1 })
+ })
+
+ it('does not throw when the pointer is outside the grid', () => {
+ const { host, opened } = setup()
+ const spy = vi.fn()
+ host.addEventListener('contextmenu', spy)
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 2, clientX: -5, clientY: -5 }))
+ host.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, button: 2, clientX: -5, clientY: -5 }))
+ expect(opened).toEqual([])
+ expect(spy).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.ts
index 4689ebac1..305ab74aa 100644
--- a/src/renderer/terminal/file-links.ts
+++ b/src/renderer/terminal/file-links.ts
@@ -506,17 +506,60 @@ function bufferPosFromEvent(term: Terminal, ev: MouseEvent): { col: number; row:
}
}
-export interface LinkClickDeps {
+/** What sits under a buffer cell: a web URL (typed or OSC 8), or a path resolved to absolute.
+ * A path is NOT yet known to exist — that is the async `lookup`'s answer, taken by the caller. */
+export type LinkHit = { kind: 'url'; url: string } | { kind: 'path'; abs: string }
+
+/** What `linkAtCell` needs to turn text into a path: the cwd and dialect the file providers use. */
+export interface LinkHitDeps {
getCwd(): string | undefined
/** See FileLinkDeps.windows. */
windows?: boolean
/** See FileLinkDeps.convention. */
convention?: () => PathConventionOpts | null
+ /** False while no correctly-routed filesystem/dialect is available. */
+ fileEnabled(): boolean
+}
+
+/**
+ * The link at buffer cell (row, col), in the order the providers rank them: an OSC 8 hyperlink
+ * (its URL is invisible — the label is all the text shows), then a typed URL, then a path-shaped
+ * token. ONE hit-test for both mouse gestures — Cmd/Ctrl+click opens what this returns, a
+ * right-click offers a menu for it — so the two can never disagree about what is under the pointer.
+ */
+export function linkAtCell(
+ term: Terminal,
+ row: number,
+ col: number,
+ deps: LinkHitDeps
+): LinkHit | null {
+ const osc8 = osc8UrlAt(term, row, col)
+ if (osc8) return { kind: 'url', url: osc8 }
+ const logical = paragraphContaining(bufferView(term), row)
+ if (!logical) return null
+ const idx = (row - logical.startRow) * term.cols + col
+ const inRange = (startIndex: number, len: number): boolean =>
+ idx >= startIndex && idx < startIndex + len
+
+ for (const u of matchUrlTokens(logical.text)) {
+ if (inRange(u.startIndex, u.text.length)) return { kind: 'url', url: u.url }
+ }
+ if (!deps.fileEnabled()) return null
+ const convention = deps.convention ? deps.convention() : { windows: deps.windows }
+ if (!convention) return null
+ for (const t of matchFileTokens(logical.text, convention)) {
+ if (inRange(t.startIndex, t.text.length)) {
+ const abs = resolveFileToken(t.path, deps.getCwd(), convention)
+ return abs ? { kind: 'path', abs } : null
+ }
+ }
+ return null
+}
+
+export interface LinkClickDeps extends LinkHitDeps {
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activateFile(abs: string, dir: boolean): void
openUrl(url: string): void
- /** False while no correctly-routed filesystem/dialect is available. */
- fileEnabled(): boolean
}
/**
@@ -543,50 +586,83 @@ export function installLinkClickFallback(
if (term.modes.mouseTrackingMode === 'none') return
const pos = bufferPosFromEvent(term, ev)
if (!pos) return
- const osc8 = osc8UrlAt(term, pos.row, pos.col)
- if (osc8) {
- ev.preventDefault()
- ev.stopPropagation()
- term.clearSelection()
- deps.openUrl(osc8)
+ const hit = linkAtCell(term, pos.row, pos.col, deps)
+ if (!hit) return
+ // Swallow the click NOW so tmux never gets the mouse report. For a path, existence is async
+ // and a Cmd/Ctrl+click on a path-shaped token is a deliberate open regardless of the outcome.
+ ev.preventDefault()
+ ev.stopPropagation()
+ term.clearSelection()
+ if (hit.kind === 'url') {
+ deps.openUrl(hit.url)
return
}
- const logical = paragraphContaining(bufferView(term), pos.row)
- if (!logical) return
- const idx = (pos.row - logical.startRow) * term.cols + pos.col
- const inRange = (startIndex: number, len: number): boolean =>
- idx >= startIndex && idx < startIndex + len
-
- for (const u of matchUrlTokens(logical.text)) {
- if (inRange(u.startIndex, u.text.length)) {
- ev.preventDefault()
- ev.stopPropagation()
- term.clearSelection()
- deps.openUrl(u.url)
- return
- }
- }
- if (!deps.fileEnabled()) return
- const convention = deps.convention ? deps.convention() : { windows: deps.windows }
- if (!convention) return
- for (const t of matchFileTokens(logical.text, convention)) {
- if (inRange(t.startIndex, t.text.length)) {
- const abs = resolveFileToken(t.path, deps.getCwd(), convention)
- if (!abs) return
- // Swallow the click NOW so tmux never gets the mouse report; existence is async and a
- // Cmd/Ctrl+click on a path-shaped token is a deliberate open regardless of the outcome.
- ev.preventDefault()
- ev.stopPropagation()
- term.clearSelection()
- void deps.lookup(abs).then((f) => {
- if (f.exists) deps.activateFile(abs, f.dir)
- })
- return
- }
- }
+ void deps.lookup(hit.abs).then((f) => {
+ if (f.exists) deps.activateFile(hit.abs, f.dir)
+ })
}
host.addEventListener('mouseup', onMouseUp, { capture: true })
return {
dispose: () => host.removeEventListener('mouseup', onMouseUp, { capture: true })
}
}
+
+export interface LinkContextMenuDeps extends LinkHitDeps {
+ /** A right-click landed on `hit` at viewport point (x, y) — the host shows its menu there. */
+ openMenu(hit: LinkHit, x: number, y: number): void
+}
+
+/**
+ * Right-click on a link → the host's link menu (open / reveal / download / copy — see
+ * link-menu.ts). A right-click anywhere else is left EXACTLY as it was: tmux's own pane menu in a
+ * plain shell (tmux 3.x binds MouseDown3Pane to `display-menu` unless the app took the mouse), the
+ * press forwarded to an agent TUI that did, and the node's context menu bubbling up to React Flow.
+ *
+ * The decision is made on the PRESS, because that is what reaches tmux: xterm reports a
+ * right-button press as a mouse escape, and once it is sent tmux has already opened its menu. So
+ * the capture-phase `mousedown` hit-tests, and on a link swallows the press, its release and the
+ * `contextmenu` that follows (that one is also what would open the node menu and xterm's own
+ * right-click handling). The menu opens on `contextmenu`, the event every platform fires for the
+ * gesture — after the press on macOS/Linux, after the release on Windows. A `contextmenu` with no
+ * right press on a link before it (Shift+F10, the Menu key) is not ours. Unlike the Cmd+click
+ * fallback this runs whatever the mouse-tracking mode: with reporting off there is no tmux to
+ * protect, but the node menu and xterm's own right-click still must not open over ours.
+ */
+export function installLinkContextMenu(
+ term: Terminal,
+ host: HTMLElement,
+ deps: LinkContextMenuDeps
+): { dispose(): void } {
+ let pending: LinkHit | null = null
+ const swallow = (ev: Event): void => {
+ ev.preventDefault()
+ ev.stopPropagation()
+ }
+ const onMouseDown = (ev: MouseEvent): void => {
+ pending = null
+ if (ev.button !== 2) return
+ const pos = bufferPosFromEvent(term, ev)
+ pending = pos ? linkAtCell(term, pos.row, pos.col, deps) : null
+ if (pending) swallow(ev)
+ }
+ const onMouseUp = (ev: MouseEvent): void => {
+ if (ev.button === 2 && pending) swallow(ev)
+ }
+ const onContextMenu = (ev: MouseEvent): void => {
+ const hit = pending
+ if (!hit) return
+ pending = null
+ swallow(ev)
+ deps.openMenu(hit, ev.clientX, ev.clientY)
+ }
+ host.addEventListener('mousedown', onMouseDown, { capture: true })
+ host.addEventListener('mouseup', onMouseUp, { capture: true })
+ host.addEventListener('contextmenu', onContextMenu, { capture: true })
+ return {
+ dispose: () => {
+ host.removeEventListener('mousedown', onMouseDown, { capture: true })
+ host.removeEventListener('mouseup', onMouseUp, { capture: true })
+ host.removeEventListener('contextmenu', onContextMenu, { capture: true })
+ }
+ }
+}
diff --git a/src/renderer/terminal/link-menu.test.ts b/src/renderer/terminal/link-menu.test.ts
new file mode 100644
index 000000000..fb5ea1543
--- /dev/null
+++ b/src/renderer/terminal/link-menu.test.ts
@@ -0,0 +1,224 @@
+import { describe, expect, it } from 'vitest'
+import type { MenuItem } from '../components/ContextMenu'
+import {
+ linkMenuItems,
+ relativeInside,
+ resolveLinkTarget,
+ urlLinkMenuItems,
+ type LinkMenuActions,
+ type LinkMenuContext,
+ type LinkMenuTarget
+} from './link-menu'
+
+/** Every action records its call, so a test can click a row and see what it did. */
+function recorder(): { calls: string[]; act: LinkMenuActions } {
+ const calls: string[] = []
+ const act: LinkMenuActions = {
+ openUrl: (u) => calls.push(`openUrl ${u}`),
+ openUrlInNode: (u) => calls.push(`openUrlInNode ${u}`),
+ copy: (t) => calls.push(`copy ${t}`),
+ openFile: (p) => calls.push(`openFile ${p}`),
+ revealInExplorer: (p) => calls.push(`revealInExplorer ${p}`),
+ revealInOs: (p) => calls.push(`revealInOs ${p}`),
+ openTerminal: (p) => calls.push(`openTerminal ${p}`),
+ download: (p, dir, pick) => calls.push(`download ${p} dir=${dir} pick=${pick}`)
+ }
+ return { calls, act }
+}
+
+const LOCAL_DESKTOP: LinkMenuContext = {
+ route: 'none',
+ localShell: true,
+ explorerRoot: '/home/me/proj',
+ terminals: true,
+ downloading: () => false
+}
+
+const SSH_DESKTOP: LinkMenuContext = {
+ route: 'scp',
+ localShell: false,
+ explorerRoot: '~/proj',
+ terminals: true,
+ downloading: () => false
+}
+
+const labels = (items: MenuItem[]): string[] =>
+ items.map((i) => (i.type === 'separator' ? '---' : 'label' in i ? i.label : `<${i.type}>`))
+
+function click(items: MenuItem[], label: string): void {
+ const item = items.find((i) => (i.type === undefined || i.type === 'item') && i.label === label)
+ if (!item || (item.type !== undefined && item.type !== 'item')) throw new Error(`no row ${label}`)
+ item.onClick()
+}
+
+describe('linkMenuItems — URL', () => {
+ const url: LinkMenuTarget = { kind: 'url', url: 'https://example.com/a' }
+
+ it('offers open, open-in-canvas and copy', () => {
+ const { calls, act } = recorder()
+ const items = linkMenuItems(url, LOCAL_DESKTOP, act)
+ expect(labels(items)).toEqual(['Open in browser', 'Open in canvas browser', '---', 'Copy link'])
+ click(items, 'Open in browser')
+ click(items, 'Open in canvas browser')
+ click(items, 'Copy link')
+ expect(calls).toEqual([
+ 'openUrl https://example.com/a',
+ 'openUrlInNode https://example.com/a',
+ 'copy https://example.com/a'
+ ])
+ })
+
+ it('offers no canvas-browser row when the host gives no way to open one (browser tab, card modal)', () => {
+ const { calls, act } = recorder()
+ const { openUrlInNode: _omitted, ...urlOnly } = act
+ const items = urlLinkMenuItems('https://example.com/a', urlOnly)
+ expect(labels(items)).toEqual(['Open in browser', '---', 'Copy link'])
+ click(items, 'Copy link')
+ expect(calls).toEqual(['copy https://example.com/a'])
+ })
+})
+
+describe('linkMenuItems — file', () => {
+ it('SSH project: a file under the project root can be opened, revealed, downloaded and copied', () => {
+ const { calls, act } = recorder()
+ const target: LinkMenuTarget = { kind: 'file', abs: '~/proj/out/report.csv', dir: false }
+ const items = linkMenuItems(target, SSH_DESKTOP, act)
+ expect(labels(items)).toEqual([
+ 'Open',
+ 'Reveal in Explorer',
+ '---',
+ 'Download',
+ 'Download to…',
+ '---',
+ 'Copy path',
+ 'Copy relative path'
+ ])
+ click(items, 'Download')
+ click(items, 'Download to…')
+ click(items, 'Copy relative path')
+ click(items, 'Open')
+ click(items, 'Reveal in Explorer')
+ expect(calls).toEqual([
+ 'download ~/proj/out/report.csv dir=false pick=false',
+ 'download ~/proj/out/report.csv dir=false pick=true',
+ 'copy out/report.csv',
+ 'openFile ~/proj/out/report.csv',
+ 'revealInExplorer ~/proj/out/report.csv'
+ ])
+ })
+
+ it('desktop local project: no Download (the file is already here), Reveal in Finder instead', () => {
+ const target: LinkMenuTarget = { kind: 'file', abs: '/home/me/proj/a.csv', dir: false }
+ const items = linkMenuItems(target, LOCAL_DESKTOP, recorder().act)
+ expect(labels(items)).toEqual([
+ 'Open',
+ 'Reveal in Explorer',
+ '---',
+ 'Copy path',
+ 'Copy relative path',
+ 'Reveal in Finder'
+ ])
+ })
+
+ it('Server Edition: the HTTP route has no "Download to…" and no OS reveal', () => {
+ const ctx: LinkMenuContext = { ...LOCAL_DESKTOP, route: 'http', localShell: false }
+ const items = linkMenuItems({ kind: 'file', abs: '/home/me/proj/a.csv', dir: false }, ctx, recorder().act)
+ expect(labels(items)).toContain('Download')
+ expect(labels(items)).not.toContain('Download to…')
+ expect(labels(items)).not.toContain('Reveal in Finder')
+ })
+
+ it('a path outside the Explorer root offers no Reveal in Explorer (it would open onto nothing)', () => {
+ const items = linkMenuItems({ kind: 'file', abs: '/tmp/x.csv', dir: false }, SSH_DESKTOP, recorder().act)
+ expect(labels(items)).toEqual(['Open', '---', 'Download', 'Download to…', '---', 'Copy path'])
+ })
+
+ it('disables Download while the same path is still downloading (a second start lands `name (2)`)', () => {
+ const ctx: LinkMenuContext = { ...SSH_DESKTOP, downloading: (p) => p === '/tmp/x.csv' }
+ const items = linkMenuItems({ kind: 'file', abs: '/tmp/x.csv', dir: false }, ctx, recorder().act)
+ const dl = items.filter((i) => 'label' in i && i.label.startsWith('Download'))
+ expect(dl).toHaveLength(2)
+ for (const row of dl) expect(row).toMatchObject({ disabled: true, hint: 'Already downloading' })
+ })
+})
+
+describe('linkMenuItems — folder', () => {
+ it('reveals, opens a terminal there, downloads the folder', () => {
+ const { calls, act } = recorder()
+ const items = linkMenuItems({ kind: 'file', abs: '~/proj/out', dir: true }, SSH_DESKTOP, act)
+ expect(labels(items)).toEqual([
+ 'Reveal in Explorer',
+ 'New terminal here',
+ '---',
+ 'Download folder',
+ 'Download to…',
+ '---',
+ 'Copy path',
+ 'Copy relative path'
+ ])
+ click(items, 'New terminal here')
+ click(items, 'Download folder')
+ expect(calls).toEqual(['openTerminal ~/proj/out', 'download ~/proj/out dir=true pick=false'])
+ })
+
+ it('names the archive on the HTTP route', () => {
+ const ctx: LinkMenuContext = { ...LOCAL_DESKTOP, route: 'http' }
+ const items = linkMenuItems({ kind: 'file', abs: '/home/me/proj/out', dir: true }, ctx, recorder().act)
+ expect(labels(items)).toContain('Download folder (.tar.gz)')
+ })
+
+ it('never offers to download `/` (the HTTP route would archive the whole server)', () => {
+ const ctx: LinkMenuContext = { ...LOCAL_DESKTOP, route: 'http', explorerRoot: undefined }
+ const items = linkMenuItems({ kind: 'file', abs: '/', dir: true }, ctx, recorder().act)
+ expect(labels(items).some((l) => l.startsWith('Download'))).toBe(false)
+ })
+
+ it('leaves no dangling rule when a whole block is withheld (relay: no terminal, outside root)', () => {
+ const ctx: LinkMenuContext = { ...LOCAL_DESKTOP, localShell: false, terminals: false }
+ const items = linkMenuItems({ kind: 'file', abs: '/tmp/out', dir: true }, ctx, recorder().act)
+ expect(labels(items)).toEqual(['Copy path'])
+ })
+})
+
+describe('linkMenuItems — a path that does not exist', () => {
+ it('says so and still lets the text be copied (the right-click was swallowed — never a dead click)', () => {
+ const { calls, act } = recorder()
+ const items = linkMenuItems({ kind: 'missing', abs: '/home/me/proj/gone.csv' }, LOCAL_DESKTOP, act)
+ expect(labels(items)).toEqual(['Not found', 'Copy path'])
+ click(items, 'Copy path')
+ expect(calls).toEqual(['copy /home/me/proj/gone.csv'])
+ })
+})
+
+describe('relativeInside', () => {
+ it('is the path below the root, or null', () => {
+ expect(relativeInside('/a/b', '/a/b/c/d.ts')).toBe('c/d.ts')
+ expect(relativeInside('/a/b/', '/a/b/c')).toBe('c')
+ expect(relativeInside('~/proj', '~/proj/x.csv')).toBe('x.csv')
+ expect(relativeInside('/a/b', '/a/bc/d')).toBeNull()
+ expect(relativeInside('/a/b', '/a/b')).toBeNull()
+ expect(relativeInside(undefined, '/a/b')).toBeNull()
+ })
+
+ it('compares Windows paths across separators', () => {
+ expect(relativeInside('C:\\Users\\me\\proj', 'C:/Users/me/proj/src/a.ts')).toBe('src/a.ts')
+ })
+})
+
+describe('resolveLinkTarget', () => {
+ it('passes a URL through and resolves a path by existence', async () => {
+ const lookup = async (abs: string) =>
+ abs === '/d' ? { exists: true, dir: true } : abs === '/f' ? { exists: true, dir: false } : { exists: false, dir: false }
+ expect(await resolveLinkTarget({ kind: 'url', url: 'https://x.io' }, lookup)).toEqual({ kind: 'url', url: 'https://x.io' })
+ expect(await resolveLinkTarget({ kind: 'path', abs: '/d' }, lookup)).toEqual({ kind: 'file', abs: '/d', dir: true })
+ expect(await resolveLinkTarget({ kind: 'path', abs: '/f' }, lookup)).toEqual({ kind: 'file', abs: '/f', dir: false })
+ expect(await resolveLinkTarget({ kind: 'path', abs: '/nope' }, lookup)).toEqual({ kind: 'missing', abs: '/nope' })
+ })
+
+ it('reads a failed lookup (dead ControlMaster) as missing, never a throw', async () => {
+ const lookup = async (): Promise<{ exists: boolean; dir: boolean }> => {
+ throw new Error('ssh down')
+ }
+ expect(await resolveLinkTarget({ kind: 'path', abs: '/x' }, lookup)).toEqual({ kind: 'missing', abs: '/x' })
+ })
+})
diff --git a/src/renderer/terminal/link-menu.ts b/src/renderer/terminal/link-menu.ts
new file mode 100644
index 000000000..b42331d7c
--- /dev/null
+++ b/src/renderer/terminal/link-menu.ts
@@ -0,0 +1,132 @@
+// Right-click on a link in terminal output → a menu of what can be done with it: open, reveal,
+// download, copy. The Cmd/Ctrl+click opener (file-links.ts) does exactly ONE thing per link; this is
+// the rest of what the Explorer offers for the same path, one right-click away, without first
+// finding the file in a tree.
+//
+// Pure: the host (TerminalNode, the kanban card's ModalTerminal) supplies the context and the
+// actions, so every gate below is a unit-testable decision rather than a branch in a component.
+//
+// The gates are the Explorer's, reused rather than restated:
+// - Download rows come from `downloadMenuEntries` — an SSH project's file comes down over scp, the
+// Server Edition's over an HTTP ticket, and a desktop LOCAL project offers none (the file is
+// already on this machine; Reveal in Finder is the honest action).
+// - The OS reveal follows `canUseLocalShell` (the host passes it in as `localShell`).
+import type { MenuItem } from '../components/ContextMenu'
+import type { DownloadRoute } from '../lib/download'
+import { downloadMenuEntries } from '../lib/filesNode'
+import { tidySeparators } from '../lib/tidySeparators'
+import type { LinkHit } from './file-links'
+
+/** What a right-click resolved to, once a path's existence is known. */
+export type LinkMenuTarget =
+ | { kind: 'url'; url: string }
+ | { kind: 'file'; abs: string; dir: boolean }
+ /** Path-shaped text with nothing behind it (or a filesystem we could not reach). The right-click
+ * was already swallowed, so it still gets a menu — a click that shows nothing reads as broken. */
+ | { kind: 'missing'; abs: string }
+
+export interface LinkMenuContext {
+ /** `downloadRoute` for the filesystem the path lives on. */
+ route: DownloadRoute
+ /** `canUseLocalShell` — this machine's file manager can act on the path. */
+ localShell: boolean
+ /** The Explorer drawer's root. Its reveal only works INSIDE that root (anything else opens the
+ * drawer onto nothing), so the row is withheld outside it. */
+ explorerRoot?: string
+ /** "New terminal here" can open on the machine that owns the path (not a relay tab). */
+ terminals: boolean
+ /** True while `path` is already downloading — a second start would land a duplicate `name (2)`. */
+ downloading: (path: string) => boolean
+}
+
+/** The actions a URL's menu needs — all a host without file links (the kanban card modal) has. */
+export interface UrlLinkActions {
+ openUrl(url: string): void
+ /** Open the page in a canvas browser node. Omitted where that node could not render (a
+ * `<webview>` is Electron-only) or would not be seen (the card modal covers the canvas) — the
+ * row is not offered then, rather than offered as a click that shows nothing. */
+ openUrlInNode?: (url: string) => void
+ copy(text: string): void
+}
+
+export interface LinkMenuActions extends UrlLinkActions {
+ /** What Cmd/Ctrl+click does for a file: an editor/media node. */
+ openFile(abs: string): void
+ revealInExplorer(abs: string): void
+ revealInOs(abs: string): void
+ openTerminal(dir: string): void
+ download(abs: string, dir: boolean, pickFolder: boolean): void
+}
+
+/** `abs` relative to `root`, or null when it is not strictly below it. Separator-agnostic, so a
+ * Windows project root (`C:\…`) compares against the `/`-separated paths the link resolver emits. */
+export function relativeInside(root: string | undefined, abs: string): string | null {
+ if (!root) return null
+ const norm = (p: string): string => p.replace(/\\/g, '/').replace(/\/+$/, '')
+ const base = norm(root)
+ const path = norm(abs)
+ return path.startsWith(base + '/') && path.length > base.length + 1 ? path.slice(base.length + 1) : null
+}
+
+/** A hit-test result → a menu target. A lookup that throws (a dead ControlMaster) is `missing`:
+ * the menu still opens, and the one thing it can honestly offer is the text. */
+export async function resolveLinkTarget(
+ hit: LinkHit,
+ lookup: (abs: string) => Promise<{ exists: boolean; dir: boolean }>
+): Promise<LinkMenuTarget> {
+ if (hit.kind === 'url') return { kind: 'url', url: hit.url }
+ try {
+ const f = await lookup(hit.abs)
+ return f.exists ? { kind: 'file', abs: hit.abs, dir: f.dir } : { kind: 'missing', abs: hit.abs }
+ } catch {
+ return { kind: 'missing', abs: hit.abs }
+ }
+}
+
+export function urlLinkMenuItems(url: string, act: UrlLinkActions): MenuItem[] {
+ const inNode = act.openUrlInNode
+ return [
+ { label: 'Open in browser', onClick: () => act.openUrl(url) },
+ ...(inNode ? [{ label: 'Open in canvas browser', onClick: () => inNode(url) }] : []),
+ { type: 'separator' },
+ { label: 'Copy link', onClick: () => act.copy(url) }
+ ]
+}
+
+export function linkMenuItems(
+ target: LinkMenuTarget,
+ ctx: LinkMenuContext,
+ act: LinkMenuActions
+): MenuItem[] {
+ if (target.kind === 'url') return urlLinkMenuItems(target.url, act)
+
+ const { abs } = target
+ if (target.kind === 'missing') {
+ return [
+ { type: 'label', label: 'Not found' },
+ { label: 'Copy path', onClick: () => act.copy(abs) }
+ ]
+ }
+
+ const { dir } = target
+ const rel = relativeInside(ctx.explorerRoot, abs)
+ const busy = ctx.downloading(abs)
+ const items: MenuItem[] = []
+ if (!dir) items.push({ label: 'Open', onClick: () => act.openFile(abs) })
+ if (rel !== null) items.push({ label: 'Reveal in Explorer', onClick: () => act.revealInExplorer(abs) })
+ if (dir && ctx.terminals) items.push({ label: 'New terminal here', onClick: () => act.openTerminal(abs) })
+ items.push({ type: 'separator' })
+ for (const d of downloadMenuEntries(ctx.route, abs, { dir, here: false })) {
+ items.push({
+ label: d.label,
+ disabled: busy,
+ hint: busy ? 'Already downloading' : undefined,
+ onClick: () => act.download(abs, dir, d.pickFolder)
+ })
+ }
+ items.push({ type: 'separator' })
+ items.push({ label: 'Copy path', onClick: () => act.copy(abs) })
+ if (rel !== null) items.push({ label: 'Copy relative path', onClick: () => act.copy(rel) })
+ if (ctx.localShell) items.push({ label: 'Reveal in Finder', onClick: () => act.revealInOs(abs) })
+ return tidySeparators(items)
+}