From a1d20058c7327aa2e2740e28615dffcc97c3563c Mon Sep 17 00:00:00 2001 From: "szymon.chmal" Date: Sun, 18 Oct 2026 17:45:51 +0200 Subject: [PATCH 1/6] =?UTF-8?q?test:=20reproduce=20#684=20=E2=80=94=20daem?= =?UTF-8?q?on=20start=20reports=20DAEMON=5FCONNECTION=5FLOST=20for=20a=20d?= =?UTF-8?q?aemon=20that=20never=20came=20up?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit why: the auto-launch loop hands back the poll's own connection the moment the launched daemon answers `hello`, and that connection's close — the dying daemon's `http-start-failed` stop, not any daemon the command ever had — is what the client then reports. Docs reserve that code for a live connection that died, so the test asserts the start-failure code #672 gave this path's timeout sibling. --- src/cli/index.test.ts | 158 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 157 insertions(+), 1 deletion(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 50d46c220..1bfe8fe18 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -15,6 +15,7 @@ import { FakeClock, FakeDaemonLauncher, FakeParentWatch, + IpcError, MemoryFilesystem, MemoryIpcTransport, NodeFilesystem, @@ -22,6 +23,8 @@ import { NoopLogger, type Filesystem, type IdGenerator, + type IpcConnection, + type IpcConnector, } from "../ports/index.js"; import { FakeSystemStats } from "../ports/index.js"; import { TokenStore } from "../http/token-store.js"; @@ -29,7 +32,12 @@ import { DaemonEndpointHost } from "../daemon/connection-host.js"; import { DaemonServer } from "../daemon/server.js"; import { AdminSecretManager } from "../daemon/admin-secret.js"; import { createCredentialRoleResolver } from "../daemon/session.js"; -import { fromWireError, SimlockError, type AnySimlockError } from "../contract/index.js"; +import { + PROTOCOL_VERSION_RANGE, + fromWireError, + SimlockError, + type AnySimlockError, +} from "../contract/index.js"; import type { CatalogGetOutput, DeviceRecoveredPush, @@ -1438,6 +1446,70 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); }); +describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { + it("reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection", async () => { + // why: this stages the daemon that loses its HTTP port race exactly as the socket shows it + // to the CLI: absent before the launch, then listening, answering `hello`, and closing on + // its own `http-start-failed` stop before the command's first real request is answered. + // The connection is the auto-launch poll's own, so `daemon start` never had a daemon to + // lose -- yet it currently prints `DAEMON_CONNECTION_LOST`, the code docs/CLI.md reserves + // for a live connection that died, leaving a script unable to tell a failed start from a + // lost daemon. The expectation below (the contract's start-failure code, which #672 gave + // the timeout sibling of this same auto-launch path) is the report's proposal. + const dyingDaemon = new HelloThenDeathIpc(); + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + dyingDaemon.startListening(); + }); + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: dyingDaemon, + launcher, + dataDirectory: "/simlock", + }); + let settled = false; + const exitCode = runCli( + ["daemon", "start", "--json", "--token", "probe"], + output.environmentWith(), + ).then((code) => { + settled = true; + return code; + }); + // why: the tick bound is generous because #671 made every module a command loads lazy, so + // one `daemon start` now passes through several more import turns than when this repro was + // first staged; the clock is fake and the loop stops the moment the command settles, so the + // extra headroom pins nothing -- it only keeps a hung command failing on this named + // assertion instead of on a test timeout. + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(settled, `simlock daemon start still had not settled at ${String(clock.now())}ms`).toBe( + true, + ); + + // why: the staging itself, proven from the fake's side -- the socket was absent until this + // command launched the daemon, the daemon did answer that command's `hello`, and every + // connection it accepted died by its own hand. Without these the assertion below could be + // reached by a connection that never saw a daemon at all. + expect(launcher.launches).toBe(1); + expect(dyingDaemon.helloReplies).toBe(1); + expect(dyingDaemon.deaths).toBe(1); + + expect(await exitCode).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: expect.stringContaining("daemon"), + }, + }); + }); +}); + describe("CLI: daemon status (ADR 0003 §11)", () => { it("reports stopped when the socket cannot be reached at all", async () => { const output = outputCapture(); @@ -6205,6 +6277,90 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { return capture; } +// why: the auto-launch poll's view of the daemon that loses the race for its HTTP port +// (#684): absent until this command launches it, then listening, answering one frame -- the +// `hello` -- and closing every connection it handed out when it stops itself on +// `http-start-failed`. `deaths` counts only the connections the daemon itself killed, never +// one the client closed. +class HelloThenDeathIpc implements IpcConnector { + helloReplies = 0; + deaths = 0; + #listening = false; + + startListening(): void { + this.#listening = true; + } + + async connect(): Promise { + if (!this.#listening) { + throw new IpcError("endpoint-not-found", "No IPC endpoint yet", undefined); + } + return new HelloThenDeathConnection(this); + } +} + +class HelloThenDeathConnection implements IpcConnection { + readonly #dataListeners = new Set<(chunk: string) => void>(); + readonly #closeListeners = new Set<() => void>(); + #closed = false; + + constructor(private readonly daemon: HelloThenDeathIpc) {} + + get closed(): boolean { + return this.#closed; + } + + onData(listener: (chunk: string) => void): () => void { + this.#dataListeners.add(listener); + return () => this.#dataListeners.delete(listener); + } + + onClose(listener: () => void): () => void { + this.#closeListeners.add(listener); + return () => this.#closeListeners.delete(listener); + } + + onError(): () => void { + return () => {}; + } + + async write(contents: string): Promise { + if (this.#closed) return; + for (const line of contents.split("\n")) { + if (line.trim() === "") continue; + const frame = JSON.parse(line) as { id?: unknown; type?: unknown }; + if (frame.type !== "hello" || typeof frame.id !== "number") continue; + this.daemon.helloReplies += 1; + const reply = { + id: frame.id, + ok: true, + payload: { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } + // why: the daemon's own stop, right after the handshake -- this start never held a live + // daemon, so the close is the death of a boot, not the loss of a running one. + this.#shutDown(true); + } + + async close(): Promise { + this.#shutDown(false); + } + + #shutDown(killedByDaemon: boolean): void { + if (this.#closed) return; + this.#closed = true; + if (killedByDaemon) this.daemon.deaths += 1; + for (const listener of this.#closeListeners) listener(); + } +} + function sequence(): IdGenerator { let next = 0; return { generate: () => `id${next++}` }; From d1e06bc3ecc4065d0ae587f67fdf2c161c4d5053 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:27:49 +0200 Subject: [PATCH 2/6] fix: classify early auto-launch connection deaths as startup failures 1 failing -> 0 failing. Keep the startup classification on the launched client until its first successful request; preserve later and pre-existing connection losses. Carry the triage regression, exercise a pending first request and mid-operation deaths, and update the CLI contract docs. --- docs/CLI.md | 12 ++- src/cli/AGENTS.md | 7 +- src/cli/environment.ts | 63 +++++++++-- src/cli/index.test.ts | 236 ++++++++++++++++++++++++++++++++--------- 4 files changed, 250 insertions(+), 68 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 9ad1e0b80..6583c8384 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -19,7 +19,8 @@ On failure, every command writes one structured line to stderr: `code` is the daemon's own error code where the failure came from the daemon, or a stable CLI-level code otherwise: `USAGE` for bad flags/missing -arguments/unknown commands, `INTERNAL` for anything unexpected. An unknown +arguments/unknown commands, `DAEMON_STARTUP_FAILED` for a failed auto-start, +`INTERNAL` for anything unexpected. An unknown command or a missing required argument gets a `message` that ends with a pointer to `simlock --help`, so a human hitting one from a terminal isn't stranded with only a JSON blob — the full command banner itself is no @@ -78,7 +79,7 @@ command starts it again) to bring the platform up. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | -| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout | +| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the first request succeeded | | 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down), or a worker named with `component install --worker` cannot be asked | | 2 | `USAGE` | usage error (bad flags, missing required args, unknown command) | | 2 | `BAD_FRAME` | malformed request frame sent to the daemon | @@ -2275,6 +2276,13 @@ from a worker whose clock is behind prints after a later gateway event. ## `simlock daemon ` +If a command auto-starts a daemon and it answers the handshake but closes +before the command's first request succeeds, the command reports +`DAEMON_STARTUP_FAILED` (exit 1). After a successful request, later deaths +report `DAEMON_CONNECTION_LOST`, including during a held lease or an operation +on the same connection. A connection to an already listening daemon keeps +the usual `DAEMON_CONNECTION_LOST` behavior. + Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` exists for operators and debugging. `start` starts whichever mode `config.mode` selects — a worker (the default) or a gateway — and diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 05a613b9c..204906477 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -54,9 +54,12 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. `resolveRequesterId(env, )`. Credential, first found: `--token` → `SIMLOCK_ADMIN_TOKEN` → `admin.token` in the data directory (3 reads, 50 ms apart). None, or a rejected one → an `agent` session and one stderr `notice` line. -3. **Auto-launch** (`AutoLaunchIpcConnector`) — when nothing listens: load the config +3. **Auto-launch** (`AutoLaunchAdminConnector`) — when nothing listens: load the config first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms - for `DAEMON_STARTUP_TIMEOUT_MS`. + for `DAEMON_STARTUP_TIMEOUT_MS`. Only the client returned by that launch poll wraps + request failures: `DAEMON_CONNECTION_LOST` before the first successful request becomes + `DAEMON_STARTUP_FAILED`. The handshake alone does not end that window. Once a request + succeeds, later failures keep their original codes; a pre-existing daemon is never wrapped. 4. **`simlock lease`** — `requestLease`; progress pushes as JSON lines on stderr; one result line on stdout, with the session's `role` (`--export-env`: shell lines). `--agent-id` sets the requester. Then, unless `--detach`: diff --git a/src/cli/environment.ts b/src/cli/environment.ts index b28c4449e..0ad295717 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -10,7 +10,6 @@ import type { Clock, DaemonLauncher, Filesystem, - IpcConnection, IpcConnector, ParentWatch, ParentWatchHandle, @@ -20,17 +19,17 @@ import { readLogFile } from "./log-file.js"; import { readPipedStdin } from "./stdio.js"; import type { CliEnvironment, CliEnvironmentPorts } from "./types.js"; -class AutoLaunchIpcConnector implements IpcConnector { +class AutoLaunchAdminConnector { constructor( - private readonly ipc: IpcConnector, + private readonly connectClient: () => Promise, private readonly clock: Clock, private readonly launcher: DaemonLauncher, private readonly checkConfig: () => Promise, ) {} - async connect(endpoint: string): Promise { + async connect(): Promise { try { - return await this.ipc.connect(endpoint); + return await this.connectClient(); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; } @@ -42,7 +41,7 @@ class AutoLaunchIpcConnector implements IpcConnector { let lastError: unknown; while (this.clock.now() < deadline) { try { - return await this.ipc.connect(endpoint); + return await withStartupFailure(await this.connectClient()); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; @@ -59,6 +58,42 @@ class AutoLaunchIpcConnector implements IpcConnector { } } +async function withStartupFailure(client: SimlockAdminClient): Promise { + const { isSimlockError, SimlockError } = await import("../contract/index.js"); + let requestAnswered = false; + return new Proxy(client, { + get(target, property) { + const value: unknown = Reflect.get(target, property, target); + if (typeof value !== "function") return value; + return (...args: unknown[]): unknown => { + const result: unknown = Reflect.apply(value, target, args); + if (!(result instanceof Promise) || property === "close") return result; + return result.then( + (answer: unknown) => { + requestAnswered = true; + return answer; + }, + (error: unknown) => { + if ( + !requestAnswered && + isSimlockError(error) && + error.code === "DAEMON_CONNECTION_LOST" + ) { + throw new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + "The daemon closed its connection while starting, before answering the first request", + {}, + ); + } + throw error; + }, + ); + }; + }, + }); +} + /** why: the class lives behind the ports barrel, which this module must not load at CLI start; * the name check picks the candidate and `instanceof` against the real class proves it. */ async function isUnavailable(error: unknown): Promise { @@ -132,9 +167,9 @@ export function buildCliEnvironment( const logPath = join(dataDirectory, "daemon.log"); const adminTokenPath = join(dataDirectory, "admin.token"); const requesterId = resolveRequesterId(env, String(process.pid)); - // why: the daemon refuses to boot on a config `loadConfig` rejects and only its log says so; - // loading the same file before the launch puts the `ConfigError` on the CLI's stderr. - const autoLaunchIpc = new AutoLaunchIpcConnector(ipc, clock, launcher, async () => { + const checkConfig = async (): Promise => { + // why: the daemon refuses to boot on a config `loadConfig` rejects and only its log says so; + // loading the same file before the launch puts the `ConfigError` on the CLI's stderr. const { loadConfig } = await import("../core/index.js"); await loadConfig({ configPath, @@ -142,7 +177,7 @@ export function buildCliEnvironment( modules: await moduleConfigEntries(), systemStats, }); - }); + }; const connect = async ( connector: IpcConnector, @@ -170,7 +205,13 @@ export function buildCliEnvironment( clock, configPath, requesterId, - connectAdmin: (resolveCredential) => connect(autoLaunchIpc, resolveCredential), + connectAdmin: (resolveCredential) => + new AutoLaunchAdminConnector( + () => connect(ipc, resolveCredential), + clock, + launcher, + checkConfig, + ).connect(), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 1bfe8fe18..7804c2a31 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1447,66 +1447,194 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { - it("reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection", async () => { - // why: this stages the daemon that loses its HTTP port race exactly as the socket shows it - // to the CLI: absent before the launch, then listening, answering `hello`, and closing on - // its own `http-start-failed` stop before the command's first real request is answered. - // The connection is the auto-launch poll's own, so `daemon start` never had a daemon to - // lose -- yet it currently prints `DAEMON_CONNECTION_LOST`, the code docs/CLI.md reserves - // for a live connection that died, leaving a script unable to tell a failed start from a - // lost daemon. The expectation below (the contract's start-failure code, which #672 gave - // the timeout sibling of this same auto-launch path) is the report's proposal. + it.each(["hello", "request"] as const)( + "reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection (after %s)", + async (closeAfter) => { + // why: this stages the daemon that loses its HTTP port race exactly as the socket shows it + // to the CLI: absent before the launch, then listening, answering `hello`, and closing on + // its own `http-start-failed` stop before the command's first real request is answered. + const dyingDaemon = new HelloThenDeathIpc(closeAfter); + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + dyingDaemon.startListening(); + }); + const output = outputCapture({ + filesystem: new MemoryFilesystem(), + clock, + systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ipc: dyingDaemon, + launcher, + dataDirectory: "/simlock", + }); + let settled = false; + const exitCode = runCli( + ["daemon", "start", "--json", "--token", "probe"], + output.environmentWith(), + ).then((code) => { + settled = true; + return code; + }); + // why: the tick bound is generous because #671 made every module a command loads lazy, so + // one `daemon start` now passes through several more import turns than when this repro was + // first staged; the clock is fake and the loop stops the moment the command settles, so the + // extra headroom pins nothing -- it only keeps a hung command failing on this named + // assertion instead of on a test timeout. + for (let tick = 0; tick < 100 && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect( + settled, + `simlock daemon start still had not settled at ${String(clock.now())}ms`, + ).toBe(true); + + // why: the staging itself, proven from the fake's side -- the socket was absent until this + // command launched the daemon, the daemon did answer that command's `hello`, and every + // connection it accepted died by its own hand. Without these the assertion below could be + // reached by a connection that never saw a daemon at all. + expect(launcher.launches).toBe(1); + expect(dyingDaemon.helloReplies).toBe(1); + expect(dyingDaemon.deaths).toBe(1); + + expect(await exitCode).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: expect.stringContaining("daemon"), + }, + }); + }, + ); + + it("keeps a pre-existing daemon's hello-then-close as DAEMON_CONNECTION_LOST", async () => { const dyingDaemon = new HelloThenDeathIpc(); - const clock = new FakeClock(0); - const launcher = new FakeDaemonLauncher(() => { - dyingDaemon.startListening(); - }); + dyingDaemon.startListening(); + const launcher = new FakeDaemonLauncher(); const output = outputCapture({ - filesystem: new MemoryFilesystem(), - clock, - systemStats: new FakeSystemStats({ cpuCount: 8, totalRamBytes: 32 * gibibyte }), + ...realCliEnvironmentPorts(), ipc: dyingDaemon, launcher, - dataDirectory: "/simlock", }); - let settled = false; - const exitCode = runCli( - ["daemon", "start", "--json", "--token", "probe"], - output.environmentWith(), - ).then((code) => { - settled = true; - return code; - }); - // why: the tick bound is generous because #671 made every module a command loads lazy, so - // one `daemon start` now passes through several more import turns than when this repro was - // first staged; the clock is fake and the loop stops the moment the command settles, so the - // extra headroom pins nothing -- it only keeps a hung command failing on this named - // assertion instead of on a test timeout. - for (let tick = 0; tick < 100 && !settled; tick += 1) { - clock.advance(50); - await settle(); - await settle(); - } - expect(settled, `simlock daemon start still had not settled at ${String(clock.now())}ms`).toBe( - true, - ); - // why: the staging itself, proven from the fake's side -- the socket was absent until this - // command launched the daemon, the daemon did answer that command's `hello`, and every - // connection it accepted died by its own hand. Without these the assertion below could be - // reached by a connection that never saw a daemon at all. - expect(launcher.launches).toBe(1); + expect( + await runCli(["daemon", "start", "--json", "--token", "probe"], output.environmentWith()), + ).toBe(1); + expect(launcher.launches).toBe(0); expect(dyingDaemon.helloReplies).toBe(1); expect(dyingDaemon.deaths).toBe(1); - - expect(await exitCode).toBe(1); expect(output.stdout).toBe(""); - expect(JSON.parse(output.stderr)).toMatchObject({ - error: { - code: "DAEMON_STARTUP_FAILED", - message: expect.stringContaining("daemon"), - }, + expect(JSON.parse(output.stderr)).toEqual({ + error: { code: "DAEMON_CONNECTION_LOST", message: "Daemon connection closed" }, + }); + }); + + it.each(["held lease", "in-flight request"] as const)( + "keeps an auto-launched daemon's death after a successful request as DAEMON_CONNECTION_LOST during %s", + async (operation) => { + const ipc = new MemoryIpcTransport(); + const clock = new FakeClock(0); + const requests: string[] = []; + const replies: string[] = []; + const connections: IpcConnection[] = []; + const launcher = new FakeDaemonLauncher(async () => { + await ipc.listen("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/simlock/daemon.sock", (connection) => { + connections.push(connection); + connection.onData((contents) => { + const frame = JSON.parse(contents) as { id: number; type: string }; + requests.push(frame.type); + const payload = + frame.type === "hello" + ? { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + } + : frame.type === "lease.request" + ? detachedGrant + : frame.type === "status.get" + ? EMPTY_STATUS + : undefined; + if (payload === undefined) return; + replies.push(frame.type); + void connection.write(`${JSON.stringify({ id: frame.id, ok: true, payload })}\n`); + }); + }); + }); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + ipc, + clock, + launcher, + }); + let settled = false; + const runPromise = runCli( + operation === "held lease" + ? ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--token", "probe"] + : ["simctl", "list", "--token", "probe"], + output.environmentWith(), + ).then((code) => { + settled = true; + return code; + }); + const ready = (): boolean => + operation === "held lease" ? output.stdout !== "" : requests.includes("driver.passthrough"); + for (let tick = 0; tick < 100 && !ready() && !settled; tick += 1) { + clock.advance(50); + await settle(); + await settle(); + } + expect(ready()).toBe(true); + expect(settled).toBe(false); + expect(launcher.launches).toBe(1); + expect(connections).toHaveLength(1); + expect(replies).toEqual([ + "hello", + operation === "held lease" ? "lease.request" : "status.get", + ]); + await connections[0]!.close(); + expect(await runPromise).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { code: "DAEMON_CONNECTION_LOST" }, + }); + if (operation === "held lease") { + expect(JSON.parse(output.stdout)).toMatchObject({ lease: detachedGrant.lease }); + expect(JSON.parse(output.stderr).error.message).toContain(detachedGrant.lease.id); + expect(requests).toEqual(["hello", "lease.request"]); + } else { + expect(output.stdout).toBe(""); + expect(requests).toEqual(["hello", "status.get", "driver.passthrough"]); + } + }, + ); + + it("preserves the daemon's refusal of the first auto-launched request", async () => { + const filesystem = new MemoryFilesystem(); + const ipc = new MemoryIpcTransport(); + const launcher = new FakeDaemonLauncher(async () => { + await startInMemoryDaemon({ + filesystem, + ipcTransport: ipc, + socketPath: "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/simlock/daemon.sock", + adminTokenPath: "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/simlock/admin.token", + }); }); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + filesystem, + ipc, + launcher, + }); + + expect( + await runCli(["lease", "--platform", "android", "--detach"], output.environmentWith()), + ).toBe(12); + expect(launcher.launches).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr)).toMatchObject({ error: { code: "NO_DRIVER" } }); }); }); @@ -6287,6 +6415,8 @@ class HelloThenDeathIpc implements IpcConnector { deaths = 0; #listening = false; + constructor(readonly closeAfter: "hello" | "request" = "hello") {} + startListening(): void { this.#listening = true; } @@ -6326,10 +6456,12 @@ class HelloThenDeathConnection implements IpcConnection { async write(contents: string): Promise { if (this.#closed) return; + let answeredHello = false; for (const line of contents.split("\n")) { if (line.trim() === "") continue; const frame = JSON.parse(line) as { id?: unknown; type?: unknown }; if (frame.type !== "hello" || typeof frame.id !== "number") continue; + answeredHello = true; this.daemon.helloReplies += 1; const reply = { id: frame.id, @@ -6344,9 +6476,7 @@ class HelloThenDeathConnection implements IpcConnection { }; for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); } - // why: the daemon's own stop, right after the handshake -- this start never held a live - // daemon, so the close is the death of a boot, not the loss of a running one. - this.#shutDown(true); + if (!answeredHello || this.daemon.closeAfter === "hello") this.#shutDown(true); } async close(): Promise { From 19bdd2c3e5e8a23f2e3fa4f6253f71e2e64248d0 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:42:24 +0200 Subject: [PATCH 3/6] fix(cli): end auto-launch classification at a bounded status probe --- docs/CLI.md | 15 ++-- src/cli/AGENTS.md | 11 ++- src/cli/environment.ts | 97 +++++++++++---------- src/cli/index.test.ts | 191 +++++++++++++++++++++++++++++++---------- 4 files changed, 214 insertions(+), 100 deletions(-) diff --git a/docs/CLI.md b/docs/CLI.md index 6583c8384..3506aa7cd 100644 --- a/docs/CLI.md +++ b/docs/CLI.md @@ -79,7 +79,7 @@ command starts it again) to bring the platform up. |---|---|---| | 0 | — | success (for a `lease` that stayed alive: the lease ended normally) | | 1 | `INTERNAL` | internal / unexpected error | -| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the first request succeeded | +| 1 | `DAEMON_STARTUP_FAILED` | the daemon was started but did not accept connections before the startup timeout, or answered the handshake then closed before the CLI's startup status probe answered | | 1 | `WORKER_UNREACHABLE` | the gateway cannot reach the worker this lease or request lives on (its uplink is down), or a worker named with `component install --worker` cannot be asked | | 2 | `USAGE` | usage error (bad flags, missing required args, unknown command) | | 2 | `BAD_FRAME` | malformed request frame sent to the daemon | @@ -2277,11 +2277,14 @@ from a worker whose clock is behind prints after a later gateway event. ## `simlock daemon ` If a command auto-starts a daemon and it answers the handshake but closes -before the command's first request succeeds, the command reports -`DAEMON_STARTUP_FAILED` (exit 1). After a successful request, later deaths -report `DAEMON_CONNECTION_LOST`, including during a held lease or an operation -on the same connection. A connection to an already listening daemon keeps -the usual `DAEMON_CONNECTION_LOST` behavior. +before the CLI's startup status probe answers, the command reports +`DAEMON_STARTUP_FAILED` (exit 1). The probe shares the launch timeout and runs +before the command's operation, including after a rejected credential falls +back to an agent session. Once status answers (even `starting`), later deaths +report `DAEMON_CONNECTION_LOST`, including while a lease request queues or +boots, during a held lease, or during an operation on the same connection. An +unanswered probe times out with `DAEMON_STARTUP_FAILED`. A connection to an +already listening daemon keeps the usual `DAEMON_CONNECTION_LOST` behavior. Manage the daemon explicitly. Other commands auto-start it on demand; `daemon` exists for operators and debugging. `start` starts whichever mode diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index 204906477..c66f6a715 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -56,10 +56,13 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. None, or a rejected one → an `agent` session and one stderr `notice` line. 3. **Auto-launch** (`AutoLaunchAdminConnector`) — when nothing listens: load the config first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms - for `DAEMON_STARTUP_TIMEOUT_MS`. Only the client returned by that launch poll wraps - request failures: `DAEMON_CONNECTION_LOST` before the first successful request becomes - `DAEMON_STARTUP_FAILED`. The handshake alone does not end that window. Once a request - succeeds, later failures keep their original codes; a pre-existing daemon is never wrapped. + for `DAEMON_STARTUP_TIMEOUT_MS`. After a launch, `status.get` probes the connection + before handing it to a command, within that same deadline. A connection loss during this + probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and closes + its client. An answered probe ends the window, including a `starting` status: subsequent + command failures retain their original codes even while a lease queues or boots. + The connector retains the launch deadline across a rejected credential and agent fallback. + A pre-existing daemon is never probed or reclassified; other daemon errors keep their codes. 4. **`simlock lease`** — `requestLease`; progress pushes as JSON lines on stderr; one result line on stdout, with the session's `role` (`--export-env`: shell lines). `--agent-id` sets the requester. Then, unless `--detach`: diff --git a/src/cli/environment.ts b/src/cli/environment.ts index 0ad295717..969f5e476 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -20,16 +20,20 @@ import { readPipedStdin } from "./stdio.js"; import type { CliEnvironment, CliEnvironmentPorts } from "./types.js"; class AutoLaunchAdminConnector { + private startupDeadline: number | undefined; + constructor( - private readonly connectClient: () => Promise, + private readonly connectClient: ( + resolveCredential: () => Promise, + ) => Promise, private readonly clock: Clock, private readonly launcher: DaemonLauncher, private readonly checkConfig: () => Promise, ) {} - async connect(): Promise { + async connect(resolveCredential: () => Promise): Promise { try { - return await this.connectClient(); + return await this.finishConnection(await this.connectClient(resolveCredential)); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; } @@ -38,10 +42,11 @@ class AutoLaunchAdminConnector { // why: the constant lives behind the ports barrel, which loads on the first connection that needs it. const { DAEMON_STARTUP_TIMEOUT_MS } = await import("../ports/index.js"); const deadline = this.clock.now() + DAEMON_STARTUP_TIMEOUT_MS; + this.startupDeadline = deadline; let lastError: unknown; while (this.clock.now() < deadline) { try { - return await withStartupFailure(await this.connectClient()); + return await this.finishConnection(await this.connectClient(resolveCredential)); } catch (error: unknown) { if (!(await isUnavailable(error))) throw error; lastError = error; @@ -56,42 +61,43 @@ class AutoLaunchAdminConnector { {}, ); } -} -async function withStartupFailure(client: SimlockAdminClient): Promise { - const { isSimlockError, SimlockError } = await import("../contract/index.js"); - let requestAnswered = false; - return new Proxy(client, { - get(target, property) { - const value: unknown = Reflect.get(target, property, target); - if (typeof value !== "function") return value; - return (...args: unknown[]): unknown => { - const result: unknown = Reflect.apply(value, target, args); - if (!(result instanceof Promise) || property === "close") return result; - return result.then( - (answer: unknown) => { - requestAnswered = true; - return answer; - }, - (error: unknown) => { - if ( - !requestAnswered && - isSimlockError(error) && - error.code === "DAEMON_CONNECTION_LOST" - ) { - throw new SimlockError( - "DAEMON_STARTUP_FAILED", - "transport", - "The daemon closed its connection while starting, before answering the first request", - {}, - ); - } - throw error; - }, + private async finishConnection(client: SimlockAdminClient): Promise { + if (this.startupDeadline === undefined) return client; + const { isSimlockError, SimlockError } = await import("../contract/index.js"); + const remainingMs = Math.max(0, this.startupDeadline - this.clock.now()); + let timer: ReturnType | undefined; + const timeout = new Promise((_resolve, reject) => { + timer = this.clock.setTimer(remainingMs, () => { + reject( + new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + "Timed out starting simlock daemon: the startup status probe was not answered", + {}, + ), ); - }; - }, - }); + }); + }); + try { + await Promise.race([client.getStatus(), timeout]); + this.startupDeadline = undefined; + return client; + } catch (error: unknown) { + await client.close(); + if (isSimlockError(error) && error.code === "DAEMON_CONNECTION_LOST") { + throw new SimlockError( + "DAEMON_STARTUP_FAILED", + "transport", + "The daemon closed its connection while starting, before answering the startup status probe", + {}, + ); + } + throw error; + } finally { + if (timer !== undefined) this.clock.cancel(timer); + } + } } /** why: the class lives behind the ports barrel, which this module must not load at CLI start; @@ -201,17 +207,18 @@ export function buildCliEnvironment( }); }; + const autoLaunch = new AutoLaunchAdminConnector( + (resolveCredential) => connect(ipc, resolveCredential), + clock, + launcher, + checkConfig, + ); + return { clock, configPath, requesterId, - connectAdmin: (resolveCredential) => - new AutoLaunchAdminConnector( - () => connect(ipc, resolveCredential), - clock, - launcher, - checkConfig, - ).connect(), + connectAdmin: (resolveCredential) => autoLaunch.connect(resolveCredential), connectExistingAdmin: (resolveCredential) => connect(ipc, resolveCredential), ...(env.SIMLOCK_ADMIN_TOKEN === undefined ? {} diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 7804c2a31..71b1d3f5a 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -1447,13 +1447,18 @@ describe("CLI: auto-launch's failed start (#672)", () => { }); describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", () => { - it.each(["hello", "request"] as const)( - "reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection (after %s)", - async (closeAfter) => { + it.each([ + { closeAfter: "hello", rejectedCredential: false }, + { closeAfter: "request", rejectedCredential: false }, + { closeAfter: "hello", rejectedCredential: true }, + { closeAfter: "request", rejectedCredential: true }, + ] as const)( + "reports a daemon it launched that answers hello then dies during that start as a failed start, not a lost connection (after $closeAfter, credential rejected: $rejectedCredential)", + async ({ closeAfter, rejectedCredential }) => { // why: this stages the daemon that loses its HTTP port race exactly as the socket shows it // to the CLI: absent before the launch, then listening, answering `hello`, and closing on // its own `http-start-failed` stop before the command's first real request is answered. - const dyingDaemon = new HelloThenDeathIpc(closeAfter); + const dyingDaemon = new HelloThenDeathIpc(closeAfter, rejectedCredential); const clock = new FakeClock(0); const launcher = new FakeDaemonLauncher(() => { dyingDaemon.startListening(); @@ -1490,16 +1495,17 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", ).toBe(true); // why: the staging itself, proven from the fake's side -- the socket was absent until this - // command launched the daemon, the daemon did answer that command's `hello`, and every - // connection it accepted died by its own hand. Without these the assertion below could be + // command launched the daemon and answered `hello` before it closed the connection. Without + // these the assertion below could be // reached by a connection that never saw a daemon at all. expect(launcher.launches).toBe(1); expect(dyingDaemon.helloReplies).toBe(1); expect(dyingDaemon.deaths).toBe(1); + expect(dyingDaemon.rejectedCredentials).toBe(rejectedCredential ? 1 : 0); expect(await exitCode).toBe(1); expect(output.stdout).toBe(""); - expect(JSON.parse(output.stderr)).toMatchObject({ + expect(JSON.parse(output.stderr.trim().split("\n").at(-1)!)).toMatchObject({ error: { code: "DAEMON_STARTUP_FAILED", message: expect.stringContaining("daemon"), @@ -1508,31 +1514,85 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", }, ); - it("keeps a pre-existing daemon's hello-then-close as DAEMON_CONNECTION_LOST", async () => { - const dyingDaemon = new HelloThenDeathIpc(); - dyingDaemon.startListening(); - const launcher = new FakeDaemonLauncher(); - const output = outputCapture({ - ...realCliEnvironmentPorts(), - ipc: dyingDaemon, - launcher, - }); + it.each([false, true])( + "keeps a pre-existing daemon's hello-then-close as DAEMON_CONNECTION_LOST (credential rejected: %s)", + async (rejectedCredential) => { + const dyingDaemon = new HelloThenDeathIpc("hello", rejectedCredential); + dyingDaemon.startListening(); + const launcher = new FakeDaemonLauncher(); + const output = outputCapture({ + ...realCliEnvironmentPorts(), + ipc: dyingDaemon, + launcher, + }); + + expect( + await runCli(["daemon", "start", "--json", "--token", "probe"], output.environmentWith()), + ).toBe(1); + expect(launcher.launches).toBe(0); + expect(dyingDaemon.helloReplies).toBe(1); + expect(dyingDaemon.deaths).toBe(1); + expect(output.stdout).toBe(""); + expect(JSON.parse(output.stderr.trim().split("\n").at(-1)!)).toEqual({ + error: { code: "DAEMON_CONNECTION_LOST", message: "Daemon connection closed" }, + }); + }, + ); + it("preserves DAEMON_STOPPING from the startup status probe and closes its client", async () => { + const daemon = new HelloThenDeathIpc("stopping"); + const launcher = new FakeDaemonLauncher(() => daemon.startListening()); + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc: daemon, launcher }); + expect(await runCli(["daemon", "start", "--token", "probe"], output.environmentWith())).toBe(1); + expect(launcher.launches).toBe(1); + expect(daemon.helloReplies).toBe(1); + expect(daemon.clientCloses).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ error: { code: "DAEMON_STOPPING" } }); + }); + + it("bounds the startup status probe by the original launch deadline and closes its client", async () => { + const daemon = new HelloThenDeathIpc("silent"); + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + clock.setTimer(19_000, () => daemon.startListening()); + }); + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc: daemon, clock, launcher }); + let settled = false; + const run = runCli(["daemon", "start", "--token", "probe"], output.environmentWith()).then( + (code) => { + settled = true; + return code; + }, + ); + for (let tick = 0; tick < 500 && !settled; tick += 1) { + clock.advance(50); + await settle(); + } + expect(settled, "silent startup probe must settle within the launch budget").toBe(true); expect( - await runCli(["daemon", "start", "--json", "--token", "probe"], output.environmentWith()), - ).toBe(1); - expect(launcher.launches).toBe(0); - expect(dyingDaemon.helloReplies).toBe(1); - expect(dyingDaemon.deaths).toBe(1); - expect(output.stdout).toBe(""); - expect(JSON.parse(output.stderr)).toEqual({ - error: { code: "DAEMON_CONNECTION_LOST", message: "Daemon connection closed" }, + clock.now(), + "probe must use the budget left after the socket appeared", + ).toBeLessThanOrEqual(20_050); + expect(await run).toBe(1); + expect(launcher.launches).toBe(1); + expect(daemon.helloReplies).toBe(1); + expect(daemon.clientCloses).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { + code: "DAEMON_STARTUP_FAILED", + message: expect.stringContaining("Timed out starting"), + }, }); }); - it.each(["held lease", "in-flight request"] as const)( - "keeps an auto-launched daemon's death after a successful request as DAEMON_CONNECTION_LOST during %s", - async (operation) => { + it.each([ + { operation: "pending lease", health: "running" }, + { operation: "pending lease", health: "starting" }, + { operation: "held lease", health: "running" }, + { operation: "in-flight request", health: "running" }, + ] as const)( + "keeps an auto-launched daemon's death after its startup status probe as DAEMON_CONNECTION_LOST during $operation (status: $health)", + async ({ operation, health }) => { const ipc = new MemoryIpcTransport(); const clock = new FakeClock(0); const requests: string[] = []; @@ -1553,10 +1613,10 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", role: "admin", principal: "test-requester", } - : frame.type === "lease.request" + : frame.type === "lease.request" && operation !== "pending lease" ? detachedGrant : frame.type === "status.get" - ? EMPTY_STATUS + ? { ...EMPTY_STATUS, daemon: { ...EMPTY_STATUS.daemon, health } } : undefined; if (payload === undefined) return; replies.push(frame.type); @@ -1572,7 +1632,7 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", }); let settled = false; const runPromise = runCli( - operation === "held lease" + operation !== "in-flight request" ? ["lease", "--platform", "ios", "--device", "iPhone 17 Pro", "--token", "probe"] : ["simctl", "list", "--token", "probe"], output.environmentWith(), @@ -1581,7 +1641,11 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", return code; }); const ready = (): boolean => - operation === "held lease" ? output.stdout !== "" : requests.includes("driver.passthrough"); + operation === "held lease" + ? output.stdout !== "" + : requests.includes( + operation === "pending lease" ? "lease.request" : "driver.passthrough", + ); for (let tick = 0; tick < 100 && !ready() && !settled; tick += 1) { clock.advance(50); await settle(); @@ -1591,22 +1655,22 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", expect(settled).toBe(false); expect(launcher.launches).toBe(1); expect(connections).toHaveLength(1); - expect(replies).toEqual([ - "hello", - operation === "held lease" ? "lease.request" : "status.get", - ]); + expect(requests).toContain( + operation === "in-flight request" ? "driver.passthrough" : "lease.request", + ); + if (operation === "pending lease") expect(replies).not.toContain("lease.request"); await connections[0]!.close(); expect(await runPromise).toBe(1); expect(JSON.parse(output.stderr)).toMatchObject({ error: { code: "DAEMON_CONNECTION_LOST" }, }); + expect(replies).toContain("status.get"); if (operation === "held lease") { expect(JSON.parse(output.stdout)).toMatchObject({ lease: detachedGrant.lease }); expect(JSON.parse(output.stderr).error.message).toContain(detachedGrant.lease.id); - expect(requests).toEqual(["hello", "lease.request"]); + expect(requests).toContain("lease.request"); } else { expect(output.stdout).toBe(""); - expect(requests).toEqual(["hello", "status.get", "driver.passthrough"]); } }, ); @@ -6405,17 +6469,18 @@ function outputCapture(ports?: CliEnvironmentPorts): OutputCapture { return capture; } -// why: the auto-launch poll's view of the daemon that loses the race for its HTTP port -// (#684): absent until this command launches it, then listening, answering one frame -- the -// `hello` -- and closing every connection it handed out when it stops itself on -// `http-start-failed`. `deaths` counts only the connections the daemon itself killed, never -// one the client closed. class HelloThenDeathIpc implements IpcConnector { helloReplies = 0; deaths = 0; #listening = false; - constructor(readonly closeAfter: "hello" | "request" = "hello") {} + rejectedCredentials = 0; + clientCloses = 0; + + constructor( + readonly closeAfter: "hello" | "request" | "silent" | "stopping" = "hello", + readonly rejectCredential = false, + ) {} startListening(): void { this.#listening = true; @@ -6459,8 +6524,39 @@ class HelloThenDeathConnection implements IpcConnection { let answeredHello = false; for (const line of contents.split("\n")) { if (line.trim() === "") continue; - const frame = JSON.parse(line) as { id?: unknown; type?: unknown }; + const frame = JSON.parse(line) as { + id?: unknown; + type?: unknown; + payload?: { credential?: string }; + }; + if (frame.type === "status.get" && this.daemon.closeAfter === "stopping") { + const reply = { + id: frame.id, + ok: false, + error: { + code: "DAEMON_STOPPING", + message: "Daemon is stopping", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } if (frame.type !== "hello" || typeof frame.id !== "number") continue; + if (this.daemon.rejectCredential && frame.payload?.credential !== undefined) { + this.daemon.rejectedCredentials += 1; + const reply = { + id: frame.id, + ok: false, + error: { + code: "ADMIN_AUTHENTICATION_FAILED", + message: "Rejected credential", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + this.#shutDown(false); + return; + } answeredHello = true; this.daemon.helloReplies += 1; const reply = { @@ -6476,10 +6572,15 @@ class HelloThenDeathConnection implements IpcConnection { }; for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); } - if (!answeredHello || this.daemon.closeAfter === "hello") this.#shutDown(true); + if ( + this.daemon.closeAfter === "hello" || + (!answeredHello && this.daemon.closeAfter === "request") + ) + this.#shutDown(true); } async close(): Promise { + this.daemon.clientCloses += 1; this.#shutDown(false); } From 45cc528461c1a30dde6dae9c9de4bcd373eab324 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Mon, 19 Oct 2026 16:43:16 +0200 Subject: [PATCH 4/6] test(cli): simplify startup probe IPC fixture --- src/cli/index.test.ts | 105 +++++++++++++++++++++++------------------- 1 file changed, 57 insertions(+), 48 deletions(-) diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index 71b1d3f5a..aa6c23ce2 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -6523,54 +6523,8 @@ class HelloThenDeathConnection implements IpcConnection { if (this.#closed) return; let answeredHello = false; for (const line of contents.split("\n")) { - if (line.trim() === "") continue; - const frame = JSON.parse(line) as { - id?: unknown; - type?: unknown; - payload?: { credential?: string }; - }; - if (frame.type === "status.get" && this.daemon.closeAfter === "stopping") { - const reply = { - id: frame.id, - ok: false, - error: { - code: "DAEMON_STOPPING", - message: "Daemon is stopping", - details: {}, - }, - }; - for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); - } - if (frame.type !== "hello" || typeof frame.id !== "number") continue; - if (this.daemon.rejectCredential && frame.payload?.credential !== undefined) { - this.daemon.rejectedCredentials += 1; - const reply = { - id: frame.id, - ok: false, - error: { - code: "ADMIN_AUTHENTICATION_FAILED", - message: "Rejected credential", - details: {}, - }, - }; - for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); - this.#shutDown(false); - return; - } - answeredHello = true; - this.daemon.helloReplies += 1; - const reply = { - id: frame.id, - ok: true, - payload: { - protocolVersion: PROTOCOL_VERSION_RANGE.max, - daemonProtocolRange: PROTOCOL_VERSION_RANGE, - version: "0.0.0-test", - role: "admin", - principal: "test-requester", - }, - }; - for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + answeredHello = this.#receiveFrame(line) || answeredHello; + if (this.#closed) return; } if ( this.daemon.closeAfter === "hello" || @@ -6579,6 +6533,61 @@ class HelloThenDeathConnection implements IpcConnection { this.#shutDown(true); } + #receiveFrame(line: string): boolean { + if (line.trim() === "") return false; + const frame = JSON.parse(line) as { + id?: unknown; + type?: unknown; + payload?: { credential?: string }; + }; + if (frame.type === "status.get" && this.daemon.closeAfter === "stopping") { + const reply = { + id: frame.id, + ok: false, + error: { + code: "DAEMON_STOPPING", + message: "Daemon is stopping", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } + if (frame.type !== "hello" || typeof frame.id !== "number") return false; + this.#answerHello(frame.id, frame.payload?.credential); + return true; + } + + #answerHello(id: number, credential: string | undefined): void { + if (this.daemon.rejectCredential && credential !== undefined) { + this.daemon.rejectedCredentials += 1; + const reply = { + id: id, + ok: false, + error: { + code: "ADMIN_AUTHENTICATION_FAILED", + message: "Rejected credential", + details: {}, + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + this.#shutDown(false); + return; + } + this.daemon.helloReplies += 1; + const reply = { + id: id, + ok: true, + payload: { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + }, + }; + for (const listener of this.#dataListeners) listener(`${JSON.stringify(reply)}\n`); + } + async close(): Promise { this.daemon.clientCloses += 1; this.#shutDown(false); From 38f75a2200f9aac8bb077f01064a1d5ae2bac386 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 08:37:49 +0200 Subject: [PATCH 5/6] fix(cli): close a timed-out startup probe without waiting on the daemon, pin its lower bound --- src/cli/AGENTS.md | 4 +-- src/cli/environment.ts | 7 +++- src/cli/index.test.ts | 75 ++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 3 deletions(-) diff --git a/src/cli/AGENTS.md b/src/cli/AGENTS.md index f17adf15f..31d000448 100644 --- a/src/cli/AGENTS.md +++ b/src/cli/AGENTS.md @@ -58,8 +58,8 @@ Surface: [CLI.md](../../docs/CLI.md) — every command, flag and exit code. first (a bad one fails on this stderr), launch the daemon detached, retry every 50 ms for `DAEMON_STARTUP_TIMEOUT_MS`. After a launch, `status.get` probes the connection before handing it to a command, within that same deadline. A connection loss during this - probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and closes - its client. An answered probe ends the window, including a `starting` status: subsequent + probe becomes `DAEMON_STARTUP_FAILED`; a silent probe times out with that code and starts closing + its client without waiting for the daemon to end its side. An answered probe ends the window, including a `starting` status: subsequent command failures retain their original codes even while a lease queues or boots. The connector retains the launch deadline across a rejected credential and agent fallback. A pre-existing daemon is never probed or reclassified; other daemon errors keep their codes. diff --git a/src/cli/environment.ts b/src/cli/environment.ts index d3a10e5de..78dcf5ad7 100644 --- a/src/cli/environment.ts +++ b/src/cli/environment.ts @@ -67,8 +67,10 @@ class AutoLaunchAdminConnector { const { isSimlockError, SimlockError } = await import("../contract/index.js"); const remainingMs = Math.max(0, this.startupDeadline - this.clock.now()); let timer: ReturnType | undefined; + let timedOut = false; const timeout = new Promise((_resolve, reject) => { timer = this.clock.setTimer(remainingMs, () => { + timedOut = true; reject( new SimlockError( "DAEMON_STARTUP_FAILED", @@ -84,7 +86,10 @@ class AutoLaunchAdminConnector { this.startupDeadline = undefined; return client; } catch (error: unknown) { - await client.close(); + // why: a daemon that went silent after `hello` never ends its side, so awaiting the close + // would hang the start this deadline bounds; other failures close against a live peer. + if (timedOut) void client.close().catch(() => undefined); + else await client.close(); if (isSimlockError(error) && error.code === "DAEMON_CONNECTION_LOST") { throw new SimlockError( "DAEMON_STARTUP_FAILED", diff --git a/src/cli/index.test.ts b/src/cli/index.test.ts index d92d4988c..455d39dcf 100644 --- a/src/cli/index.test.ts +++ b/src/cli/index.test.ts @@ -2,6 +2,7 @@ import { EventEmitter } from "node:events"; import { mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { createServer, type Socket } from "node:net"; import { Readable } from "node:stream"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -1575,6 +1576,7 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", clock.now(), "probe must use the budget left after the socket appeared", ).toBeLessThanOrEqual(20_050); + expect(clock.now(), "probe must wait out the launch deadline").toBeGreaterThanOrEqual(20_000); expect(await run).toBe(1); expect(launcher.launches).toBe(1); expect(daemon.helloReplies).toBe(1); @@ -1587,6 +1589,79 @@ describe("CLI: auto-launch's handshake cut short by the launched daemon (#684)", }); }); + it("fails a start with DAEMON_STARTUP_FAILED when the daemon stops reading after hello, without waiting for its side of the close", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock-wedged-")); + temporaryDirectories.push(directory); + const socketPath = join(directory, "daemon.sock"); + const sockets: Socket[] = []; + let hellos = 0; + const server = createServer((socket) => { + sockets.push(socket); + let buffered = ""; + socket.on("data", (chunk) => { + buffered += chunk.toString(); + for (const line of buffered.split("\n").slice(0, -1)) { + const frame = JSON.parse(line) as { id: number; type: string }; + if (frame.type !== "hello") continue; + hellos += 1; + socket.write( + `${JSON.stringify({ + id: frame.id, + ok: true, + payload: { + protocolVersion: PROTOCOL_VERSION_RANGE.max, + daemonProtocolRange: PROTOCOL_VERSION_RANGE, + version: "0.0.0-test", + role: "admin", + principal: "test-requester", + }, + })}\n`, + ); + // why: a daemon wedged after `hello` neither answers nor ends its side of the socket. + socket.pause(); + } + buffered = buffered.slice(buffered.lastIndexOf("\n") + 1); + }); + }); + await new Promise((resolve) => server.listen(socketPath, resolve)); + try { + const real = new NodeIpcTransport(); + let launched = false; + const clock = new FakeClock(0); + const launcher = new FakeDaemonLauncher(() => { + launched = true; + }); + const ipc: IpcConnector = { + connect: async () => { + if (!launched) throw new IpcError("endpoint-not-found", "not yet", undefined); + return real.connect(socketPath); + }, + }; + const output = outputCapture({ ...realCliEnvironmentPorts(), ipc, clock, launcher }); + let settled = false; + const run = runCli(["daemon", "start", "--token", "probe"], output.environmentWith()).then( + (code) => { + settled = true; + return code; + }, + ); + for (let tick = 0; tick < 200 && hellos === 0; tick += 1) { + clock.advance(50); + await new Promise((resolve) => setTimeout(resolve, 5)); + } + expect(hellos).toBe(1); + clock.advance(20_000); + await expect.poll(() => settled, { timeout: 2_000 }).toBe(true); + expect(await run).toBe(1); + expect(JSON.parse(output.stderr)).toMatchObject({ + error: { code: "DAEMON_STARTUP_FAILED" }, + }); + } finally { + for (const socket of sockets) socket.destroy(); + await new Promise((resolve) => server.close(() => resolve())); + } + }); + it.each([ { operation: "pending lease", health: "running" }, { operation: "pending lease", health: "starting" }, From dce75b38b3598caf778d51a82824486234ed20b4 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 20 Oct 2026 08:50:51 +0200 Subject: [PATCH 6/6] docs(daemon): drop manual rows for admin-secret.ts and session.ts, no longer in src/daemon --- src/daemon/AGENTS.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/daemon/AGENTS.md b/src/daemon/AGENTS.md index 23538c28b..465846957 100644 --- a/src/daemon/AGENTS.md +++ b/src/daemon/AGENTS.md @@ -17,8 +17,6 @@ Flows: [startup](../../docs/internal/flows/startup.md), [device.exec](../../docs | `dispatch.ts` | `runDispatch` pipeline, `DispatchSession`, `DispatchError` | | `dispatcher.ts` | `Dispatcher`: the worker's handlers | | `connection-host.ts` | `DaemonEndpointHost`: socket claim, stale-socket recovery | -| `admin-secret.ts` | `AdminSecretManager`: per-start secret, `admin.token` | -| `session.ts` | `createCredentialRoleResolver`: credential → role | | `owner-routed-facts.ts` | `OwnerRoutedFactBus`: lease facts with their owner | | `gateway-uplink.ts` | `GatewayUplink`: a worker's dial to its gateway | | `relay.ts` | `RelayTargets`, `RelayConnection`: relays over the uplink |