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): control-mode shadows for released sessions

enes023f01364bb8
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index dbed0cf4a..6d403c45a 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -33,6 +33,7 @@ import { parsePaneCursor } from './pane-cursor'
import { readSpawnResources, spawnResourceNote } from './spawn-resources'
import { primePtyCeiling, readPtyDevices, spawnFailureHint } from './pty-devices'
import { REAP_SWEEP_MS, shouldReap } from './pty-reap'
+import { ControlModeClient, type ControlSpawn } from './tmux-control-client'
import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { bracketedInjection } from './paste-injection'
import { releasePty, type ReleasablePty } from './pty-release'
@@ -469,6 +470,20 @@ export const TOMBSTONE_TTL_MS = 24 * 60 * 60 * 1000
*/
export const PTY_END_BUDGET = { perSec: 20, burst: 200 }
+/**
+ * How long a command issued to a SHADOW may go unanswered before that shadow is torn down.
+ *
+ * `ControlModeClient` has no timers of its own, deliberately (tmux-control-client.ts): it pairs
+ * replies with commands POSITIONALLY, so a reply that never arrives does not merely stall one
+ * caller — every later reply pairs with the wrong command, permanently, and there is no recovery
+ * short of a new client. That is why the timeout disposes rather than retries.
+ *
+ * Five seconds is orders of magnitude past what it bounds: the only command a shadow issues today
+ * is a local `refresh-client -C` over a pipe to a tmux server on this machine (sub-millisecond).
+ * Hitting it means the server is wedged or the pipe is dead, not that it is busy.
+ */
+export const SHADOW_CMD_TIMEOUT_MS = 5_000
+
/**
* Manages all live PTY processes and bridges them to the renderer over IPC.
*
@@ -537,6 +552,37 @@ export class PtyManager {
/** ONE shared sweep for the idle reap (see `reapTick` / pty-reap.ts), armed by the first
* tmux-backed session and cleared once no session is left. */
private reapTimer: ReturnType<typeof setInterval> | null = null
+ /**
+ * persistKey (node id) → the control-mode SHADOW attached to that node's tmux session.
+ *
+ * Keyed by persistKey rather than held on `Session`, because the nodes a shadow exists for are
+ * exactly the ones that HAVE no `Session`: `releaseClient` → `forget` drops the entry from
+ * `sessions` and `byPersistKey` the moment the pty client is released, and what survives is the
+ * tmux session — which is the thing a shadow attaches to.
+ *
+ * This map IS the invariant. An entry here means no painter pty client of ours is attached for
+ * that node: `shadowAttach` refuses while one is, and `spawnSession` disposes the entry before
+ * spawning one. Nothing else may put a client in here.
+ */
+ private shadows = new Map<string, ControlModeClient>()
+ /**
+ * persistKey (node id) → the last effective size this manager pushed into that node's pty before
+ * releasing it. With only a control client attached, the pane's size follows
+ * `refresh-client -C <cols>x<rows>`, so this is what a shadow re-asserts on attach.
+ *
+ * It deliberately outlives the `Session` (the tmux session outlives it too) and is dropped when
+ * the node is destroyed. Growth is one small record per tmux-backed node this process has ever
+ * released — the same order as the session map itself, and rewritten rather than appended on
+ * every subsequent release.
+ */
+ private lastSize = new Map<string, PtySize>()
+ /** The child-process seam for shadow clients. Undefined in production, where `ControlModeClient`
+ * uses `child_process` (see tmux-control-client.ts); tests inject a fake spawner. */
+ private readonly controlSpawn: ControlSpawn | undefined
+
+ constructor(deps: { controlSpawn?: ControlSpawn } = {}) {
+ this.controlSpawn = deps.controlSpawn
+ }
private ensureSnapshotTimer(): void {
if (this.snapshotTimer) return
@@ -618,10 +664,131 @@ export class PtyManager {
// Skipped when nothing arrived since the last periodic capture (pane content is unchanged).
if (session.persistKey && session.outputSinceSnapshot)
void this.snapshotScrollback(session.persistKey, session.sshRemote)
+ // Remember the grid the painter last enforced. It is the only record of it that survives this
+ // call (the Session goes with `forget` below), and a shadow attached later re-asserts it —
+ // otherwise the pane could reflow and the user would come back to a rewrapped screen.
+ if (session.persistKey && session.appliedSize)
+ this.lastSize.set(session.persistKey, session.appliedSize)
releasePty(session.proc as ReleasablePty)
this.forget(sessionId, session)
}
+ /**
+ * Attach a control-mode SHADOW to the tmux session of a node whose painter pty client has been
+ * released — `tmux -C attach-session` over plain pipes, holding ZERO pty devices — so a
+ * background feature can reach a session nobody is watching without respawning the terminal (a
+ * pty device, a tmux client, an ssh child, and a full redraw the user never asked for).
+ *
+ * Attach-or-reuse; returns the live client, or null when there is nothing to shadow or nothing to
+ * shadow it with:
+ * - tmux is unavailable or switched off: there is no tmux session to attach to, and a non-tmux
+ * session's work lives in the pty client that is already gone.
+ * - a PAINTER pty client is still attached for this node. A session never has both: the painter
+ * attaches with `-D` (it would kick the shadow off a moment later anyway), and two clients of
+ * ours on one pane would hand tmux the size negotiation that pty-size.ts exists to keep.
+ * - the shadow was torn down while its opening size push was outstanding (see `shadowCommand`).
+ *
+ * WHAT A SHADOW IS NOT: not a subscriber, not a `Session`, not a renderer client id. Nothing that
+ * decides "is somebody watching" can see it — the reap sweep asks `platform().clientIds()` and
+ * walks `this.sessions`, the renderer's park and the offscreen dispose are per-node renderer
+ * state — so a shadow can never keep a session looking watched. (It IS a real tmux client and
+ * does appear in `tmux list-clients`; nothing in this app asks tmux that question.)
+ */
+ async shadowAttach(persistKey: string): Promise<ControlModeClient | null> {
+ // Both halves of "is there a tmux session at all": the binary, and the setting that decides
+ // whether sessions are spawned under it. With tmux switched OFF, `tmuxPath` is still set (the
+ // binary is installed) but every session is a plain shell — so a shadow would attach to a name
+ // nothing ever created and die on arrival, and its caller would read that as "reached it".
+ if (!this.tmuxPath || !this.getSettings().tmuxEnabled) return null
+ const live = this.shadows.get(persistKey)
+ if (live?.alive) return live
+ // Died since it was attached (its `onExit` normally clears the entry; this covers a caller that
+ // gets here first). Re-attaching is LAZY on purpose: nothing re-shadows a session nobody asked
+ // about, so a node that is never wanted again costs nothing.
+ if (live) this.shadows.delete(persistKey)
+ if (this.sessionByPersistKey(persistKey)) return null
+ const client = new ControlModeClient({
+ tmuxBin: this.tmuxPath,
+ socket: TMUX_SOCKET,
+ sessionName: sessionName(persistKey),
+ // Nothing consumes a shadowed session's output yet (the first consumer, Task 4's background
+ // write path, only WRITES). Dropping it keeps `%output`'s ~4x octal inflation off the main
+ // thread until something actually asks for the bytes.
+ onOutput: () => {},
+ // An UNEXPECTED death only — `dispose()` is silent by design, so this can never fire for a
+ // swap-out we asked for. Forget the entry and stop there: the tmux session, its processes and
+ // its scrollback are untouched, and the next `shadowAttach` re-attaches.
+ onExit: () => {
+ if (this.shadows.get(persistKey) === client) this.shadows.delete(persistKey)
+ },
+ spawner: this.controlSpawn
+ })
+ this.shadows.set(persistKey, client)
+ client.start()
+ const size = this.lastSize.get(persistKey)
+ if (size) {
+ const line = `refresh-client -C ${size.cols}x${size.rows}`
+ const reply = await this.shadowCommand(persistKey, line)
+ // Only a torn-down shadow (timeout, or death under us) fails the attach. tmux REFUSING the
+ // size (`%error`) leaves a perfectly usable client and a pane at its standing size, which is
+ // the same outcome as having no size to push.
+ if (reply === null) return null
+ }
+ // NO recorded size pushes nothing, deliberately: the pane keeps the standing size it has had
+ // since its last painter, and inventing one here would reflow a pane that is perfectly fine.
+ // (A relay-served pty released without ever reporting a size is exactly that case.)
+ //
+ // Re-read the map rather than returning `client`: a `create()` may have swapped this shadow out
+ // for a painter across the await above, and handing back a disposed client would look live.
+ return this.shadows.get(persistKey) ?? null
+ }
+
+ /** Retire a node's shadow, if it has one. Idempotent. The entry is dropped HERE because
+ * `dispose()` is silent (it does not fire `onExit`) — a deliberate swap-out is not a death. */
+ shadowDispose(persistKey: string): void {
+ const client = this.shadows.get(persistKey)
+ if (!client) return
+ this.shadows.delete(persistKey)
+ client.dispose()
+ }
+
+ /**
+ * Run ONE control-mode command on a node's shadow, bounded by `SHADOW_CMD_TIMEOUT_MS`. EVERY
+ * command issued to a shadow must go through here: the client owns no timers, and a reply that
+ * never comes desyncs its positional FIFO for good — so the timeout is a teardown, not a retry.
+ *
+ * Returns the reply (`ok` is tmux's own verdict), or null when there is no shadow, or when the
+ * command timed out / the client died — in which case the shadow is gone and a caller that still
+ * wants one asks `shadowAttach` for a fresh client.
+ */
+ private async shadowCommand(
+ persistKey: string,
+ line: string
+ ): Promise<{ ok: boolean; body: string[] } | null> {
+ const client = this.shadows.get(persistKey)
+ if (!client) return null
+ let timer: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ client.command(line),
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(
+ () => reject(new Error(`tmux control-mode command timed out: ${line}`)),
+ SHADOW_CMD_TIMEOUT_MS
+ )
+ timer.unref?.()
+ })
+ ])
+ } catch {
+ // Only if it is still OUR client: a shadow replaced across the await was already disposed by
+ // whoever replaced it, and disposing again would take down a healthy successor.
+ if (this.shadows.get(persistKey) === client) this.shadowDispose(persistKey)
+ return null
+ } finally {
+ if (timer) clearTimeout(timer)
+ }
+ }
+
/** Must run after app is ready (needs userData path). */
init(getSettings: () => Settings): void {
this.getSettings = getSettings
@@ -1157,6 +1324,17 @@ export class PtyManager {
clientId: ClientId | null,
sinks: DetachedSinks | undefined
): string {
+ // SWAP-OUT, before anything at all is spawned: a painter pty client is arriving for this node,
+ // and a session never has both. The painter attaches with `-D` and would kick the shadow off by
+ // itself — but only once tmux has processed both attaches, leaving a window where two clients
+ // of ours negotiate one pane. Retiring it first (politely: `dispose()` sends `detach-client`)
+ // means exactly one client is ever attached, and because `dispose()` is silent this can never
+ // be mistaken for a shadow that died and wants re-attaching.
+ //
+ // Here rather than in `create()` so EVERY path to a painter is covered — the warm reattach, the
+ // relay host's `attachDetached`, and whatever spawns next — and so the ordering is provable:
+ // it is the first statement before `pty.spawn` in the same synchronous function.
+ if (options.persistKey) this.shadowDispose(options.persistKey)
const sessionId = `pty-${++this.counter}`
// For a remote (ssh-project) node the local PTY just holds the ssh client, so its local cwd
// must be a real LOCAL directory (options.cwd is a REMOTE path that wouldn't exist locally and
@@ -2261,6 +2439,11 @@ export class PtyManager {
// Also drop any in-flight create for this node: a create racing the kill-session below must
// spawn a fresh session, not await (and then join) the one we are ending.
this.inflight.delete(persistKey)
+ // The tmux session is about to be killed, so everything attached to it goes now: a shadow would
+ // otherwise linger until tmux dropped its client, and the size we remembered describes a pane
+ // that is about to stop existing.
+ this.shadowDispose(persistKey)
+ this.lastSize.delete(persistKey)
// A DELETE is remembered (the respawn guard for clients `pty:closed` cannot reach — see
// `tombstones`); a RECYCLE explicitly forgets, because the node is not going anywhere and its
// replacement session must be spawnable. Recorded even when no live session exists in this
@@ -2357,6 +2540,10 @@ export class PtyManager {
finals.push(this.snapshotScrollback(session.persistKey, session.sshRemote))
releasePty(session.proc as ReleasablePty)
}
+ // Shadows are child processes of OURS, so quitting takes them with us — the tmux sessions they
+ // were attached to keep running with no client at all, which is exactly what persistence means.
+ for (const persistKey of [...this.shadows.keys()]) this.shadowDispose(persistKey)
+ this.lastSize.clear()
this.sessions.clear()
this.byPersistKey.clear()
// Pending recycle notices die with the sessions they were waiting on (their timers would
diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.ts
new file mode 100644
index 000000000..378e6a95d
--- /dev/null
+++ b/src/core/pty-shadow.test.ts
@@ -0,0 +1,394 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { initPlatform, resetPlatformForTests } from './platform'
+import { fakePlatform, type FakePlatform } from './platform-fake'
+import { IPC } from '../shared/ipc'
+import { DEFAULT_SETTINGS } from '../shared/types'
+import { TMUX_SOCKET, sessionName } from './tmux-naming'
+import { REAP_IDLE_MS, REAP_SWEEP_MS } from './pty-reap'
+import type { ControlSpawn } from './tmux-control-client'
+
+/**
+ * SHADOW CLIENTS: a tmux control-mode (`-C`) client over plain pipes, attached to the tmux session
+ * of a node whose PAINTER pty client has already been released — the idle reap's stranded ones, and
+ * the ones a plain `pty:kill` (last subscriber out, offscreen dispose) let go immediately. It holds
+ * ZERO pty devices, which is what lets a background feature reach a node nobody is watching without
+ * respawning a terminal (a pty device, a tmux client, an ssh child and a full redraw).
+ *
+ * Two invariants carry the whole design, and most of what follows asserts one of them:
+ * - a node never has a live painter AND a live shadow at the same time;
+ * - a shadow is INVISIBLE to everything that asks "is somebody watching" — the reap sweep (which
+ * decides against `platform().clientIds()`), the renderer's 5-minute park and the 10-minute
+ * offscreen dispose. It is not a subscriber, not a `Session`, and not a renderer client id.
+ */
+
+/** One fake pty per spawn. `killed` is what a released client pty looks like from here. */
+interface FakePty {
+ onDataCb?: (d: string) => void
+ onExitCb?: (e: { exitCode: number }) => void
+ killed: boolean
+}
+const spawned: FakePty[] = []
+/** Spawn/dispose events across BOTH child kinds, so a test can assert their relative ORDER. */
+const log: string[] = []
+
+vi.mock('node-pty', () => ({
+ spawn: () => {
+ const p: FakePty = { killed: false }
+ spawned.push(p)
+ log.push('pty-spawn')
+ return {
+ onData: (cb: (d: string) => void) => {
+ p.onDataCb = cb
+ },
+ onExit: (cb: (e: { exitCode: number }) => void) => {
+ p.onExitCb = cb
+ },
+ write: () => {},
+ resize: () => {},
+ pause: () => {},
+ resume: () => {},
+ kill: () => {
+ p.killed = true
+ },
+ pid: 1
+ }
+ }
+}))
+
+/** Every tmux side-call goes through child_process; `liveTmuxSessions` answers `has-session`. */
+const liveTmuxSessions = new Set<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
+ const ok = (stdout: string): void => cb?.(null, { stdout, stderr: '' })
+ if (args.includes('has-session')) {
+ const target = args[args.indexOf('-t') + 1]
+ if (liveTmuxSessions.has(target)) ok('')
+ else cb?.(Object.assign(new Error('no such session'), { code: 1 }))
+ } else if (args[0] === '-ilc') {
+ ok('__NT_PATH_START__/usr/bin:/bin__NT_PATH_END__')
+ } else {
+ ok('')
+ }
+ return {}
+ }
+ return { execFile, execFileSync: (): string => '' }
+})
+
+/** One fake control-mode child per shadow: what was written to it, and whether it was killed. */
+interface FakeControlChild {
+ writes: string[]
+ killed: number
+ exit(code: number | null): void
+ feed(latin1: string): void
+}
+
+/**
+ * The injected `ControlSpawn`. It answers commands like a healthy tmux does — ASYNCHRONOUSLY (a
+ * reply delivered inside the `write` call would arrive before the client had queued its resolver,
+ * which is not a thing the real protocol can do) — and `autoReply = false` plays the wedged tmux
+ * that takes a command and never answers.
+ */
+class FakeControlSpawn implements ControlSpawn {
+ calls: Array<{ bin: string; args: string[] }> = []
+ children: FakeControlChild[] = []
+ autoReply = true
+ private num = 0
+ spawn(bin: string, args: string[]) {
+ this.calls.push({ bin, args })
+ log.push('control-spawn')
+ let onData: ((b: Buffer) => void) | undefined
+ let onExit: ((code: number | null) => void) | undefined
+ const child: FakeControlChild = {
+ writes: [],
+ killed: 0,
+ exit: (code) => onExit?.(code),
+ feed: (s) => onData?.(Buffer.from(s, 'latin1'))
+ }
+ this.children.push(child)
+ return {
+ stdin: {
+ write: (s: string) => {
+ child.writes.push(s)
+ // `detach-client` is the disposal handshake, not a command with a reply.
+ if (!this.autoReply || s.startsWith('detach-client')) return
+ const n = ++this.num
+ // A real microtask (not a timer): tests run under fake timers.
+ void Promise.resolve().then(() =>
+ child.feed(`%begin 1700 ${n} 0\n%end 1700 ${n} 0\n`)
+ )
+ }
+ },
+ stdout: {
+ on: (_ev: 'data', cb: (b: Buffer) => void) => {
+ onData = cb
+ }
+ },
+ on: (_ev: 'exit', cb: (code: number | null) => void) => {
+ onExit = cb
+ },
+ kill: () => {
+ child.killed++
+ log.push('control-kill')
+ }
+ }
+ }
+ get only(): FakeControlChild {
+ return this.children[0]
+ }
+}
+
+const ALICE = 1
+const BOB = 2
+
+describe('control-mode shadow clients for released sessions', () => {
+ let fake: FakePlatform
+ let userDataDir: string
+ let control: FakeControlSpawn
+
+ beforeEach(() => {
+ spawned.length = 0
+ log.length = 0
+ liveTmuxSessions.clear()
+ control = new FakeControlSpawn()
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-shadow-'))
+ fake = fakePlatform({ userDataDir })
+ initPlatform(fake)
+ vi.useFakeTimers()
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ // Best effort, as in pty-idle-reap.test.ts: a fired-and-forgotten scrollback snapshot can still
+ // be landing here, and a cleanup that fails the suite is worse than a leftover dir.
+ try {
+ fs.rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 })
+ } catch {
+ /* a temp dir we could not remove is not a test result */
+ }
+ })
+
+ /** A manager WITH init(): tmux-backed, which is what a real user always gets. */
+ async function tmuxManager() {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager({ controlSpawn: control })
+ m.init(() => DEFAULT_SETTINGS)
+ m.registerIpc()
+ return m
+ }
+ /** A manager WITHOUT init(): no tmux, so there is no tmux session to shadow. */
+ async function plainManager() {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager({ controlSpawn: control })
+ m.registerIpc()
+ return m
+ }
+ const create = (clientId: number, persistKey = 'node-1', cols = 80, rows = 24) =>
+ fake.handlers[IPC.ptyCreate](clientId, { cols, rows, persistKey }) as Promise<{
+ sessionId: string
+ fresh: boolean
+ }>
+ /** pty:kill is sender-aware: it unsubscribes ONE view, and the last one out releases the pty. */
+ const kill = (clientId: number, sessionId: string) =>
+ fake.senderListeners[IPC.ptyKill](clientId, sessionId)
+ /** Run the sweep past the idle threshold (it only decides on its own ticks). */
+ const idle = (ms = REAP_IDLE_MS + REAP_SWEEP_MS) => vi.advanceTimersByTime(ms)
+ const attachArgs = (key: string) => ['-L', TMUX_SOCKET, '-C', 'attach-session', '-t', sessionName(key)]
+
+ it('shadows a session the reap stranded — over pipes, taking no pty device', async () => {
+ const m = await tmuxManager()
+ await create(ALICE) // …and Alice's window is then destroyed without a pty:kill ever arriving
+ idle()
+ expect(spawned[0].killed).toBe(true) // the sweep released her client pty
+
+ const shadow = await m.shadowAttach('node-1')
+
+ expect(shadow).not.toBeNull()
+ expect(control.calls).toEqual([{ bin: m.getTmuxBin(), args: attachArgs('node-1') }])
+ // The whole point: reaching the session cost no second pty.
+ expect(spawned).toHaveLength(1)
+ })
+
+ it('shadows a session released the instant its last subscriber left (the offscreen path)', async () => {
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId) // offscreen dispose / node unmount: zero subscribers, released at once
+
+ expect(spawned[0].killed).toBe(true)
+ expect(await m.shadowAttach('node-1')).not.toBeNull()
+ expect(control.calls).toHaveLength(1)
+ })
+
+ it('refuses while the painter pty client is attached — never both at once', async () => {
+ const m = await tmuxManager()
+ await create(ALICE)
+
+ expect(await m.shadowAttach('node-1')).toBeNull()
+ expect(control.calls).toHaveLength(0)
+ })
+
+ it('re-uses a live shadow instead of spawning a second control client', async () => {
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+
+ const first = await m.shadowAttach('node-1')
+ const second = await m.shadowAttach('node-1')
+
+ expect(second).toBe(first)
+ expect(control.calls).toHaveLength(1)
+ })
+
+ it('re-asserts the size the painter last enforced — a control client sizes the pane', async () => {
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE, 'node-1', 100, 30)
+ kill(ALICE, sessionId)
+
+ await m.shadowAttach('node-1')
+
+ // With only a control client attached the pane follows `refresh-client -C`; without this push
+ // the user would come back to a pane reflowed to somebody else's default.
+ expect(control.only.writes).toContain('refresh-client -C 100x30\n')
+ })
+
+ it('pushes no size when the released session never recorded one', async () => {
+ const m = await tmuxManager()
+ // A relay-served (detached) pty: its sink reports no size at create time, so this manager never
+ // enforced one. Pushing an invented size would reflow a pane that is perfectly fine.
+ const sessionId = m.attachDetached('node-1', { onData: () => {}, onExit: () => {} })
+ m.kill(null, sessionId)
+
+ await m.shadowAttach('node-1')
+
+ expect(control.only.writes.some((w) => w.startsWith('refresh-client'))).toBe(false)
+ })
+
+ it('is invisible to the reaper: not a watcher, and never swept up itself', async () => {
+ const m = await tmuxManager()
+ await create(ALICE, 'node-1')
+ idle()
+ await m.shadowAttach('node-1')
+
+ // A second node is opened and abandoned the same way. If the shadow had registered anywhere the
+ // sweep looks — a client id, a subscriber, a Session — it would show here: as a session that
+ // never becomes reapable, or as a shadow the sweep tore down.
+ await create(BOB, 'node-2')
+ idle()
+
+ expect(spawned[1].killed).toBe(true) // node-2 still reaps ⇒ clientIds() is unpolluted
+ expect(control.only.killed).toBe(0) // the sweep does not touch a shadow…
+ expect(control.calls).toHaveLength(1) // …and never attaches one either
+ })
+
+ it('disposes the shadow BEFORE spawning the painter when the node comes back', async () => {
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+ await m.shadowAttach('node-1')
+ liveTmuxSessions.add(sessionName('node-1')) // tmux kept it running, as it does across a detach
+ log.length = 0
+
+ await create(ALICE) // the node scrolls back into view / the user reopens the project
+
+ // Order is the assertion: the painter attaches with `-D` and would kick the shadow off anyway,
+ // but only after tmux has processed both attaches — so the shadow goes first, and exactly one
+ // client of ours is ever negotiating the pane.
+ expect(log).toEqual(['control-kill', 'pty-spawn'])
+ expect(control.only.writes).toContain('detach-client\n') // detached politely, then killed
+ expect(spawned[1].killed).toBe(false) // the painter is live and untouched
+ })
+
+ it('leaves the session alone when its shadow dies, and re-attaches lazily on the next ask', async () => {
+ const m = await tmuxManager()
+ await create(ALICE)
+ idle()
+ await m.shadowAttach('node-1')
+
+ control.children[0].exit(1) // the control client died on its own (tmux restart, OOM kill)
+
+ // Nothing is resurrected on its behalf — no pty, no session, no eager re-attach.
+ expect(spawned).toHaveLength(1)
+ expect(control.calls).toHaveLength(1)
+
+ const again = await m.shadowAttach('node-1')
+
+ expect(again).not.toBeNull()
+ expect(control.calls).toEqual([
+ { bin: m.getTmuxBin(), args: attachArgs('node-1') },
+ { bin: m.getTmuxBin(), args: attachArgs('node-1') }
+ ])
+ })
+
+ it('disposes a shadow whose reply never comes — a lost reply desyncs the FIFO forever', async () => {
+ const { SHADOW_CMD_TIMEOUT_MS } = await import('./pty-manager')
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE, 'node-1', 100, 30)
+ kill(ALICE, sessionId)
+ control.autoReply = false // tmux takes the command and never answers
+
+ const attaching = m.shadowAttach('node-1')
+ await vi.advanceTimersByTimeAsync(SHADOW_CMD_TIMEOUT_MS)
+
+ expect(await attaching).toBeNull()
+ expect(control.only.killed).toBe(1)
+ // …and the entry is gone, so the next ask gets a fresh client rather than a desynced one.
+ control.autoReply = true
+ expect(await m.shadowAttach('node-1')).not.toBeNull()
+ expect(control.calls).toHaveLength(2)
+ })
+
+ it('destroying a node takes its shadow with it — the tmux session is going away', async () => {
+ const m = await tmuxManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+ await m.shadowAttach('node-1')
+
+ await m.destroySession(ALICE, 'node-1')
+
+ expect(control.only.killed).toBe(1)
+ })
+
+ it('app quit disposes every shadow', async () => {
+ const m = await tmuxManager()
+ const a = await create(ALICE, 'node-1')
+ const b = await create(BOB, 'node-2')
+ kill(ALICE, a.sessionId)
+ kill(BOB, b.sessionId)
+ await m.shadowAttach('node-1')
+ await m.shadowAttach('node-2')
+
+ await m.killAll()
+
+ expect(control.children.map((c) => c.killed)).toEqual([1, 1])
+ expect(control.children.every((c) => c.writes.includes('detach-client\n'))).toBe(true)
+ })
+
+ it('does nothing with tmux switched off in settings — no session is tmux-backed', async () => {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager({ controlSpawn: control })
+ m.init(() => ({ ...DEFAULT_SETTINGS, tmuxEnabled: false }))
+ m.registerIpc()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+
+ // The binary is right there, so `tmuxPath` alone would say yes — but nothing spawned a tmux
+ // session, so a shadow would attach to a name that does not exist and die on arrival.
+ expect(await m.shadowAttach('node-1')).toBeNull()
+ expect(control.calls).toHaveLength(0)
+ })
+
+ it('does nothing without tmux — there is no tmux session to shadow', async () => {
+ const m = await plainManager()
+ const { sessionId } = await create(ALICE)
+ kill(ALICE, sessionId)
+
+ expect(await m.shadowAttach('node-1')).toBeNull()
+ expect(control.calls).toHaveLength(0)
+ })
+})