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(windows): session-host client speaks watch-attach and the new reads

reviewe6a5365de689
diff --git a/src/core/__fixtures__/no-session-host.ts b/src/core/__fixtures__/no-session-host.ts
index 7f8dc8556..b9b80ea66 100644
--- a/src/core/__fixtures__/no-session-host.ts
+++ b/src/core/__fixtures__/no-session-host.ts
@@ -48,6 +48,10 @@ export function noSessionHost(): Record<string, unknown> {
sessionHostKillSession: async () => {},
sessionHostListSessions: async () => [],
sessionHostPaneCommand: async () => null,
- sessionHostSendKeys: async () => false
+ sessionHostSendKeys: async () => false,
+ sessionHostCaptureVisible: async () => null,
+ sessionHostPaneCwd: async () => null,
+ sessionHostSupportsWatch: async () => false,
+ sessionHostWatchKnown: () => undefined
}
}
diff --git a/src/core/session-host-backend.ts b/src/core/session-host-backend.ts
index 821497f6a..639b0d195 100644
--- a/src/core/session-host-backend.ts
+++ b/src/core/session-host-backend.ts
@@ -11,12 +11,17 @@ import { platform } from './platform'
import {
SessionHostClient,
SessionHostProtocolCompatibilityError,
+ SessionHostWatchUnsupportedError,
type HostShutdownOutcome,
type HostUpdateInspection
} from './session-host-client'
import { SessionHostPty } from './session-host-pty'
import { ensureStagedHostRuntime } from './session-host-runtime'
-import type { ExecuteLaunchResult, SessionHostSpawnOptions } from '../session-host/protocol'
+import type {
+ CaptureVisibleResult,
+ ExecuteLaunchResult,
+ SessionHostSpawnOptions
+} from '../session-host/protocol'
import type { PreparedAgentLaunch } from './agent-launch'
import type { PaneOwner } from '../shared/agents/pane-owner-predicate'
@@ -111,6 +116,36 @@ export function attachExistingSessionHostPty(name: string): SessionHostPty {
return new SessionHostPty(getClient(), name, null, 0)
}
+/** A live link / relay viewer's READ-ONLY attachment to an already-running session: never spawns,
+ * casts no size claim, takes no pause ticket, cannot type. `ready` rejects with
+ * `SessionHostWatchUnsupportedError` when the running host predates the `watch-attach` feature. */
+export function watchExistingSessionHostPty(name: string): SessionHostPty {
+ return new SessionHostPty(getClient(), name, null, 0, 'watch')
+}
+
+/** Does the running host speak `watch-attach`? Connects to ask (only called where the session-host
+ * backend is already the selected one). */
+export async function sessionHostSupportsWatch(): Promise<boolean> {
+ return getClient().supportsFeature('watch-attach')
+}
+
+/** The same answer WITHOUT connecting — undefined while this process has no connection (nothing
+ * session-host-backed has been opened yet). Synchronous, for `tmuxStatus`. */
+export function sessionHostWatchKnown(): boolean | undefined {
+ return client?.connectedFeature('watch-attach')
+}
+
+/** A live link's keyframe: the visible screen, cursor and active buffer. Null = no capture (an
+ * older host, a gone session, any failure) — never history in its place. */
+export async function sessionHostCaptureVisible(name: string): Promise<CaptureVisibleResult | null> {
+ return getClient().captureVisible(name)
+}
+
+/** `#{pane_current_path}`'s equivalent: the cwd the pane last REPORTED (OSC 7 / 9;9 / 633), or null. */
+export async function sessionHostPaneCwd(name: string): Promise<string | null> {
+ return getClient().paneCwd(name)
+}
+
/** Background write — works whether or not this process currently has a live client for `name`,
* exactly like `sendText`'s tmux `send-keys -t <name>` needs no attached client. */
export async function sessionHostSendKeys(name: string, text: string, enter: boolean): Promise<TextDeliveryResult> {
@@ -155,7 +190,7 @@ export async function sessionHostKillSession(
return getClient().killSession(name, options)
}
-export { SessionHostProtocolCompatibilityError }
+export { SessionHostProtocolCompatibilityError, SessionHostWatchUnsupportedError }
/** `tmux has-session`'s equivalent — currently unused by the create path (which gets `fresh`
* straight from the real attach-or-create round trip instead, via `SessionHostPty.ready`) but
diff --git a/src/core/session-host-client-live-links.test.ts b/src/core/session-host-client-live-links.test.ts
new file mode 100644
index 000000000..27a0f1385
--- /dev/null
+++ b/src/core/session-host-client-live-links.test.ts
@@ -0,0 +1,277 @@
+// Live links on the session host, client side: a watcher's attachment (`watch-attach`) carries no
+// size claim, no pause ticket and no input; the client up/downgrades its one connection's attachment
+// as voting subscribers come and go; and the two negotiated reads (`captureVisible`, `paneCwd`) are
+// never sent to a host that did not advertise them. Real client, fake host, real socket.
+import fs from 'fs'
+import net from 'net'
+import os from 'os'
+import path from 'path'
+import { afterEach, describe, expect, it } from 'vitest'
+import { sessionHostPaths } from '../session-host/paths'
+import {
+ SESSION_HOST_PROTOCOL_VERSION,
+ LineFramer,
+ encodeFrame,
+ type SessionHostRequest,
+ type SessionHostSpawnOptions
+} from '../session-host/protocol'
+import { SessionHostClient } from './session-host-client'
+import { SessionHostPty } from './session-host-pty'
+
+const openServers = new Set<net.Server>()
+const openSockets = new Set<net.Socket>()
+const tempDirs = new Set<string>()
+const livePtys = new Set<SessionHostPty>()
+const GENERATION = 'watch-generation-1'
+
+function within<T>(promise: Promise<T>, label: string, ms = 2_500): Promise<T> {
+ return new Promise<T>((resolve, reject) => {
+ const timer = setTimeout(() => reject(new Error(`${label} did not finish within ${ms}ms`)), ms)
+ promise.then(
+ (value) => {
+ clearTimeout(timer)
+ resolve(value)
+ },
+ (error) => {
+ clearTimeout(timer)
+ reject(error)
+ }
+ )
+ })
+}
+
+/** Resolves once `check` holds, polled on the event loop. */
+async function until(check: () => boolean, label: string): Promise<void> {
+ const deadline = Date.now() + 2_500
+ while (!check()) {
+ if (Date.now() > deadline) throw new Error(`${label} never happened`)
+ await new Promise((resolve) => setTimeout(resolve, 5))
+ }
+}
+
+function fixture(prefix: string): { userDataDir: string; endpoint: string } {
+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))
+ tempDirs.add(userDataDir)
+ const paths = sessionHostPaths(userDataDir)
+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))
+ fs.writeFileSync(
+ paths.statePath,
+ JSON.stringify({
+ pid: process.pid,
+ endpoint: paths.endpoint,
+ tokenPath: paths.tokenPath,
+ startedAt: Date.now(),
+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION
+ })
+ )
+ return { userDataDir, endpoint: paths.endpoint }
+}
+
+function spawnOptions(userDataDir: string, cols: number, rows: number): SessionHostSpawnOptions {
+ return { cwd: userDataDir, shell: process.execPath, args: [], env: {}, cols, rows }
+}
+
+
+type FakeHost = {
+ requests: SessionHostRequest[]
+ push(frame: unknown): void
+}
+
+async function fakeHost(endpoint: string, features: string[]): Promise<FakeHost> {
+ const sockets = new Set<net.Socket>()
+ const host: FakeHost = {
+ requests: [],
+ push: (frame) => {
+ for (const socket of sockets) socket.write(encodeFrame(frame))
+ }
+ }
+ const server = net.createServer((socket) => {
+ sockets.add(socket)
+ openSockets.add(socket)
+ socket.once('close', () => {
+ sockets.delete(socket)
+ openSockets.delete(socket)
+ })
+ const framer = new LineFramer()
+ socket.on('data', (chunk: Buffer) => {
+ for (const request of framer.push<SessionHostRequest>(chunk.toString('utf8'))) {
+ host.requests.push(request)
+ const reply = (result?: unknown): void => {
+ socket.write(encodeFrame({ id: request.id, ok: true, result }))
+ }
+ switch (request.cmd) {
+ case 'hello':
+ reply({ protocolVersion: SESSION_HOST_PROTOCOL_VERSION, features })
+ break
+ case 'attach':
+ case 'attachExisting':
+ reply({ fresh: request.cmd === 'attach', generation: GENERATION, screen: 'SCREEN' })
+ break
+ case 'hasSession':
+ reply({ exists: true, generation: GENERATION })
+ break
+ case 'captureVisible':
+ reply({ screen: 'row\n', cursor: { x: 3, y: 0 }, altScreen: true })
+ break
+ case 'paneCwd':
+ reply({ cwd: 'C:\\work' })
+ break
+ default:
+ reply()
+ }
+ }
+ })
+ })
+ openServers.add(server)
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(endpoint, resolve)
+ })
+ return host
+}
+
+afterEach(async () => {
+ for (const pty of livePtys) pty.destroy()
+ livePtys.clear()
+ await new Promise((resolve) => setImmediate(resolve))
+ for (const socket of openSockets) socket.destroy()
+ openSockets.clear()
+ await Promise.all(
+ [...openServers].map(
+ (server) =>
+ new Promise<void>((resolve) => {
+ if (!server.listening) return resolve()
+ server.close(() => resolve())
+ })
+ )
+ )
+ openServers.clear()
+ for (const dir of tempDirs) fs.rmSync(dir, { recursive: true, force: true })
+ tempDirs.clear()
+})
+
+const ALL = ['geometry', 'watch-attach', 'captureVisible', 'paneCwd']
+const NAME = 'nt-watched'
+
+function track(pty: SessionHostPty): SessionHostPty {
+ livePtys.add(pty)
+ return pty
+}
+function attaches(host: FakeHost): Array<Record<string, unknown>> {
+ return host.requests
+ .filter((r) => r.cmd === 'attachExisting' || r.cmd === 'attach')
+ .map((r) => {
+ const { id: _id, ...rest } = r as Record<string, unknown>
+ return rest
+ })
+}
+
+describe('SessionHostClient watch-attach', () => {
+ it('attaches a lone watcher WITHOUT a claim, and never sends its writes, resizes or pauses', async () => {
+ const { userDataDir, endpoint } = fixture('nt-watch-alone-')
+ const host = await fakeHost(endpoint, ALL)
+ const client = new SessionHostClient({ userDataDir })
+ const watcher = track(new SessionHostPty(client, NAME, null, 0, 'watch'))
+ await expect(within(watcher.ready, 'watch attach')).resolves.toMatchObject({ fresh: false })
+ expect(attaches(host)).toEqual([
+ { cmd: 'attachExisting', name: NAME, expectedGeneration: undefined, watch: true }
+ ])
+ watcher.write('typed')
+ watcher.resize(10, 5)
+ watcher.pause()
+ // Anything queued would ride behind this round trip.
+ await client.listSessions().catch(() => [])
+ expect(host.requests.map((r) => r.cmd)).not.toContain('write')
+ expect(host.requests.map((r) => r.cmd)).not.toContain('resize')
+ expect(host.requests.map((r) => r.cmd)).not.toContain('pause')
+ })
+
+ it('refuses a watcher outright on a host without the feature — no attach, no size vote', async () => {
+ const { userDataDir, endpoint } = fixture('nt-watch-old-')
+ const host = await fakeHost(endpoint, ['geometry'])
+ const client = new SessionHostClient({ userDataDir })
+ const watcher = track(new SessionHostPty(client, NAME, null, 0, 'watch'))
+ await expect(within(watcher.ready, 'refused watch')).rejects.toThrow(/does not support read-only watch/)
+ expect(attaches(host)).toEqual([])
+ })
+
+ it('upgrades for an owner who joins and downgrades again when the owner leaves', async () => {
+ const { userDataDir, endpoint } = fixture('nt-watch-up-')
+ const host = await fakeHost(endpoint, ALL)
+ const client = new SessionHostClient({ userDataDir })
+ const watcher = track(new SessionHostPty(client, NAME, null, 0, 'watch'))
+ await within(watcher.ready, 'watch attach')
+ const owner = track(
+ new SessionHostPty(
+ client,
+ NAME,
+ spawnOptions(userDataDir, 100, 30),
+ 100
+ )
+ )
+ await within(owner.ready, 'owner attach')
+ // The owner joins an attached state: a claim-carrying warm attach upgrades the connection.
+ expect(attaches(host).at(-1)).toMatchObject({ cmd: 'attachExisting', cols: 100, rows: 30 })
+ expect(attaches(host).at(-1)).not.toHaveProperty('watch')
+ owner.write('ls')
+ await until(() => host.requests.some((r) => r.cmd === 'write'), 'the owner typing')
+
+ owner.destroy()
+ await until(() => attaches(host).length === 3, 'the downgrade')
+ expect(attaches(host).at(-1)).toEqual({
+ cmd: 'attachExisting',
+ name: NAME,
+ expectedGeneration: GENERATION,
+ watch: true
+ })
+ // A detach would have ended the watcher's subscription too: never sent while it remains.
+ expect(host.requests.map((r) => r.cmd)).not.toContain('detach')
+ watcher.destroy()
+ await until(() => host.requests.some((r) => r.cmd === 'detach'), 'the last subscriber detaching')
+ })
+
+ it('a watcher joining an owner rides the owner claim and casts none of its own', async () => {
+ const { userDataDir, endpoint } = fixture('nt-watch-co-')
+ const host = await fakeHost(endpoint, ALL)
+ const client = new SessionHostClient({ userDataDir })
+ const owner = track(
+ new SessionHostPty(
+ client,
+ NAME,
+ spawnOptions(userDataDir, 120, 40),
+ 100
+ )
+ )
+ await within(owner.ready, 'owner attach')
+ const watcher = track(new SessionHostPty(client, NAME, null, 0, 'watch'))
+ await within(watcher.ready, 'watcher joins')
+ expect(attaches(host).at(-1)).toMatchObject({ cmd: 'attachExisting', cols: 120, rows: 40 })
+ // The watcher's own "size" never moves the pty.
+ watcher.resize(20, 10)
+ await client.listSessions().catch(() => [])
+ expect(host.requests.map((r) => r.cmd)).not.toContain('resize')
+ })
+})
+
+describe('SessionHostClient negotiated reads', () => {
+ it('returns the host answers when the feature was negotiated', async () => {
+ const { userDataDir, endpoint } = fixture('nt-reads-on-')
+ await fakeHost(endpoint, ALL)
+ const client = new SessionHostClient({ userDataDir })
+ await expect(client.captureVisible(NAME)).resolves.toEqual({
+ screen: 'row\n',
+ cursor: { x: 3, y: 0 },
+ altScreen: true
+ })
+ await expect(client.paneCwd(NAME)).resolves.toBe('C:\\work')
+ })
+
+ it('answers null WITHOUT sending when the host never advertised the feature', async () => {
+ const { userDataDir, endpoint } = fixture('nt-reads-off-')
+ const host = await fakeHost(endpoint, ['geometry'])
+ const client = new SessionHostClient({ userDataDir })
+ await expect(client.captureVisible(NAME)).resolves.toBeNull()
+ await expect(client.paneCwd(NAME)).resolves.toBeNull()
+ expect(host.requests.map((r) => r.cmd)).toEqual(['hello'])
+ })
+})
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index 451882439..162c970f0 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -32,6 +32,9 @@ import {
type HasSessionResult,
type PaneCommandResult,
type CaptureResult,
+ type CaptureVisibleResult,
+ type PaneCwdResult,
+ type SessionHostFeature,
type KillSessionResult,
type ExecuteLaunchResult,
type ListSessionsResult,
@@ -128,6 +131,9 @@ type SubscriberEntry = {
spawn?: SessionHostSpawnOptions
scrollback: number
phase: 'attaching' | 'attached'
+ /** A `watch-attach` viewer (live link / relay viewer): it never holds a size claim or a pause
+ * ticket, and its writes are dropped here — the host refuses them too. */
+ watch?: boolean
}
type BufferedFrame = {
@@ -178,6 +184,10 @@ type ClientSessionState = {
appliedAttached: boolean
appliedPaused: boolean
appliedSize: TerminalSize | null
+ /** The host holds this connection's attachment in WATCH mode (no geometry claim): true while
+ * every local subscriber is a watcher. A resize is never sent in this mode (the host refuses
+ * it); the next claim-carrying attach upgrades it, `reconcileOnSocket` downgrades it. */
+ appliedWatch?: boolean
}
function sleep(ms: number): Promise<void> {
@@ -210,6 +220,14 @@ function isTransportUncertainty(value: unknown): boolean {
/** Protocol-v1 hosts stay alive for warm terminal continuity. Operations that need atomic
* generation or replacement semantics fail closed without replacing that live host. */
+/** `attachWatch` against a host that did not advertise `watch-attach`: the viewer is refused. */
+export class SessionHostWatchUnsupportedError extends Error {
+ constructor(name: string) {
+ super(`session-host does not support read-only watch attach for '${name}'`)
+ this.name = 'SessionHostWatchUnsupportedError'
+ }
+}
+
export class SessionHostProtocolCompatibilityError extends Error {
readonly code = 'SESSION_HOST_PROTOCOL_INCOMPATIBLE'
@@ -300,6 +318,9 @@ export class SessionHostClient {
* ask the host to end every session and exit. An older host lacks it, and the app then falls
* back to the manual steps — never to killing the host itself. */
private hostShutdownFeature = false
+ /** Every additive feature the CURRENT connection negotiated (cleared with the socket). Newer
+ * features are read from here rather than given one boolean each. */
+ private hostFeatures = new Set<SessionHostFeature>()
/** The pid the host published in its state file for the current connection. Read only to
* confirm a shutdown actually ended the process. */
private hostPid: number | null = null
@@ -413,6 +434,16 @@ export class SessionHostClient {
return false
}
+ /** Every local subscriber of `state` is a watcher, and the host can hold that without a claim. */
+ private watchOnly(state: ClientSessionState): boolean {
+ return (
+ state.sizeClaims.size === 0 &&
+ state.entries.size > 0 &&
+ this.negotiatedProtocolVersion === 2 &&
+ this.hostFeatures.has('watch-attach')
+ )
+ }
+
private hasDesiredAttachments(): boolean {
for (const state of this.sessions.values()) {
if (this.hasAttachedEntry(state)) return true
@@ -609,6 +640,7 @@ export class SessionHostClient {
let protocolVersion: 1 | 2 | null = null
let geometryEvents = false
let shutdownFeature = false
+ let negotiatedFeatures: SessionHostFeature[] = []
const finish = (ok: boolean, trailing: SessionHostFrame[] = []): void => {
if (settled) return
settled = true
@@ -623,6 +655,7 @@ export class SessionHostClient {
return
}
this.hostShutdownFeature = shutdownFeature
+ this.hostFeatures = new Set(negotiatedFeatures)
this.hostPid = Number.isInteger(identity.state.pid) ? identity.state.pid : null
this.attachSocket(socket, protocolVersion, geometryEvents)
for (const frame of trailing) this.handleFrame(socket, frame)
@@ -721,6 +754,9 @@ export class SessionHostClient {
const features = (frame.result as HelloResult | undefined)?.features
geometryEvents = Array.isArray(features) && features.includes('geometry')
shutdownFeature = Array.isArray(features) && features.includes('shutdown')
+ negotiatedFeatures = Array.isArray(features)
+ ? SESSION_HOST_FEATURES.filter((feature) => features.includes(feature))
+ : []
finish(true, frames.slice(index + 1))
} else {
failHandshake(new Error(`session-host hello rejected: ${frame.error}`))
@@ -772,6 +808,7 @@ export class SessionHostClient {
this.socket = null
this.negotiatedProtocolVersion = null
this.hostGeometryEvents = false
+ this.hostFeatures = new Set()
for (const state of this.sessions.values()) {
// The next connection re-learns the size from its own attach replies.
state.hostGeometry = null
@@ -780,6 +817,7 @@ export class SessionHostClient {
state.appliedAttached = false
state.appliedPaused = false
state.appliedSize = null
+ state.appliedWatch = false
}
}
for (const [id, entry] of this.pending) {
@@ -924,6 +962,7 @@ export class SessionHostClient {
state.appliedAttached = false
state.appliedPaused = false
state.appliedSize = null
+ state.appliedWatch = false
if (state.entries.size === 0 && this.sessions.get(state.name) === state) {
this.sessions.delete(state.name)
}
@@ -1049,13 +1088,15 @@ export class SessionHostClient {
state: ClientSessionState,
socket: net.Socket,
paused: boolean,
- size: TerminalSize
+ /** Null: the host attached this connection in WATCH mode (no claim, never paused). */
+ size: TerminalSize | null
): void {
if (this.sessions.get(state.name) !== state || !this.hasAttachedEntry(state)) return
state.appliedSocket = socket
state.appliedAttached = true
state.appliedPaused = paused
state.appliedSize = size
+ state.appliedWatch = size === null
if (!paused && state.pauseOwners.size === 0) {
state.releasePending = false
this.flushData(state)
@@ -1073,7 +1114,13 @@ export class SessionHostClient {
const paused = state.pauseOwners.size > 0
const protocolVersion = this.negotiatedProtocolVersion
if (!protocolVersion) throw new Error('session-host: not connected')
+ // Only watchers here: re-attach WITHOUT a claim, or not at all — a replacement host that
+ // lost the feature must not be handed the 80x24 fallback as a viewer's size vote.
+ const watchRestore = state.sizeClaims.size === 0
try {
+ if (watchRestore && !this.watchOnly(state)) {
+ throw new Error(`session-host no longer supports watch attach for '${state.name}'`)
+ }
if (state.protocolVersion && state.protocolVersion !== protocolVersion) {
throw new Error(
`session-host protocol changed while '${state.name}' was detached; warm replay is unsafe`
@@ -1112,7 +1159,7 @@ export class SessionHostClient {
state.generation = result.generation ?? expectedGeneration
if (state.generation) this.sessionGenerations.set(state.name, state.generation)
this.recordHostGeometry(state, result.geometry)
- this.applyAttachment(state, replaySocket, paused, size)
+ this.applyAttachment(state, replaySocket, watchRestore ? false : paused, watchRestore ? null : size)
if (result.screen && state.appliedSocket === replaySocket) {
this.deliverData(state, RECONNECT_REPAINT_PREFIX + result.screen)
}
@@ -1132,14 +1179,16 @@ export class SessionHostClient {
} else {
await this.requestOnSocket<AttachResult>(
socket,
- {
- cmd: 'attachExisting',
- name: state.name,
- expectedGeneration,
- cols: size.cols,
- rows: size.rows,
- paused
- },
+ watchRestore
+ ? { cmd: 'attachExisting', name: state.name, expectedGeneration, watch: true }
+ : {
+ cmd: 'attachExisting',
+ name: state.name,
+ expectedGeneration,
+ cols: size.cols,
+ rows: size.rows,
+ paused
+ },
applyReplay
)
}
@@ -1161,6 +1210,7 @@ export class SessionHostClient {
state.appliedAttached = false
state.appliedPaused = false
state.appliedSize = null
+ state.appliedWatch = false
const failure = asError(error)
for (const entry of state.entries.values()) {
try {
@@ -1198,8 +1248,25 @@ export class SessionHostClient {
if (this.sessions.get(state.name) !== state) return
}
+ // The last voting subscriber left a watcher behind: withdraw this connection's claim, so a
+ // viewer never keeps the owner's old size pinned (the host keeps the pty at the size it has).
+ // A claim-carrying attach is the only way back up, so a watch-mode attachment never resizes.
+ if (this.watchOnly(state) && !state.appliedWatch) {
+ await this.requestOnSocket(socket, {
+ cmd: 'attachExisting',
+ name: state.name,
+ expectedGeneration: state.generation ?? this.sessionGenerations.get(state.name),
+ watch: true
+ })
+ if (this.socket !== socket) return
+ // The host returned any pause this connection held along with the claim.
+ state.appliedWatch = true
+ state.appliedSize = null
+ state.appliedPaused = false
+ if (this.sessions.get(state.name) !== state) return
+ }
const desiredSize = this.effectiveSize(state)
- if (!sameSize(state.appliedSize, desiredSize)) {
+ if (!state.appliedWatch && !sameSize(state.appliedSize, desiredSize)) {
await this.requestOnSocket(socket, {
cmd: 'resize',
name: state.name,
@@ -1289,13 +1356,44 @@ export class SessionHostClient {
)
}
+ /**
+ * A live link / relay viewer's READ-ONLY attach (`watch-attach`): never spawns, never claims a size,
+ * never pauses, never types. Rejects with `SessionHostWatchUnsupportedError` — before anything is
+ * registered — when the connected host did not advertise the feature (a long-lived host from an
+ * older build), so the caller can refuse the viewer instead of casting a size vote for it.
+ */
+ async attachWatch(name: string, sub: SessionSubscriber): Promise<AttachResult> {
+ await this.ensureConnected()
+ if (this.negotiatedProtocolVersion !== 2 || !this.hostFeatures.has('watch-attach')) {
+ throw new SessionHostWatchUnsupportedError(name)
+ }
+ return this.attachSubscriber(name, sub, { kind: 'existing', scrollback: 1 }, null)
+ }
+
+ /** Does the CURRENT connection speak `feature`? Connects first (a probe of a host that is not
+ * running yet would otherwise answer from a stale, empty set). False on any connect failure. */
+ async supportsFeature(feature: SessionHostFeature): Promise<boolean> {
+ try {
+ await this.ensureConnected()
+ } catch {
+ return false
+ }
+ return this.hostFeatures.has(feature)
+ }
+
+ /** The negotiated answer for `feature` WITHOUT connecting: undefined while there is no connection. */
+ connectedFeature(feature: SessionHostFeature): boolean | undefined {
+ return this.socket ? this.hostFeatures.has(feature) : undefined
+ }
+
private async attachSubscriber(
name: string,
sub: SessionSubscriber,
requestKind:
| { kind: 'create'; spawn: SessionHostSpawnOptions; scrollback: number }
| { kind: 'existing'; scrollback: number },
- initialSize: TerminalSize
+ /** Null: a watcher (`attachWatch`), which casts no size claim at all. */
+ initialSize: TerminalSize | null
): Promise<AttachResult> {
if (this.killReplayBarriers.has(name)) {
throw new Error(
@@ -1314,11 +1412,13 @@ export class SessionHostClient {
sub,
...(requestKind.kind === 'create' ? { spawn: requestKind.spawn } : {}),
scrollback: requestKind.scrollback,
- phase: 'attaching'
+ phase: 'attaching',
+ ...(initialSize === null ? { watch: true } : {})
}
state.entries.set(sub, entry)
// A new viewer is the most recently active one, exactly as a freshly attached tmux client is.
- state.sizeClaims.set(sub, { ...initialSize, recency: ++this.claimClock })
+ // A watcher is not a viewer in that sense: it never votes.
+ if (initialSize) state.sizeClaims.set(sub, { ...initialSize, recency: ++this.claimClock })
return this.enqueueState(state, async () => {
if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) {
@@ -1342,6 +1442,12 @@ export class SessionHostClient {
}
const expectedGeneration = state.generation ?? this.sessionGenerations.get(name)
const replacementToken = useWarmOnly ? undefined : this.replacementTokens.get(name)
+ // Nobody local votes (a watcher alone, or a watcher joining other watchers): attach without
+ // a claim. A watcher joining an owner rides the owner's claim like any co-attach.
+ const watchAttach = useWarmOnly && this.watchOnly(state)
+ if (entry.watch && !watchAttach && !this.hasAttachedEntry(state) && state.sizeClaims.size === 0) {
+ throw new SessionHostWatchUnsupportedError(name)
+ }
state.preAckEntries.add(entry)
let response: AttachResult | undefined
const attempts = replacementToken ? 2 : 1
@@ -1356,14 +1462,21 @@ export class SessionHostClient {
scrollback: 1,
paused
})
- : await this.request<AttachResult>({
- cmd: 'attachExisting',
- name,
- expectedGeneration,
- cols: size.cols,
- rows: size.rows,
- paused
- })
+ : watchAttach
+ ? await this.request<AttachResult>({
+ cmd: 'attachExisting',
+ name,
+ expectedGeneration,
+ watch: true
+ })
+ : await this.request<AttachResult>({
+ cmd: 'attachExisting',
+ name,
+ expectedGeneration,
+ cols: size.cols,
+ rows: size.rows,
+ paused
+ })
: await this.request<AttachResult>({
cmd: 'attach',
name,
@@ -1426,14 +1539,15 @@ export class SessionHostClient {
if (!socket) throw new Error('session-host: not connected')
if (this.sessions.get(name) === state && state.entries.get(sub) === entry) {
entry.phase = 'attached'
- this.applyAttachment(state, socket, paused, size)
+ this.applyAttachment(state, socket, watchAttach ? false : paused, watchAttach ? null : size)
} else {
// The attach reached the host before its owner retired. Remember the confirmed
// membership on the retired state so its ordered teardown can return pause + detach.
state.appliedSocket = socket
state.appliedAttached = true
- state.appliedPaused = paused
- state.appliedSize = size
+ state.appliedPaused = watchAttach ? false : paused
+ state.appliedSize = watchAttach ? null : size
+ state.appliedWatch = watchAttach
}
if (this.sessions.get(name) !== state || state.entries.get(sub) !== entry) {
// If another local subscriber remains, this attach also restored its socket membership;
@@ -1542,6 +1656,8 @@ export class SessionHostClient {
const state = this.sessions.get(name)
const entry = state?.entries.get(sub)
if (!state || !entry) return
+ // A watcher is read-only: its xterm's automatic answers (and anything else) never reach the pane.
+ if (entry.watch) return
// Typing makes a viewer the active one, as it does a tmux client. An emulator's automatic
// answer to a query does not: every attached xterm answers, and counting those would hand the
// session to whichever viewer answered last.
@@ -1572,6 +1688,11 @@ export class SessionHostClient {
): void {
const state = this.sessions.get(name)
if (!state || !state.entries.has(sub)) return
+ // A watcher never votes; it is only told the size the pty runs at.
+ if (state.entries.get(sub)?.watch) {
+ this.notifySize(state)
+ return
+ }
const previous = state.sizeClaims.get(sub) ?? { cols: 80, rows: 24, recency: 0 }
const next: SizeClaim = {
cols: normalizeDimension(cols, previous.cols),
@@ -1591,6 +1712,8 @@ export class SessionHostClient {
pause(name: string, sub: SessionSubscriber): void {
const state = this.sessions.get(name)
if (!state || !state.entries.has(sub) || state.pauseOwners.has(sub)) return
+ // A viewer never holds a pause ticket on the shared pty: the owner must not slow down for it.
+ if (state.entries.get(sub)?.watch) return
const wasFlowing = state.pauseOwners.size === 0
state.pauseOwners.add(sub)
if (wasFlowing) this.queueReconcile(state)
@@ -1650,6 +1773,37 @@ export class SessionHostClient {
return result.text
}
+ /** A live link's keyframe (`captureVisible` feature). Null when the host did not advertise the
+ * feature (never sent then), the session is gone, or anything failed — a keyframe is an
+ * optimisation, and "no capture" must stay distinguishable from an empty screen. */
+ async captureVisible(name: string): Promise<CaptureVisibleResult | null> {
+ try {
+ if (!(await this.supportsFeature('captureVisible'))) return null
+ const r = await this.request<CaptureVisibleResult>({ cmd: 'captureVisible', name })
+ if (!r || typeof r.screen !== 'string' || typeof r.altScreen !== 'boolean') return null
+ const c = r.cursor
+ const cursor =
+ c && Number.isInteger(c.x) && Number.isInteger(c.y) && c.x >= 0 && c.y >= 0
+ ? { x: c.x, y: c.y }
+ : null
+ return { screen: r.screen, cursor, altScreen: r.altScreen }
+ } catch {
+ return null
+ }
+ }
+
+ /** The cwd the pane last REPORTED (`paneCwd` feature); null without the feature, before any
+ * report, or on any failure. */
+ async paneCwd(name: string): Promise<string | null> {
+ try {
+ if (!(await this.supportsFeature('paneCwd'))) return null
+ const r = await this.request<PaneCwdResult>({ cmd: 'paneCwd', name })
+ return typeof r?.cwd === 'string' && r.cwd ? r.cwd : null
+ } catch {
+ return null
+ }
+ }
+
/** Execute already-rendered trusted input through the persistent generation's exactly-once
* launch ledger. Retrying with the SAME `launchId` after a lost reply is safe: the host answers
* `already-executed` rather than typing the command a second time. Never retries internally —
@@ -1895,6 +2049,7 @@ export class SessionHostClient {
state.appliedAttached = false
state.appliedPaused = false
state.appliedSize = null
+ state.appliedWatch = false
this.stopReconnectIfIdle()
}
diff --git a/src/core/session-host-pty.ts b/src/core/session-host-pty.ts
index 92b089bdc..ff471afeb 100644
--- a/src/core/session-host-pty.ts
+++ b/src/core/session-host-pty.ts
@@ -32,7 +32,10 @@ export class SessionHostPty {
client: SessionHostClient,
name: string,
spawn: SessionHostSpawnOptions | null,
- scrollback: number
+ scrollback: number,
+ /** A read-only viewer's attachment (`SessionHostClient.attachWatch`): `spawn` must be null. Its
+ * writes, resizes and pauses never reach the host. */
+ mode: 'owner' | 'watch' = 'owner'
) {
this.client = client
this.name = name
@@ -53,7 +56,9 @@ export class SessionHostPty {
}
this.ready = spawn
? client.attach(name, spawn, scrollback, this.sub)
- : client.attachExisting(name, this.sub)
+ : mode === 'watch'
+ ? client.attachWatch(name, this.sub)
+ : client.attachExisting(name, this.sub)
// node-pty's real spawn never rejects asynchronously (a spawn failure throws synchronously,
// before a Session is even constructed) — an attach failure here is the closest analogue, and
// it must not become an unhandled rejection just because some callers (write/resize/pause/