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.

fix(file-links): resolve relative paths against the pane's live cwd, toast on a miss

reviewd65b1005b17c
diff --git a/CLAUDE.md b/CLAUDE.md
index 59881eaff..cbe3530f6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -1369,7 +1369,13 @@ session.
all terminals — harmless in a plain shell). **Cmd (mac) / Ctrl+click** opens links in the
output: URLs → default browser (`@xterm/addon-web-links`), file paths → editor node and
directories → Explorer reveal (`terminal/file-links.ts`, existence-verified against the project
- fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes). The path
+ fs via cached parent-dir listings, with `path:line[:col]` compiler-output suffixes). A relative
+ path is anchored on the node's LAUNCH cwd first, then on the pane's LIVE cwd (`pty:pane-cwd` —
+ tmux `#{pane_current_path}`, local or over the ControlMaster; `findExistingPath`), because an
+ agent prints paths relative to where IT runs; the launch cwd wins a tie so a link never changes
+ meaning when the pane moves. A Cmd/Ctrl+click on a path that exists under neither raises a
+ `File not found: …` toast naming where it looked — the click is swallowed before the async
+ lookup, so without it the gesture silently did nothing. The path
dialect follows the FILESYSTEM-OWNING CORE, not the viewer: desktop-local may use its own
platform, Server Edition and relay tabs use the core's reported `process.platform`, and SSH
projects are POSIX. A failed host-platform read disables file links for that connection — it
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e01955a4f..b86a67759 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -34,6 +34,7 @@ import {
remotePasteDelivery,
remoteCapturePaneArgs,
remotePaneCommandArgs,
+ remotePaneCwdArgs,
remoteSessionAgeArgs,
parseSessionAge,
remotePaneOwnerCombinedArgs,
@@ -1846,6 +1847,7 @@ export class PtyManager {
)
platform().handle(IPC.ptyTmuxStatus, () => this.tmuxStatus())
platform().handle(IPC.ptyPaneCommand, (persistKey: string) => this.paneCommand(persistKey))
+ platform().handle(IPC.ptyPaneCwd, (persistKey: string) => this.paneCwd(persistKey))
// Registered HERE, beside its name-only sibling, rather than in either shell: core owns both
// reads, so the desktop and the Server Edition are served by one line and cannot drift.
platform().handle(IPC.ptyPaneOwner, (persistKey: string) => this.paneOwner(persistKey))
@@ -4621,6 +4623,50 @@ export class PtyManager {
}
}
+ /**
+ * The live working directory of a node's pane (`#{pane_current_path}` — the cwd of the pane's
+ * foreground process, e.g. the agent CLI), by persistKey. File links resolve a relative path
+ * against the node's LAUNCH cwd first; this is the second candidate, for output printed relative
+ * to wherever the pane has since moved (`cd`, or an agent started from another directory).
+ *
+ * Same dispatch and failure contract as `paneCommand`: the SSH branch asks the REMOTE tmux over
+ * the project's ControlMaster, and every unknown — no live session, no tmux, the session-host
+ * backend (it tracks no cwd), a failed query — is null, never a throw.
+ */
+ async paneCwd(persistKey: string): Promise<string | null> {
+ const target = sessionName(persistKey)
+ const live = this.liveSessionForPersistKey(persistKey)
+ const sshRemote = live?.sshRemote
+ if (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return null
+ try {
+ const { stdout } = await runAsync(
+ ssh,
+ remotePaneCwdArgs(sshRemote.conn, sshRemote.controlPath, target)
+ )
+ return stdout.trim() || null
+ } catch {
+ return null
+ }
+ }
+ if (live?.sessionHost || !this.tmuxPath) return null
+ try {
+ const { stdout } = await runAsync(this.tmuxPath, [
+ '-L',
+ TMUX_SOCKET,
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ '#{pane_current_path}'
+ ])
+ return stdout.trim() || null
+ } catch {
+ return null
+ }
+ }
+
/**
* How many SECONDS ago was this node's tmux session created — on the machine that holds it?
*
diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.ts
index f74a10372..85018c054 100644
--- a/src/core/relay/access-policy.ts
+++ b/src/core/relay/access-policy.ts
@@ -291,6 +291,8 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([
IPC.ptySessionAge,
IPC.ptySendText,
IPC.ptyPaneOwner,
+ // A host filesystem path, not a view of the terminal — a viewer's file links keep the node cwd.
+ IPC.ptyPaneCwd,
IPC.ptyTerminateForeground,
IPC.ptyReadSessionName,
// Workspace, project settings and setup: writes, probes of arbitrary folders, trust, scripts.
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 28407287f..26d60026a 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -9,6 +9,7 @@ import {
probeSaysAbsent,
remoteCapturePaneArgs,
remotePaneCommandArgs,
+ remotePaneCwdArgs,
remotePaneProcessArgs,
remoteTerminateForegroundArgs,
remoteListSessionsArgs,
@@ -267,6 +268,15 @@ describe('remotePaneCommandArgs', () => {
})
})
+describe('remotePaneCwdArgs', () => {
+ it('asks the remote tmux for the pane_current_path of the session', () => {
+ const args = remotePaneCwdArgs(conn, '/s.sock', 'nt-x')
+ expect(args[args.length - 1]).toBe(
+ `${TP}tmux -L ${RMT_TMUX_SOCKET} display-message -p -t nt-x '#{pane_current_path}'`
+ )
+ })
+})
+
describe('remote foreground process termination', () => {
it('reads pane pid + command through the existing ControlMaster', () => {
const args = remotePaneProcessArgs(conn, '/s.sock', 'nt-x')
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index becbf4a05..50eec55d6 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -558,6 +558,15 @@ export function remotePaneCommandArgs(conn: SshConnection, controlPath: string,
)
}
+/** The remote counterpart of `PtyManager.paneCwd`'s local `display-message` path. */
+export function remotePaneCwdArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
+ return childArgs(
+ conn,
+ controlPath,
+ tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} display-message -p -t ${sessionId} '#{pane_current_path}'`)
+ )
+}
+
/** Ask remote tmux for the shell PID and current command as one parseable, bounded record. */
export function remotePaneProcessArgs(
conn: SshConnection,
diff --git a/src/preload/index.ts b/src/preload/index.ts
index b0adc1272..1ab543ca4 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -101,6 +101,7 @@ const api: NodeTerminalApi = {
ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),
tmuxStatus: () => ipcRenderer.invoke(IPC.ptyTmuxStatus),
paneCommand: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCommand, persistKey),
+ paneCwd: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneCwd, persistKey),
launchHeadless: (req) => ipcRenderer.invoke(IPC.ptyLaunchHeadless, req),
paneOwner: (persistKey) => ipcRenderer.invoke(IPC.ptyPaneOwner, persistKey),
terminateForeground: (persistKey, expectedAgentId) =>
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index c4f7c7a38..0f5583baa 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -276,6 +276,10 @@ export function buildRealApi(
// shell yet" and gives up on its own deadline.
paneCommand: (persistKey) =>
client.request(IPC.ptyPaneCommand, persistKey).catch(() => null) as Promise<string | null>,
+ // Real: core registers it. Unknown (null) on failure — a relay host refuses it to a non-editor
+ // (EDITOR_ONLY), which reads as "no live cwd" and file links keep the node's launch cwd.
+ paneCwd: (persistKey) =>
+ client.request(IPC.ptyPaneCwd, persistKey).catch(() => null) as Promise<string | null>,
// Documented degrade (#925): the Server Edition starts nodes through its HeadlessNodeFactory,
// never through the browser renderer, so there is nothing for this to call.
launchHeadless: () => unsupported('pty.launchHeadless'),
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index f38af3c3d..999ab13d4 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -47,6 +47,9 @@ import {
createUrlLinkProvider,
installLinkClickFallback,
installLinkContextMenu,
+ cachedCwd,
+ findExistingPath,
+ missingFileMessage,
makeDirListingLookup
} from '../terminal/file-links'
import { linkMenuItems, resolveLinkTarget, type LinkMenuTarget } from '../terminal/link-menu'
@@ -3098,6 +3101,15 @@ export function TerminalNode({
pathConvention
)
const getCwd = (): string | undefined => (data.cwd as string | undefined) || undefined
+ // The pane's CURRENT directory — the second anchor for a relative path (see CwdSources).
+ const getLiveCwd = cachedCwd(() => api.pty.paneCwd(id))
+ const onMissingFile = (token: string, tried: string[]): void => {
+ window.dispatchEvent(
+ new CustomEvent('nodeterm:toast', {
+ detail: { kind: 'error', message: missingFileMessage(token, tried) }
+ })
+ )
+ }
const openFile = (abs: string, isDir: boolean): void => {
if (isDir) window.dispatchEvent(new CustomEvent('nodeterm:reveal-file', { detail: { path: abs } }))
else
@@ -3108,6 +3120,7 @@ export function TerminalNode({
term.registerLinkProvider(
createFileLinkProvider(term, {
getCwd,
+ getLiveCwd,
lookup,
activate: openFile,
convention: pathConvention
@@ -3120,8 +3133,10 @@ export function TerminalNode({
if (term.element) {
installLinkClickFallback(term, term.element, {
getCwd,
+ getLiveCwd,
lookup,
activateFile: openFile,
+ onMissing: onMissingFile,
openUrl: (uri) => window.nodeTerminal.shell.openExternal(uri),
fileEnabled: () => pathConvention() !== null,
convention: pathConvention
@@ -3130,10 +3145,13 @@ export function TerminalNode({
// same routed lookup; the menu itself is state on whichever instance is mounted now.
installLinkContextMenu(term, term.element, {
getCwd,
+ getLiveCwd,
fileEnabled: () => pathConvention() !== null,
convention: pathConvention,
openMenu: (hit, x, y) =>
- void resolveLinkTarget(hit, lookup).then((target) =>
+ void resolveLinkTarget(hit, (token) =>
+ findExistingPath(token, pathConvention() ?? {}, { getCwd, getLiveCwd, lookup })
+ ).then((target) =>
linkMenuSubs.get(termKey)?.(target, x, y)
)
})
diff --git a/src/renderer/terminal/file-links.context-menu.test.ts b/src/renderer/terminal/file-links.context-menu.test.ts
index c2be55875..ab03e06b4 100644
--- a/src/renderer/terminal/file-links.context-menu.test.ts
+++ b/src/renderer/terminal/file-links.context-menu.test.ts
@@ -66,7 +66,11 @@ describe('linkAtCell', () => {
})
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' })
+ expect(linkAtCell(term, 1, 8, deps())).toEqual({
+ kind: 'path',
+ token: 'out/report.csv',
+ abs: '/home/me/proj/out/report.csv'
+ })
})
it('is null off a link, and for paths while file links are disabled', () => {
@@ -118,7 +122,7 @@ describe('installLinkContextMenu', () => {
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 }
+ { hit: { kind: 'path', token: 'out/report.csv', 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)
diff --git a/src/renderer/terminal/file-links.live-cwd.test.ts b/src/renderer/terminal/file-links.live-cwd.test.ts
new file mode 100644
index 000000000..38f98a9cd
--- /dev/null
+++ b/src/renderer/terminal/file-links.live-cwd.test.ts
@@ -0,0 +1,148 @@
+import { describe, expect, it } from 'vitest'
+import { cachedCwd, findExistingPath, matchFileTokens, missingFileMessage } from './file-links'
+
+// A fake filesystem: exactly these absolute paths exist.
+const fsWith =
+ (...files: string[]) =>
+ async (abs: string): Promise<{ exists: boolean; dir: boolean }> => ({ exists: files.includes(abs), dir: false })
+
+describe('findExistingPath', () => {
+ it('resolves against the launch cwd first and never asks the live cwd on a hit', async () => {
+ let asked = 0
+ const r = await findExistingPath(
+ 'var/x.sql',
+ {},
+ {
+ getCwd: () => '/proj',
+ getLiveCwd: async () => {
+ asked++
+ return '/elsewhere'
+ },
+ lookup: fsWith('/proj/var/x.sql', '/elsewhere/var/x.sql')
+ }
+ )
+ expect(r).toEqual({ found: true, abs: '/proj/var/x.sql', dir: false })
+ expect(asked).toBe(0)
+ })
+
+ it('falls back to the pane\'s live cwd when the launch cwd misses (the agent runs elsewhere)', async () => {
+ const r = await findExistingPath(
+ 'var/otta-aktarim/1-OTTADA-CALISTIR.sql',
+ {},
+ {
+ getCwd: () => '/Users/me',
+ getLiveCwd: async () => '/Users/me/otta',
+ lookup: fsWith('/Users/me/otta/var/otta-aktarim/1-OTTADA-CALISTIR.sql')
+ }
+ )
+ expect(r).toEqual({ found: true, abs: '/Users/me/otta/var/otta-aktarim/1-OTTADA-CALISTIR.sql', dir: false })
+ })
+
+ it('anchors a relative token on the live cwd when the node has no cwd at all', async () => {
+ const r = await findExistingPath('src/a.ts', {}, { getCwd: () => undefined, getLiveCwd: async () => '/w', lookup: fsWith('/w/src/a.ts') })
+ expect(r).toEqual({ found: true, abs: '/w/src/a.ts', dir: false })
+ })
+
+ it('reports every path it tried, once each, when neither cwd holds the file', async () => {
+ expect(
+ await findExistingPath('a/b', {}, { getCwd: () => '/one', getLiveCwd: async () => '/two', lookup: fsWith() })
+ ).toEqual({ found: false, tried: ['/one/a/b', '/two/a/b'] })
+ // Same directory twice is one attempt.
+ expect(
+ await findExistingPath('a/b', {}, { getCwd: () => '/one', getLiveCwd: async () => '/one/', lookup: fsWith() })
+ ).toEqual({ found: false, tried: ['/one/a/b'] })
+ })
+
+ it('does not re-anchor an absolute or home-relative token on the live cwd', async () => {
+ let asked = 0
+ const getLiveCwd = async (): Promise<string> => {
+ asked++
+ return '/two'
+ }
+ expect(await findExistingPath('/abs/x', {}, { getCwd: () => '/one', getLiveCwd, lookup: fsWith() })).toEqual({
+ found: false,
+ tried: ['/abs/x']
+ })
+ expect(await findExistingPath('~/x/y', {}, { getCwd: () => '/one', getLiveCwd, lookup: fsWith() })).toEqual({
+ found: false,
+ tried: ['~/x/y']
+ })
+ expect(asked).toBe(0)
+ })
+
+ it('reads a throwing lookup or live-cwd read as a miss, never a rejection', async () => {
+ const r = await findExistingPath(
+ 'a/b',
+ {},
+ {
+ getCwd: () => '/one',
+ getLiveCwd: () => Promise.reject(new Error('tmux gone')),
+ lookup: () => Promise.reject(new Error('ssh down'))
+ }
+ )
+ expect(r).toEqual({ found: false, tried: ['/one/a/b'] })
+ })
+
+ it('uses the Windows dialect for both candidates', async () => {
+ const r = await findExistingPath(
+ 'src\\a.ts',
+ { windows: true },
+ { getCwd: () => 'C:\\one', getLiveCwd: async () => 'C:\\two', lookup: fsWith('C:/two/src/a.ts') }
+ )
+ expect(r).toEqual({ found: true, abs: 'C:/two/src/a.ts', dir: false })
+ })
+})
+
+describe('the reported line', () => {
+ it('matches the path inside an agent\'s `› [file] … (2.8KB)` line', () => {
+ const line = ' › [file] var/otta-aktarim/1-OTTADA-CALISTIR.sql (2.8KB)'
+ expect(matchFileTokens(line).map((t) => t.path)).toEqual(['var/otta-aktarim/1-OTTADA-CALISTIR.sql'])
+ })
+})
+
+describe('cachedCwd', () => {
+ it('coalesces concurrent reads and caches a value for the TTL', async () => {
+ let t = 0
+ let reads = 0
+ const get = cachedCwd(
+ async () => {
+ reads++
+ return '/w'
+ },
+ 1000,
+ () => t
+ )
+ expect(await Promise.all([get(), get(), get()])).toEqual(['/w', '/w', '/w'])
+ expect(reads).toBe(1)
+ t = 999
+ await get()
+ expect(reads).toBe(1)
+ t = 1000
+ await get()
+ expect(reads).toBe(2)
+ })
+
+ it('does not cache an unknown answer or a failure', async () => {
+ let reads = 0
+ const answers: Array<string | null | Error> = [null, new Error('x'), '/w']
+ const get = cachedCwd(async () => {
+ const a = answers[reads++]
+ if (a instanceof Error) throw a
+ return a
+ })
+ expect(await get()).toBeUndefined()
+ expect(await get()).toBeUndefined()
+ expect(await get()).toBe('/w')
+ expect(reads).toBe(3)
+ })
+})
+
+describe('missingFileMessage', () => {
+ it('names where it looked', () => {
+ expect(missingFileMessage('a/b', ['/one/a/b'])).toBe('File not found: /one/a/b')
+ expect(missingFileMessage('a/b', ['/one/a/b', '/two/a/b'])).toBe(
+ 'File not found: a/b — looked in /one/a/b and /two/a/b'
+ )
+ expect(missingFileMessage('a/b', [])).toBe('File not found: a/b (no working directory to resolve it against)')
+ })
+})
diff --git a/src/renderer/terminal/file-links.ts b/src/renderer/terminal/file-links.ts
index 305ab74aa..4000a8f21 100644
--- a/src/renderer/terminal/file-links.ts
+++ b/src/renderer/terminal/file-links.ts
@@ -284,8 +284,96 @@ function resolveWindowsFileToken(path: string, cwd: string | undefined): string
return `${drive}/${out.join('/')}`
}
-export interface FileLinkDeps {
+/** The two cwds a relative path can be anchored on, in order. `getCwd` is the node's LAUNCH cwd
+ * (persisted, synchronous); `getLiveCwd` is the pane's CURRENT directory (tmux
+ * `#{pane_current_path}`, async, may be unknown). An agent printing `var/x/y.sql` prints it relative
+ * to wherever IT runs, which is not always where the node was opened — the launch cwd alone left
+ * every such path dead with no hint why. */
+export interface CwdSources {
getCwd(): string | undefined
+ getLiveCwd?(): Promise<string | undefined>
+}
+
+/** Where a path token resolved: an existing entry, or every absolute path that was tried. */
+export type PathResolution =
+ | { found: true; abs: string; dir: boolean }
+ | { found: false; tried: string[] }
+
+/**
+ * Resolve a path token to an EXISTING file or directory: absolute (and `~/`) tokens are tried as
+ * they are; a relative token against the launch cwd first, then the pane's live cwd. The launch cwd
+ * wins when both hold a match, so a link never changes meaning just because the pane moved. The
+ * live cwd is only asked when the first candidate misses — it is a tmux round trip, and the common
+ * case never pays it. A lookup that throws counts as a miss.
+ */
+export async function findExistingPath(
+ token: string,
+ convention: PathConventionOpts,
+ deps: CwdSources & { lookup(abs: string): Promise<{ exists: boolean; dir: boolean }> }
+): Promise<PathResolution> {
+ const tried: string[] = []
+ const attempt = async (cwd: string | undefined): Promise<PathResolution | null> => {
+ const abs = resolveFileToken(token, cwd, convention)
+ if (!abs || tried.includes(abs)) return null
+ tried.push(abs)
+ const f = await deps.lookup(abs).catch(() => ({ exists: false, dir: false }))
+ return f.exists ? { found: true, abs, dir: f.dir } : null
+ }
+ const first = await attempt(deps.getCwd())
+ if (first) return first
+ if (deps.getLiveCwd && !isAnchoredToken(token, convention)) {
+ const live = await deps.getLiveCwd().catch(() => undefined)
+ if (live) {
+ const second = await attempt(live)
+ if (second) return second
+ }
+ }
+ return { found: false, tried }
+}
+
+/** Does the token carry its own root (so no cwd can change where it points)? */
+function isAnchoredToken(token: string, convention: PathConventionOpts): boolean {
+ if (convention.windows) return WIN_ABSOLUTE_RE.test(token)
+ return token.startsWith('/') || token.startsWith('~/')
+}
+
+/**
+ * Memoize an async cwd read for `ttlMs`, coalescing concurrent calls. xterm asks every link
+ * provider on each hovered row, and a live-cwd read is a tmux (or ssh) exec — uncached, a mouse
+ * sweep over agent output would fire one per row. A failure reads as unknown and is not cached.
+ */
+export function cachedCwd(
+ read: () => Promise<string | null>,
+ ttlMs = 3000,
+ now: () => number = Date.now
+): () => Promise<string | undefined> {
+ let hit: { at: number; value: string } | null = null
+ let inFlight: Promise<string | undefined> | null = null
+ return () => {
+ if (hit && now() - hit.at < ttlMs) return Promise.resolve(hit.value)
+ if (inFlight) return inFlight
+ inFlight = read()
+ .then((v) => {
+ hit = v ? { at: now(), value: v } : null
+ return v || undefined
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ inFlight = null
+ })
+ return inFlight
+ }
+}
+
+/** The toast text for a Cmd/Ctrl+click on a path that exists nowhere we looked. */
+export function missingFileMessage(token: string, tried: string[]): string {
+ if (!tried.length) return `File not found: ${token} (no working directory to resolve it against)`
+ return tried.length === 1
+ ? `File not found: ${tried[0]}`
+ : `File not found: ${token} — looked in ${tried.join(' and ')}`
+}
+
+export interface FileLinkDeps extends CwdSources {
/** Static compatibility option for direct unit consumers. Live terminals use `convention`. */
windows?: boolean
/** Dynamic host decision. `null` means the owning core's dialect was not observed, so file
@@ -399,10 +487,9 @@ export function createFileLinkProvider(term: Terminal, deps: FileLinkDeps): ILin
const cols = term.cols
void Promise.all(
tokens.map(async (t): Promise<ILink | null> => {
- const abs = resolveFileToken(t.path, deps.getCwd(), convention)
- if (!abs) return null
- const found = await deps.lookup(abs)
- if (!found.exists) return null
+ const found = await findExistingPath(t.path, convention, deps)
+ if (!found.found) return null
+ const { abs } = found
return {
text: t.text,
range: tokenRange(logical.startRow, cols, t.startIndex, t.text.length),
@@ -508,11 +595,14 @@ function bufferPosFromEvent(term: Terminal, ev: MouseEvent): { col: number; row:
/** 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 }
+export type LinkHit =
+ | { kind: 'url'; url: string }
+ /** `token` is the path as printed; `abs` its resolution against the LAUNCH cwd (null when that
+ * cannot anchor it — a relative token on a cwd-less node — which the live cwd may still). */
+ | { kind: 'path'; token: string; abs: string | null }
/** What `linkAtCell` needs to turn text into a path: the cwd and dialect the file providers use. */
-export interface LinkHitDeps {
- getCwd(): string | undefined
+export interface LinkHitDeps extends CwdSources {
/** See FileLinkDeps.windows. */
windows?: boolean
/** See FileLinkDeps.convention. */
@@ -550,7 +640,8 @@ export function linkAtCell(
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
+ // Unanchorable against the launch cwd is still a hit when a live cwd can be asked.
+ return abs || deps.getLiveCwd ? { kind: 'path', token: t.path, abs } : null
}
}
return null
@@ -560,6 +651,10 @@ export interface LinkClickDeps extends LinkHitDeps {
lookup(abs: string): Promise<{ exists: boolean; dir: boolean }>
activateFile(abs: string, dir: boolean): void
openUrl(url: string): void
+ /** A Cmd/Ctrl+click on a path that exists under neither cwd. The click is already swallowed (it
+ * must be, before the async lookup), so without this it would do nothing at all — the host says
+ * where it looked instead. `tried` may be empty (nothing could anchor the token). */
+ onMissing?(token: string, tried: string[]): void
}
/**
@@ -597,8 +692,10 @@ export function installLinkClickFallback(
deps.openUrl(hit.url)
return
}
- void deps.lookup(hit.abs).then((f) => {
- if (f.exists) deps.activateFile(hit.abs, f.dir)
+ const convention = (deps.convention ? deps.convention() : { windows: deps.windows }) ?? {}
+ void findExistingPath(hit.token, convention, deps).then((r) => {
+ if (r.found) deps.activateFile(r.abs, r.dir)
+ else deps.onMissing?.(hit.token, r.tried)
})
}
host.addEventListener('mouseup', onMouseUp, { capture: true })
diff --git a/src/renderer/terminal/link-menu.test.ts b/src/renderer/terminal/link-menu.test.ts
index fb5ea1543..ed4f61203 100644
--- a/src/renderer/terminal/link-menu.test.ts
+++ b/src/renderer/terminal/link-menu.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { MenuItem } from '../components/ContextMenu'
+import type { PathResolution } from './file-links'
import {
linkMenuItems,
relativeInside,
@@ -206,19 +207,37 @@ describe('relativeInside', () => {
})
describe('resolveLinkTarget', () => {
+ const find = async (token: string): Promise<PathResolution> =>
+ token === 'd'
+ ? { found: true, abs: '/p/d', dir: true }
+ : token === 'f'
+ ? { found: true, abs: '/p/f', dir: false }
+ : { found: false, tried: ['/p/' + token] }
+
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' })
+ expect(await resolveLinkTarget({ kind: 'url', url: 'https://x.io' }, find)).toEqual({ kind: 'url', url: 'https://x.io' })
+ expect(await resolveLinkTarget({ kind: 'path', token: 'd', abs: '/p/d' }, find)).toEqual({ kind: 'file', abs: '/p/d', dir: true })
+ expect(await resolveLinkTarget({ kind: 'path', token: 'f', abs: '/p/f' }, find)).toEqual({ kind: 'file', abs: '/p/f', dir: false })
+ expect(await resolveLinkTarget({ kind: 'path', token: 'nope', abs: '/p/nope' }, find)).toEqual({ kind: 'missing', abs: '/p/nope' })
+ })
+
+ it('takes the resolver\'s answer, which may come from the live cwd rather than hit.abs', async () => {
+ const live = async (): Promise<PathResolution> => ({ found: true, abs: '/live/var/x.sql', dir: false })
+ expect(await resolveLinkTarget({ kind: 'path', token: 'var/x.sql', abs: '/launch/var/x.sql' }, live)).toEqual({
+ kind: 'file',
+ abs: '/live/var/x.sql',
+ dir: false
+ })
+ })
+
+ it('falls back to the printed token when nothing anchored it', async () => {
+ expect(await resolveLinkTarget({ kind: 'path', token: 'var/x.sql', abs: null }, find)).toEqual({ kind: 'missing', abs: 'var/x.sql' })
})
it('reads a failed lookup (dead ControlMaster) as missing, never a throw', async () => {
- const lookup = async (): Promise<{ exists: boolean; dir: boolean }> => {
+ const boom = async (): Promise<PathResolution> => {
throw new Error('ssh down')
}
- expect(await resolveLinkTarget({ kind: 'path', abs: '/x' }, lookup)).toEqual({ kind: 'missing', abs: '/x' })
+ expect(await resolveLinkTarget({ kind: 'path', token: 'x', abs: '/x' }, boom)).toEqual({ kind: 'missing', abs: '/x' })
})
})
diff --git a/src/renderer/terminal/link-menu.ts b/src/renderer/terminal/link-menu.ts
index b42331d7c..21a9439d9 100644
--- a/src/renderer/terminal/link-menu.ts
+++ b/src/renderer/terminal/link-menu.ts
@@ -15,7 +15,7 @@ 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'
+import type { LinkHit, PathResolution } from './file-links'
/** What a right-click resolved to, once a path's existence is known. */
export type LinkMenuTarget =
@@ -72,14 +72,15 @@ export function relativeInside(root: string | undefined, abs: string): string |
* 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 }>
+ find: (token: string) => Promise<PathResolution>
): Promise<LinkMenuTarget> {
if (hit.kind === 'url') return { kind: 'url', url: hit.url }
+ const missing: LinkMenuTarget = { kind: 'missing', abs: hit.abs ?? hit.token }
try {
- const f = await lookup(hit.abs)
- return f.exists ? { kind: 'file', abs: hit.abs, dir: f.dir } : { kind: 'missing', abs: hit.abs }
+ const r = await find(hit.token)
+ return r.found ? { kind: 'file', abs: r.abs, dir: r.dir } : missing
} catch {
- return { kind: 'missing', abs: hit.abs }
+ return missing
}
}
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index 3954812cc..9fa6c1ac0 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -32,6 +32,9 @@ export const IPC = {
/** The foreground command of a node's tmux pane (`#{pane_current_command}`) — how the in-place
* agent restart sees that the CLI has exited and a shell owns the pane again. */
ptyPaneCommand: 'pty:pane-command',
+ /** The live working directory of a node's tmux pane (`#{pane_current_path}`) — where a relative
+ * path an agent printed actually lives when it is not the node's launch cwd (file links). */
+ ptyPaneCwd: 'pty:pane-cwd',
/** Desktop-only (#925): start a node's session with no viewer and deliver its held launch. */
ptyLaunchHeadless: 'pty:launch-headless',
/** Kernel truth about a node's tmux pane: its root pid, tty, tmux pane id, and the full argv of
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 92217b1f5..a85e46b62 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -1137,6 +1137,10 @@ export interface PtyApi {
* node persistKey. null when it is unknown — no session, no tmux, or the query failed — which
* callers must read as "not observed", never as evidence of a particular command. */
paneCommand(persistKey: string): Promise<string | null>
+ /** The live working directory of a node's pane (`#{pane_current_path}`). null when unknown —
+ * no session, no tmux, the session-host backend, a failed query, or a surface that does not
+ * serve it (relay tabs) — and never a rejection. Used as the second cwd for file links. */
+ paneCwd(persistKey: string): Promise<string | null>
/**
* Desktop only (#925). Spawn-or-attach a node's session with no viewer and deliver `command`
* through the echo-verified writer, then release the synthetic client (the tmux session keeps