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(pty): a visible-only capture and a join-only, non-voting watcher join

reviewa227a9f609d4
diff --git a/src/core/pty-manager.capture-visible.test.ts b/src/core/pty-manager.capture-visible.test.ts
new file mode 100644
index 000000000..ad89165df
--- /dev/null
+++ b/src/core/pty-manager.capture-visible.test.ts
@@ -0,0 +1,194 @@
+// `PtyManager.captureVisible` — a live link's keyframe: WHICH binary is asked with WHICH argv, and
+// the failure contract. The argv's meaning (exact target, visible rows only, the cursor line from the
+// same invocation) is proven against a real tmux in `watch-link/capture-route.realtmux.test.ts` and
+// through a real /bin/sh in `remote-ssh/capture-visible.realsh.test.ts`; this file pins dispatch.
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform } from './platform-fake'
+import { TMUX_SOCKET, sessionName } from './tmux-naming'
+import { RMT_TMUX_SOCKET } from './remote-ssh/control-master'
+import { VISIBLE_CAPTURE_FORMAT, unavailableCapture } from './watch-link/capture-route'
+
+/** Every `runAsync` in pty-manager lands here. `answer` decides what each call resolves to. */
+const calls: Array<{ file: string; args: string[] }> = []
+const script = vi.hoisted(() => ({
+ answer: (() => ({ stdout: '' })) as (file: string, args: string[]) => { stdout: string }
+}))
+
+vi.mock('child_process', () => {
+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void
+ const execFile = (file: string, args: string[], a?: unknown, b?: unknown): unknown => {
+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined
+ calls.push({ file, args })
+ try {
+ cb?.(null, { ...script.answer(file, args), stderr: '' })
+ } catch (e) {
+ cb?.(e as Error)
+ }
+ return {}
+ }
+ return { execFile, execFileSync: (): string => '' }
+})
+
+const ssh = vi.hoisted(() => ({ path: '/usr/bin/ssh' as string | null }))
+vi.mock('./exec-path', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./exec-path')>()),
+ findExecutableSync: (bin: string) => (bin === 'ssh' ? ssh.path : null),
+ shellPathNow: () => '/usr/bin:/bin',
+ resolveShellPath: async () => '/usr/bin:/bin'
+}))
+
+vi.mock('node-pty', () => ({
+ spawn: () => ({
+ onData: () => {},
+ onExit: () => {},
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {},
+ pid: 4321
+ })
+}))
+
+const hostCapture = vi.hoisted(() => vi.fn(async () => 'HISTORY LINE 1\nHISTORY LINE 2\n'))
+vi.mock('./session-host-backend', async (original) => ({
+ ...(await original<typeof import('./session-host-backend')>()),
+ sessionHostCapture: hostCapture
+}))
+
+const NODE = 'node-1'
+const TARGET = `=${sessionName(NODE)}:`
+const SSH_REMOTE = { conn: { host: 'h', user: 'u' }, controlPath: '/tmp/cm-abc', remoteCwd: '/srv' }
+
+/** A manager with one registered session, built without `create` — `captureVisible` reads only the
+ * session's backend fields, so a spawn harness would be noise around the thing under test. */
+async function manager(session: Record<string, unknown>, tmux: string | null = '/usr/bin/tmux') {
+ const { PtyManager } = await import('./pty-manager')
+ const mgr = new PtyManager() as unknown as {
+ tmuxPath: string | null
+ sessions: Map<string, unknown>
+ captureVisible(id: string): Promise<unknown>
+ }
+ mgr.tmuxPath = tmux
+ mgr.sessions.set('sess-1', { persistKey: NODE, indexKey: NODE, tmuxBacked: true, ...session })
+ return mgr
+}
+
+beforeEach(() => {
+ calls.length = 0
+ ssh.path = '/usr/bin/ssh'
+ hostCapture.mockClear()
+ script.answer = () => ({ stdout: 'hello\n\n2 0 0\n' })
+ // `findSsh` memoizes per module; a fresh module per test lets one test say "no ssh here".
+ vi.resetModules()
+ initPlatform(fakePlatform())
+})
+afterEach(() => resetPlatformForTests())
+
+describe('captureVisible — local tmux', () => {
+ it('asks the local tmux once: visible screen + cursor, exact target, no history', async () => {
+ const m = await manager({})
+ expect(await m.captureVisible('sess-1')).toEqual({
+ screen: 'hello\n\n',
+ cursor: { x: 2, y: 0 },
+ altScreen: false
+ })
+ expect(calls).toEqual([
+ {
+ file: '/usr/bin/tmux',
+ args: [
+ '-L',
+ TMUX_SOCKET,
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ TARGET,
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ TARGET,
+ VISIBLE_CAPTURE_FORMAT
+ ]
+ }
+ ])
+ expect(calls[0].args).not.toContain('-S')
+ })
+
+ it('a failed capture is unavailable, never a partial answer', async () => {
+ script.answer = () => {
+ throw Object.assign(new Error("can't find session: nt-node-1"), { code: 1 })
+ }
+ const m = await manager({})
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ })
+
+ it('a plain shell (not tmux-backed) gets no keyframe and runs nothing', async () => {
+ const m = await manager({ tmuxBacked: false })
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ expect(calls).toEqual([])
+ })
+
+ it('no tmux binary: no keyframe, nothing run', async () => {
+ const m = await manager({}, null)
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ expect(calls).toEqual([])
+ })
+
+ it('an unknown session is unavailable', async () => {
+ const m = await manager({})
+ expect(await m.captureVisible('nope')).toEqual(unavailableCapture())
+ expect(calls).toEqual([])
+ })
+})
+
+describe('captureVisible — never history', () => {
+ it('a session-host session gets NO keyframe — its only capture is scrollback', async () => {
+ const m = await manager({ sessionHost: true })
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ expect(hostCapture).not.toHaveBeenCalled()
+ expect(calls).toEqual([])
+ })
+
+ it('a direct Windows pane gets no keyframe either', async () => {
+ const capture = vi.fn(() => 'HISTORY')
+ const m = await manager({ nativeWindowsPane: { capture } })
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ expect(capture).not.toHaveBeenCalled()
+ expect(calls).toEqual([])
+ })
+})
+
+describe('captureVisible — SSH project', () => {
+ it('asks the REMOTE tmux over the ControlMaster, one invocation, no history', async () => {
+ const m = await manager({ sshRemote: SSH_REMOTE })
+ expect(await m.captureVisible('sess-1')).toEqual({
+ screen: 'hello\n\n',
+ cursor: { x: 2, y: 0 },
+ altScreen: false
+ })
+ expect(calls).toHaveLength(1)
+ expect(calls[0].file).toBe('/usr/bin/ssh')
+ const remote = calls[0].args.at(-1)!
+ expect(remote).toContain(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t '${TARGET}' ';' display-message`)
+ expect(remote).not.toMatch(/-S\b/)
+ expect(calls[0].args).toContain('ControlPath=/tmp/cm-abc')
+ })
+
+ it('never falls through to the LOCAL tmux for a remote node', async () => {
+ ssh.path = null
+ const m = await manager({ sshRemote: SSH_REMOTE })
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ expect(calls).toEqual([])
+ })
+
+ it('a dead ControlMaster is unavailable', async () => {
+ script.answer = () => {
+ throw Object.assign(new Error('mux_client_request_session: read from master failed'), { code: 255 })
+ }
+ const m = await manager({ sshRemote: SSH_REMOTE })
+ expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index c9f28ec79..76905afb0 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -33,6 +33,7 @@ import {
type RemoteSessionEnv,
remotePasteDelivery,
remoteCapturePaneArgs,
+ remoteCaptureVisibleArgs,
remotePaneCommandArgs,
remotePaneCwdArgs,
remoteSessionAgeArgs,
@@ -54,6 +55,13 @@ import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remot
import { probeAgentSockToPin } from './remote-ssh/agent-probe'
import { parsePaneCursor } from './pane-cursor'
import { classifyPaneCwd } from './pane-cwd'
+import {
+ localCaptureVisibleArgs,
+ parseVisibleCapture,
+ unavailableCapture,
+ visibleCaptureRoute,
+ type VisibleCapture
+} from './watch-link/capture-route'
import {
recordFreshSpawnOwner,
forgetPaneOwner,
@@ -4408,6 +4416,74 @@ export class PtyManager {
return this.captureSnapshot(key)
}
+ /**
+ * A live link's keyframe: the VISIBLE screen of a session, with the cursor and the alternate-screen
+ * flag read in the same tmux invocation — never history. Which backends get one, the exact target
+ * and the parse are `watch-link/capture-route.ts`. The session host (scrollback only), a direct
+ * Windows pane and a plain shell get `unavailableCapture()`, as does any failure — a dead
+ * ControlMaster, tmux's own "can't find session" for an exact-target miss.
+ */
+ async captureVisible(sessionId: string): Promise<VisibleCapture> {
+ const session = this.sessions.get(sessionId)
+ const key = session ? session.persistKey ?? session.indexKey : undefined
+ if (!session || !key) return unavailableCapture()
+ const route = visibleCaptureRoute(session, !!this.tmuxPath)
+ const target = sessionName(key)
+ try {
+ if (route === 'ssh' && session.sshRemote) {
+ // A remote node is captured on its HOST or not at all: never falls through to local tmux.
+ const ssh = findSsh()
+ if (!ssh) return unavailableCapture()
+ const { stdout } = await runAsync(
+ ssh,
+ remoteCaptureVisibleArgs(session.sshRemote.conn, session.sshRemote.controlPath, target),
+ { encoding: 'utf-8', maxBuffer: 8 * 1024 * 1024 }
+ )
+ return parseVisibleCapture(stdout)
+ }
+ if (route === 'tmux' && this.tmuxPath) {
+ const { stdout } = await runAsync(this.tmuxPath, localCaptureVisibleArgs(TMUX_SOCKET, target), {
+ encoding: 'utf-8',
+ maxBuffer: 8 * 1024 * 1024
+ })
+ return parseVisibleCapture(stdout)
+ }
+ } catch {
+ return unavailableCapture()
+ }
+ return unavailableCapture()
+ }
+
+ /**
+ * Join a node's RUNNING session as a live link's viewer: never spawns (`joinOnly`), never votes on
+ * the shared pty's size (`sizeVote: false`). Both are forced AFTER the caller's options, so nothing
+ * a caller passes can turn either off.
+ */
+ joinAsWatcher(
+ clientId: ClientId,
+ opts: {
+ persistKey: string
+ viewerId: string
+ cols: number
+ rows: number
+ sshRemote?: PtyCreateOptions['sshRemote']
+ requireRemote?: boolean
+ }
+ ): Promise<PtyCreateResult> {
+ return this.create(clientId, { ...opts, joinOnly: true, sizeVote: false })
+ }
+
+ /**
+ * The size a live link should report for a node: what its pty runs at now (the session host's
+ * authoritative size first, else the size pushed into the pty), or what it ran at when its last
+ * client was released. A copy; undefined when this process never ran the node.
+ */
+ watchSizeFor(persistKey: string): { cols: number; rows: number } | undefined {
+ const live = this.liveSessionForPersistKey(persistKey)
+ const size = live?.backendSize ?? live?.appliedSize ?? this.released.get(persistKey)?.size
+ return size ? { cols: size.cols, rows: size.rows } : undefined
+ }
+
/**
* Where the pane's cursor is, for a client about to PAINT a captured screen.
*
diff --git a/src/core/pty-watch-join.test.ts b/src/core/pty-watch-join.test.ts
new file mode 100644
index 000000000..f5769e9d1
--- /dev/null
+++ b/src/core/pty-watch-join.test.ts
@@ -0,0 +1,203 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import type { PtyCreateOptions, PtyCreateResult } from '../shared/types'
+
+/**
+ * A live link's viewer joins a node's RUNNING session: `joinAsWatcher` must never spawn one and never
+ * vote on its size, whatever the caller hands it, and `watchSizeFor` names the size the link reports.
+ * Harness copied from pty-join-only.test.ts (a mocked `node-pty` that records each spawn and each
+ * resize, so "spawned nothing" is `spawned.length === 0` and "kept its size" is "no resize pushed").
+ */
+
+interface FakePty {
+ args: string[]
+ onDataCb?: (d: string) => void
+ onExitCb?: (e: { exitCode: number }) => void
+ resizes: Array<{ cols: number; rows: number }>
+ killed: boolean
+}
+const spawned: FakePty[] = []
+
+vi.mock('./session-host-backend', async () =>
+ (await import('./__fixtures__/no-session-host')).noSessionHost()
+)
+
+vi.mock('node-pty', () => ({
+ spawn: (_file: string, args: string[], _opts: unknown) => {
+ const p: FakePty = { args: [...(args ?? [])], resizes: [], killed: false }
+ spawned.push(p)
+ return {
+ onData: (cb: (d: string) => void) => {
+ p.onDataCb = cb
+ },
+ onExit: (cb: (e: { exitCode: number }) => void) => {
+ p.onExitCb = cb
+ },
+ write: () => {},
+ resize: (cols: number, rows: number) => p.resizes.push({ cols, rows }),
+ pause: () => {},
+ resume: () => {},
+ kill: () => {
+ p.killed = true
+ },
+ pid: 1234
+ }
+ }
+}))
+
+vi.mock('./pty-devices', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('./pty-devices')>()),
+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })
+}))
+
+const OWNER = 1
+const WATCHER = 7
+const REFUSED: PtyCreateResult = { sessionId: '', fresh: false, unavailable: 'join-only' }
+
+let fake: FakePlatform
+
+beforeEach(() => {
+ spawned.length = 0
+ fake = fakePlatform()
+ initPlatform(fake)
+ vi.useFakeTimers()
+})
+afterEach(() => {
+ vi.useRealTimers()
+ resetPlatformForTests()
+})
+
+type ConfirmedProcessRun = (file: string, args: readonly string[], opts?: object) => Promise<unknown>
+
+async function manager(deps: { confirmedProcessRun?: ConfirmedProcessRun } = {}) {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager(deps)
+ m.registerIpc()
+ return m
+}
+
+/** `has-session` as tmux 3.4 resolves it: `=name` is exact, a bare name prefix-matches a miss. */
+function hasSession(live: string[], args: readonly string[]): boolean {
+ const target = args[args.indexOf('-t') + 1] ?? ''
+ if (target.startsWith('=')) return live.includes(target.slice(1))
+ return live.some((s) => s === target || s.startsWith(target))
+}
+
+/** A tmux-backed manager whose probes answer from `live` without touching a tmux socket. */
+async function tmuxManager(live: string[]) {
+ const confirmedProcessRun: ConfirmedProcessRun = async (_file, args) => {
+ if (hasSession(live, args)) return { stdout: '', stderr: '' }
+ throw Object.assign(new Error("can't find session"), { code: 1 })
+ }
+ const m = await manager({ confirmedProcessRun })
+ ;(m as unknown as { tmuxPath: string }).tmuxPath = '/usr/bin/tmux'
+ vi.spyOn(
+ m as unknown as { tmuxSessionExists: (k: string) => Promise<boolean> },
+ 'tmuxSessionExists'
+ ).mockImplementation(async (k: string) => hasSession(live, ['-t', `nt-${k}`]))
+ vi.spyOn(
+ m as unknown as { paneCwdStale: (k: string) => Promise<boolean> },
+ 'paneCwdStale'
+ ).mockResolvedValue(false)
+ return m
+}
+
+const create = (clientId: number, options: Partial<PtyCreateOptions>) =>
+ fake.handlers[IPC.ptyCreate](clientId, {
+ cols: 80,
+ rows: 24,
+ persistKey: 'n1',
+ ...options
+ }) as Promise<PtyCreateResult>
+const kill = (clientId: number, sessionId: string) =>
+ fake.senderListeners[IPC.ptyKill](clientId, sessionId)
+const WATCH = { persistKey: 'n1', viewerId: 'watch-s1', cols: 40, rows: 10 }
+
+describe('joinAsWatcher', () => {
+ it('never starts a session: no live session is a join-only refusal, and nothing spawns', async () => {
+ const m = await manager()
+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+ })
+
+ it('refuses when only a session whose name EXTENDS this node id is alive', async () => {
+ const m = await tmuxManager(['nt-n12'])
+ expect(await m.joinAsWatcher(WATCHER, WATCH)).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+ })
+
+ it("joins the owner's live session and never shrinks it", async () => {
+ const m = await manager()
+ const a = await create(OWNER, { cols: 120, rows: 40 })
+ const w = await m.joinAsWatcher(WATCHER, WATCH)
+ expect(w.sessionId).toBe(a.sessionId)
+ expect(w.fresh).toBe(false)
+ expect(w.unavailable).toBeUndefined()
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0].resizes).toEqual([])
+ // Still a subscriber: told the authoritative size to render.
+ const sizes = fake.sent.filter((s) => s.channel === IPC.ptySize(a.sessionId))
+ expect(sizes.map((s) => s.to)).toEqual([WATCHER])
+ expect(sizes[0].args[0]).toEqual({ cols: 120, rows: 40 })
+ })
+
+ it('warm-reattaches a running tmux session as a mirror (no -D), never creating one', async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const w = await m.joinAsWatcher(WATCHER, WATCH)
+ expect(w.unavailable).toBeUndefined()
+ expect(w.fresh).toBe(false)
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0].args).toContain('-A')
+ expect(spawned[0].args).not.toContain('-D')
+ })
+
+ it('the join-only, non-voting rules are FORCED — a caller cannot turn them off', async () => {
+ const m = await manager()
+ const smuggled = { ...WATCH, joinOnly: false, sizeVote: true } as never
+ expect(await m.joinAsWatcher(WATCHER, smuggled)).toEqual(REFUSED)
+ expect(spawned).toHaveLength(0)
+
+ await create(OWNER, { cols: 120, rows: 40 })
+ await m.joinAsWatcher(WATCHER, smuggled)
+ expect(spawned[0].resizes).toEqual([])
+ })
+})
+
+describe('watchSizeFor', () => {
+ it('is the size the live pty runs at, whatever the watcher reported', async () => {
+ const m = await manager()
+ await create(OWNER, { cols: 120, rows: 40 })
+ await m.joinAsWatcher(WATCHER, WATCH)
+ expect(m.watchSizeFor('n1')).toEqual({ cols: 120, rows: 40 })
+ })
+
+ it('follows the pty when the owner resizes it', async () => {
+ const m = await manager()
+ const { sessionId } = await create(OWNER, { cols: 120, rows: 40 })
+ fake.senderListeners[IPC.ptyResize](OWNER, sessionId, 100, 30)
+ expect(m.watchSizeFor('n1')).toEqual({ cols: 100, rows: 30 })
+ })
+
+ it('is the size the pty had when its last client was released', async () => {
+ const m = await tmuxManager(['nt-n1'])
+ const { sessionId } = await create(OWNER, { cols: 132, rows: 43 })
+ kill(OWNER, sessionId)
+ expect(spawned[0].killed).toBe(true)
+ expect(m.watchSizeFor('n1')).toEqual({ cols: 132, rows: 43 })
+ })
+
+ it('is undefined for a node this process never ran', async () => {
+ const m = await manager()
+ expect(m.watchSizeFor('n1')).toBeUndefined()
+ })
+
+ it('hands back a copy, not the live size record', async () => {
+ const m = await manager()
+ await create(OWNER, { cols: 120, rows: 40 })
+ const size = m.watchSizeFor('n1')!
+ size.cols = 1
+ expect(m.watchSizeFor('n1')).toEqual({ cols: 120, rows: 40 })
+ })
+})
diff --git a/src/core/remote-ssh/capture-visible.realsh.test.ts b/src/core/remote-ssh/capture-visible.realsh.test.ts
new file mode 100644
index 000000000..fe342cd7e
--- /dev/null
+++ b/src/core/remote-ssh/capture-visible.realsh.test.ts
@@ -0,0 +1,135 @@
+// The SSH visible capture, executed by a REAL /bin/sh — the remote shell is what reads this line.
+//
+// The command carries two things a remote shell would happily eat: tmux's command separator (a bare
+// `;` there ENDS the tmux command and runs `display-message` as a shell command of its own) and the
+// `#{…}` format (brace/`#` handling). Only execution proves they reach tmux verbatim, so:
+// 1. a stub `tmux` on PATH dumps its argv NUL-separated — the exact argv the remote tmux gets;
+// 2. a stub that delegates to the REAL tmux on a private socket proves the whole line end to end:
+// screen + cursor from one invocation, and an exact-target miss yields nothing.
+// Private socket in a private TMUX_TMPDIR; the delegating stub re-points `-L nodeterm-rmt` at it, so
+// the production socket name is never bound anywhere.
+import { describe, expect, it, beforeAll, afterAll } from 'vitest'
+import { execFileSync } from 'child_process'
+import fs from 'fs'
+import path from 'path'
+import { remoteCaptureVisibleArgs, RMT_TMUX_SOCKET } from './control-master'
+import { VISIBLE_CAPTURE_FORMAT, parseVisibleCapture } from '../watch-link/capture-route'
+import { testTmpDir } from '../test-tmp'
+import { makeTmuxTmpdir } from '../tmux-test-socket'
+
+const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }
+const SOCKET = `nt-wlrsh-${process.pid}`
+const REAL_TMUX = (() => {
+ if (process.platform === 'win32') return null
+ try {
+ return execFileSync('/bin/sh', ['-c', 'command -v tmux'], { encoding: 'utf8' }).trim() || null
+ } catch {
+ return null
+ }
+})()
+
+let recordDir: string
+let delegateDir: string
+let tmuxTmp = ''
+
+/** The last argv element of an `ssh …` argv IS the remote command line. */
+const remoteCommand = (sessionId: string): string => remoteCaptureVisibleArgs(conn, '/cm/p1', sessionId).at(-1)!
+
+function runUnder(binDir: string, line: string): { status: number; stdout: string; stderr: string } {
+ try {
+ const stdout = execFileSync('/bin/sh', ['-c', line], {
+ env: { PATH: `${binDir}:/usr/bin:/bin`, HOME: '/home/u', ...(tmuxTmp ? { TMUX_TMPDIR: tmuxTmp } : {}) },
+ encoding: 'utf8',
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+ return { status: 0, stdout, stderr: '' }
+ } catch (e) {
+ const err = e as { status?: number; stdout?: string; stderr?: string }
+ return { status: err.status ?? -1, stdout: String(err.stdout ?? ''), stderr: String(err.stderr ?? '') }
+ }
+}
+
+beforeAll(() => {
+ const root = testTmpDir('ntcvs-')
+ recordDir = path.join(root, 'record')
+ delegateDir = path.join(root, 'delegate')
+ fs.mkdirSync(recordDir)
+ fs.mkdirSync(delegateDir)
+ fs.writeFileSync(path.join(recordDir, 'tmux'), `#!/bin/sh\nfor a in "$@"; do printf '%s\\0' "$a"; done\n`, {
+ mode: 0o755
+ })
+ if (!REAL_TMUX) return
+ tmuxTmp = makeTmuxTmpdir('ntwr-', SOCKET)
+ // Re-point the production socket name at the private one, and refuse anything else: this stub
+ // must never forward a command that does not start `-L nodeterm-rmt`.
+ fs.writeFileSync(
+ path.join(delegateDir, 'tmux'),
+ `#!/bin/sh\n[ "$1" = "-L" ] && [ "$2" = "${RMT_TMUX_SOCKET}" ] || exit 99\nshift 2\nexec '${REAL_TMUX}' -L '${SOCKET}' "$@"\n`,
+ { mode: 0o755 }
+ )
+ execFileSync(REAL_TMUX, ['-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', 'nt-r-12', '-x', '30', '-y', '4', "printf 'REMOTE-12\\n'; sleep 60"], {
+ env: { ...process.env, TMUX_TMPDIR: tmuxTmp },
+ stdio: 'ignore'
+ })
+ for (let i = 0; i < 100; i++) {
+ const out = execFileSync(REAL_TMUX, ['-L', SOCKET, 'capture-pane', '-p', '-t', '=nt-r-12:'], {
+ env: { ...process.env, TMUX_TMPDIR: tmuxTmp },
+ encoding: 'utf8'
+ })
+ if (out.includes('REMOTE-12')) break
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20)
+ }
+})
+
+afterAll(() => {
+ if (!REAL_TMUX || !tmuxTmp) return
+ try {
+ execFileSync(REAL_TMUX, ['-L', SOCKET, 'kill-session', '-t', '=nt-r-12'], {
+ env: { ...process.env, TMUX_TMPDIR: tmuxTmp },
+ stdio: 'ignore'
+ })
+ } catch {
+ /* already gone */
+ }
+ fs.rmSync(tmuxTmp, { recursive: true, force: true })
+})
+
+describe('remoteCaptureVisibleArgs (real /bin/sh)', () => {
+ it('the separator and the format reach the remote tmux as their own argv elements', () => {
+ const { status, stdout } = runUnder(recordDir, remoteCommand('nt-abc'))
+ expect(status).toBe(0)
+ const argv = stdout.split('\0')
+ expect(argv.pop()).toBe('')
+ expect(argv).toEqual([
+ '-L',
+ RMT_TMUX_SOCKET,
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ '=nt-abc:',
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ '=nt-abc:',
+ VISIBLE_CAPTURE_FORMAT
+ ])
+ })
+
+ it.skipIf(!REAL_TMUX)('end to end through a real tmux: the screen, then the cursor, from one invocation', () => {
+ // Skipped without a tmux binary: the second half of the proof is tmux's own reply.
+ const { status, stdout } = runUnder(delegateDir, remoteCommand('nt-r-12'))
+ expect(status).toBe(0)
+ const got = parseVisibleCapture(stdout)
+ expect(got.screen).toContain('REMOTE-12')
+ expect(got.cursor).toEqual({ x: 0, y: 1 })
+ expect(got.altScreen).toBe(false)
+ })
+
+ it.skipIf(!REAL_TMUX)('an exact-target miss prints nothing and fails — never the longer-named session', () => {
+ const { status, stdout } = runUnder(delegateDir, remoteCommand('nt-r-1'))
+ expect(status).not.toBe(0)
+ expect(stdout).toBe('')
+ })
+})
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index 26d60026a..b6648808e 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -8,6 +8,7 @@ import {
remoteTmuxEnterArgs,
probeSaysAbsent,
remoteCapturePaneArgs,
+ remoteCaptureVisibleArgs,
remotePaneCommandArgs,
remotePaneCwdArgs,
remotePaneProcessArgs,
@@ -32,6 +33,7 @@ import {
remoteScpPath
} from './control-master'
import { remoteTmuxPathPrologue } from '../../shared/ssh'
+import { VISIBLE_CAPTURE_FORMAT } from '../watch-link/capture-route'
/** The PATH-append prologue every remote tmux line now starts with (issue #449). */
const TP = remoteTmuxPathPrologue()
@@ -259,6 +261,24 @@ describe('remoteCapturePaneArgs', () => {
})
})
+describe('remoteCaptureVisibleArgs', () => {
+ it('the visible capture never asks for history', () => {
+ const args = remoteCaptureVisibleArgs({ host: 'h', user: 'u' } as never, '/tmp/cp', 'nt-abc')
+ const cmd = args.join(' ')
+ expect(cmd).toContain("capture-pane -p -e -t '=nt-abc:'")
+ expect(cmd).not.toMatch(/-S\b/)
+ })
+
+ it('captures and reads the cursor in ONE remote tmux invocation, exact targets on both', () => {
+ const args = remoteCaptureVisibleArgs(conn, '/s.sock', 'nt-x')
+ expect(args.slice(0, childPrefix.length)).toEqual(childPrefix)
+ expect(args[args.length - 1]).toBe(
+ `${TP}tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t '=nt-x:' ';' ` +
+ `display-message -p -t '=nt-x:' '${VISIBLE_CAPTURE_FORMAT}'`
+ )
+ })
+})
+
describe('remotePaneCommandArgs', () => {
it('asks the remote tmux for the pane_current_command of the session', () => {
const args = remotePaneCommandArgs(conn, '/s.sock', 'nt-x')
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index d1ca58041..5bd3daad4 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -20,6 +20,7 @@ import {
import { sanitizePasteText } from '../paste-injection'
import { canControlCanvas } from '../../shared/agents/config'
import { COMBINED_PANE_MARKER, PANE_OWNER_FMT, PS_FOREGROUND_FLAGS } from '../agents/pane-owner'
+import { VISIBLE_CAPTURE_FORMAT, exactPaneTarget } from '../watch-link/capture-route'
// Dependency-free (no node-pty): safe to import from these pure builders.
/** Dedicated remote tmux socket so an SSH project never collides with the user's own tmux. */
@@ -518,6 +519,25 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,
tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S ${full ? '-' : '-200'}`)
)
}
+/**
+ * The VISIBLE screen of a remote session, with SGR, and nothing above it — a live link's keyframe
+ * must never carry history, and `remoteCapturePaneArgs` always adds `-S`. The cursor line rides the
+ * SAME tmux invocation (see `watch-link/capture-route.ts` for why, and for the measured exact-target
+ * spelling). Every piece that the REMOTE shell would otherwise read is single-quoted: tmux's `;`
+ * separator (bare, it would end the tmux command and run `display-message` as a shell command), the
+ * `=name:` target and the `#{…}` format. Proven under a real /bin/sh in capture-visible.realsh.test.ts.
+ */
+export function remoteCaptureVisibleArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
+ const target = posixQuote(exactPaneTarget(sessionId))
+ return childArgs(
+ conn,
+ controlPath,
+ tmuxCmd(
+ `tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${target} ';' ` +
+ `display-message -p -t ${target} ${posixQuote(VISIBLE_CAPTURE_FORMAT)}`
+ )
+ )
+}
/**
* Ask the REMOTE tmux when a node's session was created, AND what the host's clock says now — in
* one round trip, because the caller wants an AGE and the two clocks are not the same clock.
diff --git a/src/core/watch-link/capture-route.realtmux.test.ts b/src/core/watch-link/capture-route.realtmux.test.ts
new file mode 100644
index 000000000..799779aff
--- /dev/null
+++ b/src/core/watch-link/capture-route.realtmux.test.ts
@@ -0,0 +1,134 @@
+// A LIVE LINK'S KEYFRAME, CAPTURED FROM A REAL TMUX (R10 + R17).
+//
+// What is measured here is a property of tmux, not of our code, so it cannot be unit-tested:
+// - the one invocation `capture-pane … ; display-message …` really does print the visible screen
+// and THEN the cursor line, and only the visible rows (never the history above them);
+// - the target spelling is EXACT. Node ids end in a counter, so `nt-x-1` is a prefix of `nt-x-12`,
+// and tmux falls back to prefix matching on a miss: a bare target would capture ANOTHER node's
+// screen and send it to this link's viewers. `=name:` is the spelling that is exact AND resolves
+// for a target-pane (measured on tmux 3.4: `=name` alone is "can't find pane").
+//
+// Private socket in a private TMUX_TMPDIR (`makeTmuxTmpdir`), never `node-terminal`/`nodeterm-rmt`;
+// each session is killed by exact target.
+import { describe, it, expect, beforeAll, afterAll } from 'vitest'
+import { execFileSync } from 'child_process'
+import fs from 'fs'
+import {
+ localCaptureVisibleArgs,
+ parseVisibleCapture,
+ unavailableCapture,
+ type VisibleCapture
+} from './capture-route'
+import { makeTmuxTmpdir } from '../tmux-test-socket'
+
+const SOCKET = `nt-wlcap-${process.pid}`
+const HAS_TMUX = (() => {
+ if (process.platform === 'win32') return false
+ try {
+ execFileSync('tmux', ['-V'], { stdio: 'ignore' })
+ return true
+ } catch {
+ return false
+ }
+})()
+// Skipped where there is no tmux binary (Windows, a bare CI image): the measurement is of tmux.
+const itTmux = it.skipIf(!HAS_TMUX)
+
+let tmp = ''
+const sessions: string[] = []
+
+function tmux(args: string[]): string {
+ return execFileSync('tmux', args, {
+ env: { ...process.env, TMUX_TMPDIR: tmp },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ encoding: 'utf8'
+ })
+}
+
+/** Exactly what `PtyManager.captureVisible` does with the argv: parse on success, unavailable on
+ * any failure (tmux's non-zero exit included). */
+function captureVisible(sessionName: string): VisibleCapture {
+ try {
+ return parseVisibleCapture(tmux(localCaptureVisibleArgs(SOCKET, sessionName)))
+ } catch {
+ return unavailableCapture()
+ }
+}
+
+function sleepMs(ms: number): void {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
+}
+
+/** Start a session running `script`, and wait until its screen shows `ready`. */
+function start(name: string, script: string, ready: string, cols = 30, rows = 4): void {
+ // `-f /dev/null` on the call that boots the private server: a contributor's ~/.tmux.conf must not
+ // join the measurement.
+ tmux(['-L', SOCKET, '-f', '/dev/null', 'new-session', '-d', '-s', name, '-x', String(cols), '-y', String(rows), script])
+ sessions.push(name)
+ for (let i = 0; i < 100; i++) {
+ // Polled with the literal spelling, not `exactPaneTarget`: a broken target must fail the test
+ // that is about it, not this setup.
+ if (tmux(['-L', SOCKET, 'capture-pane', '-p', '-t', `=${name}:`]).includes(ready)) return
+ sleepMs(20)
+ }
+ throw new Error(`session ${name} never printed ${ready}`)
+}
+
+beforeAll(() => {
+ if (!HAS_TMUX) return
+ tmp = makeTmuxTmpdir('ntwl-', SOCKET)
+ start('nt-x-12', "printf 'SCREEN-OF-12\\n'; sleep 60", 'SCREEN-OF-12')
+ start('nt-hist', 'for i in 1 2 3 4 5 6 7 8 9 10; do echo L$i; done; sleep 60', 'L10')
+ start('nt-alt', "printf 'MAIN\\n'; printf '\\033[?1049h\\033[2;3HALT'; sleep 60", 'ALT')
+})
+
+afterAll(() => {
+ if (!HAS_TMUX) return
+ for (const name of sessions) {
+ try {
+ tmux(['-L', SOCKET, 'kill-session', '-t', `=${name}`])
+ } catch {
+ /* already gone */
+ }
+ }
+ fs.rmSync(tmp, { recursive: true, force: true })
+})
+
+describe('visible capture against a real tmux', () => {
+ itTmux('the trap is real on this tmux: a BARE target captures the longer-named session', () => {
+ // The control for the next test. If tmux ever stops prefix-matching, this goes red and says so,
+ // rather than the exact-target test passing for a reason that no longer holds.
+ expect(tmux(['-L', SOCKET, 'capture-pane', '-p', '-t', 'nt-x-1'])).toContain('SCREEN-OF-12')
+ })
+
+ itTmux('capturing nt-x-1 while only nt-x-12 is alive is UNAVAILABLE, never 12’s screen', () => {
+ const got = captureVisible('nt-x-1')
+ expect(got).toEqual(unavailableCapture())
+ expect(got.screen).not.toContain('SCREEN-OF-12')
+ })
+
+ itTmux('the exact target captures its own session, with the cursor from the same invocation', () => {
+ const got = captureVisible('nt-x-12')
+ expect(got.screen).toContain('SCREEN-OF-12')
+ expect(got.cursor).toEqual({ x: 0, y: 1 })
+ expect(got.altScreen).toBe(false)
+ // The cursor line is not left in the screen.
+ expect(got.screen).not.toMatch(/\d+ \d+ [01]\n?$/)
+ })
+
+ itTmux('only the visible rows — the history above them is never in the keyframe', () => {
+ const got = captureVisible('nt-hist')
+ expect(got.screen).toContain('L10')
+ expect(got.screen).not.toMatch(/^L1$/m)
+ expect(got.screen).not.toContain('L6')
+ expect(got.screen.split('\n').filter(Boolean)).toEqual(['L8', 'L9', 'L10'])
+ })
+
+ itTmux('reads the alternate screen and its flag', () => {
+ const got = captureVisible('nt-alt')
+ expect(got.screen).toContain('ALT')
+ expect(got.screen).not.toContain('MAIN')
+ expect(got.altScreen).toBe(true)
+ expect(got.cursor).toEqual({ x: 5, y: 1 })
+ })
+})
diff --git a/src/core/watch-link/capture-route.test.ts b/src/core/watch-link/capture-route.test.ts
new file mode 100644
index 000000000..2c710eea7
--- /dev/null
+++ b/src/core/watch-link/capture-route.test.ts
@@ -0,0 +1,142 @@
+import { describe, it, expect } from 'vitest'
+import {
+ VISIBLE_CAPTURE_FORMAT,
+ exactPaneTarget,
+ localCaptureVisibleArgs,
+ parseVisibleCapture,
+ unavailableCapture,
+ visibleCaptureRoute
+} from './capture-route'
+
+describe('visibleCaptureRoute', () => {
+ it('never routes to a capture that returns history', () => {
+ expect(visibleCaptureRoute({ sessionHost: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ nativeWindowsPane: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ sshRemote: {} }, true)).toBe('ssh')
+ expect(visibleCaptureRoute({ tmuxBacked: true }, true)).toBe('tmux')
+ expect(visibleCaptureRoute({ tmuxBacked: true }, false)).toBe('none')
+ expect(visibleCaptureRoute({ tmuxBacked: false }, true)).toBe('none')
+ })
+
+ it('a session-host session is none even when it is also marked tmux-backed or remote', () => {
+ // The session host's only capture is ~200 lines of scrollback; nothing may route around that.
+ expect(visibleCaptureRoute({ sessionHost: true, tmuxBacked: true }, true)).toBe('none')
+ expect(visibleCaptureRoute({ sessionHost: true, sshRemote: {} }, true)).toBe('none')
+ expect(visibleCaptureRoute({ nativeWindowsPane: {}, tmuxBacked: true }, true)).toBe('none')
+ })
+})
+
+describe('exactPaneTarget', () => {
+ it('is the exact-session, active-pane spelling measured on tmux 3.4', () => {
+ // `=name` alone is "can't find pane" for capture-pane (and silently EMPTY for display-message);
+ // a bare `name` prefix-matches another node's session. Only `=name:` is exact AND resolves.
+ expect(exactPaneTarget('nt-abc')).toBe('=nt-abc:')
+ })
+})
+
+describe('localCaptureVisibleArgs', () => {
+ const args = localCaptureVisibleArgs('sock', 'nt-abc')
+
+ it('captures the visible screen with SGR and asks for the cursor in the SAME invocation', () => {
+ expect(args).toEqual([
+ '-L',
+ 'sock',
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ '=nt-abc:',
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ '=nt-abc:',
+ VISIBLE_CAPTURE_FORMAT
+ ])
+ })
+
+ it('never asks for history', () => {
+ expect(args).not.toContain('-S')
+ expect(args).not.toContain('-a')
+ })
+
+ it('targets EXACTLY — never a bare name tmux would prefix-match', () => {
+ expect(args.filter((a) => a.includes('nt-abc'))).toEqual(['=nt-abc:', '=nt-abc:'])
+ })
+
+ it('asks for the cursor and the alternate-screen flag', () => {
+ expect(VISIBLE_CAPTURE_FORMAT).toBe('#{cursor_x} #{cursor_y} #{alternate_on}')
+ })
+})
+
+describe('parseVisibleCapture', () => {
+ it('splits the trailing cursor line off a real tmux 3.4 reply', () => {
+ // Measured: a 20x4 pane after 10 lines of output — only the visible rows, then the cursor line.
+ expect(parseVisibleCapture('L8\nL9\nL10\n\n0 3 0\n')).toEqual({
+ screen: 'L8\nL9\nL10\n\n',
+ cursor: { x: 0, y: 3 },
+ altScreen: false
+ })
+ })
+
+ it('reads the alternate-screen flag', () => {
+ expect(parseVisibleCapture('\n ALT\n\n\n5 1 1\n')).toEqual({
+ screen: '\n ALT\n\n\n',
+ cursor: { x: 5, y: 1 },
+ altScreen: true
+ })
+ })
+
+ it('keeps the screen byte-identical to what capture-pane printed on its own', () => {
+ const screen = '\u001b[1mbold\u001b[0m\nplain\n'
+ expect(parseVisibleCapture(`${screen}12 1 0\n`).screen).toBe(screen)
+ })
+
+ it('an empty screen is an empty string, not the cursor line', () => {
+ expect(parseVisibleCapture('0 0 0\n')).toEqual({
+ screen: '',
+ cursor: { x: 0, y: 0 },
+ altScreen: false
+ })
+ })
+
+ it('a screen whose own last line looks like a cursor line keeps that line', () => {
+ // Only the LAST line is the cursor; a numeric-ish row above it is screen text.
+ expect(parseVisibleCapture('10 20 1\n3 4 0\n')).toEqual({
+ screen: '10 20 1\n',
+ cursor: { x: 3, y: 4 },
+ altScreen: false
+ })
+ })
+
+ it('reads CRLF line endings', () => {
+ expect(parseVisibleCapture('a\r\nb\r\n7 1 1\r\n')).toEqual({
+ screen: 'a\r\nb\r\n',
+ cursor: { x: 7, y: 1 },
+ altScreen: true
+ })
+ })
+
+ it('without a cursor line the whole output is the screen and the cursor is unknown', () => {
+ for (const out of ['a\nb\n', 'a\nb', 'a\n3 4 5\n', 'a\n3 4\n', 'a\nx 1 0\n', 'a\n \n', '']) {
+ expect(parseVisibleCapture(out)).toEqual({ screen: out, cursor: null, altScreen: null })
+ }
+ })
+
+ it('does not accept a padded or signed cursor line', () => {
+ for (const line of [' 1 2 0', '1 2 0 ', '-1 2 0', '1 2 0', '1\t2\t0']) {
+ const out = `s\n${line}\n`
+ expect(parseVisibleCapture(out)).toEqual({ screen: out, cursor: null, altScreen: null })
+ }
+ })
+})
+
+describe('unavailableCapture', () => {
+ it('is an empty screen with nothing known', () => {
+ expect(unavailableCapture()).toEqual({ screen: '', cursor: null, altScreen: null })
+ })
+
+ it('is a fresh object each time (a caller may mutate what it was handed)', () => {
+ expect(unavailableCapture()).not.toBe(unavailableCapture())
+ })
+})
diff --git a/src/core/watch-link/capture-route.ts b/src/core/watch-link/capture-route.ts
new file mode 100644
index 000000000..916dcdf7e
--- /dev/null
+++ b/src/core/watch-link/capture-route.ts
@@ -0,0 +1,102 @@
+// A live link's KEYFRAME: the visible screen of a node's session, never the history above it.
+//
+// Pure: no tmux, no ssh, no PtyManager. `PtyManager.captureVisible` runs the argv built here (locally,
+// or over the ControlMaster through `remoteCaptureVisibleArgs`) and parses the reply here.
+//
+// Which backend gets one (`visibleCaptureRoute`): the session host's capture is ~200 lines of
+// scrollback and a direct Windows pane has no visible-only read, so both get NO keyframe (the viewer
+// starts from the live stream) rather than history. A plain shell has no tmux to ask.
+//
+// The screen, the cursor and the alternate-screen flag are read in ONE tmux invocation
+// (`capture-pane … ; display-message …`), so all three describe the same instant: a cursor read in a
+// second round trip could describe a screen that has since scrolled.
+//
+// The target is EXACT (`exactPaneTarget`). Node ids end in a counter, so `nt-x-1` is a prefix of
+// `nt-x-12`, and tmux resolves a bare target by fnmatch then PREFIX on a miss: a bare target would
+// capture ANOTHER node's screen and send it to this link's viewers. Measured on tmux 3.4, with only
+// `nt-x-12` alive:
+// capture-pane -t nt-x-1 → 12's screen, exit 0 (the trap)
+// capture-pane -t =nt-x-1 → "can't find pane", exit 1 (also for =nt-x-12: `=name` alone never
+// resolves a target-PANE)
+// capture-pane -t =nt-x-1: → "can't find session", exit 1
+// capture-pane -t =nt-x-12: → 12's screen, exit 0 (exact AND resolves)
+// display-message -t =nt-x-1: → exit 0, every format EMPTY
+// and the combined `capture-pane -t =nt-x-1: ; display-message …` stops at the failed capture: exit 1,
+// nothing on stdout. So an exact miss is a failed command, which the caller reads as unavailable.
+
+export interface VisibleCapture {
+ /** The visible screen with SGR, byte-identical to what `capture-pane -p -e` prints on its own
+ * (one `\n`-terminated line per row); '' when there is none. Never history. */
+ screen: string
+ /** The pane's cursor at capture time, 0-based (`#{cursor_x}`, `#{cursor_y}`); null when unread. */
+ cursor: { x: number; y: number } | null
+ /** Whether the pane's application is on the alternate screen (`#{alternate_on}`); null when unread. */
+ altScreen: boolean | null
+}
+
+/** A session with no visible-only capture, or one that failed: an empty screen, nothing known. */
+export function unavailableCapture(): VisibleCapture {
+ return { screen: '', cursor: null, altScreen: null }
+}
+
+export function visibleCaptureRoute(
+ s: { sessionHost?: unknown; nativeWindowsPane?: unknown; sshRemote?: unknown; tmuxBacked?: boolean },
+ tmuxAvailable: boolean
+): 'none' | 'ssh' | 'tmux' {
+ if (s.sessionHost || s.nativeWindowsPane) return 'none'
+ if (s.sshRemote) return 'ssh'
+ return tmuxAvailable && s.tmuxBacked ? 'tmux' : 'none'
+}
+
+/** The tmux format read beside the screen: cursor column, cursor row, alternate screen (0/1). */
+export const VISIBLE_CAPTURE_FORMAT = '#{cursor_x} #{cursor_y} #{alternate_on}'
+
+/** "Exactly this session, its active pane" — the only spelling that is exact AND resolves for a
+ * target-pane command (see the measurement at the top of this file). */
+export function exactPaneTarget(sessionName: string): string {
+ return `=${sessionName}:`
+}
+
+/**
+ * The local tmux argv (after the binary): visible screen with SGR, then the cursor line, in one
+ * invocation. The `;` is tmux's own command separator, passed as its own argv element (no shell).
+ * No `-S`: capture-pane without it starts at the first VISIBLE row.
+ */
+export function localCaptureVisibleArgs(socket: string, sessionName: string): string[] {
+ const target = exactPaneTarget(sessionName)
+ return [
+ '-L',
+ socket,
+ 'capture-pane',
+ '-p',
+ '-e',
+ '-t',
+ target,
+ ';',
+ 'display-message',
+ '-p',
+ '-t',
+ target,
+ VISIBLE_CAPTURE_FORMAT
+ ]
+}
+
+const CURSOR_LINE = /^(\d+) (\d+) ([01])$/
+
+/**
+ * Split the combined reply: the LAST line is the cursor line when it has exactly the format's shape,
+ * and everything before it is the screen. Anything else (no such line, an older tmux that printed
+ * something different) leaves the whole output as the screen and the cursor unknown.
+ */
+export function parseVisibleCapture(stdout: string): VisibleCapture {
+ const body = stdout.replace(/\r?\n$/, '')
+ const cut = body.lastIndexOf('\n')
+ const last = cut === -1 ? body : body.slice(cut + 1)
+ const m = CURSOR_LINE.exec(last)
+ if (!m) return { screen: stdout, cursor: null, altScreen: null }
+ return {
+ screen: cut === -1 ? '' : body.slice(0, cut + 1),
+ cursor: { x: Number(m[1]), y: Number(m[2]) },
+ altScreen: m[3] === '1'
+ }
+}