Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(windows): live links join, keyframe and pane cwd on session-host nodes
review86cb7dfe9a6c
diff --git a/src/core/pty-manager.capture-visible.test.ts b/src/core/pty-manager.capture-visible.test.tsindex d8f1dc6df..1a19a437a 100644--- a/src/core/pty-manager.capture-visible.test.ts+++ b/src/core/pty-manager.capture-visible.test.ts@@ -52,9 +52,14 @@ vi.mock('node-pty', () => ({}))const hostCapture = vi.hoisted(() => vi.fn(async () => 'HISTORY LINE 1\nHISTORY LINE 2\n'))+// The host's negotiated visible-only read; null = an older host without the feature.+const hostCaptureVisible = vi.hoisted(() =>+ vi.fn(async (_name: string): Promise<{ screen: string; cursor: { x: number; y: number } | null; altScreen: boolean } | null> => null)+)vi.mock('./session-host-backend', async (original) => ({...(await original<typeof import('./session-host-backend')>()),- sessionHostCapture: hostCapture+ sessionHostCapture: hostCapture,+ sessionHostCaptureVisible: hostCaptureVisible}))const NODE = 'node-1'@@ -144,7 +149,17 @@ describe('captureVisible — local tmux', () => {})describe('captureVisible — never history', () => {- it('a session-host session gets NO keyframe — its only capture is scrollback', async () => {+ it("a session-host session's keyframe is the host's visible-only read, with its own altScreen", async () => {+ hostCaptureVisible.mockResolvedValueOnce({ screen: 'vis\n', cursor: { x: 3, y: 0 }, altScreen: false })+ const m = await manager({ sessionHost: true })+ expect(await m.captureVisible('sess-1')).toEqual({ screen: 'vis\n', cursor: { x: 3, y: 0 }, altScreen: false })+ expect(hostCaptureVisible).toHaveBeenCalledWith(sessionName(NODE))+ expect(hostCapture).not.toHaveBeenCalled()+ expect(calls).toEqual([])+ })++ it('a session host without the read (older build) gets NO keyframe — never its scrollback capture', async () => {+ hostCaptureVisible.mockResolvedValueOnce(null)const m = await manager({ sessionHost: true })expect(await m.captureVisible('sess-1')).toEqual(unavailableCapture())expect(hostCapture).not.toHaveBeenCalled()diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 0e7282b15..ee9f9afdf 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -213,7 +213,12 @@ import {sessionHostMessageEnvelope,sessionHostSendKeys,sessionHostSupported,- SessionHostProtocolCompatibilityError+ SessionHostProtocolCompatibilityError,+ watchExistingSessionHostPty,+ sessionHostSupportsWatch,+ sessionHostWatchKnown,+ sessionHostCaptureVisible,+ sessionHostPaneCwd} from './session-host-backend'import type { SessionHostPty } from './session-host-pty'import { NativeWindowsPane } from './native-windows-pane'@@ -743,6 +748,17 @@ type WatcherCreateOptions = PtyCreateOptions & { readonly [WATCHER_CLIENT]?: trufunction isWatcherCreate(options: PtyCreateOptions): boolean {return (options as WatcherCreateOptions)[WATCHER_CLIENT] === true}+/**+ * Marks a join-only create that `spawnNew` PROVED has a live session-host generation to watch (the+ * host advertised `watch-attach` and answered `hasSession` strictly). Same symbol discipline as+ * `WATCHER_CLIENT`: set only inside this process, never from a wire payload. `spawnSession` turns it+ * into a read-only `watchExistingSessionHostPty` — no spawn plan, no size claim, no pause ticket.+ */+const SESSION_HOST_WATCH: unique symbol = Symbol('nodeterm.sessionHostWatch')+type SessionHostWatchOptions = PtyCreateOptions & { readonly [SESSION_HOST_WATCH]?: true }+function isSessionHostWatch(options: PtyCreateOptions): boolean {+ return (options as SessionHostWatchOptions)[SESSION_HOST_WATCH] === true+}interface Session {proc: pty.IPty@@ -2092,16 +2108,7 @@ export class PtyManager {installCommand: hint?.command ?? null,installLabel: hint?.label ?? null,platform: this.runtimePlatform,- persistence: {- enabled: this.getSettings().tmuxEnabled,- backend:- // Zellij when it is selected AND found: that is where a new local terminal goes.- this.zellijSelected() && this.zellijBin() && this.zellijSocketFitsFor(TYPICAL_SESSION_NAME)- ? 'zellij'- : this.runtimePlatform !== 'win32' && available- ? 'tmux'- : sessionHostSupported() ? 'session-host' : null- },+ persistence: this.persistenceStatus(available),...(this.runtimePlatform !== 'win32'? {zellij: {@@ -2114,6 +2121,24 @@ export class PtyManager {}}+ /** `tmuxStatus().persistence`: where a new local terminal goes, and what a viewer can join there. */+ private persistenceStatus(available: boolean): NonNullable<TmuxStatus['persistence']> {+ const backend =+ // Zellij when it is selected AND found: that is where a new local terminal goes.+ this.zellijSelected() && this.zellijBin() && this.zellijSocketFitsFor(TYPICAL_SESSION_NAME)+ ? 'zellij'+ : this.runtimePlatform !== 'win32' && available+ ? 'tmux'+ : sessionHostSupported() ? 'session-host' : null+ return {+ enabled: this.getSettings().tmuxEnabled,+ backend,+ // Live links can join a session-host node nobody holds open (`watch-attach`). Only a+ // CONNECTED host's negotiated answer counts; unknown stays absent (the conservative note).+ ...(backend === 'session-host' && sessionHostWatchKnown() === true ? { watchJoin: true } : {})+ }+ }+/*** Does this client actually WATCH this session? The membership check every wire-facing pty cast* (write / resize / flow / kill) is gated on.@@ -2624,9 +2649,28 @@ export class PtyManager {options.joinOnly && !options.sshRemote && !warmWindowsBackend && tmuxBacked? await this.strictTmuxVerdict(options.persistKey as string): undefined+ // The same strict question for a node whose terminals live in the SESSION HOST (Windows, or no+ // tmux): a viewer may join only a generation the host CONFIRMED (`hasSession`, never the folded+ // `.catch(() => true)` the reaper's probe uses — an unanswered probe refuses), and only through+ // a read-only `watch-attach` attachment, which a host from an older build does not have (refused+ // too: its only attach would cast the viewer's size vote). Never a spawn either way.+ if (+ options.joinOnly &&+ !options.sshRemote &&+ !warmWindowsBackend &&+ !tmuxBacked &&+ options.persistKey &&+ this.hostBackendEligible()+ ) {+ const live = await sessionHostHasSession(sessionName(options.persistKey)).catch(() => false)+ if (!live || !(await sessionHostSupportsWatch().catch(() => false)))+ return { sessionId: '', fresh: false, unavailable: 'join-only' }+ options = { ...options, [SESSION_HOST_WATCH]: true } as SessionHostWatchOptions+ }+ const sessionHostWatch = isSessionHostWatch(options)let fresh = options.sshRemote? remoteVerdict === 'absent'- : warmWindowsBackend+ : warmWindowsBackend || sessionHostWatch? false: tmuxBacked? joinOnlyLocalVerdict@@ -2647,6 +2691,7 @@ export class PtyManager {!options.sshRemote &&options.persistKey &&!warmWindowsBackend &&+ !sessionHostWatch &&this.runtimePlatform !== 'win32' &&this.getSettings().tmuxEnabled &&!(tmuxBacked && !fresh)@@ -2670,11 +2715,19 @@ export class PtyManager {// `join` above); it just gets no keyframe (`visibleCaptureRoute`).if (isWatcherCreate(options) && zellijChoice?.use)return { sessionId: '', fresh: false, unavailable: 'join-only' }+ // A session-host watch needs neither of the tmux watcher gates below: there is no tmux client to+ // flag, and the attachment takes the pty's size from the host's own answer (`geometry`) rather+ // than spawning at a read one. `create` (and its in-flight barrier) still runs as for tmux.// A watcher's own LOCAL client needs client flags (tmux >= 3.2). Without them it would either fail// to attach or — worse, spelled without the flags — resize the owner's window. Refused the same// way as a session that cannot be confirmed. Over SSH the host's version is unknown here: the// flags are passed and an old remote tmux rejects them (see `remoteTmuxWatcherArgs`).- if (isWatcherCreate(options) && !options.sshRemote && !(await this.localTmuxSupportsWatcherClient()))+ if (+ isWatcherCreate(options) &&+ !sessionHostWatch &&+ !options.sshRemote &&+ !(await this.localTmuxSupportsWatcherClient())+ )return { sessionId: '', fresh: false, unavailable: 'join-only' }// A watcher's own client is spawned at the window's CURRENT size, read here, just before the spawn// — never at a guessed one (the caller's, a remembered size, a default). `ignore-size` only holds@@ -2685,7 +2738,7 @@ export class PtyManager {// waits for this client and then shares it, instead of spawning another. The cost, accepted: an// owner opening the same node in that instant waits for the read too — bounded by the probe and// process timeouts (`runAsync`) — and then spawns its own client as usual.- if (isWatcherCreate(options)) {+ if (isWatcherCreate(options) && !sessionHostWatch) {const windowSize = await this.readWindowSize(options.persistKey as string, options.sshRemote)if (!windowSize) return { sessionId: '', fresh: false, unavailable: 'join-only' }options = { ...options, cols: windowSize.cols, rows: windowSize.rows }@@ -3952,6 +4005,7 @@ export class PtyManager {// remote/ssh node must never fall into it, and neither may a node with no persistKey at all).let useSessionHost = falselet attachExistingHost = false+ let watchHost = false// Unlike the installed-binary probe, this records the backend selected for THIS generation.// A Windows profile may coexist with an MSYS/Cygwin tmux on PATH and must not inherit it.let useLocalTmux = false@@ -4138,6 +4192,12 @@ export class PtyManager {options.sshRemote.tmuxConfPath,remoteSessionEnv)+ } else if (isSessionHostWatch(options)) {+ // A proven session-host generation, joined read-only (see `SESSION_HOST_WATCH`).+ useSessionHost = true+ watchHost = true+ file = ''+ args = []} else if (warmWindowsBackend === 'session-host') {useSessionHost = trueattachExistingHost = true@@ -4293,7 +4353,9 @@ export class PtyManager {//// The non-session-host branch above already resolves this correctly. Sharing that logic is// the fix; two places deciding "which shell" is what let them disagree.- proc = (attachExistingHost+ proc = (watchHost+ ? watchExistingSessionHostPty(sessionName(options.persistKey as string))+ : attachExistingHost? attachExistingSessionHostPty(sessionName(options.persistKey as string)): createSessionHostPty(sessionName(options.persistKey as string),@@ -4383,7 +4445,12 @@ export class PtyManager {// The spawn's claim went to the backend unbounded (a renderer view adapts to any size).appliedBounding: false,nodeId: options.persistKey,- indexKey: options.persistKey && !sinks && !isWatcherCreate(options) ? options.persistKey : undefined,+ // A read-only session-host attachment is never the node's session either: an owner opening the+ // node must spawn its own (typing, size-voting) attachment rather than join this one.+ indexKey:+ options.persistKey && !sinks && !isWatcherCreate(options) && !watchHost+ ? options.persistKey+ : undefined,onData: sinks?.onData,onExit: sinks?.onExit,onSinkSize: sinks?.onSize,@@ -4405,7 +4472,7 @@ export class PtyManager {pausedBy: new Set<string>(),accountFallback,sessionHost: useSessionHost,- ...(isWatcherCreate(options) ? { watcherClient: true } : {}),+ ...(isWatcherCreate(options) || watchHost ? { watcherClient: true } : {}),...(useLocalZellij ? { zellij: true } : {})}// Both shared timers are armed by the first session that needs them: the scrollback snapshots@@ -5173,6 +5240,14 @@ export class PtyManager {const route = visibleCaptureRoute(session, !!this.tmuxPath)const target = sessionName(key)try {+ if (route === 'sessionHost') {+ // The host's own emulator answers (a negotiated `captureVisible`); an older host, a gone+ // session or any failure is null ⇒ no keyframe. Never the scrollback `capture` in its place.+ // `altScreen` comes from the emulator's ACTIVE buffer: no tmux client sits between the pane+ // and the stream here, so the pane's own buffer IS the stream's.+ const cap = await sessionHostCaptureVisible(target)+ return cap ? { screen: cap.screen, cursor: cap.cursor, altScreen: cap.altScreen } : unavailableCapture()+ }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()@@ -5212,6 +5287,10 @@ export class PtyManager {if (!s) return 'none'if (s.zellij) return 'none' // session-wide key bindings: refusedif (s.sshRemote) return s.tmuxBacked ? 'ssh' : 'none'+ // A read-only session-host attachment (`watch-attach`, the node not held here) has no typing+ // path: the host refuses writes from it, and its keys must not be retyped as a framed paste.+ // Control typing reaches a session-host node while the node is open in this app.+ if (s.sessionHost && s.watcherClient) return 'none'if (s.sessionHost || s.nativeWindowsPane) return 'write'if (s.tmuxBacked) return this.tmuxPath ? 'tmux' : 'none'// A watcher's own client is read-only and always tmux-backed; were one ever not, writing into it@@ -5456,6 +5535,9 @@ export class PtyManager {try {const session = this.sessions.get(sessionId)if (!session?.watcherClient || !session.persistKey) return false+ // A session-host watch attachment has no window to read: the host pushes the pty's size+ // itself (`geometry`), and `applyBackendSize` already forwards it to the viewers.+ if (session.sessionHost) return trueconst size = await this.readWindowSize(session.persistKey, session.sshRemote)if (!size || this.sessions.get(sessionId) !== session) return falseif (session.appliedSize?.cols !== size.cols || session.appliedSize?.rows !== size.rows) {@@ -5989,6 +6071,10 @@ export class PtyManager {return null}}+ // The session host answers from the cwd the pane last REPORTED (OSC 7 / 9;9 / 633), null when it+ // never reported one or the host predates the `paneCwd` feature. A released or never-attached+ // node asks the backend that owns it (`sessionHostOwns`), exactly as messaging does.+ if (this.sessionHostOwns(persistKey, live)) return sessionHostPaneCwd(target).catch(() => null)if (live?.sessionHost || !this.tmuxPath) return nulltry {const { stdout } = await runAsync(this.tmuxPath, [diff --git a/src/core/pty-persistence-status.test.ts b/src/core/pty-persistence-status.test.tsindex 9095d1c82..32f0fdd94 100644--- a/src/core/pty-persistence-status.test.ts+++ b/src/core/pty-persistence-status.test.ts@@ -3,12 +3,22 @@ import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform } from './platform-fake'import { PtyManager } from './pty-manager'-const host = vi.hoisted(() => ({ supported: vi.fn(() => false) }))-vi.mock('./session-host-backend', () => ({ sessionHostSupported: host.supported }))+const host = vi.hoisted(() => ({+ supported: vi.fn(() => false),+ watchKnown: vi.fn((): boolean | undefined => undefined)+}))+vi.mock('./session-host-backend', () => ({+ sessionHostSupported: host.supported,+ sessionHostWatchKnown: host.watchKnown+}))vi.mock('node-pty', () => ({ spawn: vi.fn() }))describe('local persistence discovery (#575)', () => {- beforeEach(() => { initPlatform(fakePlatform()); host.supported.mockReturnValue(false) })+ beforeEach(() => {+ initPlatform(fakePlatform())+ host.supported.mockReturnValue(false)+ host.watchKnown.mockReset().mockReturnValue(undefined)+ })afterEach(() => { vi.restoreAllMocks(); resetPlatformForTests() })function manager(platform: NodeJS.Platform, tmux: boolean, enabled = true): PtyManager {@@ -33,6 +43,22 @@ describe('local persistence discovery (#575)', () => {it('never treats a Windows tmux path as protection', () => {expect(manager('win32', true).tmuxStatus().persistence?.backend).toBeNull()})+ it('reports watchJoin only for a session-host backend whose CONNECTED host speaks watch-attach', () => {+ host.supported.mockReturnValue(true)+ host.watchKnown.mockReturnValue(true)+ expect(manager('win32', false).tmuxStatus().persistence).toEqual({+ enabled: true,+ backend: 'session-host',+ watchJoin: true+ })+ // tmux has its own watcher client: the flag is never asked there.+ host.watchKnown.mockClear()+ expect(manager('linux', true).tmuxStatus().persistence).toEqual({ enabled: true, backend: 'tmux' })+ expect(host.watchKnown).not.toHaveBeenCalled()+ // An older host (false) or no connection yet (undefined): absent, the conservative note stays.+ host.watchKnown.mockReturnValue(false)+ expect(manager('win32', false).tmuxStatus().persistence).not.toHaveProperty('watchJoin')+ })it('keeps the user setting distinct from backend discovery', () => {host.supported.mockReturnValue(true)expect(manager('win32', false, false).tmuxStatus().persistence).toEqual({ enabled: false, backend: 'session-host' })diff --git a/src/core/pty-session-host-watch.test.ts b/src/core/pty-session-host-watch.test.tsnew file mode 100644index 000000000..ee4c834b6--- /dev/null+++ b/src/core/pty-session-host-watch.test.ts@@ -0,0 +1,251 @@+// Live links on a SESSION-HOST node (Windows, or no tmux): a join-only create — a live link watcher or+// a hosted-relay viewer — joins a generation the host CONFIRMED through a read-only `watch-attach`+// attachment, and is refused for every other answer; the keyframe and the pane cwd come from the+// host's own negotiated reads. Harness mirrors pty-session-host.test.ts: no local tmux, so the+// session host is the selected backend, and every backend export this file reaches is mocked.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { IPC } from '../shared/ipc'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { sessionName } from './tmux-naming'+import type { PtyCreateResult } from '../shared/types'++const backend = vi.hoisted(() => ({+ supported: vi.fn(() => true),+ create: vi.fn(),+ attachExisting: vi.fn(),+ watch: vi.fn(),+ hasSession: vi.fn(async (_name: string): Promise<boolean> => true),+ supportsWatch: vi.fn(async (): Promise<boolean> => true),+ captureVisible: vi.fn(+ async (+ _name: string+ ): Promise<{ screen: string; cursor: { x: number; y: number } | null; altScreen: boolean } | null> =>+ null+ ),+ paneCwd: vi.fn(async (_name: string): Promise<string | null> => null),+ capture: vi.fn(async () => 'HISTORY'),+ kill: vi.fn(async () => {}),+ list: vi.fn(async () => []),+ paneCommand: vi.fn(async () => null),+ sendKeys: vi.fn(async () => false)+}))++vi.mock('./session-host-backend', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./session-host-backend')>()),+ sessionHostSupported: backend.supported,+ createSessionHostPty: backend.create,+ attachExistingSessionHostPty: backend.attachExisting,+ watchExistingSessionHostPty: backend.watch,+ sessionHostHasSession: backend.hasSession,+ sessionHostSupportsWatch: backend.supportsWatch,+ sessionHostWatchKnown: () => undefined,+ sessionHostCaptureVisible: backend.captureVisible,+ sessionHostPaneCwd: backend.paneCwd,+ sessionHostCapture: backend.capture,+ sessionHostKillSession: backend.kill,+ sessionHostListSessions: backend.list,+ sessionHostPaneCommand: backend.paneCommand,+ sessionHostSendKeys: backend.sendKeys+}))++vi.mock('node-pty', () => ({+ spawn: vi.fn(() => {+ throw new Error('direct node-pty spawn must not run in the session-host suite')+ })+}))++vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++function fakeSessionHostPty(ready: Promise<unknown> = Promise.resolve({ fresh: false })) {+ let sizeCb: ((size: { cols: number; rows: number }) => void) | undefined+ return {+ ready,+ onSize: vi.fn((cb: (size: { cols: number; rows: number }) => void) => {+ sizeCb = cb+ }),+ emitSize: (cols: number, rows: number) => sizeCb?.({ cols, rows }),+ onData: vi.fn(),+ onExit: vi.fn(),+ onAttachError: vi.fn(),+ write: vi.fn(),+ resize: vi.fn(),+ pause: vi.fn(),+ resume: vi.fn(),+ kill: vi.fn(),+ destroy: vi.fn()+ }+}++const NODE = 'node-w'+const VIEWER = 9+const OWNER = 7++describe('PtyManager: join-only creates on the session host', () => {+ let manager: import('./pty-manager').PtyManager | undefined+ let host: FakePlatform++ beforeEach(() => {+ host = fakePlatform()+ initPlatform(host)+ backend.supported.mockReturnValue(true)+ backend.create.mockReset().mockImplementation(() => fakeSessionHostPty(Promise.resolve({ fresh: true })))+ backend.attachExisting.mockReset().mockImplementation(() => fakeSessionHostPty())+ backend.watch.mockReset().mockImplementation(() => fakeSessionHostPty())+ backend.hasSession.mockReset().mockResolvedValue(true)+ backend.supportsWatch.mockReset().mockResolvedValue(true)+ backend.captureVisible.mockReset().mockResolvedValue(null)+ backend.paneCwd.mockReset().mockResolvedValue(null)+ })++ afterEach(async () => {+ await manager?.killAll()+ manager = undefined+ resetPlatformForTests()+ vi.restoreAllMocks()+ })++ async function makeManager() {+ const { PtyManager } = await import('./pty-manager')+ manager = new PtyManager()+ manager.registerIpc()+ return manager+ }++ /** The option shape the relay access policy forwards for a viewer (`viewerCreateOptions`). */+ function viewerCreate(): Promise<PtyCreateResult> {+ return host.handlers[IPC.ptyCreate](VIEWER, {+ persistKey: NODE,+ cols: 50,+ rows: 20,+ joinOnly: true,+ sizeVote: false+ }) as Promise<PtyCreateResult>+ }++ it('joins a confirmed generation read-only: no spawn plan, no size claim', async () => {+ const shim = fakeSessionHostPty()+ backend.watch.mockReturnValue(shim)+ await makeManager()+ const res = await viewerCreate()+ expect(res.unavailable).toBeUndefined()+ expect(res.sessionId).toBeTruthy()+ expect(res.fresh).toBe(false)+ expect(backend.hasSession).toHaveBeenCalledWith(sessionName(NODE))+ expect(backend.watch).toHaveBeenCalledWith(sessionName(NODE))+ expect(backend.create).not.toHaveBeenCalled()+ expect(backend.attachExisting).not.toHaveBeenCalled()+ expect(shim.resize).not.toHaveBeenCalled()+ })++ it.each([+ ['the session is absent', () => backend.hasSession.mockResolvedValue(false)],+ ['the existence probe failed', () => backend.hasSession.mockRejectedValue(new Error('EPIPE'))],+ ['the host predates watch-attach', () => backend.supportsWatch.mockResolvedValue(false)]+ ])('refuses join-only when %s, and spawns nothing', async (_label, arrange) => {+ arrange()+ await makeManager()+ await expect(viewerCreate()).resolves.toMatchObject({ sessionId: '', unavailable: 'join-only' })+ expect(backend.watch).not.toHaveBeenCalled()+ expect(backend.create).not.toHaveBeenCalled()+ expect(backend.attachExisting).not.toHaveBeenCalled()+ })++ it('a live link watcher (joinAsWatcher) takes the same route and has no typing path', async () => {+ const m = await makeManager()+ const res = await m.joinAsWatcher(VIEWER, { persistKey: NODE, viewerId: 'link-a' })+ expect(res.unavailable).toBeUndefined()+ expect(backend.watch).toHaveBeenCalledTimes(1)+ expect(m.watcherInputRoute(res.sessionId)).toBe('none')+ // A session-host watch has no tmux window to read; the host pushes its size itself.+ await expect(m.syncWatcherClientSize(res.sessionId)).resolves.toBe(true)+ })++ it('an owner opening the node afterwards gets its OWN attachment, never the viewer one', async () => {+ await makeManager()+ const viewer = await viewerCreate()+ const owner = (await host.handlers[IPC.ptyCreate](OWNER, {+ persistKey: NODE,+ cols: 100,+ rows: 30+ })) as PtyCreateResult+ expect(owner.sessionId).toBeTruthy()+ expect(owner.sessionId).not.toBe(viewer.sessionId)+ expect(backend.create).toHaveBeenCalledTimes(1)+ })++ it('an owner create is untouched: no existence probe, no watch route', async () => {+ await makeManager()+ await host.handlers[IPC.ptyCreate](OWNER, { persistKey: NODE, cols: 100, rows: 30 })+ expect(backend.watch).not.toHaveBeenCalled()+ expect(backend.supportsWatch).not.toHaveBeenCalled()+ expect(backend.create).toHaveBeenCalledTimes(1)+ })+})++describe('PtyManager: session-host keyframe and pane cwd', () => {+ let manager: import('./pty-manager').PtyManager | undefined+ let host: FakePlatform++ beforeEach(() => {+ host = fakePlatform()+ initPlatform(host)+ backend.supported.mockReturnValue(true)+ backend.create.mockReset().mockImplementation(() => fakeSessionHostPty(Promise.resolve({ fresh: true })))+ backend.captureVisible.mockReset().mockResolvedValue(null)+ backend.paneCwd.mockReset().mockResolvedValue(null)+ backend.capture.mockClear()+ })++ afterEach(async () => {+ await manager?.killAll()+ manager = undefined+ resetPlatformForTests()+ vi.restoreAllMocks()+ })++ async function owned(): Promise<{ m: import('./pty-manager').PtyManager; sessionId: string }> {+ const { PtyManager } = await import('./pty-manager')+ manager = new PtyManager()+ manager.registerIpc()+ const res = (await host.handlers[IPC.ptyCreate](OWNER, {+ persistKey: NODE,+ cols: 80,+ rows: 24+ })) as PtyCreateResult+ return { m: manager, sessionId: res.sessionId }+ }++ it("returns the host's visible capture, with the emulator's own buffer as altScreen", async () => {+ backend.captureVisible.mockResolvedValue({ screen: 'a\nb\n', cursor: { x: 1, y: 1 }, altScreen: true })+ const { m, sessionId } = await owned()+ await expect(m.captureVisible(sessionId)).resolves.toEqual({+ screen: 'a\nb\n',+ cursor: { x: 1, y: 1 },+ altScreen: true+ })+ expect(backend.captureVisible).toHaveBeenCalledWith(sessionName(NODE))+ })++ it('maps no capture (older host, gone session) to unavailable — never the scrollback capture', async () => {+ const { m, sessionId } = await owned()+ await expect(m.captureVisible(sessionId)).resolves.toMatchObject({ unavailable: true })+ backend.captureVisible.mockRejectedValue(new Error('boom'))+ await expect(m.captureVisible(sessionId)).resolves.toMatchObject({ unavailable: true })+ expect(backend.capture).not.toHaveBeenCalled()+ })++ it('routes paneCwd to the host for a session-host node, live or not', async () => {+ backend.paneCwd.mockResolvedValue('C:\\work')+ const { m } = await owned()+ await expect(m.paneCwd(NODE)).resolves.toBe('C:\\work')+ expect(backend.paneCwd).toHaveBeenCalledWith(sessionName(NODE))+ // A node this process never attached: the session host is still this machine's backend.+ await expect(m.paneCwd('node-other')).resolves.toBe('C:\\work')+ backend.paneCwd.mockRejectedValue(new Error('gone'))+ await expect(m.paneCwd(NODE)).resolves.toBeNull()+ })+})diff --git a/src/core/watch-link/capture-route.test.ts b/src/core/watch-link/capture-route.test.tsindex ca147b13b..e6dd48b1f 100644--- a/src/core/watch-link/capture-route.test.ts+++ b/src/core/watch-link/capture-route.test.ts@@ -10,7 +10,8 @@ import {describe('visibleCaptureRoute', () => {it('never routes to a capture that returns history', () => {- expect(visibleCaptureRoute({ sessionHost: {} }, true)).toBe('none')+ // The session host answers its own visible-only `captureVisible`, never its scrollback capture.+ expect(visibleCaptureRoute({ sessionHost: {} }, true)).toBe('sessionHost')expect(visibleCaptureRoute({ nativeWindowsPane: {} }, true)).toBe('none')expect(visibleCaptureRoute({ sshRemote: {} }, true)).toBe('ssh')expect(visibleCaptureRoute({ tmuxBacked: true }, true)).toBe('tmux')@@ -18,10 +19,11 @@ describe('visibleCaptureRoute', () => {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')+ it('a session-host session goes to the host even when it is also marked tmux-backed or remote', () => {+ // Never aimed at a tmux socket (local or over ssh): the host's emulator is the only screen it has.+ expect(visibleCaptureRoute({ sessionHost: true, tmuxBacked: true }, true)).toBe('sessionHost')+ expect(visibleCaptureRoute({ sessionHost: true, tmuxBacked: true }, false)).toBe('sessionHost')+ expect(visibleCaptureRoute({ sessionHost: true, sshRemote: {} }, true)).toBe('sessionHost')expect(visibleCaptureRoute({ nativeWindowsPane: {}, tmuxBacked: true }, true)).toBe('none')})diff --git a/src/core/watch-link/capture-route.ts b/src/core/watch-link/capture-route.tsindex 14ba7ba22..c0ff10135 100644--- a/src/core/watch-link/capture-route.ts+++ b/src/core/watch-link/capture-route.ts@@ -3,10 +3,12 @@// 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, and neither has-// a Zellij session (the optional local backend, zellij-backend.ts).+// Which backend gets one (`visibleCaptureRoute`): the session host answers its own negotiated+// `captureVisible` from its headless emulator (route `sessionHost`; an older host without the feature+// answers nothing, never its ~200-line scrollback `capture`). A direct Windows pane has no visible-only+// read, so it gets NO keyframe (the viewer starts from the live stream) rather than history. A plain+// shell has no tmux to ask, and neither has a Zellij session (the optional local backend,+// zellij-backend.ts).//// The screen and the cursor are read in ONE tmux invocation (`capture-pane … ; display-message …`), so// both describe the same instant: a cursor read in a second round trip could describe a screen that has@@ -28,13 +30,16 @@/*** What a visible-only capture returns: the screen and the cursor, read at one instant.*- * Deliberately NO alternate-screen flag (controller ruling R18). A keyframe's `altScreen` is decided- * by the CALLER from the join (a tmux-backed client ⇒ `true`), not from the capture: a watcher+ * No alternate-screen flag on the tmux and SSH routes (controller ruling R18). A keyframe's `altScreen`+ * is decided by the CALLER from the join (a tmux-backed client ⇒ `true`), not from the capture: a watcher* co-attaches to the tmux CLIENT's output, and tmux paints its client on the alternate screen* whatever the pane's application does, so every `tmux`/`ssh`-route join means `altScreen: true`.* The pane's own `#{alternate_on}` (vim, a TUI) describes a different screen — a shell pane reads 0* while the stream is on the alternate screen — and mapping it into the keyframe would scroll every* tmux redraw into the viewer's history.+ *+ * The SESSION-HOST route is the exception and sets `altScreen` itself: there is no tmux client between+ * the pane and the stream, so the emulator's active buffer is exactly the stream's.*/export interface VisibleCapture {/** The visible screen with SGR, byte-identical to what `capture-pane -p -e` prints on its own@@ -49,6 +54,9 @@ export interface VisibleCapture {* "no capture" would erase everything the stream had drawn. The link host sends no keyframe for it.*/unavailable?: true+ /** Set ONLY by the `sessionHost` route (see above); the link host then uses it instead of the+ * join's. Absent on every tmux/SSH capture. */+ altScreen?: boolean}/** A session with no visible-only capture, or one that failed: nothing to paint, nothing known. */@@ -59,11 +67,12 @@ export function unavailableCapture(): VisibleCapture {export function visibleCaptureRoute(s: { sessionHost?: unknown; nativeWindowsPane?: unknown; sshRemote?: unknown; tmuxBacked?: boolean; zellij?: boolean },tmuxAvailable: boolean-): 'none' | 'ssh' | 'tmux' {+): 'none' | 'ssh' | 'tmux' | 'sessionHost' {// A Zellij session is `tmuxBacked` too (that field means "releasing a client destroys nothing"),// but there is no tmux session to capture: never aim the tmux socket at it (pty-manager's rule// for every path that would talk to tmux). No keyframe — the viewer starts from the live stream.- if (s.sessionHost || s.nativeWindowsPane || s.zellij) return 'none'+ if (s.nativeWindowsPane || s.zellij) return 'none'+ if (s.sessionHost) return 'sessionHost'if (s.sshRemote) return 'ssh'return tmuxAvailable && s.tmuxBacked ? 'tmux' : 'none'}diff --git a/src/core/watch-link/link-host.test.ts b/src/core/watch-link/link-host.test.tsindex 10565cee2..ac8284ba6 100644--- a/src/core/watch-link/link-host.test.ts+++ b/src/core/watch-link/link-host.test.ts@@ -352,6 +352,16 @@ describe('createLinkHost — a viewer session', () => {expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: '', altScreen: false })})+ it("a session-host capture states its own altScreen, which wins over the join's (no tmux client between)", async () => {+ const t = setup({+ join: () => ({ sessionId: 's1', cols: 80, rows: 24, altScreen: false }),+ capture: () => ({ screen: 'vim\n', cursor: { x: 0, y: 0 }, altScreen: true })+ })+ t.host.start()+ const v = await openViewer(t)+ expect(v.keyframes()[0]).toEqual({ sessionId: 's1', screen: 'vim\n', altScreen: true, cursor: { x: 0, y: 0 } })+ })+it("denies a peer whose key is not the link's viewer key, and reopens a listener", async () => {const t = setup()t.host.start()diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.tsindex e7f9b5ecb..5a4d5cd55 100644--- a/src/core/watch-link/link-host.ts+++ b/src/core/watch-link/link-host.ts@@ -96,9 +96,9 @@// keyframe needs a capture STARTED after it asked. A per-viewer sequence makes sure an older result// is never painted after a newer one, and streaming resumes only on the newest.//-// NO CAPTURE IS NOT AN EMPTY SCREEN (R36). A backend with no visible-only capture (the Windows session-// host, a direct Windows pty, a plain shell) and a capture that failed answer `unavailable`, and then-// NO keyframe is sent: the viewer paints a keyframe as reset + clear, so an empty one would erase what+// NO CAPTURE IS NOT AN EMPTY SCREEN (R36). A backend with no visible-only capture (a session host from+// a build before `captureVisible`, a direct Windows pty, a plain shell) and a capture that failed answer+// `unavailable`, and then NO keyframe is sent: the viewer paints a keyframe as reset + clear, so an empty one would erase what// the stream had drawn. The viewer follows the stream instead (at the join it still gets meta), and a// throttled viewer resumes streaming without a repaint. Residual: on such a backend a throttled// viewer shows gaps until the application repaints them.@@ -465,7 +465,12 @@ function normalizeCapture(c: unknown): VisibleCapture {if ((c as VisibleCapture).unavailable === true) return unavailableCapture()const cur = (c as VisibleCapture).cursorconst ok = !!cur && Number.isInteger(cur.x) && Number.isInteger(cur.y) && cur.x >= 0 && cur.y >= 0- return { screen: (c as VisibleCapture).screen, cursor: ok ? { x: cur!.x, y: cur!.y } : null }+ const alt = (c as VisibleCapture).altScreen+ return {+ screen: (c as VisibleCapture).screen,+ cursor: ok ? { x: cur!.x, y: cur!.y } : null,+ ...(typeof alt === 'boolean' ? { altScreen: alt } : {})+ }}export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinkHost {@@ -675,7 +680,8 @@ export function createLinkHost(record: WatchLinkRecord, deps: LinkHostDeps): LinsessionId: sid,// A FRESH filter: the capture starts in ground state, and carries OSC 8 links verbatim (R9).screen: createStreamFilter().push(cap.screen),- altScreen: c.altScreen,+ // The join's answer (R18), unless the capture knows the stream's buffer itself (session host).+ altScreen: cap.altScreen ?? c.altScreen,...(cap.cursor ? { cursor: { x: cap.cursor.x, y: cap.cursor.y } } : {})}if (!send(c, WATCH_EVENT.keyframe, kf)) returndiff --git a/src/renderer/lib/liveLink.test.ts b/src/renderer/lib/liveLink.test.tsindex 550043ee1..8578cc663 100644--- a/src/renderer/lib/liveLink.test.ts+++ b/src/renderer/lib/liveLink.test.ts@@ -385,6 +385,17 @@ describe('watchableOnlyWhileOpen', () => {expect(watchableOnlyWhileOpen({ persistence: undefined, remoteNode: false })).toBe(false)expect(watchableOnlyWhileOpen({ persistence: null, remoteNode: false })).toBe(false)})++ it('a session host that speaks watch-attach can be watched with the node closed', () => {+ const p = (backend: string | null, watchJoin?: boolean, enabled = true) => ({ enabled, backend, watchJoin })+ expect(watchableOnlyWhileOpen({ persistence: p('session-host', true), remoteNode: false })).toBe(false)+ // An older running host, or one not connected yet: the conservative note stays.+ expect(watchableOnlyWhileOpen({ persistence: p('session-host', false), remoteNode: false })).toBe(true)+ expect(watchableOnlyWhileOpen({ persistence: p('session-host'), remoteNode: false })).toBe(true)+ // The flag is the session host's alone, and persistence switched off still wins.+ expect(watchableOnlyWhileOpen({ persistence: p('zellij', true), remoteNode: false })).toBe(true)+ expect(watchableOnlyWhileOpen({ persistence: p('session-host', true, false), remoteNode: false })).toBe(true)+ })})// R64/M3: the stream follows the terminal CLIENT, so tmux's chooser and a session switch reach viewers.diff --git a/src/renderer/lib/liveLink.ts b/src/renderer/lib/liveLink.tsindex bb66edb01..90b90178b 100644--- a/src/renderer/lib/liveLink.ts+++ b/src/renderer/lib/liveLink.ts@@ -374,17 +374,23 @@ export function capUnits(s: string, max: number): string {/*** R63: whether a link to a node can be watched ONLY while the node is open in this app. A viewer joins* a session this process holds (the canvas node, a parked view) or — with nothing held — spawns its- * own read-only tmux client; a machine whose LOCAL terminals are not tmux (Windows' session host, tmux- * switched off or missing, Zellij) has no such client. An SSH project's node runs in the HOST's tmux,- * which does. Unknown (the status not read yet, or unreadable) claims nothing: the popover's waiting- * line still tells the truth at runtime.+ * own read-only tmux client; a machine whose LOCAL terminals are not tmux (tmux switched off or+ * missing, Zellij) has no such client. The session host has its read-only equivalent (`watch-attach`)+ * when the running host speaks it (`watchJoin`); one from an older build does not. An SSH project's+ * node runs in the HOST's tmux, which does. Unknown (the status not read yet, or unreadable) claims+ * nothing: the popover's waiting line still tells the truth at runtime.*/export function watchableOnlyWhileOpen(o: {- persistence: { enabled: boolean; backend: string | null } | null | undefined+ persistence:+ | { enabled: boolean; backend: string | null; watchJoin?: boolean }+ | null+ | undefinedremoteNode: boolean}): boolean {if (o.remoteNode || !o.persistence) return false- return !(o.persistence.enabled && o.persistence.backend === 'tmux')+ if (!o.persistence.enabled) return true+ if (o.persistence.backend === 'tmux') return false+ return !(o.persistence.backend === 'session-host' && o.persistence.watchJoin === true)}export function watchWhileOpenNote(): string {return `On ${thisMachine()}, viewers can watch this terminal only while it is open in nodeterm; otherwise they wait until you open it.`diff --git a/src/shared/types.ts b/src/shared/types.tsindex 679d2e87a..7fda72fd9 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -1201,7 +1201,13 @@ export interface TmuxStatus {/** tmux discovery only; retained for older callers and install polling. */available: boolean/** Absent on older peers; null when discovery could not be read. */- persistence?: { enabled: boolean; backend: 'tmux' | 'zellij' | 'session-host' | null } | null+ persistence?: {+ enabled: boolean+ backend: 'tmux' | 'zellij' | 'session-host' | null+ /** Session host only: the CONNECTED host speaks `watch-attach`, so a live link viewer can join a+ * node nobody holds open. Absent = no / not known yet. */+ watchJoin?: boolean+ } | null/*** The optional Zellij backend (@shared/session-backend): whether a `zellij` binary was found and* whether this machine's setting selects it for NEW local terminals. Absent on older peers and on