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): background writes into released sessions, no painter respawn

enes2f3e60f0d3a7
diff --git a/src/core/pty-background-write.test.ts b/src/core/pty-background-write.test.ts
new file mode 100644
index 000000000..a781bfdc8
--- /dev/null
+++ b/src/core/pty-background-write.test.ts
@@ -0,0 +1,471 @@
+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, isSessionName } from './tmux-naming'
+import type { ControlSpawn } from './tmux-control-client'
+
+/**
+ * BACKGROUND WRITES: typing into a node whose PAINTER pty client has been released, without
+ * respawning one. `send-keys` is server-wide in control mode, so the fallthrough is
+ * painter → the node's own shadow (if one is already up) → ONE shared control client for the whole
+ * tmux server, started lazily on the first background write and disposed after a short linger.
+ *
+ * The harness is `pty-shadow.test.ts`'s, with one addition: the fake pty records what was written
+ * into it, because "the painter got the bytes" is half of what this file asserts.
+ */
+
+/** 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
+ writes: string[]
+ killed: boolean
+ /** node-pty throws on a write to a process that has already gone (as `resize` does). */
+ throwOnWrite: 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 = { writes: [], killed: false, throwOnWrite: 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: (d: string) => {
+ if (p.throwOnWrite) throw new Error('write EIO')
+ p.writes.push(d)
+ },
+ 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 client: 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
+
+/** `ls\n` as the wire sees it: hex bytes, because a control-mode command is one text line. */
+const LS_KEYS = (target: string): string => `send-keys -t ${target} -H 6c 73 0a\n`
+
+describe('background writes into 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-bgwrite-'))
+ fake = fakePlatform({ userDataDir })
+ initPlatform(fake)
+ vi.useFakeTimers()
+ })
+ afterEach(() => {
+ vi.useRealTimers()
+ vi.restoreAllMocks()
+ resetPlatformForTests()
+ // Best effort, as in pty-shadow.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 */
+ }
+ })
+
+ async function tmuxManager() {
+ const { PtyManager } = await import('./pty-manager')
+ const m = new PtyManager({ controlSpawn: control })
+ m.init(() => DEFAULT_SETTINGS)
+ 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)
+ /** Open a node and let it go — the state every background write in this file starts from. */
+ const release = async (clientId: number, persistKey: string) => {
+ const { sessionId } = await create(clientId, persistKey)
+ kill(clientId, sessionId)
+ return sessionId
+ }
+ const attachArgs = (key: string) => [
+ '-L',
+ TMUX_SOCKET,
+ '-C',
+ 'attach-session',
+ '-t',
+ sessionName(key)
+ ]
+
+ it('types into a released session over a control client — no pty, exact send-keys line', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+
+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)
+
+ expect(control.calls).toEqual([{ bin: m.getTmuxBin(), args: attachArgs('node-1') }])
+ expect(control.only.writes).toContain(LS_KEYS('nt-node-1'))
+ // The whole point: reaching the session cost no second pty device.
+ expect(spawned).toHaveLength(1)
+ expect(spawned[0].killed).toBe(true)
+ })
+
+ it('writes straight into the painter while the node is on screen — control clients untouched', async () => {
+ const m = await tmuxManager()
+ await create(ALICE, 'node-1')
+
+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)
+
+ expect(spawned[0].writes).toEqual(['ls\n'])
+ expect(control.calls).toHaveLength(0)
+ })
+
+ it('reports a failure rather than rejecting when the painter’s pty is already gone', async () => {
+ const m = await tmuxManager()
+ await create(ALICE, 'node-1')
+ spawned[0].throwOnWrite = true // node-pty throws on a write to a process that has exited
+
+ // `write()` fires this path and forgets it, so a rejection here would surface as an UNHANDLED
+ // rejection in the main process — a crash risk, from a pty that merely died first.
+ await expect(m.backgroundWrite('node-1', 'ls\n')).resolves.toBe(false)
+ })
+
+ it('prefers the node’s own shadow to the shared client', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.shadowAttach('node-1')
+
+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)
+
+ // One client, and it is the shadow that was already up: a second attach to the same session
+ // would put two clients of ours on one pane for nothing.
+ expect(control.calls).toHaveLength(1)
+ expect(control.only.writes).toContain(LS_KEYS('nt-node-1'))
+ })
+
+ it('starts ONE shared client for a burst of writes to different nodes', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await release(BOB, 'node-2')
+ await release(BOB, 'node-3')
+
+ await m.backgroundWrite('node-1', 'ls\n')
+ await m.backgroundWrite('node-2', 'ls\n')
+ await m.backgroundWrite('node-3', 'ls\n')
+
+ // `send-keys` is SERVER-wide: one attached client can target every session on the socket, so a
+ // burst costs one process, not one per node.
+ expect(control.calls).toHaveLength(1)
+ expect(control.only.writes).toEqual([
+ LS_KEYS('nt-node-1'),
+ LS_KEYS('nt-node-2'),
+ LS_KEYS('nt-node-3')
+ ])
+ })
+
+ it('disposes the shared client after the linger, and starts a fresh one for a later write', async () => {
+ const { BACKGROUND_WRITE_LINGER_MS } = await import('./pty-manager')
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.backgroundWrite('node-1', 'ls\n')
+
+ expect(control.only.killed).toBe(0)
+ vi.advanceTimersByTime(BACKGROUND_WRITE_LINGER_MS)
+
+ expect(control.only.writes).toContain('detach-client\n') // detached politely, then killed
+ expect(control.only.killed).toBe(1)
+
+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(true)
+ expect(control.calls).toHaveLength(2)
+ })
+
+ it('pushes the linger out on every background write', async () => {
+ const { BACKGROUND_WRITE_LINGER_MS } = await import('./pty-manager')
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ const almost = BACKGROUND_WRITE_LINGER_MS - 1
+
+ await m.backgroundWrite('node-1', 'ls\n')
+ vi.advanceTimersByTime(almost)
+ await m.backgroundWrite('node-1', 'ls\n')
+ vi.advanceTimersByTime(almost)
+
+ // A steady trickle of background writes keeps ONE client instead of churning a process per
+ // write — which is the entire reason the linger exists.
+ expect(control.only.killed).toBe(0)
+ expect(control.calls).toHaveLength(1)
+ vi.advanceTimersByTime(BACKGROUND_WRITE_LINGER_MS)
+ expect(control.only.killed).toBe(1)
+ })
+
+ it('refuses a released REMOTE node — its tmux lives on the far host, not on our socket', async () => {
+ const m = await tmuxManager()
+ const res = (await fake.handlers[IPC.ptyCreate](ALICE, {
+ cols: 80,
+ rows: 24,
+ persistKey: 'node-r',
+ sshRemote: { conn: { host: 'h1', user: 'u' }, controlPath: '/tmp/cm', remoteCwd: '/srv/app' }
+ })) as { sessionId: string }
+ expect(m.sshRemoteForNode('node-r')).toBeDefined() // the spawn really did take the remote branch
+ kill(ALICE, res.sessionId)
+
+ // `nt-node-r` on OUR socket is either nothing at all or — worse — the local orphan a create
+ // issued with the master down once left behind. Typing into that is typing into the wrong box.
+ expect(await m.backgroundWrite('node-r', 'ls\n')).toBe(false)
+ expect(control.calls).toHaveLength(0)
+ })
+
+ it('refuses a node it has no released record for — it cannot prove that session is ours', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+
+ // No record means this process never opened the node: `nt-<id>` on our socket could be a remote
+ // node's local orphan, or another machine's idea of it. Blind-writing it is the one thing a
+ // background feature must never do.
+ expect(await m.backgroundWrite('node-nobody-opened', 'ls\n')).toBe(false)
+ expect(control.calls).toHaveLength(0)
+ })
+
+ it('never retries a timed-out send-keys on another client — tmux may already have run it', async () => {
+ const { SHADOW_CMD_TIMEOUT_MS } = await import('./pty-manager')
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.shadowAttach('node-1')
+ control.autoReply = false // tmux takes the command and never answers
+
+ const writing = m.backgroundWrite('node-1', 'ls\n')
+ await vi.advanceTimersByTimeAsync(SHADOW_CMD_TIMEOUT_MS)
+
+ expect(await writing).toBe(false)
+ expect(control.only.killed).toBe(1) // the desynced client is gone…
+ expect(control.calls).toHaveLength(1) // …and nothing re-sent the keys anywhere else
+ })
+
+ it('falls through from a released session id — a stale write lands instead of vanishing', async () => {
+ const m = await tmuxManager()
+ const sessionId = await release(ALICE, 'node-1')
+
+ // The session id a caller was holding when the pty client went away (the relay host keeps one
+ // per stream). It resolves to no `Session` at all, and used to drop the bytes on the floor.
+ m.write(ALICE, sessionId, 'ls\n')
+ await vi.advanceTimersByTimeAsync(0)
+
+ expect(control.only.writes).toContain(LS_KEYS('nt-node-1'))
+ })
+
+ it('retires the shared client BEFORE the painter spawns when the node comes back', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.backgroundWrite('node-1', 'ls\n')
+ liveTmuxSessions.add(sessionName('node-1')) // tmux kept it running, as it does across a detach
+ log.length = 0
+
+ await create(ALICE, 'node-1')
+
+ // Same rule as a per-session shadow: 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')
+ })
+
+ it('yields to a shadow of the session it is attached to — one client of ours per session', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.backgroundWrite('node-1', 'ls\n')
+
+ await m.shadowAttach('node-1')
+
+ // Two of our clients on one session would break the session budget's "subtract one" arithmetic
+ // and put two grids on one pane. The shared client is the one that goes: it is re-startable
+ // anywhere, the shadow is not.
+ expect(control.only.killed).toBe(1)
+ expect(m.shadowedTmuxSessions(TMUX_SOCKET)).toEqual([sessionName('node-1')])
+ })
+
+ it('app quit disposes the shared client', async () => {
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.backgroundWrite('node-1', 'ls\n')
+
+ await m.killAll()
+
+ expect(control.only.killed).toBe(1)
+ expect(control.only.writes).toContain('detach-client\n')
+ })
+
+ it('is subtracted from the session budget, exactly like a shadow', async () => {
+ // A shared client is a real tmux client on whatever session it attached to, so it flips that
+ // session's `#{session_attached}` — and an attached session is never culled. Without the
+ // subtraction, one background write would exempt a session from the memory-pressure valve for
+ // as long as the client lingered.
+ const { createSessionReaper } = await import('./session-budget')
+ const m = await tmuxManager()
+ await release(ALICE, 'node-1')
+ await m.backgroundWrite('node-1', 'ls\n')
+
+ const NOW = 1_000_000
+ const OLD = NOW - 100_000 // well past the 6h grace window
+ const killed: Array<{ socket: string; target: string }> = []
+ const reaper = createSessionReaper({
+ tmuxBin: () => m.getTmuxBin(),
+ sockets: [TMUX_SOCKET],
+ shadowed: (socket) => m.shadowedTmuxSessions(socket),
+ exec: async (_bin: string, args: string[]) => {
+ if (args.includes('kill-session')) {
+ killed.push({
+ socket: args[args.indexOf('-L') + 1],
+ target: args[args.indexOf('-t') + 1]
+ })
+ return ''
+ }
+ // `nt-node-1` reads as attached because our shared client IS one; `nt-node-9` is genuinely
+ // attached (somebody is looking at it) and must survive.
+ return `nt-node-1|1|${OLD}\nnt-node-9|1|${OLD}`
+ },
+ readMem: () => ({ availableMb: 100, totalMb: 8000 }), // under the watermark: real pressure
+ env: {},
+ nowSec: () => NOW
+ })
+
+ expect(await reaper.sweep()).toBe(1)
+ expect(killed).toEqual([{ socket: TMUX_SOCKET, target: '=nt-node-1' }])
+ })
+
+ it('does nothing with tmux switched off in settings', 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 the keys would go to a name that does not exist.
+ expect(await m.backgroundWrite('node-1', 'ls\n')).toBe(false)
+ expect(control.calls).toHaveLength(0)
+ })
+})
+
+describe('isSessionName', () => {
+ // `encodeSendKeysHex` interpolates the target UNQUOTED into the command line, so anything that is
+ // not a name this app generated is refused before it is interpolated (Task 2 handoff note 12).
+ it('accepts the names sessionName generates', () => {
+ expect(isSessionName(sessionName('node-1'))).toBe(true)
+ expect(isSessionName(sessionName('Node_9-x'))).toBe(true)
+ })
+ it('rejects a name this app did not generate', () => {
+ expect(isSessionName('scratch')).toBe(false) // no nt- prefix: somebody else's session
+ expect(isSessionName('nt-')).toBe(false) // the empty node id
+ expect(isSessionName('nt-a b')).toBe(false) // a space splits the command line
+ expect(isSessionName('nt-a;kill-server')).toBe(false)
+ expect(isSessionName('nt-a\nkill-server')).toBe(false)
+ })
+})
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e53ebf835..6c7d55f5a 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -34,7 +34,8 @@ 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 { TMUX_SOCKET, sessionName, isSessionName } from './tmux-naming'
+import { encodeSendKeysHex } from './tmux-control'
import { bracketedInjection } from './paste-injection'
import { releasePty, type ReleasablePty } from './pty-release'
import { effectiveSize, type PtySize } from './pty-size'
@@ -484,6 +485,20 @@ export const PTY_END_BUDGET = { perSec: 20, burst: 200 }
*/
export const SHADOW_CMD_TIMEOUT_MS = 5_000
+/**
+ * How long the SHARED background-write control client stays attached after the last background
+ * write (see `backgroundWrite`).
+ *
+ * It exists so a BURST — an agent pushing a multi-line prompt, a run of slash commands — costs one
+ * `tmux -C` child instead of one per keystroke batch, and nothing more. Ten seconds is past any
+ * plausible gap inside one such burst and far short of every lifecycle it must not interfere with:
+ * the renderer's 5-minute park (`TERM_PARK_MS`), the 10-minute offscreen dispose
+ * (`offscreen-policy.ts`) and the 10-minute idle reap (`REAP_IDLE_MS`). That ordering is the point
+ * of picking a number this small: an idle client is a real tmux client on some session, and the
+ * shorter it lives the smaller the window in which anything has to reason about it at all.
+ */
+export const BACKGROUND_WRITE_LINGER_MS = 10_000
+
/**
* Manages all live PTY processes and bridges them to the renderer over IPC.
*
@@ -568,7 +583,10 @@ export class PtyManager {
/**
* persistKey (node id) → what a shadow needs to know about a session whose pty client this
* manager has RELEASED. Written by `releaseClient`, because `forget` then drops the `Session` and
- * with it the only other record of either fact:
+ * with it the only other record of any of these facts:
+ * - `sessionId`: the id that session answered to. A caller can still be holding it — the relay
+ * host keeps one per stream — and `write()` resolves it back to this node instead of dropping
+ * the bytes, which is the only route a released session has left to an existing write path.
* - `size`: the effective grid the painter last enforced. With only a control client attached
* the pane follows `refresh-client -C <cols>x<rows>`, so this is what a shadow re-asserts.
* - `remote`: this node's tmux ran on a REMOTE host (an SSH project) — over that project's
@@ -583,7 +601,23 @@ export class PtyManager {
* persisted node this process has ever released: the same order as the session map itself, and
* rewritten rather than appended on every subsequent release of the same node.
*/
- private released = new Map<string, { size?: PtySize; remote: boolean }>()
+ private released = new Map<string, { sessionId: string; size?: PtySize; remote: boolean }>()
+ /**
+ * The ONE control-mode client this manager keeps for background WRITES, plus the node whose tmux
+ * session it is attached to (see `backgroundWrite` / `sharedClientFor`).
+ *
+ * Shared rather than per-session because control-mode COMMANDS are server-wide: `send-keys -t X`
+ * reaches every session on the socket from whatever session the client happens to be attached to.
+ * Only `%output` streaming is scoped to the attachment, and this client streams nothing.
+ *
+ * `persistKey` is kept because the attachment is the one thing about it that is NOT server-wide:
+ * it makes this a real tmux client of THAT session, so it has to be subtracted from the session
+ * budget (`shadowedTmuxSessions`) and retired whenever something else wants to be that session's
+ * only client of ours — a painter spawning, or a per-session shadow attaching.
+ */
+ private shared: { client: ControlModeClient; persistKey: string } | null = null
+ /** Disposes `shared` once no background write has needed it for `BACKGROUND_WRITE_LINGER_MS`. */
+ private sharedLinger: ReturnType<typeof setTimeout> | null = null
/** 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
@@ -678,6 +712,7 @@ export class PtyManager {
// below; this is the record that survives it.
if (session.persistKey)
this.released.set(session.persistKey, {
+ sessionId,
size: session.appliedSize,
remote: !!session.sshRemote
})
@@ -732,6 +767,12 @@ export class PtyManager {
// name, which is a different machine's idea of the node and must never be typed into. Routing
// control mode over ssh is a separate job; refusing is the honest answer until it exists.
if (known?.remote) return null
+ // At most ONE client of ours per tmux session. The shared background-write client may already
+ // be attached to this one (it attaches to whatever session first needed a background write);
+ // it is the one that yields, because it can be re-started against any session and a shadow
+ // cannot. Two of ours here would also break the session budget's "subtract one client per
+ // shadowed name" arithmetic, which has no way to know it should subtract two.
+ this.sharedDisposeOn(persistKey)
const client = new ControlModeClient({
tmuxBin: this.tmuxPath,
socket: TMUX_SOCKET,
@@ -792,6 +833,11 @@ export class PtyManager {
const names: string[] = []
for (const [persistKey, client] of this.shadows)
if (client.alive) names.push(sessionName(persistKey))
+ // The shared background-write client is a tmux client of the session it attached to, exactly
+ // like a shadow, and is subtracted the same way. It can never DOUBLE with a shadow of that same
+ // session — `shadowAttach` retires it first — which is what keeps the budget's "minus one
+ // client per name" arithmetic (session-budget.ts) honest.
+ if (this.shared?.client.alive) names.push(sessionName(this.shared.persistKey))
return names
}
@@ -823,6 +869,23 @@ export class PtyManager {
): Promise<{ ok: boolean; body: string[] } | null> {
const client = this.shadows.get(persistKey)
if (!client) return null
+ return this.controlCommand(client, line, () => {
+ // 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)
+ })
+ }
+
+ /**
+ * The timeout that every control-mode command in this manager is issued under — the shared body
+ * of `shadowCommand` and of the shared background-write client's commands. `onBroken` is how the
+ * caller retires ITS client; this method never decides which registry a client lives in.
+ */
+ private async controlCommand(
+ client: ControlModeClient,
+ line: string,
+ onBroken: () => void
+ ): Promise<{ ok: boolean; body: string[] } | null> {
// Refuse a multi-line command HERE rather than letting the client refuse it below. Both answer
// null, but the difference is what happens to the shadow: the catch treats a rejection as
// evidence the channel is unusable and DISPOSES, which is right for a timeout or a death and
@@ -844,15 +907,147 @@ export class PtyManager {
})
])
} 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)
+ onBroken()
return null
} finally {
if (timer) clearTimeout(timer)
}
}
+ /**
+ * Type `data` into a node whose PAINTER pty client is gone, without spawning one.
+ *
+ * The fallthrough, in order:
+ * 1. **the painter**, if the node is on screen after all — the session's own pty, exactly as a
+ * keystroke from its terminal. (A caller holding a stale session id can land here; it is the
+ * same NODE either way, which is what the caller asked for.)
+ * 2. **the node's own shadow**, if one is already up. Never attaches one: a shadow exists to be
+ * re-used by whoever attached it, and a write does not need a session-scoped client.
+ * 3. **the shared control client** (`sharedClientFor`) — one `tmux -C` child for the whole
+ * server, because `send-keys -t <session>` is a server-wide command.
+ *
+ * Returns whether the keys were delivered. **A false is never retried on another client**: a
+ * timed-out `send-keys` may well have run — control mode loses the REPLY, not necessarily the
+ * command — so re-sending it elsewhere risks typing the input twice, which is worse than not
+ * typing it at all.
+ *
+ * REFUSALS, both of them the same rule — never write into a session this process cannot prove is
+ * the node's own local one:
+ * - a node with no `released` record: this process never released it, so `nt-<id>` on our socket
+ * is a name we have no claim to (a remote node's local orphan, another machine's idea of it, a
+ * session someone else made). An unknown key is not evidence of a session.
+ * - a node whose record says `remote`: its tmux is on the far host. Reaching it means the
+ * project's ControlMaster (`remoteTmuxSendKeysArgs`), not this channel; refusing is the honest
+ * answer until that exists.
+ */
+ async backgroundWrite(persistKey: string, data: string): Promise<boolean> {
+ // Nothing to type — and `encodeSendKeysHex` would build a `send-keys -H ` with no bytes after
+ // it, which is a command line worth not sending.
+ if (!data) return false
+ const live = this.sessionByPersistKey(persistKey)
+ if (live) {
+ try {
+ live.proc.write(data)
+ } catch {
+ // node-pty throws on a write to a process that has already exited (the same hazard
+ // `applySize` guards on resize). This method is called fire-and-forget from `write()`, so a
+ // throw would surface as an UNHANDLED rejection in the main process — the crash risk Task
+ // 2's handoff note 2 names. A dead painter is a delivery failure, not an exception.
+ return false
+ }
+ return true
+ }
+ if (!this.tmuxPath || !this.getSettings().tmuxEnabled) return false
+ const known = this.released.get(persistKey)
+ if (!known || known.remote) return false
+ const target = sessionName(persistKey)
+ // Belt and braces: `encodeSendKeysHex` interpolates the target UNQUOTED (Task 2 handoff note
+ // 12), and this line reaches a tmux server holding every session on the socket. `sessionName`
+ // cannot produce anything else today — which is exactly why this stays cheap.
+ if (!isSessionName(target)) return false
+ const line = encodeSendKeysHex(target, data)
+ const shadow = this.shadows.get(persistKey)
+ if (shadow) return (await this.shadowCommand(persistKey, line))?.ok ?? false
+ const client = this.sharedClientFor(persistKey)
+ if (!client) return false
+ return (await this.controlCommand(client, line, () => this.sharedDispose(client)))?.ok ?? false
+ }
+
+ /**
+ * The shared background-write client, started on demand and attached to `persistKey`'s session.
+ *
+ * WHICH session it attaches to is deterministic and deliberately the least interesting choice
+ * available: the session of the background write that needed it. That session was just proved to
+ * be local, released and ours — so the attach cannot land on a foreign session, and cannot put a
+ * second client of ours on a pane a painter is already drawing. Every command it then issues
+ * carries its own explicit `-t`, so the attachment never decides where the keys go.
+ *
+ * It pushes NO size, unlike a per-session shadow: it displays nothing, and `refresh-client -C`
+ * would resize the pane for whoever IS watching that session (their own `tmux attach`). The pane
+ * keeps the standing size its last painter left it at.
+ *
+ * Null when tmux is unavailable or the child could not be spawned (`child_process.spawn` throws
+ * synchronously on EMFILE and friends — the machine a background feature reaches for a client on).
+ */
+ private sharedClientFor(persistKey: string): ControlModeClient | null {
+ if (!this.tmuxPath) return null
+ this.armSharedLinger()
+ const live = this.shared
+ if (live?.client.alive) return live.client
+ if (live) this.shared = null // died since it was started; its onExit normally clears this
+ const client = new ControlModeClient({
+ tmuxBin: this.tmuxPath,
+ socket: TMUX_SOCKET,
+ sessionName: sessionName(persistKey),
+ // This client writes; it never reads. Dropping `%output` keeps its ~4x octal inflation off
+ // the main thread for every session on the server it happens to be attached to.
+ onOutput: () => {},
+ onExit: () => {
+ if (this.shared?.client === client) this.shared = null
+ },
+ spawner: this.controlSpawn
+ })
+ this.shared = { client, persistKey }
+ try {
+ client.start()
+ } catch {
+ this.shared = null
+ return null
+ }
+ return client
+ }
+
+ /** (Re)arm the linger: the client goes `BACKGROUND_WRITE_LINGER_MS` after the LAST write wanted
+ * it, so a burst keeps one child and a trickle does not churn one per write. */
+ private armSharedLinger(): void {
+ if (this.sharedLinger) clearTimeout(this.sharedLinger)
+ this.sharedLinger = setTimeout(() => this.sharedDispose(), BACKGROUND_WRITE_LINGER_MS)
+ // Node keeps the process alive for a pending timer, and this one must never be the reason a
+ // quitting app lingers (the other manager timers unref for the same reason).
+ this.sharedLinger.unref?.()
+ }
+
+ /** Retire the shared client. Idempotent. `only` makes it a no-op unless that exact client is
+ * still the current one — a caller reacting to a failure must not take down its successor. */
+ private sharedDispose(only?: ControlModeClient): void {
+ const live = this.shared
+ if (!live || (only && live.client !== only)) return
+ this.shared = null
+ if (this.sharedLinger) {
+ clearTimeout(this.sharedLinger)
+ this.sharedLinger = null
+ }
+ live.client.dispose()
+ }
+
+ /** Retire the shared client if it is attached to THIS node's session — for the two events that
+ * claim that session for another client of ours (a painter spawning, a shadow attaching) and for
+ * the one that ends it (`endSession`). Elsewhere it keeps lingering; the attachment is
+ * incidental, and it can be re-started against any session. */
+ private sharedDisposeOn(persistKey: string): void {
+ if (this.shared?.persistKey === persistKey) this.sharedDispose()
+ }
+
/** Must run after app is ready (needs userData path). */
init(getSettings: () => Settings): void {
this.getSettings = getSettings
@@ -1398,7 +1593,12 @@ export class PtyManager {
// 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)
+ // The shared background-write client goes too, for the same reason, when it is this node's
+ // session it happens to be attached to.
+ if (options.persistKey) {
+ this.shadowDispose(options.persistKey)
+ this.sharedDisposeOn(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
@@ -1992,12 +2192,36 @@ export class PtyManager {
*/
write(clientId: ClientId | null, sessionId: string, data: string): void {
const session = this.sessions.get(sessionId)
- if (!session) return
+ if (!session) return this.backgroundWriteBySessionId(sessionId, data)
if (clientId !== null && session.nodeId && presenceHub.peerCount() > 1)
presenceHub.noteTyping(clientId, session.nodeId)
session.proc.write(data)
}
+ /**
+ * The `write()` miss: no live session answers to this id. It may still be a session THIS process
+ * released — the pty client detached, the tmux session (and everything running in it) untouched —
+ * whose id a caller is still holding, which is what the relay host does for the lifetime of a
+ * stream. Those bytes used to go on the floor; now they take the background path, which reaches
+ * the node without respawning a pty client for it.
+ *
+ * A linear scan rather than a second index: the `released` map is one small record per node this
+ * process has released, this is the cold path (a stray write, not a keystroke stream), and two
+ * maps that have to agree about the same fact is precisely the shape of bug the session-budget
+ * subtraction already had to be fixed for once.
+ *
+ * Fire-and-forget, because `write()` is: `backgroundWrite` never rejects, and there is nobody to
+ * report a delivery failure to on this path. No typing badge either — a released session is one
+ * nobody is watching, so the badge would light up on a terminal that is not on anybody's screen.
+ */
+ private backgroundWriteBySessionId(sessionId: string, data: string): void {
+ for (const [persistKey, rec] of this.released) {
+ if (rec.sessionId !== sessionId) continue
+ void this.backgroundWrite(persistKey, data)
+ return
+ }
+ }
+
/**
* A subscriber reports the size IT can render. The pty runs at the smallest of them, so nobody
* is ever sent more columns than their xterm can draw (a subscriber with room to spare
@@ -2507,6 +2731,7 @@ export class PtyManager {
// otherwise linger until tmux dropped its client, and what we remembered about the released
// session describes a pane that is about to stop existing.
this.shadowDispose(persistKey)
+ this.sharedDisposeOn(persistKey)
this.released.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
@@ -2607,6 +2832,8 @@ export class PtyManager {
// 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)
+ // …and so does the shared background-write client, along with its linger timer.
+ this.sharedDispose()
this.released.clear()
this.sessions.clear()
this.byPersistKey.clear()
diff --git a/src/core/session-budget.ts b/src/core/session-budget.ts
index 0ffd2d915..dd55b5f3c 100644
--- a/src/core/session-budget.ts
+++ b/src/core/session-budget.ts
@@ -163,16 +163,25 @@ export interface SessionReaperOpts {
* process) is the natural owner of reaping them; the desktops that spawned them may be gone. */
sockets?: string[]
/**
- * The tmux sessions THIS process holds a control-mode SHADOW on, per socket (see
- * `PtyManager.shadowedTmuxSessions`). They are reported as DETACHED regardless of what tmux says,
- * in the plan AND in the kill-time re-verify.
+ * The tmux sessions THIS process holds a control-mode client on, per socket — a per-session
+ * shadow or the shared background-write client (see `PtyManager.shadowedTmuxSessions`). Each name
+ * listed has exactly ONE client SUBTRACTED FROM ITS COUNT, in the plan AND in the kill-time
+ * re-verify; anything left over is somebody else's client and keeps its exemption.
*
- * A shadow is a real tmux client, so a held `-C attach` flips `#{session_attached}` to 1 — and an
- * attached session is never evicted here. Without this hook, attaching a shadow (something no
- * user asked for and nobody is watching) would make a session permanently exempt from the
- * memory-pressure safety valve this whole module exists to be. A shadow is not a watcher: the
- * session may be reaped under it exactly as if nothing were attached, and the shadow's client
- * dies with the session it was attached to.
+ * A control client is a real tmux client, so a held `-C attach` puts this process into
+ * `#{session_attached}` — and an attached session is never evicted here. Without this hook,
+ * attaching one (something no user asked for and nobody is watching) would make a session
+ * permanently exempt from the memory-pressure safety valve this whole module exists to be. It is
+ * not a watcher: the session may be reaped under it exactly as if nothing were attached, and the
+ * client dies with the session it was attached to.
+ *
+ * SUBTRACT, never force-detach — `#{session_attached}` is a client COUNT, not a flag. A session
+ * holding ours PLUS a real one (the user's own `tmux attach`, a second nodeterm process on this
+ * socket) must stay exempt, or the budget kills a session out from under a live user. That is
+ * this module's one hard rule, and forcing the state inverts it.
+ *
+ * At most one of ours per name: PtyManager retires the shared client before shadowing the session
+ * it is attached to, so nothing here ever owes a subtraction of two.
*
* Per SOCKET, not per name: `nt-<node>` is only unique within a socket, and a genuinely attached
* session of the same name on `nodeterm-rmt` must keep its exemption.
diff --git a/src/core/tmux-naming.ts b/src/core/tmux-naming.ts
index 31fda682b..527f54ea4 100644
--- a/src/core/tmux-naming.ts
+++ b/src/core/tmux-naming.ts
@@ -7,3 +7,18 @@ export const TMUX_SOCKET = 'node-terminal'
export function sessionName(persistKey: string): string {
return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`
}
+
+/**
+ * Is this a tmux target THIS app generated (i.e. the output of `sessionName` for some node id)?
+ *
+ * The check exists for the one caller that cannot quote: a tmux control-mode command is a single
+ * text line and `encodeSendKeysHex` interpolates its target into it UNQUOTED, so a target carrying
+ * a space would split into the wrong arguments and one carrying a newline would run a second
+ * command. `sessionName` already sanitizes everything outside `[A-Za-z0-9_-]` away, so this can only
+ * fail on a name that did not come from it — an empty node id, or a raw target somebody passed in.
+ * Refusing there is cheap; the alternative is a shell-grade escaping problem on a line that reaches
+ * a tmux server with every session on it.
+ */
+export function isSessionName(target: string): boolean {
+ return /^nt-[A-Za-z0-9_-]+$/.test(target)
+}