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.

perf(ssh): one remote session-list read per switch, not one probe per node

enes2cfb8aa420ef
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index e691c42dc..a131c67e5 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -22,7 +22,8 @@ import { hookServer, PERM_WAIT_SECS_DEFAULT } from './agents/hook-server'
import {
probeSaysAbsent,
remoteHookEnvArgs,
- remoteTmuxHasSessionArgs,
+ remoteListSessionsArgs,
+ parseRemoteSessionNames,
remoteTmuxKillArgs,
localKillSockets,
localTmuxKillArgs,
@@ -41,6 +42,8 @@ import {
type RemoteEndPlan,
type RemoteNodeOwnerResolver
} from './remote-end'
+import { RemoteSessionIndex } from './remote-ssh/remote-session-index'
+import type { SshConnection } from '../shared/ssh'
import { recordPendingRemoteKill, type PendingRemoteKill } from './pending-remote-kills'
import { probeAgentSockToPin } from './remote-ssh/agent-probe'
import { parsePaneCursor } from './pane-cursor'
@@ -2339,23 +2342,40 @@ export class PtyManager {
/** Does the node's remote tmux session exist (over the project's ControlMaster)? Async so the
* network round-trip never blocks the main event loop. A probe that FAILED for transport
* reasons answers "exists": only tmux's own exit 1 is evidence of absence (probeSaysAbsent) —
- * a dead/reconnecting master read as "cold" typed a resume command into a live agent session. */
+ * a dead/reconnecting master read as "cold" typed a resume command into a live agent session.
+ *
+ * ONE `list-sessions` per host per burst, not one `has-session` per node: a project switch
+ * mounts every node in the same tick, and N probe channels on top of N pty channels overruns a
+ * stock host's `MaxSessions`, which costs each excess child a full TCP+auth login. The whole
+ * measurement is in `remote-session-index.ts`. The verdict contract is identical either way. */
private async remoteSessionExists(
sshRemote: NonNullable<PtyCreateOptions['sshRemote']>,
sessionId: string
): Promise<boolean> {
- const ssh = findSsh()
- if (!ssh) return true // can't probe → not evidence of absence; warm attach types nothing
- try {
- await runAsync(ssh, remoteTmuxHasSessionArgs(sshRemote.conn, sshRemote.controlPath, sessionId), {
- timeout: PROBE_TIMEOUT_MS
- })
- return true
- } catch (e) {
- return !probeSaysAbsent(e)
- }
+ return this.remoteSessions.exists(sshRemote.controlPath, sessionId, sshRemote.conn)
}
+ /** One coalesced remote `tmux list-sessions` per ControlMaster (see remote-session-index.ts).
+ * `list` carries the SAME classification the per-node probe had: tmux's own exit 1 ("no server
+ * running") is the only evidence of absence; ssh 255 / 127 / a timeout answer `unknown`, which
+ * the index renders as "exists" — a warm attach, which types nothing into the pane. */
+ private remoteSessions = new RemoteSessionIndex<SshConnection>({
+ list: async (controlPath, conn) => {
+ const ssh = findSsh()
+ // No ssh binary to probe with: not evidence of absence.
+ if (!ssh) return { kind: 'unknown' }
+ try {
+ const { stdout } = await runAsync(ssh, remoteListSessionsArgs(conn, controlPath), {
+ timeout: PROBE_TIMEOUT_MS
+ })
+ return { kind: 'names', names: parseRemoteSessionNames(stdout) }
+ } catch (e) {
+ // `list-sessions` exits 1 with "no server running" — the host genuinely holds no session.
+ return probeSaysAbsent(e) ? { kind: 'names', names: [] } : { kind: 'unknown' }
+ }
+ }
+ })
+
/** Find the live session registered under a node id (persistKey), if any. */
private sessionByPersistKey(persistKey: string): Session | undefined {
for (const session of this.sessions.values()) {
@@ -2989,6 +3009,10 @@ export class PtyManager {
'[pty] remote session env skipped (no remote home or no uploader) — agent will launch without gateway/custom env'
)
}
+ // `new-session -A` is about to make this session exist on the host. Record it, so a second
+ // look inside the index's cache window (a respawn, a co-attach) cannot be told it is cold —
+ // which is what makes the renderer replay a snapshot and type a resume line into a live pane.
+ this.remoteSessions.markPresent(options.sshRemote.controlPath, sessionName(options.persistKey))
args = remoteTmuxPtyArgs(
options.sshRemote.conn,
options.sshRemote.controlPath,
@@ -4760,6 +4784,9 @@ export class PtyManager {
await owe(plan.reason)
return
}
+ // The host's session set is about to change under the cached list; drop it rather than let a
+ // recreate inside the window read as warm.
+ this.remoteSessions.invalidate(plan.controlPath)
try {
await this.confirmedProcessRun(
plan.ssh,
diff --git a/src/core/remote-ssh/control-master.test.ts b/src/core/remote-ssh/control-master.test.ts
index b5502624a..28407287f 100644
--- a/src/core/remote-ssh/control-master.test.ts
+++ b/src/core/remote-ssh/control-master.test.ts
@@ -4,7 +4,6 @@ import {
controlPathFor,
masterArgs,
childArgs,
- remoteTmuxHasSessionArgs,
remoteTmuxPasteArgs,
remoteTmuxEnterArgs,
probeSaysAbsent,
@@ -172,16 +171,6 @@ describe('childArgs', () => {
})
})
-describe('remoteTmuxHasSessionArgs', () => {
- it('checks the remote socket for the node session', () => {
- expect(remoteTmuxHasSessionArgs(conn, '/s.sock', 'nt-x')).toEqual([
- ...childPrefix,
- `${TP}tmux -L ${RMT_TMUX_SOCKET} has-session -t nt-x`
- ])
- })
-})
-
describe('remoteTmuxPasteArgs', () => {
const TMUX = `tmux -L ${RMT_TMUX_SOCKET}`
const BUF = 'nt-paste-deadbeef'
diff --git a/src/core/remote-ssh/control-master.ts b/src/core/remote-ssh/control-master.ts
index 9db3fa2d1..f36a42138 100644
--- a/src/core/remote-ssh/control-master.ts
+++ b/src/core/remote-ssh/control-master.ts
@@ -226,9 +226,6 @@ export function checkMasterArgs(conn: SshConnection, controlPath: string): strin
export function exitMasterArgs(conn: SshConnection, controlPath: string): string[] {
return ['-O', 'exit', '-o', `ControlPath=${controlPath}`, ...portArgs(conn), target(conn)]
}
-export function remoteTmuxHasSessionArgs(conn: SshConnection, controlPath: string, sessionId: string): string[] {
- return childArgs(conn, controlPath, tmuxCmd(`tmux -L ${RMT_TMUX_SOCKET} has-session -t ${sessionId}`))
-}
/**
* Every nodeterm tmux session on the host, by name.
*
diff --git a/src/core/remote-ssh/remote-session-index.test.ts b/src/core/remote-ssh/remote-session-index.test.ts
new file mode 100644
index 000000000..a4762bf0f
--- /dev/null
+++ b/src/core/remote-ssh/remote-session-index.test.ts
@@ -0,0 +1,116 @@
+import { describe, it, expect, vi } from 'vitest'
+import {
+ RemoteSessionIndex,
+ REMOTE_SESSION_INDEX_TTL_MS,
+ type SessionListOutcome
+} from './remote-session-index'
+
+function deferred<T>() {
+ let resolve!: (v: T) => void
+ const promise = new Promise<T>((r) => {
+ resolve = r
+ })
+ return { promise, resolve }
+}
+
+describe('RemoteSessionIndex', () => {
+ it('answers N concurrent callers with ONE list read (the burst this exists for)', async () => {
+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: ['nt-a', 'nt-b'] }))
+ const idx = new RemoteSessionIndex<null>({ list })
+
+ const answers = await Promise.all(
+ ['nt-a', 'nt-b', 'nt-c', 'nt-d'].map((id) => idx.exists('/cm/p1', id, null))
+ )
+
+ expect(answers).toEqual([true, true, false, false])
+ expect(list).toHaveBeenCalledTimes(1)
+ })
+
+ it('keeps hosts separate — one control path per read', async () => {
+ const list = vi.fn(async (cp: string): Promise<SessionListOutcome> =>
+ cp === '/cm/p1' ? { kind: 'names', names: ['nt-a'] } : { kind: 'names', names: [] }
+ )
+ const idx = new RemoteSessionIndex<null>({ list })
+
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(true)
+ expect(await idx.exists('/cm/p2', 'nt-a', null)).toBe(false)
+ expect(list).toHaveBeenCalledTimes(2)
+ })
+
+ it('a failed READ answers "exists" — never evidence of absence', async () => {
+ const idx = new RemoteSessionIndex<null>({ list: async () => ({ kind: 'unknown' }) })
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(true)
+ })
+
+ it('a THROWN list is a failed read, not an absence', async () => {
+ const idx = new RemoteSessionIndex<null>({
+ list: async () => {
+ throw new Error('ssh 255')
+ }
+ })
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(true)
+ })
+
+ it('an empty name list IS absence (tmux has no server / no sessions)', async () => {
+ const idx = new RemoteSessionIndex<null>({ list: async () => ({ kind: 'names', names: [] }) })
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(false)
+ })
+
+ it('markPresent beats a cached absence — a session we just spawned is never cold', async () => {
+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: [] }))
+ const idx = new RemoteSessionIndex<null>({ list })
+
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(false)
+ idx.markPresent('/cm/p1', 'nt-a')
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(true)
+ // ...and only for that session.
+ expect(await idx.exists('/cm/p1', 'nt-b', null)).toBe(false)
+ expect(list).toHaveBeenCalledTimes(1)
+ })
+
+ it('markPresent applies to a read that is still on the wire', async () => {
+ const gate = deferred<SessionListOutcome>()
+ const idx = new RemoteSessionIndex<null>({ list: () => gate.promise })
+
+ const pending = idx.exists('/cm/p1', 'nt-a', null)
+ idx.markPresent('/cm/p1', 'nt-a') // the spawn raced the probe
+ gate.resolve({ kind: 'names', names: [] })
+ await pending
+
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(true)
+ })
+
+ it('re-reads once the window has passed', async () => {
+ let now = 1_000
+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: ['nt-a'] }))
+ const idx = new RemoteSessionIndex<null>({ list, now: () => now })
+
+ await idx.exists('/cm/p1', 'nt-a', null)
+ now += REMOTE_SESSION_INDEX_TTL_MS - 1
+ await idx.exists('/cm/p1', 'nt-a', null)
+ expect(list).toHaveBeenCalledTimes(1)
+
+ now += 2
+ await idx.exists('/cm/p1', 'nt-a', null)
+ expect(list).toHaveBeenCalledTimes(2)
+ })
+
+ it('invalidate forgets the host, markPresent included', async () => {
+ const list = vi.fn(async (): Promise<SessionListOutcome> => ({ kind: 'names', names: [] }))
+ const idx = new RemoteSessionIndex<null>({ list })
+
+ idx.markPresent('/cm/p1', 'nt-a')
+ idx.invalidate('/cm/p1')
+ expect(await idx.exists('/cm/p1', 'nt-a', null)).toBe(false)
+ })
+
+ it('hands the caller ctx through to the list builder', async () => {
+ const list = vi.fn(async (_cp: string, ctx: { host: string }): Promise<SessionListOutcome> => ({
+ kind: 'names',
+ names: [ctx.host]
+ }))
+ const idx = new RemoteSessionIndex<{ host: string }>({ list })
+ expect(await idx.exists('/cm/p1', 'nt-x', { host: 'nt-x' })).toBe(true)
+ expect(list).toHaveBeenCalledWith('/cm/p1', { host: 'nt-x' })
+ })
+})
diff --git a/src/core/remote-ssh/remote-session-index.ts b/src/core/remote-ssh/remote-session-index.ts
new file mode 100644
index 000000000..d6160bf93
--- /dev/null
+++ b/src/core/remote-ssh/remote-session-index.ts
@@ -0,0 +1,122 @@
+// One `tmux list-sessions` per host per switch, instead of one `has-session` per node.
+//
+// WHY THIS EXISTS (measured, 2026-09-14). Every remote terminal node asks the host "does my tmux
+// session already exist?" before it spawns, because the answer decides whether the renderer
+// replays a scrollback snapshot and re-issues `claude --resume` (cold) or lets tmux repaint (warm).
+// That probe was one ssh child per node, and a project switch mounts every node in ONE tick — so a
+// project with N remote terminals fired N probe channels at the same instant as its N pty channels.
+//
+// A stock sshd allows `MaxSessions 10` CHANNELS on one connection, and our ControlMaster is one
+// connection. Past that limit ssh answers `mux_client_request_session: session request failed:
+// Session open refused by peer`; the refused child then tries to become a master itself, cannot
+// bind the socket the live master already owns (`ControlSocket … already exists, disabling
+// multiplexing`) and completes a FULL TCP+KEX+auth login instead. Both lines in that order are the
+// user-visible symptom, and they are one failure, not two. Enough simultaneous logins then trip the
+// host's `MaxStartups` and some are reset outright, which fails a terminal, which starts the
+// reconnect backoff — seconds of black pane.
+//
+// Measured against a real sshd (MaxSessions 10, 20 ms RTT), one switch to a 12-terminal project:
+// per-node probes: 14 refusals, 12 full logins, 4 connections reset, 1.67 s to paint all panes
+// coalesced (here): 3 refusals, 3 full logins, 0 connections reset, 1.06 s
+// With 18 terminals the per-node version left a pane that never painted at all (17/18).
+//
+// The verdict contract is unchanged, and it is the load-bearing part: only tmux's own exit 1
+// ("no server running") is evidence of absence. Any other outcome — ssh 255 on a dead master,
+// 127 with tmux off the remote PATH, a timeout — is a failed READ, and a failed read answers
+// "exists", because a transport failure read as "cold" makes the desktop type `claude --resume …`
+// into a LIVE fullscreen agent session (see `probeSaysAbsent`).
+
+/** How long one host's session list may answer for. Long enough to cover a single mount burst,
+ * short enough that the answer cannot survive into an unrelated interaction. The coalescing of
+ * CONCURRENT callers (the burst itself) does not depend on this at all — it rides the in-flight
+ * promise — so the window only serves stragglers. */
+export const REMOTE_SESSION_INDEX_TTL_MS = 1000
+
+/** What one `tmux list-sessions` read established. `unknown` is a failed READ, never absence. */
+export type SessionListOutcome = { kind: 'names'; names: string[] } | { kind: 'unknown' }
+
+export interface RemoteSessionIndexDeps<Ctx> {
+ /** Run `tmux list-sessions` on the host behind `controlPath` and classify the result. `ctx` is
+ * whatever the caller needs to BUILD that command (the project's `SshConnection`); the index
+ * itself never looks inside it, which is what keeps this module free of ssh types. */
+ list: (controlPath: string, ctx: Ctx) => Promise<SessionListOutcome>
+ now?: () => number
+}
+
+interface Entry {
+ at: number
+ outcome?: SessionListOutcome
+ inflight?: Promise<SessionListOutcome>
+ /** Sessions THIS process created since the entry was made. A session we just spawned exists,
+ * whatever a list read taken a moment earlier said — without this a respawn inside the window
+ * would be told "cold" and replay a snapshot over a live pane. */
+ spawned: Set<string>
+}
+
+export class RemoteSessionIndex<Ctx> {
+ private byPath = new Map<string, Entry>()
+ private now: () => number
+ constructor(private deps: RemoteSessionIndexDeps<Ctx>) {
+ this.now = deps.now ?? (() => Date.now())
+ }
+
+ /**
+ * Does `sessionId` exist on the host behind `controlPath`?
+ *
+ * `true` also means "we could not tell" — the caller must treat it as a warm attach, which types
+ * nothing into the pane. Concurrent callers for the same host share ONE list read.
+ */
+ async exists(controlPath: string, sessionId: string, ctx: Ctx): Promise<boolean> {
+ const entry = this.fresh(controlPath)
+ if (entry?.spawned.has(sessionId)) return true
+ if (entry?.outcome) return verdict(entry.outcome, sessionId)
+ if (entry?.inflight) return verdict(await entry.inflight, sessionId)
+
+ const spawned = entry?.spawned ?? new Set<string>()
+ const inflight = this.deps
+ .list(controlPath, ctx)
+ .catch((): SessionListOutcome => ({ kind: 'unknown' }))
+ .then((outcome) => {
+ const held = this.byPath.get(controlPath)
+ // Only settle the entry this read belongs to: `invalidate` may have replaced it while the
+ // read was on the wire, and caching onto the newer entry would resurrect a stale answer.
+ if (held && held.inflight === inflight) {
+ held.outcome = outcome
+ held.inflight = undefined
+ held.at = this.now()
+ }
+ return outcome
+ })
+ this.byPath.set(controlPath, { at: this.now(), inflight, spawned })
+ return verdict(await inflight, sessionId)
+ }
+
+ /** Record a session this process just created on that host. */
+ markPresent(controlPath: string, sessionId: string): void {
+ const entry = this.fresh(controlPath)
+ if (entry) entry.spawned.add(sessionId)
+ else this.byPath.set(controlPath, { at: this.now(), spawned: new Set([sessionId]) })
+ }
+
+ /** Forget everything known about a host — used when its session set changed under us (a kill). */
+ invalidate(controlPath: string): void {
+ this.byPath.delete(controlPath)
+ }
+
+ private fresh(controlPath: string): Entry | undefined {
+ const entry = this.byPath.get(controlPath)
+ if (!entry) return undefined
+ // An in-flight read is always current: it was started now and nothing may supersede it by age.
+ if (entry.inflight) return entry
+ if (this.now() - entry.at > REMOTE_SESSION_INDEX_TTL_MS) {
+ this.byPath.delete(controlPath)
+ return undefined
+ }
+ return entry
+ }
+}
+
+function verdict(outcome: SessionListOutcome, sessionId: string): boolean {
+ // A failed read is never evidence of absence.
+ return outcome.kind === 'unknown' ? true : outcome.names.includes(sessionId)
+}
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 35dbf75be..b292db211 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1272,7 +1272,7 @@ export class SshProjectManager {
* Called on project delete BEFORE disconnect, so the remote `nt-<id>` sessions are killed
* regardless of whether the nodes were mounted (only the active project's nodes are). `nodeIds`
* are raw node ids; we map each to its `nt-<id>` session name (the same name `spawnSession` /
- * `remoteTmuxHasSessionArgs` use). Best-effort per id, a missing session is ignored.
+ * `remoteListSessionsArgs` reports). Best-effort per id, a missing session is ignored.
*
* `everySocket` widens the kill to EVERY tmux socket on the host instead of just the
* `nodeterm-rmt` one an SSH project spawns on, and it is **opt-in for one caller**. The