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.

fix(ssh): self-heal a guessed freshness verdict, and stop the burst that causes it

enesf739838a30b1
diff --git a/CLAUDE.md b/CLAUDE.md
index 72981f227..d77a0cc22 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -907,6 +907,64 @@ Two additive changes, and the rules that keep them safe:
attempt in flight. `closeProject` is non-destructive, so a closed tab is the user saying "not
now".
+### When a freshness verdict was a GUESS: the late cold-start check
+
+The cold-restore section above states the rule that makes the remote freshness read safe: only
+tmux's own exit 1 is evidence of absence, and every other outcome answers "exists", because a
+transport failure read as "cold" types `claude --resume …` into a LIVE agent pane. That rule is
+right and does not change. What it costs, and what this closes, is the other side of the fold.
+
+**THE INCIDENT (measured on the reporting host, 2026-09-15).** The host's `nodeterm-rmt` tmux
+server died, so every remote session was gone; ten minutes later a 108-node SSH project was opened
+and 107 sessions had to be created in one mount burst. sshd logged **757 `Accepted publickey` full
+logins in seven minutes** — on a healthy ControlMaster that number is ~0, because everything
+multiplexes over one connection. Under that pressure the freshness read times out, the fold answers
+"exists", `tmux new-session -A` CREATES an empty session, `fresh:false` skips cold restore, and the
+node sits at a bare shell with the user's conversation stranded on disk:
+
+ 15:29 burst, 22 sessions: 18 claude / 4 bash -> 82% resumed
+ 15:39 burst, 107 sessions: 41 claude / 66 bash -> 38% resumed
+
+Load-dependent, i.e. a race. Three changes, and the order matters — the first saves the
+conversation, the other two stop the burst that strands it:
+
+- **A second opinion, never a different fold.** `create()` now reports `freshUnverified` when
+ `fresh:false` came from an `unknown` verdict rather than a read. The renderer re-asks ONCE, after
+ the attach has landed and the burst is over, and tmux settles it authoritatively:
+ `#{session_created}` survives a `new-session -A` attach, so a session created within seconds of
+ our own attach is one WE made (`PtyApi.sessionAge` → `remoteSessionAgeArgs`, which prints the
+ stamp AND the host's `date +%s` on one line so the host's clock skew never enters the number).
+ Every rule in `renderer/terminal/cold-self-heal.ts` is a refusal: never for a verdict that was
+ READ (that would spend a round trip per warm node on every switch), never for an unknown age,
+ never past the window, and never unless a SHELL still owns the pane — the same gate the
+ hibernation wake and the resume-miss watcher keep. The scrollback replay is deliberately NOT
+ re-run: by then tmux has painted the live pane, and writing a snapshot over it splices two points
+ in time (the warm-attach seeding rule). The agent relaunch is what matters and is what runs.
+- **The per-node token write is coalesced, not gated** — the brief that prompted this said
+ `ensureRemoteNodeToken` bypassed the `SshChildGate`, and that was measurably wrong: main wires
+ `RemoteHooks` with the gated runner, so it queues like everything else. The real cost was that it
+ is one round trip PER SPAWN for work the connect path already did (`materialiseNodeTokens` writes
+ every node's token), competing for a budget of 6 for the whole burst. It now memoizes per
+ (control path, node) for the app run — seeded by the connect — and coalesces a burst into ONE
+ remote write.
+- **Remote pty spawns are paced** (`core/remote-ssh/pty-spawn-gate.ts`, cap 4 per ControlMaster).
+ A pty deliberately never went through the `SshChildGate` — "a terminal is never queued for a
+ screen the user is looking at" — which is right for a handful of terminals and wrong for a
+ canvas. The one thing that makes pacing acceptable is that a slot is held only until the session
+ starts painting: released on the pty's FIRST OUTPUT (one round trip for a warm attach) and
+ unconditionally after `REMOTE_PTY_SPAWN_SETTLE_MS`, because a gate that can hang is worse than no
+ gate. A node that ends up waiting SAYS so (`SLOW_REMOTE_SPAWN_NOTICE_MS`), for the same reason the
+ `[connecting…]` line exists. Measured in the lab (real sshd, `MaxSessions 10`, 50 ms RTT, one warm
+ master, 107 attaches):
+
+ | | full logins | panes painted | wall |
+ |---|---|---|---|
+ | ungated | 72 / 77 | 102 and 96 of 107 | 2.1 / 2.3 s |
+ | gated at 4 | **1** / **1** | **107 / 107** | 3.2 / 4.0 s |
+
+ Wall time is the price and it is the right trade: ungated, five to eleven panes never painted at
+ all inside a 20 s budget — the same shape `remote-session-index.ts` reports for its own burst.
+
### We have our own VT emulator — check it before asking tmux
xterm.js is not just a renderer. It parses the pane's output stream, so it **tracks DECSET modes
diff --git a/src/core/agents/node-token-service.test.ts b/src/core/agents/node-token-service.test.ts
index 90b845f8f..c02de1d19 100644
--- a/src/core/agents/node-token-service.test.ts
+++ b/src/core/agents/node-token-service.test.ts
@@ -16,9 +16,16 @@ import {
nodeIdsForCanvas,
remoteNodeTokenMinter,
setRemoteNodeTokenWriter,
- ensureRemoteNodeToken
+ ensureRemoteNodeToken,
+ forgetRemoteNodeTokens,
+ seedRemoteNodeTokens,
+ REMOTE_TOKEN_COALESCE_MS
} from './node-token-service'
+/** The coalescing window is a real timer (see REMOTE_TOKEN_COALESCE_MS); wait it out. */
+const flushCoalesce = (): Promise<void> =>
+ new Promise((r) => setTimeout(r, REMOTE_TOKEN_COALESCE_MS + 20))
+
let dir = ''
beforeEach(() => {
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-svc-'))
@@ -252,19 +259,68 @@ describe('node token service — the remote (SSH) minter', () => {
expect(nodeIdsForCanvas('nope')).toEqual([])
})
- it('the spawn-path writer is a no-op until one is registered, and never throws', () => {
+ it('the spawn-path writer is a no-op until one is registered, and never throws', async () => {
+ forgetRemoteNodeTokens('/cm.sock')
setRemoteNodeTokenWriter(null)
expect(() => ensureRemoteNodeToken('/cm.sock', 'node-1')).not.toThrow()
- const seen: string[][] = []
- setRemoteNodeTokenWriter((cp, id) => seen.push([cp, id]))
+ const seen: [string, string[]][] = []
+ setRemoteNodeTokenWriter((cp, ids) => seen.push([cp, [...ids]]))
ensureRemoteNodeToken('/cm.sock', 'node-1')
- expect(seen).toEqual([['/cm.sock', 'node-1']])
+ await flushCoalesce()
+ expect(seen).toEqual([['/cm.sock', ['node-1']]])
// a writer that throws must not reach the pty spawn that called it
+ forgetRemoteNodeTokens('/cm.sock')
setRemoteNodeTokenWriter(() => {
throw new Error('ssh gone')
})
expect(() => ensureRemoteNodeToken('/cm.sock', 'node-1')).not.toThrow()
+ await flushCoalesce()
+ setRemoteNodeTokenWriter(null)
+ })
+
+ it('COALESCES a mount burst into ONE remote write, and never rewrites an id twice', async () => {
+ // The shape that prompted this: a project switch mounts every node in the same tick, and each
+ // spawn used to be its own ssh exec child on the one multiplexed connection.
+ forgetRemoteNodeTokens('/cm.sock')
+ const seen: [string, string[]][] = []
+ setRemoteNodeTokenWriter((cp, ids) => seen.push([cp, [...ids]]))
+ for (const id of ['n1', 'n2', 'n3', 'n2']) ensureRemoteNodeToken('/cm.sock', id)
+ await flushCoalesce()
+ expect(seen).toEqual([['/cm.sock', ['n1', 'n2', 'n3']]])
+ // A second burst for ids this run already wrote costs NOTHING at all.
+ seen.length = 0
+ for (const id of ['n1', 'n2', 'n3']) ensureRemoteNodeToken('/cm.sock', id)
+ await flushCoalesce()
+ expect(seen).toEqual([])
+ // …and a genuinely new node still gets its token.
+ ensureRemoteNodeToken('/cm.sock', 'n4')
+ await flushCoalesce()
+ expect(seen).toEqual([['/cm.sock', ['n4']]])
+ setRemoteNodeTokenWriter(null)
+ forgetRemoteNodeTokens('/cm.sock')
+ })
+
+ it('keeps hosts separate, and a connect-time seed silences the spawn path for what it wrote', async () => {
+ forgetRemoteNodeTokens('/a.sock')
+ forgetRemoteNodeTokens('/b.sock')
+ const seen: [string, string[]][] = []
+ setRemoteNodeTokenWriter((cp, ids) => seen.push([cp, [...ids]]))
+ // This is what `materialiseNodeTokens` records after the connect wrote every node's token.
+ seedRemoteNodeTokens('/a.sock', ['n1', 'n2'])
+ ensureRemoteNodeToken('/a.sock', 'n1') // already on that host ⇒ no round trip
+ ensureRemoteNodeToken('/b.sock', 'n1') // a DIFFERENT host has never seen it
+ await flushCoalesce()
+ expect(seen).toEqual([['/b.sock', ['n1']]])
+ // A re-connect re-seeds, and the seed RESETS: the control path is keyed by project, so it can
+ // point at a different host after a server edit, where nothing of ours has been written.
+ seen.length = 0
+ seedRemoteNodeTokens('/a.sock', [])
+ ensureRemoteNodeToken('/a.sock', 'n1')
+ await flushCoalesce()
+ expect(seen).toEqual([['/a.sock', ['n1']]])
setRemoteNodeTokenWriter(null)
+ forgetRemoteNodeTokens('/a.sock')
+ forgetRemoteNodeTokens('/b.sock')
})
})
diff --git a/src/core/agents/node-token-service.ts b/src/core/agents/node-token-service.ts
index 3242d9384..03880e5c5 100644
--- a/src/core/agents/node-token-service.ts
+++ b/src/core/agents/node-token-service.ts
@@ -231,18 +231,93 @@ export function remoteNodeTokenMinter(): ((nodeId: string) => string) | null {
* must keep building without electron. Unregistered — the Server Edition, every test — it is a
* no-op, which is the correct behavior there too.
*/
-type RemoteNodeTokenWriter = (controlPath: string, nodeId: string) => void
+type RemoteNodeTokenWriter = (controlPath: string, nodeIds: readonly string[]) => void
let remoteWriter: RemoteNodeTokenWriter | null = null
export function setRemoteNodeTokenWriter(writer: RemoteNodeTokenWriter | null): void {
remoteWriter = writer
}
-/** Fire-and-forget, fail-open: a token that cannot be written costs the node `legacy`, never its
- * terminal. Nothing here may throw into a pty spawn. */
+/**
+ * Which node ids this app run has already materialised on which host, keyed by ControlPath.
+ *
+ * WHY (measured, 2026-09-15). This is one ssh exec child PER SPAWN, and a project switch mounts
+ * every node in the same tick: a 108-node canvas fired 107 of these at the exact moment 107 pty
+ * channels were opening, and a stock host allows `MaxSessions` channels on the ONE connection they
+ * all multiplex over. They are gated (`SshChildGate`, so they queue rather than fall back to full
+ * logins — the brief that prompted this said otherwise and was wrong), but a queue of 107 round
+ * trips behind a budget of 6 still competes with the terminals for that budget for the whole burst.
+ *
+ * And nearly all of them have nothing to do: the CONNECT path already wrote a token for every node
+ * the canvas held (`materialiseNodeTokens`), so a node that existed at connect is asking the host to
+ * rewrite a file it already has. The memo turns that into zero round trips, and `seedRemoteNodeTokens`
+ * is what the connect path calls to record what it just wrote.
+ */
+const remoteWritten = new Map<string, Set<string>>()
+/** Ids waiting to be written for a control path, and the timer that will flush them. */
+const remotePending = new Map<string, { ids: Set<string>; timer: ReturnType<typeof setTimeout> }>()
+
+/** How long a burst is collected before one write goes out. A project switch mounts every node in
+ * the SAME tick, so this only has to outlive a task queue — not a network round trip. */
+export const REMOTE_TOKEN_COALESCE_MS = 50
+
+/**
+ * Record ids the CONNECT path has just written on this host, so the spawn path does not rewrite
+ * them. Called with the same list `materialiseNodeTokens` handed the host — and it RESETS the
+ * memo first, because a connect may be to a different host on the same (project-keyed) control
+ * path, and the connect writes every id anyway.
+ */
+export function seedRemoteNodeTokens(controlPath: string, nodeIds: readonly string[]): void {
+ remoteWritten.set(controlPath, new Set(nodeIds))
+}
+
+/** Forget a host's memo (its master went away, or the node's token was swept). */
+export function forgetRemoteNodeTokens(controlPath: string): void {
+ remoteWritten.delete(controlPath)
+ const pending = remotePending.get(controlPath)
+ if (pending) {
+ clearTimeout(pending.timer)
+ remotePending.delete(controlPath)
+ }
+}
+
+/**
+ * Fire-and-forget, fail-open: a token that cannot be written costs the node `legacy`, never its
+ * terminal. Nothing here may throw into a pty spawn.
+ *
+ * Skipped outright for an id this run already materialised on that host, and otherwise COALESCED
+ * (see `remoteWritten`) so a mount burst is one remote write rather than one per node. The memo is
+ * marked at flush time, not at request time, so a flush that throws leaves the ids owed.
+ */
export function ensureRemoteNodeToken(controlPath: string, nodeId: string): void {
try {
- remoteWriter?.(controlPath, nodeId)
+ if (!remoteWriter) return
+ if (remoteWritten.get(controlPath)?.has(nodeId)) return
+ const pending = remotePending.get(controlPath)
+ if (pending) {
+ pending.ids.add(nodeId)
+ return
+ }
+ const ids = new Set([nodeId])
+ const timer = setTimeout(() => {
+ remotePending.delete(controlPath)
+ const list = [...ids]
+ // Mark BEFORE the call, not after: the writer is fire-and-forget (it returns void and
+ // reports nothing), so there is no "after" to key on. A write that silently fails costs the
+ // node its `verified` label until the next connect — which is exactly what it cost before
+ // this memo existed, for a node created after connect on a host that refuses the write.
+ const seen = remoteWritten.get(controlPath) ?? new Set<string>()
+ for (const id of list) seen.add(id)
+ remoteWritten.set(controlPath, seen)
+ try {
+ remoteWriter?.(controlPath, list)
+ } catch {
+ /* fail-open */
+ }
+ }, REMOTE_TOKEN_COALESCE_MS)
+ // Never hold the process open for a best-effort token write.
+ ;(timer as { unref?: () => void }).unref?.()
+ remotePending.set(controlPath, { ids, timer })
} catch {
/* fail-open */
}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index af8498879..901df0cd3 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -32,6 +32,8 @@ import {
remotePasteDelivery,
remoteCapturePaneArgs,
remotePaneCommandArgs,
+ remoteSessionAgeArgs,
+ parseSessionAge,
remotePaneOwnerCombinedArgs,
remotePaneProcessArgs,
remoteTerminateForegroundArgs,
@@ -42,7 +44,8 @@ import {
type RemoteEndPlan,
type RemoteNodeOwnerResolver
} from './remote-end'
-import { RemoteSessionIndex } from './remote-ssh/remote-session-index'
+import { RemoteSessionIndex, type SessionVerdict } from './remote-ssh/remote-session-index'
+import { remotePtySpawnGate, type SpawnSlot } from './remote-ssh/pty-spawn-gate'
import type { SshConnection } from '../shared/ssh'
import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remote-kills'
import { probeAgentSockToPin } from './remote-ssh/agent-probe'
@@ -587,6 +590,30 @@ function normalizeSize(cols: number, rows: number): PtySize {
return effectiveSize([{ cols, rows }]) as PtySize // one entry in ⇒ never null out
}
+/**
+ * Hand a remote spawn's gate slot back the moment its pty produces its first byte — the cheapest
+ * signal that the ssh channel is up and the host has answered.
+ *
+ * Releases IMMEDIATELY when there is no session to listen to (a refusal, a discarded spawn), and
+ * the slot's own settle deadline covers a pty that never speaks. `onData` is an extra listener on
+ * the same pty the session already reads; it disposes itself on the first chunk.
+ */
+function releaseSpawnSlotOnOutput(session: Session | undefined, release: SpawnSlot): void {
+ if (!session) {
+ release()
+ return
+ }
+ try {
+ const sub = session.proc.onData(() => {
+ sub.dispose()
+ release()
+ })
+ } catch {
+ // A pty that cannot be listened to is one we cannot pace against; do not hold the queue for it.
+ release()
+ }
+}
+
interface Session {
proc: pty.IPty
/** Every VIEW watching this session, keyed by the composite `(ClientId, viewerId)` (`SubKey`).
@@ -2156,11 +2183,17 @@ export class PtyManager {
// (a cheap name-only `has-session` probe, decided before spawning anything) the session-host
// backend's attach-or-create IS the probe — see the `spawned?.sessionHost` branch below, which
// overwrites both `fresh` and `screen` from that same round trip once `spawnSession` returns.
+ // For an SSH node the freshness answer is TRI-STATE, and the third value is the point: a read
+ // that could not complete answers `unknown`, which folds to "exists" (never type a resume into
+ // a live agent pane) — but that fold is a GUESS, and under a mount burst that saturates the
+ // host's `MaxSessions` it is the WRONG guess often enough to strand a conversation. See
+ // `freshUnverified`; the renderer re-asks once, after the attach, when this is set.
+ const remoteVerdict = options.sshRemote
+ ? await this.remoteSessionVerdict(options.sshRemote, sessionName(options.persistKey as string))
+ : undefined
+ const freshUnverified = remoteVerdict === 'unknown'
let fresh = options.sshRemote
- ? !(await this.remoteSessionExists(
- options.sshRemote,
- sessionName(options.persistKey as string)
- ))
+ ? remoteVerdict === 'absent'
: warmWindowsBackend
? false
: tmuxBacked
@@ -2208,14 +2241,27 @@ export class PtyManager {
}
}
}
- const sessionId = this.spawnSession(
- options,
- clientId,
- undefined,
- warmWindowsBackend,
- projectOverrides
- )
+ // PACE THE REMOTE SPAWNS (see remote-ssh/pty-spawn-gate.ts). A project switch mounts every node
+ // in one tick, and a remote terminal is an ssh client on the project's ONE multiplexed
+ // connection — past the host's `MaxSessions` each excess one performs a full login, and the
+ // pressure that creates is what makes the freshness read time out and strand a conversation.
+ // The slot is released on the session's first output, so a warm attach holds it for one round
+ // trip. Local spawns are not gated: there is no connection to overrun.
+ const spawnSlot =
+ options.sshRemote && options.persistKey
+ ? await remotePtySpawnGate.acquire(options.sshRemote.controlPath)
+ : null
+ let sessionId: string
+ try {
+ sessionId = this.spawnSession(options, clientId, undefined, warmWindowsBackend, projectOverrides)
+ } catch (err) {
+ // A spawn that never happened must not hold a slot until the settle deadline — the next node
+ // in the queue is waiting on it.
+ spawnSlot?.()
+ throw err
+ }
const spawned = this.sessions.get(sessionId)
+ if (spawnSlot) releaseSpawnSlotOnOutput(spawned, spawnSlot)
// PANE OWNERSHIP (agent messaging, PR #237 fix round 2): record the OWNING project of a pane
// this process just GENUINELY spawned. Gated on `fresh` — an attach/co-attach to a session
// someone else spawned (incl. an app-restart re-attach) leaves the pane UNPROVEN, so a second
@@ -2290,6 +2336,9 @@ export class PtyManager {
sessionId,
fresh,
persistent,
+ // Only when the fold actually happened: a verdict we READ needs no second opinion, and
+ // setting this on a confident `fresh:false` would spend a round trip per warm node.
+ ...(freshUnverified && !fresh ? { freshUnverified: true as const } : {}),
...(accountFallback ? { accountFallback } : {}),
...(staleCwd ? { staleCwd: true as const } : {}),
...(screen ? { screen } : {})
@@ -2355,6 +2404,15 @@ export class PtyManager {
return this.remoteSessions.exists(sshRemote.controlPath, sessionId, sshRemote.conn)
}
+ /** The tri-state behind `remoteSessionExists`, for the one caller that must act on the
+ * difference between "the host says it is not there" and "we could not read the host". */
+ private async remoteSessionVerdict(
+ sshRemote: NonNullable<PtyCreateOptions['sshRemote']>,
+ sessionId: string
+ ): Promise<SessionVerdict> {
+ return this.remoteSessions.verdict(sshRemote.controlPath, sessionId, sshRemote.conn)
+ }
+
/**
* Was this node's remote tmux session POSITIVELY listed on the host? The strict half of the
* probe above, for the renderer's early-attach gate.
@@ -4143,6 +4201,57 @@ export class PtyManager {
}
}
+ /**
+ * How many SECONDS ago was this node's tmux session created — on the machine that holds it?
+ *
+ * The late cold-start check (`PtyCreateResult.freshUnverified`). When the freshness read could
+ * not complete, `fresh:false` was a guess, and `tmux new-session -A` may have CREATED the very
+ * session we then treated as a warm reattach. tmux itself can settle that after the fact:
+ * `#{session_created}` survives an `-A` attach, so a session created within seconds of our own
+ * attach is one WE made, i.e. the node was cold.
+ *
+ * Remote answers are computed ENTIRELY on the host (`remoteSessionAgeArgs`) so the host's clock
+ * skew never enters the number; local ones compare tmux's stamp against this machine's own clock,
+ * which is the same clock.
+ *
+ * `null` is "we could not tell" for every reason there is — no live session, no tmux, the
+ * session-host backend (which has no creation stamp to offer), an unreadable host, a garbled
+ * line. Never an age, and never a throw: the caller ACTS on a small number, so every uncertainty
+ * has to come back as the value that means "do nothing".
+ */
+ async sessionAgeSeconds(persistKey: string): Promise<number | null> {
+ const target = sessionName(persistKey)
+ const live = this.liveSessionForPersistKey(persistKey)
+ const sshRemote = live?.sshRemote
+ if (sshRemote) {
+ const ssh = findSsh()
+ if (!ssh) return null
+ try {
+ const { stdout } = await runAsync(
+ ssh,
+ remoteSessionAgeArgs(sshRemote.conn, sshRemote.controlPath, target),
+ { timeout: PROBE_TIMEOUT_MS }
+ )
+ return parseSessionAge(stdout)
+ } catch {
+ return null
+ }
+ }
+ // The session-host backend keeps no creation stamp, and a plain shell has no session at all.
+ if (live?.sessionHost || !this.tmuxPath) return null
+ try {
+ const { stdout } = await runAsync(
+ this.tmuxPath,
+ ['-L', TMUX_SOCKET, 'display-message', '-p', '-t', `=${target}:`, '#{session_created}'],
+ { timeout: PROBE_TIMEOUT_MS }
+ )
+ // One clock here, so the host half of the remote line is ours to supply.
+ return parseSessionAge(`${stdout.trim()} ${Math.floor(Date.now() / 1000)}`)
+ } catch {
+ return null
+ }
+ }
+
/**
* Terminate the foreground agent process group in a node's tmux pane without writing anything
* into the terminal. This is intentionally narrower than recycling the session: model switching
diff --git a/src/core/pty-shadow.test.ts b/src/core/pty-shadow.test.ts
index c519cc411..30c47b617 100644
--- a/src/core/pty-shadow.test.ts
+++ b/src/core/pty-shadow.test.ts
@@ -10,7 +10,11 @@ import { TMUX_SOCKET, sessionName } from './tmux-naming'
import { REAP_IDLE_MS, REAP_SWEEP_MS } from './pty-reap'
import type { ControlSpawn } from './tmux-control-client'
import type { PtyDevices } from './pty-devices'
-import { setRemoteNodeTokenWriter } from './agents/node-token-service'
+import {
+ setRemoteNodeTokenWriter,
+ forgetRemoteNodeTokens,
+ REMOTE_TOKEN_COALESCE_MS
+} from './agents/node-token-service'
/**
* SHADOW CLIENTS: a tmux control-mode (`-C`) client over plain pipes, attached to the tmux session
@@ -529,8 +533,8 @@ describe('control-mode shadow clients for released sessions', () => {
// The connect writes a token for every node the canvas had THEN. Without this leg a node
// created afterwards has no token file on the host until the next reconnect — which for a
// long-lived SSH project is never — and spends that whole time on `legacy`.
- const seen: string[][] = []
- setRemoteNodeTokenWriter((controlPath, nodeId) => seen.push([controlPath, nodeId]))
+ const seen: [string, string[]][] = []
+ setRemoteNodeTokenWriter((controlPath, nodeIds) => seen.push([controlPath, [...nodeIds]]))
try {
await tmuxManager()
await fake.handlers[IPC.ptyCreate](ALICE, {
@@ -539,13 +543,17 @@ describe('control-mode shadow clients for released sessions', () => {
persistKey: 'node-r2',
sshRemote: { conn: { host: 'h1', user: 'u' }, controlPath: '/tmp/cm', remoteCwd: '/srv/app' }
})
- expect(seen).toEqual([['/tmp/cm', 'node-r2']])
+ // Coalesced: the spawn path collects a burst and writes once (REMOTE_TOKEN_COALESCE_MS).
+ // Fake timers are in force for this suite, so advance rather than wait.
+ await vi.advanceTimersByTimeAsync(REMOTE_TOKEN_COALESCE_MS + 20)
+ expect(seen).toEqual([['/tmp/cm', ['node-r2']]])
// ...and a LOCAL node never asks a host for anything.
seen.length = 0
await fake.handlers[IPC.ptyCreate](ALICE, { cols: 80, rows: 24, persistKey: 'node-local' })
expect(seen).toEqual([])
} finally {
setRemoteNodeTokenWriter(null)
+ forgetRemoteNodeTokens('/tmp/cm')
}
})
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index f36a42138..1a2f39895 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -475,6 +475,49 @@ export function remoteCapturePaneArgs(conn: SshConnection, controlPath: string,
tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} capture-pane -p -e -t ${sessionId} -S ${full ? '-' : '-200'}`)
)
}
+/**
+ * Ask the REMOTE tmux when a node's session was created, AND what the host's clock says now — in
+ * one round trip, because the caller wants an AGE and the two clocks are not the same clock.
+ *
+ * `#{session_created}` is an epoch stamp taken on the HOST, so subtracting our own `Date.now()`
+ * would fold that host's clock skew (and every NTP correction) into the answer. Computing the
+ * difference from two numbers the host produced in the same shell removes the question entirely.
+ *
+ * Verified on tmux 3.3a and 3.4: `session_created` has been a format variable since long before
+ * either (unlike `#{bracket_paste_flag}`, the version trap this file's neighbours document), and
+ * `new-session -A` on an EXISTING session preserves the original creation time — which is the whole
+ * reason the answer can distinguish "this session was already here" from "our attach made it".
+ * Targeted `-t '=<name>:'` — the same exact-match form `PtyManager.paneCwdStale` documents, and
+ * for the same measured reason: without `=` tmux falls back to fnmatch then PREFIX matching, so
+ * `nt-abc` could answer about `nt-abcdef`, and a bare `=name` (no trailing colon) resolves NOTHING
+ * for a target-PANE query — exit 0, every format empty. Re-measured here on tmux 3.3a and 3.4.
+ */
+export function remoteSessionAgeArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
+ return childArgs(
+ conn,
+ controlPath,
+ tmuxCmd(
+ `printf '%s %s\n' "$(tmux -L ${RMT_TMUX_SOCKET} display-message -p -t '=${sessionId}:' '#{session_created}')" "$(date +%s)"`
+ )
+ )
+}
+
+/**
+ * Seconds since a tmux session was created, from the `"<created> <now>"` line
+ * `remoteSessionAgeArgs` (and its local twin) produce. `null` for anything we cannot read as two
+ * epoch numbers — a missing session, an empty format, a shell that printed something else. Never
+ * negative: a host whose clock stepped backwards between the two `$( )` is unknowable, not brand
+ * new, and the caller ACTS on a small age.
+ */
+export function parseSessionAge(stdout: string): number | null {
+ const [created, now] = stdout.trim().split(/\s+/)
+ const a = Number(created)
+ const b = Number(now)
+ if (!Number.isFinite(a) || !Number.isFinite(b) || a <= 0 || b <= 0) return null
+ const age = b - a
+ return age < 0 ? null : age
+}
+
/**
* Ask the REMOTE tmux which command is in the foreground of a node's pane — the remote
* counterpart of `PtyManager.paneCommand`'s local `display-message` path. The format is
diff --git a/src/core/remote-ssh/pty-spawn-gate.test.ts b/src/core/remote-ssh/pty-spawn-gate.test.ts
new file mode 100644
index 000000000..452b26ecc
--- /dev/null
+++ b/src/core/remote-ssh/pty-spawn-gate.test.ts
@@ -0,0 +1,117 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ PtySpawnGate,
+ REMOTE_PTY_SPAWN_CONCURRENCY,
+ REMOTE_PTY_SPAWN_SETTLE_MS
+} from './pty-spawn-gate'
+
+/** A schedule seam whose timers only fire when the test says so. */
+function fakeClock() {
+ const timers: { fn: () => void; ms: number; cancelled: boolean }[] = []
+ return {
+ schedule: (fn: () => void, ms: number) => {
+ const t = { fn, ms, cancelled: false }
+ timers.push(t)
+ return {
+ cancel: () => {
+ t.cancelled = true
+ }
+ }
+ },
+ fireAll: () => {
+ for (const t of timers) if (!t.cancelled) t.fn()
+ },
+ pending: () => timers.filter((t) => !t.cancelled).length
+ }
+}
+
+/** `acquire` awaits internally, so a pending `.then` needs more than one microtask turn. */
+const tick = async (): Promise<void> => {
+ for (let i = 0; i < 5; i++) await Promise.resolve()
+}
+
+describe('PtySpawnGate', () => {
+ it('lets the budget through at once and queues the rest', async () => {
+ const clock = fakeClock()
+ const gate = new PtySpawnGate(2, 5000, clock.schedule)
+ const a = await gate.acquire('/cm/p1')
+ await gate.acquire('/cm/p1')
+ expect(gate.inFlight('/cm/p1')).toBe(2)
+
+ let thirdIn = false
+ const third = gate.acquire('/cm/p1').then((r) => {
+ thirdIn = true
+ return r
+ })
+ await tick()
+ expect(thirdIn).toBe(false)
+ expect(gate.queued('/cm/p1')).toBe(1)
+
+ a()
+ await third
+ expect(thirdIn).toBe(true)
+ // The permit is handed straight over: the count never dips below the limit mid-burst.
+ expect(gate.inFlight('/cm/p1')).toBe(2)
+ })
+
+ it('keeps hosts separate — one budget per ControlMaster, like MaxSessions itself', async () => {
+ const clock = fakeClock()
+ const gate = new PtySpawnGate(1, 5000, clock.schedule)
+ await gate.acquire('/cm/p1')
+ let second = false
+ void gate.acquire('/cm/p2').then(() => (second = true))
+ await tick()
+ expect(second).toBe(true)
+ })
+
+ it('releases on the settle deadline, so a pty that never speaks cannot wedge the queue', async () => {
+ // The rule that makes pacing terminals acceptable at all: a gate that can hang is worse than
+ // no gate, because the failure it prevents is at least visible.
+ const clock = fakeClock()
+ const gate = new PtySpawnGate(1, 5000, clock.schedule)
+ await gate.acquire('/cm/p1') // never released by the caller
+ let next = false
+ void gate.acquire('/cm/p1').then(() => (next = true))
+ await tick()
+ expect(next).toBe(false)
+ clock.fireAll()
+ await tick()
+ expect(next).toBe(true)
+ })
+
+ it('release is idempotent — first output and the deadline both call it', async () => {
+ const clock = fakeClock()
+ const gate = new PtySpawnGate(1, 5000, clock.schedule)
+ const release = await gate.acquire('/cm/p1')
+ release()
+ expect(gate.inFlight('/cm/p1')).toBe(0)
+ release() // the deadline losing the race must be a no-op, not a second permit
+ clock.fireAll()
+ expect(gate.inFlight('/cm/p1')).toBe(0)
+ // A released slot cancels its own deadline rather than leaving a timer behind per spawn.
+ expect(clock.pending()).toBe(0)
+ })
+
+ it('paces a 107-node burst into waves instead of one flood', async () => {
+ // The shape of the incident: one project switch, 107 remote sessions created at once.
+ const clock = fakeClock()
+ const gate = new PtySpawnGate(4, 5000, clock.schedule)
+ let peak = 0
+ const releases: (() => void)[] = []
+ const all = Array.from({ length: 107 }, async () => {
+ const r = await gate.acquire('/cm/p1')
+ peak = Math.max(peak, gate.inFlight('/cm/p1'))
+ releases.push(r)
+ // Hand it straight back, as a first-output release would.
+ r()
+ })
+ await Promise.all(all)
+ expect(peak).toBe(4)
+ expect(gate.queued('/cm/p1')).toBe(0)
+ })
+
+ it('ships a budget small enough to leave the host room for the terminals themselves', () => {
+ expect(REMOTE_PTY_SPAWN_CONCURRENCY).toBeLessThan(10) // a stock sshd's MaxSessions
+ expect(REMOTE_PTY_SPAWN_SETTLE_MS).toBeGreaterThan(1000)
+ })
+})
diff --git a/src/core/remote-ssh/pty-spawn-gate.ts b/src/core/remote-ssh/pty-spawn-gate.ts
new file mode 100644
index 000000000..60b2c99c6
--- /dev/null
+++ b/src/core/remote-ssh/pty-spawn-gate.ts
@@ -0,0 +1,116 @@
+// A per-ControlMaster ceiling on how many REMOTE pty spawns may be in flight at once.
+//
+// WHY (measured on the reporting host, 2026-09-15). A remote terminal is `ssh -t … tmux
+// new-session -A …` spawned through node-pty, which deliberately does NOT go through the
+// `SshChildGate` — "a pty is never queued for a screen the user is looking at" (see
+// ssh-child-gate.ts). That is right for a handful of terminals and wrong for a canvas: a project
+// switch mounts every node in the SAME tick, so a 108-node project opened 107 ssh clients at once
+// on one multiplexed connection. sshd logged **757 `Accepted publickey` full logins** in the seven
+// minutes around it, against the ~0 a healthy ControlMaster produces — each channel past the
+// host's `MaxSessions` is refused, falls back to becoming a master, cannot bind the socket the
+// live master owns, and performs a complete TCP+KEX+auth login instead.
+//
+// The cost is not the logins. It is that under that pressure every OTHER read on the connection
+// times out, including the "does my session already exist?" probe — whose fail-safe answers
+// "exists", so `new-session -A` creates an empty session and the node never cold-restores. 66 of
+// those 107 sessions ended at a bare shell with the user's conversation stranded on disk.
+//
+// So the terminals are paced now, and the ONE thing that makes that acceptable is that a slot is
+// held only until the session starts painting — not for the terminal's life:
+//
+// - a slot is released on the pty's FIRST OUTPUT, which for a warm attach is one round trip
+// (measured: 18 parallel warm attaches at 50 ms RTT painted in a median of 0.16 s);
+// - and unconditionally after `REMOTE_PTY_SPAWN_SETTLE_MS`, because a pty that never produces a
+// byte must not be able to wedge the queue behind it. A gate that can hang is worse than no
+// gate at all — the failure it is preventing is at least visible.
+//
+// LOCAL terminals are not gated at all: there is no connection to overrun, and node-pty spawns
+// cost nothing a queue would save.
+
+/** Remote pty spawns allowed in flight per ControlMaster. Deliberately small: each one is an ssh
+ * channel that will be held for the terminal's whole life, so the burst is the only thing worth
+ * pacing, and pacing it hard is what keeps the host's `MaxSessions` for the terminals themselves. */
+export const REMOTE_PTY_SPAWN_CONCURRENCY = 4
+
+/** Hard ceiling on how long one spawn may hold its slot. Generous against a slow host (a cold
+ * master establish measured 0.44 s at 50 ms RTT, and this runs behind one), and short enough that
+ * a pty which never speaks costs the queue seconds rather than the app run. */
+export const REMOTE_PTY_SPAWN_SETTLE_MS = 5_000
+
+/** Release a held slot. Idempotent — the caller's first-output hook and the settle deadline both
+ * call it, and whichever loses must be a no-op. */
+export type SpawnSlot = () => void
+
+export class PtySpawnGate {
+ private active = new Map<string, number>()
+ private waiting = new Map<string, (() => void)[]>()
+
+ constructor(
+ private limit: number = REMOTE_PTY_SPAWN_CONCURRENCY,
+ private settleMs: number = REMOTE_PTY_SPAWN_SETTLE_MS,
+ /** Injected so tests do not wait on real time. */
+ private schedule: (fn: () => void, ms: number) => { cancel: () => void } = (fn, ms) => {
+ const t = setTimeout(fn, ms)
+ ;(t as { unref?: () => void }).unref?.()
+ return { cancel: () => clearTimeout(t) }
+ }
+ ) {}
+
+ /** Wait for a slot on this control path. The returned release is idempotent and is ALSO armed
+ * on the settle deadline, so a caller that forgets (or a pty that never starts) cannot wedge
+ * the queue. */
+ async acquire(controlPath: string): Promise<SpawnSlot> {
+ await this.take(controlPath)
+ let released = false
+ const deadline = this.schedule(() => release(), this.settleMs)
+ const release: SpawnSlot = () => {
+ if (released) return
+ released = true
+ deadline.cancel()
+ this.give(controlPath)
+ }
+ return release
+ }
+
+ /** In-flight spawns for a control path — for tests and diagnostics. */
+ inFlight(controlPath: string): number {
+ return this.active.get(controlPath) ?? 0
+ }
+
+ /** Spawns queued behind the limit for a control path. */
+ queued(controlPath: string): number {
+ return this.waiting.get(controlPath)?.length ?? 0
+ }
+
+ private take(key: string): Promise<void> {
+ const n = this.active.get(key) ?? 0
+ if (n < this.limit) {
+ this.active.set(key, n + 1)
+ return Promise.resolve()
+ }
+ return new Promise<void>((resolve) => {
+ const q = this.waiting.get(key)
+ if (q) q.push(resolve)
+ else this.waiting.set(key, [resolve])
+ })
+ }
+
+ private give(key: string): void {
+ const q = this.waiting.get(key)
+ const next = q?.shift()
+ if (next) {
+ if (q && q.length === 0) this.waiting.delete(key)
+ // Hand the permit straight to the waiter — `active` never dips, so a burst cannot slip past
+ // the limit in the gap between one spawn finishing and the next starting.
+ next()
+ return
+ }
+ const n = (this.active.get(key) ?? 1) - 1
+ if (n <= 0) this.active.delete(key)
+ else this.active.set(key, n)
+ }
+}
+
+/** One budget per ControlMaster for the whole process — module-level for the same reason
+ * `SshChildGate` is: a manager rebuilt in a test must not hand a host two budgets. */
+export const remotePtySpawnGate = new PtySpawnGate()
diff --git a/src/core/remote-ssh/session-age.realsh.test.ts b/src/core/remote-ssh/session-age.realsh.test.ts
new file mode 100644
index 000000000..a201f91aa
--- /dev/null
+++ b/src/core/remote-ssh/session-age.realsh.test.ts
@@ -0,0 +1,85 @@
+// The generated `#{session_created}` line, executed by a REAL /bin/sh against a stub tmux.
+//
+// It is generated shell that no compiler checks, and its job is to produce TWO epoch numbers on the
+// HOST so the caller never has to subtract two different clocks. The failure this guards is the one
+// the session-memory work already hit once: a plan whose `echo ##MEM` printed an EMPTY LINE under
+// POSIX sh, so every healthy host reported a failure. Only running it catches that.
+import { describe, expect, it, beforeAll } from 'vitest'
+import { execFileSync } from 'child_process'
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { remoteSessionAgeArgs, parseSessionAge } from './control-master'
+
+const conn = { host: 'h.example.com', user: 'deploy' }
+let binDir: string
+
+/** The last argv element of an `ssh …` argv IS the remote command line. */
+function remoteCommand(args: string[]): string {
+ return args[args.length - 1]
+}
+
+/** Run that line under a real /bin/sh with a stub `tmux` that answers `created`. */
+function runWithTmuxAnswer(line: string, created: string): string {
+ fs.writeFileSync(path.join(binDir, 'tmux'), `#!/bin/sh\nprintf '%s' '${created}'\n`, { mode: 0o755 })
+ return execFileSync('/bin/sh', ['-c', line], {
+ env: { ...process.env, PATH: `${binDir}:${process.env.PATH ?? ''}` },
+ encoding: 'utf8'
+ })
+}
+
+beforeAll(() => {
+ binDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ntage-'))
+})
+
+describe('remoteSessionAgeArgs (real /bin/sh)', () => {
+ it('prints the tmux stamp and the HOST clock on one line, so the age needs one clock', () => {
+ const line = remoteCommand(remoteSessionAgeArgs(conn, '/cm/p1', 'nt-abc'))
+ const now = Math.floor(Date.now() / 1000)
+ const out = runWithTmuxAnswer(line, String(now - 3))
+ const [created, hostNow] = out.trim().split(/\s+/)
+ expect(Number(created)).toBe(now - 3)
+ expect(Number(hostNow)).toBeGreaterThanOrEqual(now)
+ expect(parseSessionAge(out)).toBeGreaterThanOrEqual(3)
+ })
+
+ it('a session tmux cannot find yields no age — the empty format leaves ONE field', () => {
+ // Measured against a real sshd + tmux 3.3a: an unknown target prints an empty first field, so
+ // the line comes back as just the host clock. `parseSessionAge` must read that as "no answer",
+ // never as an epoch — the caller ACTS on a small number.
+ const line = remoteCommand(remoteSessionAgeArgs(conn, '/cm/p1', 'nt-nope'))
+ const out = runWithTmuxAnswer(line, '')
+ expect(out.trim().split(/\s+/)).toHaveLength(1)
+ expect(parseSessionAge(out)).toBeNull()
+ })
+
+ it('carries the PATH prologue, so a host with tmux outside the exec-channel PATH still answers', () => {
+ // Issue #449: an ssh exec channel gets a non-login shell, and Homebrew's tmux lives in
+ // /opt/homebrew/bin. Every remote tmux invocation goes through the same prologue.
+ const line = remoteCommand(remoteSessionAgeArgs(conn, '/cm/p1', 'nt-abc'))
+ expect(line).toContain('/opt/homebrew/bin')
+ })
+
+ it('targets EXACTLY one session — tmux prefix matching could answer about another node', () => {
+ const line = remoteCommand(remoteSessionAgeArgs(conn, '/cm/p1', 'nt-abc'))
+ expect(line).toContain("-t '=nt-abc:'")
+ })
+})
+
+describe('parseSessionAge', () => {
+ it('reads a well-formed pair', () => {
+ expect(parseSessionAge('1000 1042\n')).toBe(42)
+ expect(parseSessionAge(' 1000 1000 ')).toBe(0)
+ })
+
+ it('answers null for everything it cannot read as two epochs', () => {
+ for (const bad of ['', '\n', 'abc def', '1000', '1000 abc', 'abc 1000', '0 1000', '1000 0']) {
+ expect(parseSessionAge(bad)).toBeNull()
+ }
+ })
+
+ it('a clock that stepped BACKWARDS is unknowable, not brand new', () => {
+ // The caller acts on a small age, so a negative must never round to zero.
+ expect(parseSessionAge('1042 1000')).toBeNull()
+ })
+})
diff --git a/src/main/index.ts b/src/main/index.ts
index 26b8a6cd3..834844701 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1453,6 +1453,10 @@ app.whenReady().then(async () => {
ptyManager.remoteSessionConfirmed(persistKey, sshRemote)
)
+ // The late cold-start check (PtyCreateResult.freshUnverified). Registered in core's shared pty
+ // block below on the server side too — this one is here beside its sibling.
+ corePlatform.handle(IPC.ptySessionAge, (persistKey: string) => ptyManager.sessionAgeSeconds(persistKey))
+
// Gemini's title read needs the transcript path its own context tail already tracks (nothing
// scans for it). That tail is created ~600 lines below with the rest of the hook plumbing, while
// this deps object is consumed by the ptyReadSessionName handler just under here and by the
diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.ts
index a5b60446e..4ae20ed19 100644
--- a/src/main/remote-ssh/ssh-project.test.ts
+++ b/src/main/remote-ssh/ssh-project.test.ts
@@ -2702,12 +2702,12 @@ describe('SshProjectManager — per-node tokens on the host', () => {
const { controlPath } = await mgr.connect('p1', conn)
await settle()
run.mockClear()
- await mgr.writeNodeTokenForNode(controlPath, 'node-9')
+ await mgr.writeNodeTokenForNode(controlPath, ['node-9'])
const cmds = run.mock.calls.map(([a]) => (a as string[]).join(' '))
expect(cmds.some((c) => /mv -f -- .*node-tokens\/\.nodeterm-[0-9a-f-]{36}\.tmp' '\/home\/u\/\.nodeterm\/node-tokens\/node-9'/.test(c))).toBe(true)
// an unknown control path is a no-op, not a throw
run.mockClear()
- await expect(mgr.writeNodeTokenForNode('/nope.sock', 'node-9')).resolves.toBeUndefined()
+ await expect(mgr.writeNodeTokenForNode('/nope.sock', ['node-9'])).resolves.toBeUndefined()
expect(run.mock.calls).toHaveLength(0)
})
})
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 08c0cbf14..c81536f1a 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -53,6 +53,7 @@ import { hookServer } from '../../core/agents/hook-server'
import {
nodeIdsForCanvas,
remoteNodeTokenMinter,
+ seedRemoteNodeTokens,
setRemoteNodeTokenWriter
} from '../../core/agents/node-token-service'
import { setRemoteSessionEnvWriter } from '../../core/remote-ssh/session-env'
@@ -1521,6 +1522,10 @@ export class SshProjectManager {
const ids = this.r.nodeIdsForProject?.(projectId) ?? []
if (!ids.length) return
await this.remoteHooks.writeNodeTokens(conn, controlPath, remoteHome, ids, mint)
+ // Tell the SPAWN path what this host now has, so a switch to this project does not re-ask for
+ // one round trip per node it already wrote (see `ensureRemoteNodeToken`). After the write, so
+ // a connect that never got that far claims nothing.
+ seedRemoteNodeTokens(controlPath, ids)
} catch {
/* fail-open: an identity file must never be able to fail a connect */
}
@@ -1566,14 +1571,17 @@ export class SshProjectManager {
}
}
- async writeNodeTokenForNode(controlPath: string, nodeId: string): Promise<void> {
+ async writeNodeTokenForNode(controlPath: string, nodeIds: readonly string[]): Promise<void> {
try {
+ if (!nodeIds.length) return
for (const c of this.conns.values()) {
if (c.controlPath !== controlPath) continue
if (!c.remoteHome || !c.hookEndpointPath) return
const mint = this.r.nodeTokenMinter?.()
if (!mint) return
- await this.remoteHooks.writeNodeTokens(c.conn, c.controlPath, c.remoteHome, [nodeId], mint)
+ // A LIST, because the spawn path coalesces a mount burst into one call (see
+ // `ensureRemoteNodeToken`). `writeNodeTokens` already de-duplicates and gates each id.
+ await this.remoteHooks.writeNodeTokens(c.conn, c.controlPath, c.remoteHome, nodeIds, mint)
return
}
} catch {
@@ -2582,8 +2590,8 @@ export function initSshProject(
})
// The spawn-path leg of the remote materialiser: `pty-manager` (core) reaches the ControlMaster
// through this registration, because the runner that owns it lives here, in main.
- setRemoteNodeTokenWriter((controlPath, nodeId) => {
- void mgr.writeNodeTokenForNode(controlPath, nodeId)
+ setRemoteNodeTokenWriter((controlPath, nodeIds) => {
+ void mgr.writeNodeTokenForNode(controlPath, nodeIds)
})
// Same seam, same shape: the pty spawn path stages a remote session's env file (gateway/custom
// values, argv-free) through the manager that owns the ssh runner. See core/remote-ssh/session-env.ts.
diff --git a/src/preload/index.ts b/src/preload/index.ts
index a91d77d3e..f06380b32 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -92,6 +92,7 @@ const api: NodeTerminalApi = {
capture: (persistKey, full) => ipcRenderer.invoke(IPC.ptyCapture, persistKey, full),
remoteSessionConfirmed: (persistKey, sshRemote) =>
ipcRenderer.invoke(IPC.ptyRemoteSessionConfirmed, persistKey, sshRemote),
+ sessionAge: (persistKey) => ipcRenderer.invoke(IPC.ptySessionAge, persistKey),
readScrollback: (persistKey) => ipcRenderer.invoke(IPC.ptyReadScrollback, persistKey),
sendText: (persistKey, text, opts) =>
ipcRenderer.invoke(IPC.ptySendText, persistKey, text, opts?.enter),
diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.ts
index 9836fcea5..0b279a02e 100644
--- a/src/renderer/bridge/ws-bridge.ts
+++ b/src/renderer/bridge/ws-bridge.ts
@@ -247,6 +247,11 @@ export function buildRealApi(
// ControlMaster to attach early over. `false` = "never attach early" = the pre-feature wait,
// which is exactly right for a shell that cannot produce the question.
remoteSessionConfirmed: () => Promise.resolve(false),
+ // REAL, unlike `remoteSessionConfirmed` above: the server runs on the machine whose tmux it is
+ // reading, so the local leg of this probe is exactly right there. Fail-open to `null` = "could
+ // not tell", the same answer every other failure path gives.
+ sessionAge: (persistKey) =>
+ client.request(IPC.ptySessionAge, persistKey).catch(() => null) as Promise<number | null>,
readScrollback: (persistKey) =>
client.request(IPC.ptyReadScrollback, persistKey) as Promise<string>,
sendText: (persistKey, text, opts) =>
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 40c597798..20fb3b175 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -147,6 +147,7 @@ import {
LIVENESS_QUERY_MS
} from '../terminal/agent-liveness'
import { shouldAutoWake, shouldColdResume } from '../terminal/hibernation-policy'
+import { coldSelfHealVerdict } from '../terminal/cold-self-heal'
import { WakeInputBuffer } from '../terminal/wake-input-buffer'
import { FindBar } from '../components/FindBar'
import { IconChat, IconChevronDown, IconChevronRight, IconClose, IconEye, IconEyeOff, IconGrid, IconMic, IconMoveTo, IconPlay, IconReload, IconSearch, IconSparkle } from '../components/icons'
@@ -231,6 +232,13 @@ const isMac = isMacPlatform()
* overlay it falls back to is cheap and self-healing, so waiting longer buys nothing. */
export const SSH_REMOTE_WAIT_MS = 20000
+/** How long a REMOTE spawn may take before the node says out loud that it is waiting.
+ *
+ * Longer than a healthy attach by a wide margin — 18 parallel warm attaches at 50 ms RTT painted
+ * in a median of 0.16 s — so a normal switch never prints it, and short enough that a node held
+ * behind the spawn queue (or a contended master) is not blank for seconds with nothing to read. */
+export const SLOW_REMOTE_SPAWN_NOTICE_MS = 1500
+
/**
* Which connection scope a remote node in the ACTIVE project runs over: the project's own id when
* the project IS that SSH endpoint, otherwise the project × endpoint host attachment — a remote
@@ -3008,6 +3016,20 @@ export function TerminalNode({
setCo(termKey, { offline: false })
sentCols = term.cols
sentRows = term.rows
+ // A remote spawn can now WAIT, and a terminal that waits in silence reads as broken — the
+ // same reason the "[connecting…]" line above exists. Core paces remote spawns per
+ // ControlMaster (pty-spawn-gate.ts), so on a project switch the later nodes of a big canvas
+ // sit in a queue for a moment; a slow host or a contended master does the same thing without
+ // any queue. The wording claims only what is true from here: we are waiting for the host,
+ // whichever of those it is. Cleared the instant the create resolves (or the node tears down).
+ const slowSpawn =
+ sshRemoteTmux && ssh
+ ? setTimeout(() => {
+ if (!disposed) term.write(`[waiting for ${ssh.user}@${ssh.host}…]
+`)
+ }, SLOW_REMOTE_SPAWN_NOTICE_MS)
+ : undefined
+ if (slowSpawn !== undefined) cleanups.push(() => clearTimeout(slowSpawn))
transport
.create({
cols: term.cols,
@@ -3037,6 +3059,7 @@ export function TerminalNode({
async ({
sessionId: sid,
fresh,
+ freshUnverified,
accountFallback: fellBack,
staleCwd,
closed,
@@ -3046,6 +3069,8 @@ export function TerminalNode({
persistent,
unavailable
}) => {
+ // The spawn answered: whatever it says, we are no longer waiting on the host.
+ clearTimeout(slowSpawn)
// REFUSED: `requireRemote` and core could not spawn remotely (the master died inside our
// round-trip, or `ssh` is missing). Nothing was spawned — land in the same offline state
// the near-side guard above produces, retry included.
@@ -3370,25 +3395,68 @@ export function TerminalNode({
// node is armed is Canvas's question, it can change after the spawn resolves, and the
// subscribers filter by id anyway.
whenShellSettled(() => setSessionReady(id, true))
+ // Paused (see agentStatus.paused) is the ONE exception to the "a cold start always resumes"
+ // rule below: it exists precisely to survive a cold restart, so it must NOT be dropped, and
+ // the auto-resume branch must be skipped — only an explicit Resume (which reuses the same
+ // command-building path through the registered hibernate/wake pair) may relaunch it. Read
+ // HERE because the late cold-start check below is gated on it too: a paused node has
+ // nothing to relaunch, so it must not pay two probe round trips to find that out.
+ const pausedNow = !!useAgentStatus.getState().byId[id]?.paused
+ // LATE COLD-START DETECTION (see terminal/cold-self-heal.ts). `freshUnverified` says the
+ // create's `fresh:false` came from a freshness read that never completed, so "a session
+ // already exists" was a fold and not an answer — and `new-session -A` may have made the
+ // session we are now attached to. tmux can settle it after the fact, so ask ONCE, here,
+ // where the attach has landed: a session created within seconds of it is one WE created.
+ //
+ // Deliberately gated on there being something to DO with the answer: no `initialCommand`
+ // (that branch wins anyway and must not be delayed by two round trips), an agent we can
+ // resume, not armed, not paused. A plain terminal has no conversation to lose, and paying
+ // a probe to tell it so would be the channel pressure this whole area exists to reduce.
+ const canColdRestore =
+ !!agentId && canResume(agentId) && !data.pendingLaunch && shouldColdResume(pausedNow)
+ let coldStart = fresh
+ if (!fresh && freshUnverified && !data.initialCommand && canColdRestore) {
+ // After the shell has settled, not at this instant: the attach is a network round trip
+ // and the session may not exist yet when the create promise resolves. This is the same
+ // settle the held-launch and initialCommand writers use, so by the time it fires the
+ // pane is alive and a shell has printed its prompt.
+ await new Promise<void>((resolve) => {
+ whenShellSettled(resolve)
+ // …and settle on a TEARDOWN too. `whenShellSettled`'s own cleanup marks itself done
+ // WITHOUT running the callback, so without this an unmount mid-wait would leave this
+ // continuation parked on a promise nothing can ever resolve — holding the xterm and
+ // every closure in it for the life of the app. `cleanups` does not run for a PARK
+ // (same array, same session), so the healthy re-adoption path is untouched.
+ cleanups.push(resolve)
+ })
+ if (onDisposed()) return
+ const [ageSeconds, paneCommand] = await Promise.all([
+ api.pty.sessionAge(id).catch(() => null),
+ api.pty.paneCommand(id).catch(() => null)
+ ])
+ if (onDisposed()) return
+ coldStart =
+ coldSelfHealVerdict({
+ fresh,
+ freshUnverified: true,
+ ageSeconds,
+ paneCommand,
+ isShell: isShellCommand
+ }) === 'cold'
+ }
// Hibernation × cold restore. `hibernated` is PERSISTED, so it can outlive the very thing
// it describes:
- // - `fresh` (the tmux session is GONE — a reboot, a reaped server, a first open): the CLI
- // it refers to died with the session. The node is not hibernated, it is simply gone, so
- // the flag is dropped and the ORDINARY cold-restore auto-resume below brings the
- // conversation back exactly as it does for any other node. Leaving the flag set would
- // park a SLEEPING chip over a dead pane and hand the resume to the wake path, which
- // (rightly) refuses a pane it cannot see a shell in.
- // - warm attach (`!fresh`): the shell we exited to is still sitting in the pane, by
- // design. Nothing auto-resumes here — the branch below is `fresh`-only — and the wake
- // path owns the relaunch. That is the whole feature.
- if (fresh && useAgentStatus.getState().byId[id]?.hibernated) {
+ // - a COLD start (the tmux session is GONE — a reboot, a reaped server, a first open, or
+ // the late detection above): the CLI it refers to died with the session. The node is not
+ // hibernated, it is simply gone, so the flag is dropped and the ORDINARY cold-restore
+ // auto-resume below brings the conversation back exactly as it does for any other node.
+ // Leaving it set would park a SLEEPING chip over a dead pane and hand the resume to the
+ // wake path, which (rightly) refuses a pane it cannot see a shell in.
+ // - a real warm attach: the shell we exited to is still sitting in the pane, by design.
+ // Nothing auto-resumes here and the wake path owns the relaunch. That is the feature.
+ if (coldStart && useAgentStatus.getState().byId[id]?.hibernated) {
useAgentStatus.getState().setHibernated(id, false)
}
- // Paused (see agentStatus.paused) is the ONE exception to the "fresh always resumes" rule
- // above: it exists precisely to survive a cold restart, so it must NOT be dropped here, and
- // the auto-resume branch below must be skipped — only an explicit Resume (which reuses the
- // same command-building path through the registered hibernate/wake pair) may relaunch it.
- const pausedNow = !!useAgentStatus.getState().byId[id]?.paused
// The clear-env strip is one-shot: once this spawn has applied it, clear the flag so a later
// ordinary Restart re-applies the gateway. (The recycle action re-sets it for its own spawn.)
if (data.clearEnv) {
@@ -3399,13 +3467,7 @@ export function TerminalNode({
if (data.initialCommand) {
writeWhenShellReady(data.initialCommand)
updateNodeData(id, { initialCommand: undefined })
- } else if (
- fresh &&
- agentId &&
- canResume(agentId) &&
- !data.pendingLaunch &&
- shouldColdResume(pausedNow)
- ) {
+ } else if (coldStart && canColdRestore) {
// Cold restart of an agent node: the live agent is gone, so re-launch it. Resume the
// prior conversation by its session id when we have one; otherwise start the agent
// fresh. Plain terminals get nothing here — just the restored shell.
@@ -3585,6 +3647,8 @@ export function TerminalNode({
}
})
.catch((err: unknown) => {
+ // Same reason as the fulfilled path: we are no longer waiting on the host.
+ clearTimeout(slowSpawn)
// THE missing handler, and the answer to "some terminals are black" (2026-08-06).
//
// A rejected create means core started NOTHING: no session to tear down, no data gate to
diff --git a/src/renderer/nodes/session-ready-signal.test.ts b/src/renderer/nodes/session-ready-signal.test.ts
index 5ae2cb997..69bf87571 100644
--- a/src/renderer/nodes/session-ready-signal.test.ts
+++ b/src/renderer/nodes/session-ready-signal.test.ts
@@ -77,13 +77,27 @@ describe('an offscreen release keeps a tmux-backed session READY (source pins)',
describe('an ARMED node does not cold-start its agent under the hold (source pins)', () => {
it('the cold-restore relaunch is gated on there being no pendingLaunch', () => {
- // A first open is `fresh` by definition, so without this every `--after` / `verify` node
+ // A first open is a cold start by definition, so without this every `--after` / `verify` node
// launched a bare CLI on mount — and Canvas's held launch then arrived as TEXT typed into
// the session the hold existed to prevent.
- // Matched inside the condition rather than as one literal line: the branch also carries the
- // `paused` gate (shouldColdResume), and the two guards are independent refusals that must
- // both survive a reformat.
- expect(src).toMatch(/fresh &&\s*\n?\s*agentId &&\s*\n?\s*canResume\(agentId\) &&\s*\n?\s*!data\.pendingLaunch/)
+ //
+ // The four refusals now live in ONE predicate (`canColdRestore`) because the late cold-start
+ // check asks the same question before spending two probe round trips — so this pins the
+ // predicate's contents rather than the branch's old inline shape. `!data.pendingLaunch` and
+ // `shouldColdResume` are independent refusals and must both survive a reformat.
+ expect(src).toMatch(
+ /const canColdRestore =\s*\n?\s*!!agentId && canResume\(agentId\) && !data\.pendingLaunch && shouldColdResume\(pausedNow\)/
+ )
+ // …and the relaunch branch is the one that reads it.
+ expect(src).toContain('} else if (coldStart && canColdRestore) {')
+ })
+
+ it('the LATE cold-start check refuses the same node an armed hold would', () => {
+ // Same reason, one layer earlier: an armed node must not even pay the probe, and it must
+ // certainly not be handed a relaunch behind the hold's back.
+ expect(src).toMatch(
+ /if \(!fresh && freshUnverified && !data\.initialCommand && canColdRestore\) \{/
+ )
})
})
diff --git a/src/renderer/terminal/cold-self-heal.test.ts b/src/renderer/terminal/cold-self-heal.test.ts
new file mode 100644
index 000000000..6df8441d5
--- /dev/null
+++ b/src/renderer/terminal/cold-self-heal.test.ts
@@ -0,0 +1,63 @@
+import { describe, it, expect } from 'vitest'
+import { coldSelfHealVerdict, COLD_SELF_HEAL_MAX_AGE_S } from './cold-self-heal'
+
+/** A shell allowlist of the shape `isShellCommand` uses; the real one is injected in production. */
+const isShell = (c: string): boolean => ['bash', 'zsh', 'sh', 'fish'].includes(c)
+
+const base = {
+ fresh: false,
+ freshUnverified: true,
+ ageSeconds: 2,
+ paneCommand: 'bash',
+ isShell
+}
+
+describe('coldSelfHealVerdict', () => {
+ it('heals the case it exists for: an unverified verdict over a session our attach just made', () => {
+ expect(coldSelfHealVerdict(base)).toBe('cold')
+ })
+
+ it('never re-asks a verdict that came from a REAL read', () => {
+ // The whole point: a confident `fresh:false` is an answer, and re-asking it would spend a
+ // round trip per warm node on every project switch.
+ expect(coldSelfHealVerdict({ ...base, freshUnverified: false })).toBe('verdict-was-read')
+ })
+
+ it('does nothing when the cold path already ran', () => {
+ expect(coldSelfHealVerdict({ ...base, fresh: true })).toBe('already-cold')
+ })
+
+ it('an UNREADABLE age is not evidence — it refuses', () => {
+ // `null` covers an unreachable host, a dead master, the session-host backend and a garbled
+ // line. None of them say the session is new, and acting on one types into a live pane.
+ expect(coldSelfHealVerdict({ ...base, ageSeconds: null })).toBe('age-unknown')
+ })
+
+ it('refuses a session that predates our attach', () => {
+ expect(coldSelfHealVerdict({ ...base, ageSeconds: COLD_SELF_HEAL_MAX_AGE_S + 1 })).toBe(
+ 'session-predates-attach'
+ )
+ // …and accepts exactly at the boundary, so the window is inclusive as documented.
+ expect(coldSelfHealVerdict({ ...base, ageSeconds: COLD_SELF_HEAL_MAX_AGE_S })).toBe('cold')
+ expect(coldSelfHealVerdict({ ...base, ageSeconds: 0 })).toBe('cold')
+ })
+
+ it('refuses when an agent CLI already owns the pane, however young the session is', () => {
+ // Belt to the age check's braces: whatever the clock says, we must not type into a live agent.
+ expect(coldSelfHealVerdict({ ...base, ageSeconds: 1, paneCommand: 'claude' })).toBe(
+ 'pane-not-a-shell'
+ )
+ })
+
+ it('an UNREADABLE pane refuses too — never "nothing is running in it"', () => {
+ expect(coldSelfHealVerdict({ ...base, paneCommand: null })).toBe('pane-not-a-shell')
+ expect(coldSelfHealVerdict({ ...base, paneCommand: '' })).toBe('pane-not-a-shell')
+ })
+
+ it('the verdict-was-read refusal outranks every later check', () => {
+ // A confident answer must cost nothing even when the other inputs happen to look cold.
+ expect(
+ coldSelfHealVerdict({ ...base, freshUnverified: false, ageSeconds: 0, paneCommand: 'bash' })
+ ).toBe('verdict-was-read')
+ })
+})
diff --git a/src/renderer/terminal/cold-self-heal.ts b/src/renderer/terminal/cold-self-heal.ts
new file mode 100644
index 000000000..522851014
--- /dev/null
+++ b/src/renderer/terminal/cold-self-heal.ts
@@ -0,0 +1,85 @@
+/**
+ * Was a remote session we treated as a WARM reattach actually created by our own attach?
+ *
+ * THE INCIDENT (measured on the reporting host, 2026-09-15). The host's `nodeterm-rmt` tmux server
+ * died, so every remote session was gone; ten minutes later a 108-node SSH project was opened and
+ * 107 sessions had to be created in one mount burst. In the seven minutes around it sshd logged
+ * **757 `Accepted publickey` full logins** — on a healthy ControlMaster that number is ~0, because
+ * everything multiplexes over one connection. Under that pressure the per-node freshness read
+ * times out, and the read's own fail-safe (`RemoteSessionIndex`: anything that is not tmux's exit 1
+ * answers "exists", because typing `claude --resume …` into a LIVE agent pane is the worse failure)
+ * hands back "warm" for a session that does not exist. `tmux new-session -A` then CREATES an empty
+ * one, `fresh:false` skips the cold-restore branch, and the node sits at a bare shell forever with
+ * the user's conversation stranded on disk.
+ *
+ * 15:29 burst, 22 sessions: 18 claude / 4 bash -> 82% resumed
+ * 15:39 burst, 107 sessions: 41 claude / 66 bash -> 38% resumed
+ *
+ * Load-dependent, i.e. a race, not a deterministic bug.
+ *
+ * THE FIX IS A SECOND OPINION, NOT A DIFFERENT FOLD. The fail-safe stays exactly as it is: it is
+ * right, and it is right for a reason that has not changed. What is added is that when the verdict
+ * came from a FAILED read (`PtyCreateResult.freshUnverified`), the answer is re-asked ONCE after
+ * the attach has landed — by which time the burst is over, the master is healthy, and tmux itself
+ * can settle it authoritatively: `#{session_created}` survives a `new-session -A` attach, so a
+ * session created within seconds of our own attach is one WE made.
+ *
+ * Every rule below is a refusal, and each closes a way this could type into somebody's live work.
+ */
+
+/** How young a session may be and still be read as "our attach created it".
+ *
+ * Sized for the case it exists for, which is a SLOW one: the attach it is dated against is the
+ * same ssh round trip the burst was starving, so a couple of seconds is routine. It is bounded on
+ * the other side by what it has to exclude — a session a human opened and started working in —
+ * and 30 s is far short of that while covering a badly contended attach. */
+export const COLD_SELF_HEAL_MAX_AGE_S = 30
+
+export interface ColdSelfHealInput {
+ /** The create's own verdict. `true` means the cold path already ran — nothing to heal. */
+ fresh: boolean
+ /** The create reported that `fresh:false` came from a read it could not complete. */
+ freshUnverified: boolean
+ /** Seconds since the session was created, on the machine that holds it. `null` = could not tell. */
+ ageSeconds: number | null
+ /** `#{pane_current_command}` for this node. `null` = could not tell. */
+ paneCommand: string | null
+ /** Does a shell own the pane? Injected (the caller owns `isShellCommand`) so this stays pure. */
+ isShell: (command: string) => boolean
+}
+
+export type ColdSelfHealVerdict =
+ /** The session was created by our own attach: run the cold-restore relaunch. */
+ | 'cold'
+ /** Anything else. Named so a caller (and a test) can say WHY nothing happened. */
+ | 'verdict-was-read'
+ | 'already-cold'
+ | 'age-unknown'
+ | 'session-predates-attach'
+ | 'pane-not-a-shell'
+
+/**
+ * Rules, in the order they refuse:
+ *
+ * 1. **Never for a verdict that came from a real read.** A confident `fresh:false` is an answer,
+ * and re-asking it would spend a round trip per warm node on every switch — the channel
+ * pressure this whole area exists to reduce.
+ * 2. **Never twice, and never when the cold path already ran.** `fresh` means the relaunch has
+ * happened; the caller additionally fires this at most once per spawn.
+ * 3. **An unknown age is not evidence.** `null` covers an unreadable host, a dead master, a
+ * session-host backend and a garbled line — none of which say the session is new.
+ * 4. **A session older than the window is somebody's live work**, whether ours or another
+ * client's, and nothing may be typed into it.
+ * 5. **The pane must be a SHELL**, re-read at this moment — the same gate the hibernation wake and
+ * the resume-miss watcher keep. It is belt to rule 4's braces: if an agent CLI already owns the
+ * pane then whatever the clock says, the answer is no. `null` is "we could not see the pane",
+ * never "nothing is running in it", so it refuses too.
+ */
+export function coldSelfHealVerdict(input: ColdSelfHealInput): ColdSelfHealVerdict {
+ if (input.fresh) return 'already-cold'
+ if (!input.freshUnverified) return 'verdict-was-read'
+ if (input.ageSeconds === null) return 'age-unknown'
+ if (input.ageSeconds > COLD_SELF_HEAL_MAX_AGE_S) return 'session-predates-attach'
+ if (!input.paneCommand || !input.isShell(input.paneCommand)) return 'pane-not-a-shell'
+ return 'cold'
+}
diff --git a/src/server/index.ts b/src/server/index.ts
index ade8f4e52..33ef8f837 100644
--- a/src/server/index.ts
+++ b/src/server/index.ts
@@ -295,6 +295,9 @@ export async function startServer(
platform.handle(IPC.ptyCapture, (persistKey: string, full?: boolean) =>
ptyManager.captureSession(persistKey, full)
)
+ // The late cold-start check (PtyCreateResult.freshUnverified). Pure core, and this shell runs on
+ // the machine whose tmux it reads, so the answer is as good as the desktop's local one.
+ platform.handle(IPC.ptySessionAge, (persistKey: string) => ptyManager.sessionAgeSeconds(persistKey))
// fs + git + commit handlers (shared with desktop core services). The ticket store is shared
// between the RPC side (which mints) and the HTTP side (which redeems) — one instance, so a
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index ed2428e51..14e1fc4f0 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -23,6 +23,9 @@ export const IPC = {
* Gates the early-attach path (attach as soon as the master answers `-O check`, before the
* connect's remote setup chain finishes); desktop-only, like SSH projects themselves. */
ptyRemoteSessionConfirmed: 'pty:remote-session-confirmed',
+ /** Renderer → core: seconds since this node's tmux session was created, measured on the machine
+ * that holds it (`PtyApi.sessionAge`). The late cold-start check behind `freshUnverified`. */
+ ptySessionAge: 'pty:session-age',
ptyReadScrollback: 'pty:read-scrollback',
ptySendText: 'pty:send-text',
ptyTmuxStatus: 'pty:tmux-status',
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 45de04503..6411e5473 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -182,6 +182,24 @@ export interface PaneCursor {
export interface PtyCreateResult {
sessionId: string
fresh: boolean
+ /**
+ * `fresh` is FALSE, but the freshness read never completed — so "a session already exists" was a
+ * fold, not an answer (`RemoteSessionIndex`: only tmux's own exit 1 is evidence of absence, and
+ * every other outcome answers "exists" because typing `claude --resume …` into a live agent pane
+ * is the worse failure). SSH nodes only; a local `has-session` does not have this failure mode.
+ *
+ * Under a mount burst that overruns the host's `MaxSessions`, that fold is wrong often enough to
+ * matter: `tmux new-session -A` then CREATES an empty session, `fresh:false` skips cold restore,
+ * and the node sits at a bare shell with the user's conversation stranded on disk. MEASURED on
+ * the reporting host: of 107 sessions created in one switch, 66 ended at a bare shell — against
+ * 4 of 22 in a smaller burst minutes earlier, i.e. load-dependent, i.e. a race.
+ *
+ * The renderer re-asks ONCE after the attach has landed (tmux's own `#{session_created}` settles
+ * it; see `PtyApi.sessionAge`) and runs the cold-restore relaunch if the session turns out to be
+ * one we just made. Absent = the verdict was read, or this is not a remote node ⇒ nothing to
+ * re-ask.
+ */
+ freshUnverified?: boolean
/** Set when the node's `accountId` had no config dir at spawn, so the session fell back to the
* system account. The renderer flags the account chip (folder-missing warning) when true. */
accountFallback?: boolean
@@ -941,6 +959,16 @@ export interface PtyApi {
generateGroupName(memberKeys: string[], cwd: string): Promise<GitResult>
/** Capture a terminal session's output as text. `full` grabs the entire scrollback. */
capture(persistKey: string, full?: boolean): Promise<string>
+ /**
+ * Seconds since this node's tmux session was created, measured on the machine that holds it, or
+ * `null` when that cannot be told (no session, no tmux, an unreadable host, a garbled answer).
+ *
+ * The late cold-start check behind `PtyCreateResult.freshUnverified`: `#{session_created}`
+ * survives a `new-session -A` attach, so a session created within seconds of our own attach is
+ * one we just made — i.e. the node was cold after all. `null` is never an age; the caller acts
+ * only on a small number.
+ */
+ sessionAge(persistKey: string): Promise<number | null>
/**
* Has the host behind `sshRemote.controlPath` POSITIVELY listed this node's remote tmux session?
*