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(session-host): wait out a busy endpoint instead of probing our own empty lock

enesffb5eb115840
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 34df00d72..25d538aae 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -71,4 +71,4 @@ jobs:
run: npm run host:build
- name: Windows-relevant tests
- run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts
+ run: npx vitest run src/core/fs-atomic.test.ts src/core/fs-atomic.guard.test.ts src/core/exec-path.test.ts src/core/claude-cli.test.ts src/core/codex-identity-caps.test.ts src/core/grok-cli.test.ts src/core/commit-message.test.ts src/core/context-link.windows.test.ts src/core/git-service.windows.test.ts src/core/usage/codex-usage.windows.test.ts src/session-host/ src/core/session-host-client.test.ts src/core/session-host-launch-ledger.test.ts src/core/session-host-client-startup-wait.test.ts src/core/agent-launch.test.ts src/core/pty-session-host.test.ts src/main/bootstrap-windows.test.ts src/main/media-protocol.test.ts src/main/remote-atomic-write.test.ts src/main/ssh-fs.test.ts src/main/remote-ssh/ssh-project.test.ts src/renderer/terminal/file-links.test.ts src/renderer/terminal/file-links.windows.test.ts src/renderer/terminal/file-link-dialect.test.ts src/renderer/terminal/host-platform.test.ts
diff --git a/src/core/session-host-client-startup-wait.test.ts b/src/core/session-host-client-startup-wait.test.ts
new file mode 100644
index 000000000..968f97bff
--- /dev/null
+++ b/src/core/session-host-client-startup-wait.test.ts
@@ -0,0 +1,77 @@
+// Issue #783: a host that loses `listen` to a still-busy endpoint keeps its startup lock and
+// retries for up to two minutes. The client must WAIT while that is happening — its old 4.5 s
+// budget left every node that mounted in the window on a permanent "could not be started" until
+// the user clicked Try again — and must stop waiting the moment nothing is starting any more.
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { mkdtempSync } from 'fs'
+import os from 'os'
+import path from 'path'
+
+const launcherMocks = vi.hoisted(() => ({
+ resolveSessionHostScript: vi.fn(() => 'fake-session-host.cjs'),
+ spawnSessionHost: vi.fn()
+}))
+const identityMocks = vi.hoisted(() => ({
+ readExistingSessionHostIdentity: vi.fn(),
+ startupLockState: vi.fn(() => 'other' as string),
+ LISTEN_RETRY_BUDGET_MS: 120_000,
+ EMPTY_LOCK_STALE_MS: 15_000
+}))
+
+vi.mock('./session-host-launcher', () => launcherMocks)
+vi.mock('../session-host/existing-host-state', () => identityMocks)
+
+import { SessionHostClient } from './session-host-client'
+
+const emptyLock = (): never => {
+ throw new Error('invalid session-host state: file is empty')
+}
+
+const tempDir = (): string => mkdtempSync(path.join(os.tmpdir(), 'nt-host-wait-'))
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ launcherMocks.resolveSessionHostScript.mockReturnValue('fake-session-host.cjs')
+})
+
+describe('SessionHostClient waits for a host that is still starting', () => {
+ it('keeps polling well past the ordinary budget while the lock is being heartbeated', async () => {
+ identityMocks.readExistingSessionHostIdentity.mockImplementation(emptyLock)
+ // 'starting' for the first 45 reads — i.e. past the 30-attempt budget — then nothing is
+ // starting any more and the wait must end.
+ identityMocks.startupLockState.mockImplementation(() =>
+ identityMocks.readExistingSessionHostIdentity.mock.calls.length < 45 ? 'starting' : 'other'
+ )
+
+ await expect(new SessionHostClient({ userDataDir: tempDir() }).listSessions()).rejects.toThrow(
+ 'file is empty'
+ )
+ // Proof it did not stop at 30: the ordinary budget would have given up long before this.
+ expect(identityMocks.readExistingSessionHostIdentity.mock.calls.length).toBeGreaterThan(40)
+ }, 30_000)
+
+ it('does not spawn a second host while one is starting', async () => {
+ identityMocks.readExistingSessionHostIdentity.mockImplementation(emptyLock)
+ identityMocks.startupLockState.mockImplementation(() =>
+ identityMocks.readExistingSessionHostIdentity.mock.calls.length < 35 ? 'starting' : 'other'
+ )
+
+ await expect(
+ new SessionHostClient({ userDataDir: tempDir() }).listSessions()
+ ).rejects.toThrow()
+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled()
+ }, 30_000)
+
+ it('fails fast, exactly as before, when nothing is starting', async () => {
+ identityMocks.readExistingSessionHostIdentity.mockImplementation(emptyLock)
+ identityMocks.startupLockState.mockReturnValue('other')
+
+ await expect(new SessionHostClient({ userDataDir: tempDir() }).listSessions()).rejects.toThrow(
+ 'file is empty'
+ )
+ // Unchanged behaviour: an empty lock nobody is heartbeating is an integrity failure, reported
+ // after the small pre-launch batch — no host is launched and nothing waits on it.
+ expect(identityMocks.readExistingSessionHostIdentity.mock.calls.length).toBeLessThanOrEqual(6)
+ expect(launcherMocks.spawnSessionHost).not.toHaveBeenCalled()
+ }, 30_000)
+})
diff --git a/src/core/session-host-client-transport.test.ts b/src/core/session-host-client-transport.test.ts
index b22b41586..39da15f8c 100644
--- a/src/core/session-host-client-transport.test.ts
+++ b/src/core/session-host-client-transport.test.ts
@@ -19,6 +19,12 @@ const launcherMocks = vi.hoisted(() => ({
const identityMocks = vi.hoisted(() => ({
readExistingSessionHostIdentity: vi.fn(),
+ // The client also classifies the startup lock (issue #783): "empty and still being touched" =
+ // a host is starting, so keep waiting. These boundary tests are about the identity read, so the
+ // lock answers 'other' — nothing is starting — and the launch budget stays the ordinary one.
+ startupLockState: vi.fn(() => "other"),
+ LISTEN_RETRY_BUDGET_MS: 120_000,
+ EMPTY_LOCK_STALE_MS: 15_000,
}));
vi.mock("./session-host-launcher", () => launcherMocks);
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index a40bef0ab..3dac5c1b9 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -9,7 +9,12 @@ import { randomUUID } from 'crypto'
// socket 'close' events dispatch first, even inside fake-timer tests.
import { setImmediate as realSetImmediate } from 'timers'
import { sessionHostPaths } from '../session-host/paths'
-import { readExistingSessionHostIdentity } from '../session-host/existing-host-state'
+import {
+ EMPTY_LOCK_STALE_MS,
+ LISTEN_RETRY_BUDGET_MS,
+ readExistingSessionHostIdentity,
+ startupLockState
+} from '../session-host/existing-host-state'
import {
SESSION_HOST_PROTOCOL_VERSION,
LineFramer,
@@ -354,9 +359,13 @@ export class SessionHostClient {
'or `npm run build` which now runs it too)'
)
}
- spawnSessionHost(script, this.deps.userDataDir)
+ // A host that is ALREADY starting needs no second one. Spawning anyway is not harmful (it
+ // exits on the exclusive-create lock), but it is a process per create during the window this
+ // wait exists for — see `hostIsStarting`.
+ if (!this.hostIsStarting()) spawnSessionHost(script, this.deps.userDataDir)
let lastPublicationError: Error | null = null
- for (let attempt = 0; attempt < 30; attempt++) {
+ const waitStartedAt = Date.now()
+ for (let attempt = 0; ; attempt++) {
await sleep(150)
try {
if (await this.tryConnectOnce()) {
@@ -370,6 +379,15 @@ export class SessionHostClient {
if (!this.isTransientPublicationLock(typed)) throw typed
lastPublicationError = typed
}
+ if (attempt < 29) continue
+ // Past the ordinary 4.5 s budget. Keep waiting ONLY while a host is demonstrably still
+ // starting — an empty startup lock whose mtime it keeps moving. That is a host waiting out
+ // an endpoint someone else still holds (issue #783: a Windows named pipe stayed busy for
+ // ~1.5 min after its owner was killed), and erroring here left every node that mounted in
+ // that window on a permanent "could not be started" until the user clicked Try again.
+ // A lock that stops being touched is abandoned, so this can never wait forever.
+ if (!this.hostIsStarting()) break
+ if (Date.now() - waitStartedAt > LISTEN_RETRY_BUDGET_MS + EMPTY_LOCK_STALE_MS) break
}
if (lastPublicationError) throw lastPublicationError
throw new Error('session-host did not come up in time')
@@ -379,6 +397,12 @@ export class SessionHostClient {
return error.message === 'invalid session-host state: file is empty'
}
+ /** Is a host process between its exclusive-create lock and publication right now? True only for
+ * an EMPTY lock it is still touching; a lock nobody moves is abandoned (see startupLockState). */
+ private hostIsStarting(): boolean {
+ return startupLockState(sessionHostPaths(this.deps.userDataDir).statePath) === 'starting'
+ }
+
/** An exclusive-create startup lock is briefly empty before atomic state publication. Retry
* only that exact state within a small bound; every other unreadable or malformed observation
* remains an immediate integrity failure and never reaches the launcher. */
@@ -391,6 +415,9 @@ export class SessionHostClient {
const typed = asError(error)
if (!this.isTransientPublicationLock(typed)) throw typed
lastError = typed
+ // Still empty after the small bound — but a host that is heartbeating that lock is simply
+ // still starting, so the launch path's own wait owns it rather than failing this create.
+ if (this.hostIsStarting()) return false
await sleep(50)
}
}
diff --git a/src/session-host/existing-host-state.test.ts b/src/session-host/existing-host-state.test.ts
index c5aaee012..8df4d30d0 100644
--- a/src/session-host/existing-host-state.test.ts
+++ b/src/session-host/existing-host-state.test.ts
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
-import { readExistingSessionHostIdentity } from './existing-host-state'
+import { EMPTY_LOCK_STALE_MS, readExistingSessionHostIdentity, startupLockState } from './existing-host-state'
const statePath = 'session-host.json'
const tokenPath = 'session-host.token'
@@ -156,3 +156,33 @@ describe('existing session-host ownership reads', () => {
expect(helloTarget).toBeUndefined()
})
})
+
+describe('startupLockState', () => {
+ const stat = (size: number, ageMs: number) => () => ({ size, mtimeMs: 1_000_000 - ageMs })
+ const now = 1_000_000
+
+ it('calls an empty lock that is still being touched a live starter', () => {
+ expect(startupLockState('s', now, stat(0, 0))).toBe('starting')
+ expect(startupLockState('s', now, stat(0, EMPTY_LOCK_STALE_MS - 1))).toBe('starting')
+ })
+
+ it('calls an empty lock nothing has touched abandoned', () => {
+ expect(startupLockState('s', now, stat(0, EMPTY_LOCK_STALE_MS + 1))).toBe('abandoned')
+ })
+
+ it('never judges a lock with content — the fail-closed reader owns that', () => {
+ expect(startupLockState('s', now, stat(120, 60_000))).toBe('other')
+ })
+
+ it('reads a missing or unreadable lock as nothing to say', () => {
+ expect(
+ startupLockState('s', now, () => {
+ throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' })
+ })
+ ).toBe('other')
+ })
+
+ it('treats a future mtime as fresh, so a backwards clock cannot orphan a live starter', () => {
+ expect(startupLockState('s', now, stat(0, -60_000))).toBe('starting')
+ })
+})
diff --git a/src/session-host/existing-host-state.ts b/src/session-host/existing-host-state.ts
index 7b8e41275..367e6a472 100644
--- a/src/session-host/existing-host-state.ts
+++ b/src/session-host/existing-host-state.ts
@@ -124,3 +124,49 @@ export function readExistingSessionHostIdentity(
return { kind: 'ready', state, token }
}
+
+/**
+ * How long a host that lost `listen` to EADDRINUSE keeps retrying while holding its startup lock,
+ * and how long an EMPTY lock may go untouched before another launch may reclaim it.
+ *
+ * The two are one mechanism. The retrying host owns the lock for minutes (issue #783 measured the
+ * Windows pipe staying busy for ~1.5 min after its host was killed), so the lock cannot simply be
+ * "young = live" any more. Instead the retrying host TOUCHES the lock on every attempt, and an
+ * empty lock whose mtime has stopped moving belongs to a process that is gone. The stale window is
+ * comfortably longer than one retry interval and far shorter than the retry budget, so a live
+ * retrier is never robbed and a dead one is never waited on for minutes.
+ */
+export const LISTEN_RETRY_BUDGET_MS = 120_000
+export const LISTEN_RETRY_MAX_DELAY_MS = 2_000
+export const EMPTY_LOCK_STALE_MS = 15_000
+
+export type StartupLockState =
+ /** An empty lock a live starter is heartbeating — wait for it, never reclaim it. */
+ | 'starting'
+ /** An empty lock nothing has touched for EMPTY_LOCK_STALE_MS — its owner died mid-startup. */
+ | 'abandoned'
+ /** No lock at all, or a lock with content (published state, or something unreadable — the
+ * fail-closed readers above own that case). */
+ | 'other'
+
+/**
+ * Classify the startup lock WITHOUT interpreting its bytes: only its existence, its emptiness and
+ * how recently it was touched. Pure but for the injected stat, so both ends can be tested.
+ */
+export function startupLockState(
+ statePath: string,
+ now: number = Date.now(),
+ statSync: (p: string) => { size: number; mtimeMs: number } = (p) => fs.statSync(p)
+): StartupLockState {
+ let stat: { size: number; mtimeMs: number }
+ try {
+ stat = statSync(statePath)
+ } catch {
+ // Absent, or unreadable — neither is our call to make here.
+ return 'other'
+ }
+ if (stat.size !== 0) return 'other'
+ // A clock that jumped backwards must not make a live starter look abandoned, so a future mtime
+ // reads as fresh rather than as a huge age.
+ return now - stat.mtimeMs > EMPTY_LOCK_STALE_MS ? 'abandoned' : 'starting'
+}
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index 6c0d89c4d..6cd927c10 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -34,7 +34,13 @@ import { sendKeysWrites } from './send-keys-delivery'
import { paneCommand as readPaneCommand } from './process-tree'
import { terminateWindowsProcessTree } from './windows-process-tree'
import { publishSessionHostState } from './state-file'
-import { readExistingSessionHostIdentity } from './existing-host-state'
+import {
+ EMPTY_LOCK_STALE_MS,
+ LISTEN_RETRY_BUDGET_MS,
+ LISTEN_RETRY_MAX_DELAY_MS,
+ readExistingSessionHostIdentity,
+ startupLockState
+} from './existing-host-state'
import {
RETRY_SESSION_GENERATION,
SessionGenerationCoordinator,
@@ -158,9 +164,18 @@ async function main(): Promise<void> {
try {
alive = await probeExisting(paths.statePath, paths.endpoint, paths.tokenPath)
} catch (error) {
- log(`fatal: existing host ownership state is unreadable: ${String(error)}`)
- process.exit(1)
- return
+ // An EMPTY lock is the one unreadable state with a second, independent witness: a live
+ // starter heartbeats it (see startupLockState). One that has stopped moving belonged to a
+ // process that died between the exclusive create and publication — before issue #783 that
+ // deadlocked every later launch, since the fail-closed reader can only ever say "unreadable"
+ // about it. Anything else unreadable still refuses, as it must.
+ if (startupLockState(paths.statePath) !== 'abandoned') {
+ log(`fatal: existing host ownership state is unreadable: ${String(error)}`)
+ process.exit(1)
+ return
+ }
+ log(`abandoned empty startup lock (untouched for >${EMPTY_LOCK_STALE_MS}ms) — reclaiming`)
+ alive = false
}
if (alive) {
log('another host is already running and answered hello — exiting quietly')
@@ -1033,32 +1048,61 @@ async function main(): Promise<void> {
}
}
+ // EADDRINUSE retry state. The endpoint can stay busy for a while after its owner dies — issue
+ // #783 measured ~1.5 minutes on a Windows named pipe — so we WAIT for it instead of giving up.
+ const listenDeadline = Date.now() + LISTEN_RETRY_BUDGET_MS
+ let listenDelay = 250
+ let lastRetryLogAt = 0
+
+ /** Keep the empty startup lock's mtime moving, so other launches can tell this retry apart from
+ * a host that died mid-startup (startupLockState). Best effort: a lock a scanner holds open for
+ * a moment is not a reason to abandon the retry. */
+ function touchStartupLock(): void {
+ try {
+ const now = new Date()
+ fs.utimesSync(paths.statePath, now, now)
+ } catch {
+ /* best effort */
+ }
+ }
+
server.on('error', (err: NodeJS.ErrnoException) => {
- log(`listen error: ${err.code ?? err.message}`)
// We hold the state-file lock, so a genuine EADDRINUSE here means a PRIOR host (from before
// this file existed, or one that crashed after binding but before this run started) is still
- // bound. Give the probe one more honest look before giving up.
- if (err.code === 'EADDRINUSE') {
- void probeExisting(paths.statePath, paths.endpoint, paths.tokenPath).then(
- (alive) => {
- if (alive) process.exit(0)
- cleanupFiles()
- process.exit(1)
- },
- (error) => {
- log(`fatal: ownership probe after EADDRINUSE failed: ${String(error)}`)
- cleanupFiles()
- process.exit(1)
- }
- )
+ // bound to the endpoint.
+ //
+ // Do NOT probe our own state file here: it is the EMPTY lock this process just created, so
+ // every read of it says "file is empty" and the probe can never answer alive or absent. That
+ // was issue #783 — the "one more honest look" was structurally a no-op, and the exit deleted
+ // the lock, so the next launch repeated it from scratch. Nothing here can identify whoever
+ // holds the endpoint, so the honest move is to keep the lock and wait for it to free up.
+ if (err.code === 'EADDRINUSE' && Date.now() < listenDeadline) {
+ const now = Date.now()
+ if (now - lastRetryLogAt > 10_000) {
+ lastRetryLogAt = now
+ log(
+ `listen error: EADDRINUSE — endpoint still held; retrying for ` +
+ `${Math.round((listenDeadline - now) / 1000)}s more`
+ )
+ }
+ touchStartupLock()
+ const timer = setTimeout(() => {
+ touchStartupLock()
+ server.listen(paths.endpoint)
+ }, listenDelay)
+ timer.unref?.()
+ listenDelay = Math.min(listenDelay * 2, LISTEN_RETRY_MAX_DELAY_MS)
return
}
+ log(`listen error: ${err.code ?? err.message}`)
cleanupFiles()
process.exit(1)
})
const token = crypto.randomBytes(32).toString('hex')
- server.listen(paths.endpoint, () => {
+ // `once`, and the listen calls below carry no callback: a retry would otherwise register this
+ // again and run the whole publication block once per attempt when the endpoint finally frees.
+ server.once('listening', () => {
// Defence in depth: the 0600 token already gates every command, but a process running under a
// permissive umask would otherwise publish the AF_UNIX socket world-writable, letting a co-user
// at least connect() (and reach the pre-auth framer). Pin it to owner-only. Windows named pipes
@@ -1096,6 +1140,7 @@ async function main(): Promise<void> {
log(`listening pid=${process.pid} endpoint=${paths.endpoint}`)
scheduleGraceExitIfEmpty() // a host with zero sessions ever attached still exits eventually
})
+ server.listen(paths.endpoint)
// Detaching every client (app quit) is not a lifecycle event here at all — there is no
// "client" concept at the process level, only sockets, and their 'close' handler above already
diff --git a/src/session-host/startup-failure.test.ts b/src/session-host/startup-failure.test.ts
index 8fff5c446..298bd2767 100644
--- a/src/session-host/startup-failure.test.ts
+++ b/src/session-host/startup-failure.test.ts
@@ -7,6 +7,7 @@ import {
readFileSync,
rmSync,
statSync,
+ utimesSync,
writeFileSync
} from 'fs'
import net from 'net'
@@ -219,3 +220,105 @@ describe('session-host startup ownership reads', () => {
await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)
}, 15_000)
})
+
+/** Poll until `check` is true, or fail after `budgetMs`. */
+async function waitUntil(check: () => boolean, budgetMs: number, what: string): Promise<void> {
+ const deadline = Date.now() + budgetMs
+ while (Date.now() < deadline) {
+ if (check()) return
+ await new Promise((r) => setTimeout(r, 100))
+ }
+ throw new Error(`timed out waiting for ${what}`)
+}
+
+const publishedState = (statePath: string): boolean =>
+ existsSync(statePath) && statSync(statePath).size > 0
+
+describe('session-host startup lock liveness (issue #783)', () => {
+ it('reclaims an EMPTY lock nothing has touched — the host that died mid-startup', async () => {
+ // Before this, the fail-closed reader could only say "file is empty" about such a lock, so the
+ // probe threw on all 10 attempts and every later launch exited fatally. The app then could not
+ // start a terminal again until someone deleted the file by hand.
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-abandoned-lock-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ writeFileSync(paths.statePath, '')
+ const longAgo = new Date(Date.now() - 60_000)
+ utimesSync(paths.statePath, longAgo, longAgo)
+
+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])
+ try {
+ await waitUntil(() => publishedState(paths.statePath), 10_000, 'the host to publish its state')
+ const state = JSON.parse(readFileSync(paths.statePath, 'utf8'))
+ expect(state.endpoint).toBe(paths.endpoint)
+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(true)
+ } finally {
+ child.kill()
+ }
+ }, 30_000)
+
+ it('still refuses a FRESH empty lock — another host may be seconds from publishing', async () => {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-fresh-lock-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+ if (process.platform !== 'win32') cleanupPaths.push(paths.endpoint)
+ writeFileSync(paths.statePath, '')
+
+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])
+ const outcome = await waitForExit(child, 15_000)
+
+ expect(outcome.timedOut).toBe(false)
+ expect(outcome.code).not.toBe(0)
+ // The lock is left exactly as found: it is not ours to delete.
+ expect(existsSync(paths.statePath)).toBe(true)
+ expect(statSync(paths.statePath).size).toBe(0)
+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(false)
+ }, 30_000)
+
+ // Windows-only because only a named pipe reproduces it: on POSIX the host unlinks a stale socket
+ // path before binding, so a second listener never sees EADDRINUSE. #783 measured the pipe staying
+ // busy for ~1.5 min after its host was killed.
+ it.skipIf(process.platform !== 'win32')(
+ 'waits out an endpoint someone else still holds, instead of dying on it',
+ async () => {
+ const fixtureDir = mkdtempSync(path.join(os.tmpdir(), 'nt-session-host-busy-endpoint-'))
+ cleanupPaths.push(fixtureDir)
+ const dataDir = path.join(fixtureDir, 'user-data')
+ mkdirSync(dataDir)
+ const paths = sessionHostPaths(dataDir)
+
+ // Hold the endpoint the way the killed host's leftover pipe did.
+ const squatter = net.createServer()
+ await new Promise<void>((resolve, reject) => {
+ squatter.once('error', reject)
+ squatter.listen(paths.endpoint, () => resolve())
+ })
+
+ const { child } = await buildAndStartHost(fixtureDir, dataDir, [inertPtyPlugin()])
+ try {
+ // It must still be alive with the lock held and empty — and heartbeating it, which is what
+ // tells other launches (and the client) that this is a live starter rather than a corpse.
+ await waitUntil(() => existsSync(paths.statePath), 10_000, 'the startup lock')
+ const firstTouch = statSync(paths.statePath).mtimeMs
+ await new Promise((r) => setTimeout(r, 3_000))
+ expect(child.exitCode).toBeNull()
+ expect(statSync(paths.statePath).size).toBe(0)
+ expect(statSync(paths.statePath).mtimeMs).toBeGreaterThan(firstTouch)
+
+ // Release it: the host must take the endpoint without being restarted.
+ await new Promise<void>((resolve) => squatter.close(() => resolve()))
+ await waitUntil(() => publishedState(paths.statePath), 15_000, 'the host to bind and publish')
+ await expect(endpointAcceptsConnections(paths.endpoint)).resolves.toBe(true)
+ } finally {
+ child.kill()
+ squatter.close()
+ }
+ },
+ 45_000
+ )
+})