Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(windows): observability reads never launch a host; reaper kills spare re-watched sessions
review0e7dc330e6f9
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex 1ca777b36..be8f660aa 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -3065,6 +3065,17 @@ export class PtyManager {return sessionHostListSessionsDetailed()}+ /** Does this process hold a live (non-watcher) session whose node maps to session `name`?+ * Compared through `sessionName()` — never by slicing the prefix back off — because the name+ * is a SANITIZED node id, so the inverse is not unique. */+ private watchesSessionName(name: string): boolean {+ for (const session of this.sessions.values()) {+ if (session.watcherClient || !session.persistKey) continue+ if (sessionName(session.persistKey) === name) return true+ }+ return false+ }+/** Generation each name had in the reaper backend's most recent listing (see below). */private readonly reaperGenerations = new Map<string, string>()@@ -3092,7 +3103,7 @@ export class PtyManager {this.reaperGenerations.clear()return listing.sessions.map((row) => {this.reaperGenerations.set(row.name, row.generation)- const watched = this.sessionByPersistKey(row.name.slice('nt-'.length)) ? 1 : 0+ const watched = this.watchesSessionName(row.name) ? 1 : 0const outputSec = Math.floor(row.lastOutputMs / 1000)return {name: row.name,@@ -3107,6 +3118,9 @@ export class PtyManager {const expectedGeneration = this.reaperGenerations.get(name)// Never kill by name alone: without the observed generation a same-name successor could die.if (!expectedGeneration) return false+ // Re-asked at kill time, not taken from the listing: a node opened since the plan is now+ // watched, and the kill must spare it exactly as the listing's `watched` mapping would.+ if (this.watchesSessionName(name)) return falseawait sessionHostKillSession(name, { expectedGeneration })return true}diff --git a/src/core/pty-session-host-observability.test.ts b/src/core/pty-session-host-observability.test.tsindex e3e9d6ab1..462e48ff9 100644--- a/src/core/pty-session-host-observability.test.ts+++ b/src/core/pty-session-host-observability.test.ts@@ -150,4 +150,32 @@ describe('PtyManager session-host observability', () => {backend.kill.mockRejectedValueOnce(new Error('unconfirmed'))await expect(reaper?.kill('nt-a')).rejects.toThrow('unconfirmed')})++ it('a node opened AFTER the listing is spared at kill time, not killed off the stale plan', async () => {+ backend.listDetailed.mockResolvedValue({+ running: true,+ names: ['nt-late'],+ sessions: [row('nt-late', 0, 'gen-llllllll')]+ })+ const m = await makeManager()+ m.registerIpc()+ const reaper = m.sessionHostReaperBackend()+ expect((await reaper?.list())?.[0].clients).toBe(0)+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'late' })+ expect(await reaper?.kill('nt-late')).toBe(false)+ expect(backend.kill).not.toHaveBeenCalled()+ })++ it('watched-ness maps node ids through sessionName(), so a sanitized id is still recognised', async () => {+ // `sessionName('a.b')` is `nt-a_b`: slicing the prefix back off would ask about node `a_b`.+ backend.listDetailed.mockResolvedValue({+ running: true,+ names: ['nt-a_b'],+ sessions: [row('nt-a_b', 0, 'gen-dddddddd')]+ })+ const m = await makeManager()+ m.registerIpc()+ await host.handlers[IPC.ptyCreate](7, { cols: 80, rows: 24, persistKey: 'a.b' })+ expect((await m.sessionHostReaperBackend()?.list())?.[0].clients).toBe(1)+ })})diff --git a/src/core/session-host-client-details-nolaunch.test.ts b/src/core/session-host-client-details-nolaunch.test.tsnew file mode 100644index 000000000..bfce686b2--- /dev/null+++ b/src/core/session-host-client-details-nolaunch.test.ts@@ -0,0 +1,64 @@+// `listSessionsDetailed` is a READ for the session reaper, the memory panel and the ports chip: it+// must never start the host it is asking about. Absent state was already covered; this pins the+// other half — a published-but-STALE state file (the host was killed, or the machine rebooted)+// used to fall through `request()` into the launch path, so every poll spawned a fresh host.+import fs from 'fs'+import os from 'os'+import path from 'path'+import { afterEach, describe, expect, it, vi } from 'vitest'++const launcher = vi.hoisted(() => ({+ resolveSessionHostScript: vi.fn(() => null as string | null),+ spawnSessionHost: vi.fn()+}))+vi.mock('./session-host-launcher', () => launcher)++import { sessionHostPaths } from '../session-host/paths'+import { SESSION_HOST_PROTOCOL_VERSION } from '../session-host/protocol'+import { SessionHostClient } from './session-host-client'++const dirs: string[] = []+afterEach(() => {+ for (const d of dirs.splice(0)) fs.rmSync(d, { recursive: true, force: true })+ launcher.resolveSessionHostScript.mockClear()+ launcher.spawnSessionHost.mockClear()+})++function staleState(): string {+ const userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-details-stale-'))+ dirs.push(userDataDir)+ const paths = sessionHostPaths(userDataDir)+ fs.writeFileSync(paths.tokenPath, 'a'.repeat(64))+ // Published, but nothing listens on the endpoint.+ fs.writeFileSync(+ paths.statePath,+ JSON.stringify({+ pid: 999999,+ endpoint: paths.endpoint,+ tokenPath: paths.tokenPath,+ startedAt: Date.now(),+ protocolVersion: SESSION_HOST_PROTOCOL_VERSION+ })+ )+ return userDataDir+}++describe('listSessionsDetailed never launches a host', () => {+ it('a stale state file is a FAILED read, and no launch is attempted', async () => {+ const client = new SessionHostClient({ userDataDir: staleState() })+ await expect(client.listSessionsDetailed()).resolves.toBeNull()+ expect(launcher.resolveSessionHostScript).not.toHaveBeenCalled()+ expect(launcher.spawnSessionHost).not.toHaveBeenCalled()+ })++ it('a launching caller racing the no-launch probe still takes the launch path', async () => {+ const client = new SessionHostClient({ userDataDir: staleState() })+ const read = client.listSessionsDetailed()+ // A normal request (what create/attach rides) arriving while the probe is in flight must not+ // inherit the probe's "do not launch" — it reaches the launcher (which here finds no bundle).+ const normal = client.listSessions()+ await expect(read).resolves.toBeNull()+ await expect(normal).rejects.toThrow(/bundle not found/)+ expect(launcher.resolveSessionHostScript).toHaveBeenCalledTimes(1)+ })+})diff --git a/src/core/session-host-client-details.test.ts b/src/core/session-host-client-details.test.tsindex 550cb9aa7..287ccd532 100644--- a/src/core/session-host-client-details.test.ts+++ b/src/core/session-host-client-details.test.ts@@ -95,6 +95,8 @@ async function fakeHost(}})+ } else if (req.cmd === 'attach') {+ reply({ ok: true, result: { fresh: false, generation: GEN_A } })} else {reply({ ok: true, result: {} })}@@ -192,4 +194,22 @@ describe('SessionHostClient.listSessionsDetailed', () => {// No existence probe was needed: the caller already observed the generation.expect(requests.some((r) => r.cmd === 'hasSession')).toBe(false)})++ it('an observed-generation kill is refused while this client is attached to the name', async () => {+ const { userDataDir, endpoint } = fixture(true)+ const requests = await fakeHost(endpoint, { details: true })+ const client = new SessionHostClient({ userDataDir })+ await client.listSessionsDetailed()+ // A terminal opened after the reaper's listing: this process now watches nt-a.+ await client.attach(+ 'nt-a',+ { cwd: os.tmpdir(), shell: 'sh', args: [], env: {}, cols: 80, rows: 24 },+ 1000,+ { onData: () => {}, onExit: () => {} } as never+ )+ await expect(client.killSession('nt-a', { expectedGeneration: GEN_A })).rejects.toThrow(+ /attached in this process/+ )+ expect(requests.some((r) => r.cmd === 'killSession')).toBe(false)+ })})diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.tsindex aefda8b53..2b8f4d2e6 100644--- a/src/core/session-host-client.ts+++ b/src/core/session-host-client.ts@@ -201,6 +201,10 @@ type KillOperationIdentity = {requireV2: booleanexpectedAbsent: booleanprepared?: boolean+ /** The generation came from the CALLER's observation (a `listSessionsDetailed` row), not from+ * this client's own attachment. Such a kill never tears down local attachment state that is+ * not provably the generation it ended (see `killSession`). */+ observed?: boolean}type ClientSessionState = {@@ -378,6 +382,8 @@ export class SessionHostClient {private readonly killOperations = new Map<string, KillOperationIdentity>()private readonly replacementTokens = new Map<string, string>()private connecting: Promise<void> | null = null+ /** The in-flight `connecting` attempt was started with `launch: false` (see `ensureConnected`). */+ private connectingWithoutLaunch = falseprivate everConnected = falseprivate reconnectTimer: ReturnType<typeof setTimeout> | null = nullprivate reconnectAttempt = 0@@ -517,16 +523,30 @@ export class SessionHostClient {return true}- private async ensureConnected(): Promise<void> {+ /**+ * `launch: false` connects only to a host that is ALREADY answering — a read-only observer (the+ * session reaper, the memory panel, the ports chip) must never start the process it is asking+ * about. A published-but-stale state file (the host was killed, or the machine rebooted) would+ * otherwise make every such poll spawn a fresh host. A launching caller that arrives while such+ * a no-launch attempt is in flight waits for it and, if it found nothing, connects normally.+ */+ private async ensureConnected(options: { launch?: boolean } = {}): Promise<void> {+ const launch = options.launch !== falseif (this.shutDownForUpdate) {throw new Error('session-host was shut down to prepare for an update; restart nodeterm')}// A newly authenticated socket is visible while its reconnect restoration is still running.// The barrier wins over the raw socket check so no later request can overtake replay.- if (this.connecting) return this.connecting+ if (this.connecting) {+ if (launch && this.connectingWithoutLaunch) {+ return this.connecting.catch(() => this.ensureConnected())+ }+ return this.connecting+ }if (this.socket && !this.socket.destroyed) return- const attempt = this.doConnect()+ const attempt = this.doConnect(launch)this.connecting = attempt+ this.connectingWithoutLaunch = !launchvoid attempt.then(() => {if (this.connecting === attempt) this.connecting = null@@ -540,13 +560,14 @@ export class SessionHostClient {return attempt}- private async doConnect(): Promise<void> {+ private async doConnect(launch = true): Promise<void> {const wasConnectedBefore = this.everConnectedif (await this.tryConnectBeforeLaunch()) {const socket = this.socketif (wasConnectedBefore && socket) await this.restoreSocket(socket)return}+ if (!launch) throw new Error('session-host: no running host answered (not launching one)')const script = resolveSessionHostScript({resourcesPath: this.deps.resourcesPath,@@ -1786,6 +1807,15 @@ export class SessionHostClient {`expectedAbsent=${String(knownIdentity.expectedAbsent)}`)}+ // A kill planned from a LISTING (the session reaper) is for a session nobody in this process is+ // watching. If this client holds attachments for the name now, the plan is stale: refuse rather+ // than end — or, for a same-name successor, silently strand — a terminal someone just opened.+ if (options.expectedGeneration !== undefined && !knownIdentity) {+ const local = this.sessions.get(name)+ if (local && (local.entries.size > 0 || local.preAckEntries.size > 0)) {+ throw new Error(`session-host: '${name}' is attached in this process; observed-generation kill refused`)+ }+ }const active = this.killsInFlight.get(name)if (active) return active@@ -1799,7 +1829,8 @@ export class SessionHostClient {options.expectedGeneration ?? state?.generation ?? this.sessionGenerations.get(name),reserveReplacement,requireV2,- expectedAbsent+ expectedAbsent,+ observed: options.expectedGeneration !== undefined}this.killOperations.set(name, identity)let operation!: Promise<void>@@ -1856,7 +1887,8 @@ export class SessionHostClient {identity.operationId,identity.expectedGeneration,identity.reserveReplacement,- identity.requireV2+ identity.requireV2,+ identity.observed === true)}@@ -1865,7 +1897,8 @@ export class SessionHostClient {operationId: string,expectedGeneration: string | undefined,reserveReplacement: boolean,- requireV2: boolean+ requireV2: boolean,+ observed = false): Promise<void> {let lastError = new Error('session-host kill did not run')for (let attempt = 0; attempt < KILL_CONFIRMATION_ATTEMPTS; attempt++) {@@ -1904,8 +1937,17 @@ export class SessionHostClient {}this.replacementTokens.delete(name)}- this.clearLocalSessionState(name)- this.sessionGenerations.delete(name)+ // An observed-generation kill whose name gained a local attachment meanwhile must not+ // clear it: the host answers success for a generation that is already gone, so the live+ // attachment may be a same-name SUCCESSOR. If it really was the generation just ended,+ // the host's exit frame retires it through the ordinary exit path instead.+ const local = this.sessions.get(name)+ const raced =+ observed && !!local && (local.entries.size > 0 || local.preAckEntries.size > 0)+ if (!raced) {+ this.clearLocalSessionState(name)+ this.sessionGenerations.delete(name)+ }this.killReplayBarriers.delete(name)if (!reserveReplacement && this.killOperations.get(name)?.operationId === operationId) {this.killOperations.delete(name)@@ -2063,6 +2105,9 @@ export class SessionHostClient {expectedTokenPath: paths.tokenPath})if (identity.kind === 'absent') return { running: false, names: [], sessions: [] }+ // Published state is not proof of a live host (a killed host, a reboot): connect only to+ // one that answers. Nothing answering is a FAILED read (null) — never a launch.+ await this.ensureConnected({ launch: false })}const result = await this.request<ListSessionsResult>({ cmd: 'listSessions' })if (!result || !Array.isArray(result.names) || !result.names.every((n) => typeof n === 'string')) {