From ac6aed8114aad4388129ea15d0c521606d197ef6 Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 07:53:01 -0300 Subject: [PATCH 1/6] fix(android): stop the emulator's qemu child too when killing it on Windows On Windows a ProcessHandle kill ended the child alone unless it was a batch file's cmd.exe wrapper, so the Android driver's SIGKILL of emulator.exe (a readiness timeout, a shutdown that outlives its wait) left qemu-system-x86_64-headless.exe running with ~4 GB and its console port. Every Windows child is now killed with `taskkill /PID /T /F`, as every POSIX child already is through its process group, and the handle reports the kill rather than taskkill's exit code. macOS and Linux are unchanged. Co-Authored-By: Claude Opus 5.5 --- src/ports/AGENTS.md | 58 +++++++++++++++---------------- src/ports/process-runner.ts | 47 +++++++++++-------------- src/ports/windows-command.test.ts | 29 ++++++++++++++++ 3 files changed, 78 insertions(+), 56 deletions(-) diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 0c85ec260..71fc41b29 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -7,35 +7,35 @@ Uses: nothing from other components. Imported by: every component that touches t ## Ports -| Port | File | Node adapter | Fake | What it covers | -| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | -| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, copy, stat, delete, disk free; `mkdirp(path, { mode })` gives every directory it creates, parents included, and none that exists, exactly that mode (chmod past the umask) | -| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output; on Windows a `.bat`/`.cmd` runs through `cmd.exe /d /s /c` (`windows-command.ts`), and an argument holding `%`, `"` or a line break is refused; every child asks Windows for no console window (`windowsHide`), since the daemon has none | -| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | -| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it; `commandLine`: its arguments joined by spaces, from `ps -ww -o args=`, or on Windows `Win32_Process` through `powershell.exe`, unquoted; 5 s; unreadable is `undefined`. The adapter takes the runner and the platform | -| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log (and the data directory, `0700`, when missing), `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | -| `NpmCli` | `npm-cli.ts` | `NodeNpmCli` | `FakeNpmCli` | `view`, `install`, `globalRoot`: runs `process.execPath` with the real path of the `npm` beside it, in the daemon's data directory; 30 s for `view` and `globalRoot`, 10 min for `install`, the child killed at the limit; an error is the last 2000 characters of stderr | -| `UpdaterLauncher` | `updater-launcher.ts` | `NodeUpdaterLauncher` | `FakeUpdaterLauncher` | `launch` spawns the built entry of `src/updater/main.ts` detached with the Node that runs it: stdout a pipe (`lines`), stderr appended to the log, `exited` the exit code | -| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | -| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | -| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket, or a named pipe on Windows | -| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | -| `LeaseSocket` | `lease-socket.ts` | the upgrade router (`upgrade-router.ts`): `/v1/uplink` to the uplink, `/v1/leases/{id}/` to the app's lease socket resolution, else 404; a ping every 15 s, no pong ends the socket | `MemoryLeaseSocket` | A module's end of a lease WebSocket: `send`, `close(code, reason)`, `onMessage`, `onClose` | -| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | -| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | -| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | -| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `WindowsHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | -| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | -| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | -| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout; stdin is its liveness, or the commands `writeStdin` sends it (the fake records `stdinWrites`); no console window on Windows (`windowsHide`) | -| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | -| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | -| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | -| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | -| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | -| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `DATA_DIRECTORY_MODE` (`0700`), `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | +| Port | File | Node adapter | Fake | What it covers | +| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | +| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, copy, stat, delete, disk free; `mkdirp(path, { mode })` gives every directory it creates, parents included, and none that exists, exactly that mode (chmod past the umask) | +| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output; on Windows a `.bat`/`.cmd` runs through `cmd.exe /d /s /c` (`windows-command.ts`), and an argument holding `%`, `"` or a line break is refused; every child asks Windows for no console window (`windowsHide`), since the daemon has none; `kill` ends the child's process group, or on Windows its whole tree (`taskkill /T /F`), so `emulator.exe`'s qemu goes with it | +| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | +| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it; `commandLine`: its arguments joined by spaces, from `ps -ww -o args=`, or on Windows `Win32_Process` through `powershell.exe`, unquoted; 5 s; unreadable is `undefined`. The adapter takes the runner and the platform | +| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log (and the data directory, `0700`, when missing), `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | +| `NpmCli` | `npm-cli.ts` | `NodeNpmCli` | `FakeNpmCli` | `view`, `install`, `globalRoot`: runs `process.execPath` with the real path of the `npm` beside it, in the daemon's data directory; 30 s for `view` and `globalRoot`, 10 min for `install`, the child killed at the limit; an error is the last 2000 characters of stderr | +| `UpdaterLauncher` | `updater-launcher.ts` | `NodeUpdaterLauncher` | `FakeUpdaterLauncher` | `launch` spawns the built entry of `src/updater/main.ts` detached with the Node that runs it: stdout a pipe (`lines`), stderr appended to the log, `exited` the exit code | +| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | +| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | +| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket, or a named pipe on Windows | +| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | +| `LeaseSocket` | `lease-socket.ts` | the upgrade router (`upgrade-router.ts`): `/v1/uplink` to the uplink, `/v1/leases/{id}/` to the app's lease socket resolution, else 404; a ping every 15 s, no pong ends the socket | `MemoryLeaseSocket` | A module's end of a lease WebSocket: `send`, `close(code, reason)`, `onMessage`, `onClose` | +| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | +| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | +| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | +| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `WindowsHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | +| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | +| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | +| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout; stdin is its liveness, or the commands `writeStdin` sends it (the fake records `stdinWrites`); no console window on Windows (`windowsHide`) | +| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | +| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | +| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | +| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | +| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | +| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `DATA_DIRECTORY_MODE` (`0700`), `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | On Windows `resolveDaemonSocketPath` answers a named pipe, `\\.\pipe\simlock-`, because Node cannot listen on a file path there; `isPipeEndpoint` recognises it, and a pipe is never `stat`ed, removed or given a directory (`stat` on a live one fails `EBUSY`). No directory guards a pipe: the default pipe ACL lets other accounts only read (a client requires read and write access), and libuv's first-instance flag makes a second listener fail `address-in-use`. The name is predictable, so another local account that creates it before the daemon starts receives the CLI's `hello` (any `--token` or `SIMLOCK_ADMIN_TOKEN` with it) and answers in the daemon's place: a known gap, accepted for single-user machines only in the 2026-10-30 amendment to ADR 0003 section 4. diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 927e539a2..d41211005 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -268,7 +268,7 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, - launch.windowsVerbatimArguments, + process.platform === "win32", ); } @@ -301,7 +301,7 @@ export class NodeProcessRunner implements ProcessRunner { options.onChunk, this.exitDeferralCapMs, this.exitGraceMs, - launch.windowsVerbatimArguments, + process.platform === "win32", ); if (options.input !== undefined) { // One shot, then closed (ADR 0005 §19c): a command reading stdin sees exactly this and @@ -391,7 +391,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { onChunk: (stream: "stdout" | "stderr", chunk: string) => void | Promise, private readonly exitDeferralCapMs: number, private readonly exitGraceMs: number, - private readonly wrapped: boolean, + private readonly treeKilled: boolean, ) { this.pid = pid; this.#forward(child.stdout, "stdout", onChunk); @@ -405,7 +405,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { settled = true; const killedWith = this.#killedWith; resolve( - wrapped && killedWith !== undefined + treeKilled && killedWith !== undefined ? { code: null, signal: killedWith } : { code, signal }, ); @@ -478,7 +478,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { kill(signal: NodeJS.Signals = "SIGTERM"): void { if (isRunning(this.child)) this.#killedWith ??= signal; - killProcessTree(this.child, this.pid, signal, this.wrapped); + killProcessTree(this.child, this.pid, signal); } wait(): Promise { @@ -543,14 +543,14 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { const TASKKILL_TIMEOUT_MS = 10_000; /** - * why: Windows has no process groups, and a batch file runs under a `cmd.exe` wrapper - * (`windows-command.ts`): signalling the wrapper alone would leave the script's own processes, - * `sdkmanager`'s Java, running. `taskkill /T` walks the tree from the wrapper's pid, so it runs - * while the wrapper is still alive; the wrapper outlives what it runs, since a script runs its - * commands in the foreground. Windows ends a process on any signal, so `/F` is no harsher than - * `child.kill`. `taskkill` makes the wrapper exit with a code where `child.kill` reports a - * signal, so the handle reports the signal it sent instead. Should `taskkill` itself fail, the - * wrapper alone is killed as before. + * why: Windows has no process groups, and `child.kill` there ends the child alone: a batch + * file's `cmd.exe` wrapper (`windows-command.ts`) would leave the script's own processes, + * `sdkmanager`'s Java, running, and `emulator.exe` would leave the qemu it runs holding its RAM + * and console port. `taskkill /T` walks the tree from the child's pid, so it runs while the + * child is still alive; a tree whose parent already exited is out of its reach. Windows ends a + * process on any signal, so `/F` is no harsher than `child.kill`. `taskkill` makes the child exit + * with a code where `child.kill` reports a signal, so the handle reports the signal it sent + * instead. Should `taskkill` itself fail, the child alone is killed as before. */ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { const fallback = () => { @@ -569,8 +569,7 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS /** * why: Signals the child's whole process group (children are spawned `detached`, so the group is - * the unit that actually dies), or on Windows a batch file's whole tree and any other child - * alone, treating an already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` + * the unit that actually dies), or on Windows the child's whole tree, treating an already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` * kill identically -- a timeout that only reached the direct child would leave a tool's own * subprocesses running. * @@ -583,17 +582,11 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS * already handed to someone else -- latent before this PR, but `device.exec` is what makes the * timing remotely triggerable. */ -function killProcessTree( - child: ChildProcess, - pid: number, - signal: NodeJS.Signals, - wrapped: boolean, -): void { +function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { if (!isRunning(child)) return; if (process.platform === "win32") { - if (wrapped) killWindowsProcessTree(child, pid, signal); - else child.kill(signal); + killWindowsProcessTree(child, pid, signal); return; } @@ -608,7 +601,7 @@ function killProcessTree( } } -// why: a wrapper that already exited, its output still held open by a grandchild, is never +// why: a child that already exited, its output still held open by a grandchild, is never // signalled, so its own exit code stands rather than a kill nobody sent. function isRunning(child: ChildProcess): boolean { return child.exitCode === null && child.signalCode === null; @@ -629,7 +622,7 @@ class NodeProcessHandle implements ProcessHandle { lineEnd: LineEnd, private readonly exitDeferralCapMs: number, private readonly exitGraceMs: number, - private readonly wrapped: boolean, + private readonly treeKilled: boolean, ) { this.pid = pid; captureLines(child.stdout, this.stdout, this.#stdoutChunks, lineEnd); @@ -644,7 +637,7 @@ class NodeProcessHandle implements ProcessHandle { } settled = true; resolve({ - code: wrapped && this.#killedWith !== undefined ? null : code, + code: treeKilled && this.#killedWith !== undefined ? null : code, stderr: this.#stderrChunks.join(""), stdout: this.#stdoutChunks.join(""), }); @@ -678,7 +671,7 @@ class NodeProcessHandle implements ProcessHandle { kill(signal: NodeJS.Signals = "SIGTERM"): void { if (isRunning(this.child)) this.#killedWith ??= signal; - killProcessTree(this.child, this.pid, signal, this.wrapped); + killProcessTree(this.child, this.pid, signal); } unref(): void { diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index fa1a90b4e..4566c2e7c 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -136,6 +136,35 @@ describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () } }); + /** + * why: `emulator.exe` runs the emulator itself as a child (`qemu-system-x86_64-headless.exe`); + * a kill that reached only the parent left that child running with its RAM and console port. + * The child here is `detached` because libuv otherwise puts it in a job object that ends it with + * its parent, which `emulator.exe` does not do for qemu. + */ + it("ends the children of an .exe it kills, not only the .exe, and reports no exit code", async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock exe ")); + const pidFile = join(directory, "child.pid"); + const childScript = `require('fs').writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000)`; + const parentScript = `require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(childScript)}, process.argv[1]], { detached: true, stdio: 'ignore' }); setInterval(() => {}, 1000)`; + let childPid: number | undefined; + try { + const handle = new NodeProcessRunner().spawn(process.execPath, ["-e", parentScript, pidFile]); + await expect + .poll(() => readFile(pidFile, "utf8").catch(() => ""), { timeout: 5_000 }) + .not.toBe(""); + childPid = Number(await readFile(pidFile, "utf8")); + + handle.kill("SIGKILL"); + + await expect(handle.wait()).resolves.toMatchObject({ code: null }); + await expect.poll(() => isAlive(childPid ?? 0), { timeout: 5_000 }).toBe(false); + } finally { + if (childPid !== undefined && isAlive(childPid)) process.kill(childPid); + await rm(directory, { force: true, recursive: true }); + } + }); + it("reports a batch file's own exit code when kill comes after cmd.exe exited but a grandchild still holds its output", async () => { const directory = await mkdtemp(join(tmpdir(), "simlock bat ")); const pidFile = join(directory, "grandchild.pid"); From b5eef750f15aec83a4d27280543495a83ba5342f Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 08:31:29 -0300 Subject: [PATCH 2/6] fix(android): kill the process tree only for the emulator on Windows #1129's tree kill reached every child, adb clients included, and an adb client can start the shared 5037 server as its child. The runner again kills an ordinary child alone on Windows (a .bat/.cmd still as a tree); a new ProcessRunOptions.killTree opts a child into the tree kill, and only the emulator spawn sets it. Co-Authored-By: Claude Opus 5.5 --- src/drivers/android/AGENTS.md | 4 +- src/drivers/android/index.test.ts | 17 +++++++- src/drivers/android/index.ts | 4 +- src/ports/AGENTS.md | 58 +++++++++++++-------------- src/ports/process-runner.ts | 49 +++++++++++++++-------- src/ports/windows-command.test.ts | 65 ++++++++++++++++++++++--------- 6 files changed, 130 insertions(+), 67 deletions(-) diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 3d2c6a389..14eb8e45d 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -80,7 +80,9 @@ Reclaim — `reclaim`: Ownership gate: before any `emu kill` or snapshot load, `adb emu avd path` (5 s timeout, asked every time, never cached) must name this device's own AVD directory; unreachable, timed out or another path → nothing is sent (a snapshot reclaim then shuts down and wipes). -`shutdown`: gate, then `adb emu kill`, wait, SIGKILL. `destroy`: kills the emulator this process started, or after a restart each attached +`shutdown`: gate, then `adb emu kill`, wait, SIGKILL. +The emulator alone is spawned with `killTree`, so a kill of its handle (that SIGKILL, a boot timeout) also ends its qemu child on Windows; elsewhere its process group. No adb command asks for it: an adb client can start the 5037 server as its child, so a kill ends that client alone. +`destroy`: kills the emulator this process started, or after a restart each attached emulator whose bounded `emu avd path` names this AVD (any serial that cannot answer → refuse), then `avdmanager delete avd`, frees the port. `listManaged`: `/*.avd` + `adb devices` + `ro.boot.qemu.avd_name` per serial; only root members count. Profiles — library (`profiles/`), SDK (`avdmanager list device`), devices.xml diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index f615967f8..69f9225ea 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -56,7 +56,7 @@ const scopedEnv = { } as const; const scopedOptions = { env: scopedEnv } as const; // why: The emulator outlives the daemon and is never read from, so it is spawned detached. -const emulatorOptions = { env: scopedEnv, stdio: "ignore" } as const; +const emulatorOptions = { env: scopedEnv, killTree: true, stdio: "ignore" } as const; const binaries = { adb: `${sdk}/platform-tools/adb`, avdmanager: `${sdk}/cmdline-tools/latest/bin/avdmanager`, @@ -516,6 +516,21 @@ describe("AndroidDriver", () => { }); }); + // why: On Windows a kill ends the child alone, and `emulator.exe`'s qemu child would keep its + // RAM; but an `adb` client can start the adb server as its child, and for a phone that is the + // shared 5037 server, which a tree kill would take down. + it("asks for a tree kill when it starts the emulator, and for no adb command", async () => { + const harness = await provisionedHarness(); + + await harness.driver.makeReady(harness.device); + + const emulatorCalls = harness.runner.calls.filter((call) => call.command === binaries.emulator); + const adbCalls = harness.runner.calls.filter((call) => call.command === binaries.adb); + expect(emulatorCalls.map((call) => call.options.killTree)).toEqual([true]); + expect(adbCalls.length).toBeGreaterThan(0); + expect(adbCalls.filter((call) => call.options.killTree !== undefined)).toEqual([]); + }); + // why: The gRPC port follows the reserved console port, so two parallel leases never share one. it("puts the gRPC endpoint at the reserved console port plus 3000", async () => { const filesystem = await androidFilesystem(); diff --git a/src/drivers/android/index.ts b/src/drivers/android/index.ts index 8782ae034..9dbc5107e 100644 --- a/src/drivers/android/index.ts +++ b/src/drivers/android/index.ts @@ -2146,7 +2146,9 @@ export class AndroidDriver implements Driver { ...this.#emulatorFlags, ...launchArgs, ], - { env: this.#env(), stdio: "ignore" }, + // why: on Windows a kill otherwise ends `emulator.exe` alone, and its qemu child keeps + // running with the guest's RAM; no adb command asks for this (the 5037 server rule). + { env: this.#env(), killTree: true, stdio: "ignore" }, ); handle.unref(); state.handle = handle; diff --git a/src/ports/AGENTS.md b/src/ports/AGENTS.md index 71fc41b29..7cd805ba1 100644 --- a/src/ports/AGENTS.md +++ b/src/ports/AGENTS.md @@ -7,35 +7,35 @@ Uses: nothing from other components. Imported by: every component that touches t ## Ports -| Port | File | Node adapter | Fake | What it covers | -| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | -| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, copy, stat, delete, disk free; `mkdirp(path, { mode })` gives every directory it creates, parents included, and none that exists, exactly that mode (chmod past the umask) | -| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output; on Windows a `.bat`/`.cmd` runs through `cmd.exe /d /s /c` (`windows-command.ts`), and an argument holding `%`, `"` or a line break is refused; every child asks Windows for no console window (`windowsHide`), since the daemon has none; `kill` ends the child's process group, or on Windows its whole tree (`taskkill /T /F`), so `emulator.exe`'s qemu goes with it | -| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | -| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it; `commandLine`: its arguments joined by spaces, from `ps -ww -o args=`, or on Windows `Win32_Process` through `powershell.exe`, unquoted; 5 s; unreadable is `undefined`. The adapter takes the runner and the platform | -| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | -| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log (and the data directory, `0700`, when missing), `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | -| `NpmCli` | `npm-cli.ts` | `NodeNpmCli` | `FakeNpmCli` | `view`, `install`, `globalRoot`: runs `process.execPath` with the real path of the `npm` beside it, in the daemon's data directory; 30 s for `view` and `globalRoot`, 10 min for `install`, the child killed at the limit; an error is the last 2000 characters of stderr | -| `UpdaterLauncher` | `updater-launcher.ts` | `NodeUpdaterLauncher` | `FakeUpdaterLauncher` | `launch` spawns the built entry of `src/updater/main.ts` detached with the Node that runs it: stdout a pipe (`lines`), stderr appended to the log, `exited` the exit code | -| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | -| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | -| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket, or a named pipe on Windows | -| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | -| `LeaseSocket` | `lease-socket.ts` | the upgrade router (`upgrade-router.ts`): `/v1/uplink` to the uplink, `/v1/leases/{id}/` to the app's lease socket resolution, else 404; a ping every 15 s, no pong ends the socket | `MemoryLeaseSocket` | A module's end of a lease WebSocket: `send`, `close(code, reason)`, `onMessage`, `onClose` | -| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | -| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | -| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | -| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `WindowsHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | -| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | -| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | -| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout; stdin is its liveness, or the commands `writeStdin` sends it (the fake records `stdinWrites`); no console window on Windows (`windowsHide`) | -| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | -| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | -| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | -| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | -| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | -| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `DATA_DIRECTORY_MODE` (`0700`), `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | +| Port | File | Node adapter | Fake | What it covers | +| ------------------------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `Clock` | `clock.ts` | `SystemClock` | `FakeClock` | `now`, `setTimer`, `cancel` | +| `Filesystem` | `filesystem.ts` | `NodeFilesystem` | `MemoryFilesystem` | Read, atomic write, copy, stat, delete, disk free; `mkdirp(path, { mode })` gives every directory it creates, parents included, and none that exists, exactly that mode (chmod past the umask) | +| `ProcessRunner` | `process-runner.ts` | `NodeProcessRunner` | `ScriptedProcessRunner` | Run or stream a command, capture output; on Windows a `.bat`/`.cmd` runs through `cmd.exe /d /s /c` (`windows-command.ts`), and an argument holding `%`, `"` or a line break is refused; every child asks Windows for no console window (`windowsHide`), since the daemon has none; `kill` ends the child's process group, but on Windows the child alone, except the whole tree (`taskkill /T /F`; the child alone should it fail) of a `.bat`/`.cmd` or of a child spawned with `killTree` | +| (wrapper) | `logging-process-runner.ts` | `LoggingProcessRunner` | — | One `process` log line per command, at `debug` only | +| `ProcessSupervisor` | `process-supervisor.ts` | `NodeProcessSupervisor` | `FakeProcessSupervisor` | Is a pid alive; signal it; `commandLine`: its arguments joined by spaces, from `ps -ww -o args=`, or on Windows `Win32_Process` through `powershell.exe`, unquoted; 5 s; unreadable is `undefined`. The adapter takes the runner and the platform | +| `ParentWatch` | `parent-watch.ts` | `NodeParentWatch` | `FakeParentWatch` | Call once when a pid exits (polls) | +| `DaemonLauncher` | `daemon-launcher.ts` | `NodeDaemonLauncher` | `FakeDaemonLauncher` | Detached daemon, its log (and the data directory, `0700`, when missing), `DAEMON_STARTUP_TIMEOUT_MS`; `launch()` answers a `LaunchedDaemon` (`exited`, `readOutput` of the log since the launch); `startErrorFrom` | +| `NpmCli` | `npm-cli.ts` | `NodeNpmCli` | `FakeNpmCli` | `view`, `install`, `globalRoot`: runs `process.execPath` with the real path of the `npm` beside it, in the daemon's data directory; 30 s for `view` and `globalRoot`, 10 min for `install`, the child killed at the limit; an error is the last 2000 characters of stderr | +| `UpdaterLauncher` | `updater-launcher.ts` | `NodeUpdaterLauncher` | `FakeUpdaterLauncher` | `launch` spawns the built entry of `src/updater/main.ts` detached with the Node that runs it: stdout a pipe (`lines`), stderr appended to the log, `exited` the exit code | +| `ServiceManager` | `service-manager.ts` | `LaunchdServiceManager`, `SystemdServiceManager` (`productionServiceManager(platform)`: `darwin`, `linux`; `undefined` elsewhere) | `FakeServiceManager` | A per-user service for one role: `state` (`not-installed`, `installed`, `not-loaded`, `broken`), `install`, `uninstall`, `start` (kickstart); every `launchctl`/`plutil`/`systemctl --user` call has a 10 s limit; systemd writes `$XDG_CONFIG_HOME/systemd/user/.service` (absolute only, else `~/.config`); `serviceDefinition` builds the name, path, command and saved variables | +| (factory) | `service-launcher.ts` | `launcherFor` | — | The one start choice for the CLI and the MCP server: kickstart a loaded service (`readOutput` is `daemon.log` since the start), else notice and spawn through `NodeDaemonLauncher`; `startTimeoutMessage` adds those lines at the deadline | +| `IpcConnector`, `IpcListenerFactory` | `ipc.ts` | `NodeIpcTransport` | `MemoryIpcTransport` | The daemon's unix socket, or a named pipe on Windows | +| `UplinkConnector`, `UplinkListenerFactory` | `uplink.ts` | `WebSocketUplinkConnector`, `WebSocketUplinkListenerFactory` | `MemoryUplinkTransport` | A worker's uplink to its gateway | +| `LeaseSocket` | `lease-socket.ts` | the upgrade router (`upgrade-router.ts`): `/v1/uplink` to the uplink, `/v1/leases/{id}/` to the app's lease socket resolution, else 404; a ping every 15 s, no pong ends the socket | `MemoryLeaseSocket` | A module's end of a lease WebSocket: `send`, `close(code, reason)`, `onMessage`, `onClose` | +| `Logger`, `LogSink` | `logger.ts` | `JsonLinesLogger`, `NodeFileLogSink` | `NoopLogger`, `MemoryLogSink` | JSON-line logs, `child(module)`, rotation | +| `SystemStats` | `system-stats.ts` | `NodeSystemStats` | `FakeSystemStats` | CPU count, total RAM | +| `HostInfo` | `host-info.ts` | `NodeHostInfo` | `FakeHostInfo` | OS, version (`sw_vers` on macOS), arch | +| `HostLoadProbe` | `host-load.ts` | `DarwinHostLoadProbe`, `WindowsHostLoadProbe`, `LinuxHostLoadProbe` | `FakeHostLoadProbe` | CPU, memory, disk counters | +| `TcpProbe` | `tcp-probe.ts` | `NodeTcpProbe` | `FakeTcpProbe` | Is a loopback port listening; send bytes | +| `TcpStreamConnector` | `tcp-stream.ts` | `NodeTcpStreamConnector` | `FakeTcpStreamConnector` | A long-lived loopback connection, bytes both ways | +| `BytePipeLauncher` | `byte-pipe.ts` | `NodeBytePipeLauncher` | `FakeBytePipeLauncher` | A child with binary stdout; stdin is its liveness, or the commands `writeStdin` sends it (the fake records `stdinWrites`); no console window on Windows (`windowsHide`) | +| `KeySetFetcher` | `key-set-fetcher.ts` | `NodeKeySetFetcher` | `FakeKeySetFetcher` | One GET of a key-set URL: no redirects, body capped at 64 KiB | +| `SqliteOpener` | `sqlite.ts` | `NodeSqliteOpener` | none; tests use the adapter on a temp file | Open a SQLite file (`:memory:` is not pre-created); `exec`, `prepare`, `close`. `sqlite.ts` also holds `SqliteSchemaOwner` (`name`, `version`, `migrations[i]` takes version `i` to `i + 1`), `passesQuickCheck` and `isLockError` | +| `WebhookPoster` | `webhook-poster.ts` | `FetchWebhookPoster` | `FakeWebhookPoster` (`testing.ts`) | POST to an operator-named URL; a redirect is not followed | +| `IdGenerator` | `id-generator.ts` | `CryptoIdGenerator` | none; tests inline one | Random ids | +| `TokenSecrets` | `token-secrets.ts` | `CryptoTokenSecrets` | none; tests inline one | New secret, its hash | +| Paths | `paths.ts` | `resolveSimlockHome`, `daemonDataDirectory`, `DATA_DIRECTORY_MODE` (`0700`), `resolveDaemonHome`, `resolveDaemonSocketPath` | — | `SIMLOCK_HOME` (test root; default `~/.simlock`), a gateway in `/gateway`, socket path length; `resolveDaemonHome` picks the folder from the flag (`gateway`, `local`) or, with none, the gateway only when `/gateway/{instance,config}.json` exists and `/instance.json` does not | On Windows `resolveDaemonSocketPath` answers a named pipe, `\\.\pipe\simlock-`, because Node cannot listen on a file path there; `isPipeEndpoint` recognises it, and a pipe is never `stat`ed, removed or given a directory (`stat` on a live one fails `EBUSY`). No directory guards a pipe: the default pipe ACL lets other accounts only read (a client requires read and write access), and libuv's first-instance flag makes a second listener fail `address-in-use`. The name is predictable, so another local account that creates it before the daemon starts receives the CLI's `hello` (any `--token` or `SIMLOCK_ADMIN_TOKEN` with it) and answers in the daemon's place: a known gap, accepted for single-user machines only in the 2026-10-30 amendment to ADR 0003 section 4. diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index d41211005..0c5fc0661 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -56,6 +56,14 @@ export interface ProcessRunOptions { * newline. The captured `ProcessResult` text is the same either way. */ readonly lineEnd?: LineEnd; + /** + * why: on Windows, `kill` ends the child's whole process tree (`taskkill /T /F`), not the child + * alone; should `taskkill` fail, the child alone. For `emulator.exe`, whose qemu child would + * otherwise keep running. Off by default: an `adb` client can start the adb server as its + * child, and for a phone that is the shared 5037 server. A `.bat`/`.cmd` is always killed + * as a tree. Elsewhere `kill` already ends the child's process group, so this changes nothing. + */ + readonly killTree?: boolean; } export type LineEnd = "newline" | "carriage-return-too"; @@ -268,7 +276,8 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, - process.platform === "win32", + launch.windowsVerbatimArguments || + (process.platform === "win32" && options.killTree === true), ); } @@ -301,7 +310,7 @@ export class NodeProcessRunner implements ProcessRunner { options.onChunk, this.exitDeferralCapMs, this.exitGraceMs, - process.platform === "win32", + launch.windowsVerbatimArguments, ); if (options.input !== undefined) { // One shot, then closed (ADR 0005 §19c): a command reading stdin sees exactly this and @@ -478,7 +487,7 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { kill(signal: NodeJS.Signals = "SIGTERM"): void { if (isRunning(this.child)) this.#killedWith ??= signal; - killProcessTree(this.child, this.pid, signal); + killProcessTree(this.child, this.pid, signal, this.treeKilled); } wait(): Promise { @@ -543,14 +552,15 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { const TASKKILL_TIMEOUT_MS = 10_000; /** - * why: Windows has no process groups, and `child.kill` there ends the child alone: a batch - * file's `cmd.exe` wrapper (`windows-command.ts`) would leave the script's own processes, - * `sdkmanager`'s Java, running, and `emulator.exe` would leave the qemu it runs holding its RAM - * and console port. `taskkill /T` walks the tree from the child's pid, so it runs while the - * child is still alive; a tree whose parent already exited is out of its reach. Windows ends a - * process on any signal, so `/F` is no harsher than `child.kill`. `taskkill` makes the child exit - * with a code where `child.kill` reports a signal, so the handle reports the signal it sent - * instead. Should `taskkill` itself fail, the child alone is killed as before. + * why: Windows has no process groups, and a batch file runs under a `cmd.exe` wrapper + * (`windows-command.ts`): signalling the wrapper alone would leave the script's own processes, + * `sdkmanager`'s Java, running; `emulator.exe` (spawned with `killTree`) would likewise leave + * the qemu it runs. `taskkill /T` walks the tree from the child's pid, so it runs while the + * child is still alive; a wrapper outlives what it runs, since a script runs its commands in the + * foreground. Windows ends a process on any signal, so `/F` is no harsher than `child.kill`. + * `taskkill` makes the child exit with a code where `child.kill` reports a signal, so the handle + * reports the signal it sent instead. Should `taskkill` itself fail, the child alone is killed + * as before. */ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { const fallback = () => { @@ -569,7 +579,8 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS /** * why: Signals the child's whole process group (children are spawned `detached`, so the group is - * the unit that actually dies), or on Windows the child's whole tree, treating an already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` + * the unit that actually dies), or on Windows the whole tree of a batch file or a `killTree` + * child and any other child alone, treating an already-exited process as success. Extracted so `ProcessHandle` and `StreamingProcessHandle` * kill identically -- a timeout that only reached the direct child would leave a tool's own * subprocesses running. * @@ -582,11 +593,17 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS * already handed to someone else -- latent before this PR, but `device.exec` is what makes the * timing remotely triggerable. */ -function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signals): void { +function killProcessTree( + child: ChildProcess, + pid: number, + signal: NodeJS.Signals, + treeKilled: boolean, +): void { if (!isRunning(child)) return; if (process.platform === "win32") { - killWindowsProcessTree(child, pid, signal); + if (treeKilled) killWindowsProcessTree(child, pid, signal); + else child.kill(signal); return; } @@ -601,7 +618,7 @@ function killProcessTree(child: ChildProcess, pid: number, signal: NodeJS.Signal } } -// why: a child that already exited, its output still held open by a grandchild, is never +// why: a wrapper that already exited, its output still held open by a grandchild, is never // signalled, so its own exit code stands rather than a kill nobody sent. function isRunning(child: ChildProcess): boolean { return child.exitCode === null && child.signalCode === null; @@ -671,7 +688,7 @@ class NodeProcessHandle implements ProcessHandle { kill(signal: NodeJS.Signals = "SIGTERM"): void { if (isRunning(this.child)) this.#killedWith ??= signal; - killProcessTree(this.child, this.pid, signal); + killProcessTree(this.child, this.pid, signal, this.treeKilled); } unref(): void { diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index 4566c2e7c..aafb69aa8 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -4,7 +4,7 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; -import { NodeProcessRunner } from "./index.js"; +import { NodeProcessRunner, type ProcessHandle, type ProcessRunOptions } from "./index.js"; import { childLaunch } from "./windows-command.js"; const sdkmanager = String.raw`C:\Android\Sdk/cmdline-tools/latest/bin/sdkmanager.bat`; @@ -142,27 +142,26 @@ describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () * The child here is `detached` because libuv otherwise puts it in a job object that ends it with * its parent, which `emulator.exe` does not do for qemu. */ - it("ends the children of an .exe it kills, not only the .exe, and reports no exit code", async () => { - const directory = await mkdtemp(join(tmpdir(), "simlock exe ")); - const pidFile = join(directory, "child.pid"); - const childScript = `require('fs').writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000)`; - const parentScript = `require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(childScript)}, process.argv[1]], { detached: true, stdio: 'ignore' }); setInterval(() => {}, 1000)`; - let childPid: number | undefined; - try { - const handle = new NodeProcessRunner().spawn(process.execPath, ["-e", parentScript, pidFile]); - await expect - .poll(() => readFile(pidFile, "utf8").catch(() => ""), { timeout: 5_000 }) - .not.toBe(""); - childPid = Number(await readFile(pidFile, "utf8")); - + it("ends the children of an .exe spawned with killTree, not only the .exe, and reports no exit code", async () => { + await withParentOfDetachedChild({ killTree: true }, async (handle, childPid) => { handle.kill("SIGKILL"); await expect(handle.wait()).resolves.toMatchObject({ code: null }); - await expect.poll(() => isAlive(childPid ?? 0), { timeout: 5_000 }).toBe(false); - } finally { - if (childPid !== undefined && isAlive(childPid)) process.kill(childPid); - await rm(directory, { force: true, recursive: true }); - } + await expect.poll(() => isAlive(childPid), { timeout: 5_000 }).toBe(false); + }); + }); + + /** + * why: an `adb` client can start the adb server as its child, and for a phone that is the + * shared 5037 server, which a timed-out command must not take down with it. + */ + it("kills an .exe spawned without killTree alone, leaving its children running", async () => { + await withParentOfDetachedChild({}, async (handle, childPid) => { + handle.kill("SIGKILL"); + + await handle.wait(); + expect(isAlive(childPid)).toBe(true); + }); }); it("reports a batch file's own exit code when kill comes after cmd.exe exited but a grandchild still holds its output", async () => { @@ -199,6 +198,34 @@ exit /b 0 }); }); +async function withParentOfDetachedChild( + options: ProcessRunOptions, + use: (handle: ProcessHandle, childPid: number) => Promise, +): Promise { + const directory = await mkdtemp(join(tmpdir(), "simlock exe ")); + const pidFile = join(directory, "child.pid"); + const childScript = `require('fs').writeFileSync(process.argv[1], String(process.pid)); setInterval(() => {}, 1000)`; + const parentScript = `require('child_process').spawn(process.execPath, ['-e', ${JSON.stringify(childScript)}, process.argv[1]], { detached: true, stdio: 'ignore' }); setInterval(() => {}, 1000)`; + let handle: ProcessHandle | undefined; + let childPid: number | undefined; + try { + handle = new NodeProcessRunner().spawn( + process.execPath, + ["-e", parentScript, pidFile], + options, + ); + await expect + .poll(() => readFile(pidFile, "utf8").catch(() => ""), { timeout: 5_000 }) + .not.toBe(""); + childPid = Number(await readFile(pidFile, "utf8")); + await use(handle, childPid); + } finally { + handle?.kill("SIGKILL"); + if (childPid !== undefined && isAlive(childPid)) process.kill(childPid); + await rm(directory, { force: true, recursive: true }); + } +} + function isAlive(pid: number): boolean { try { process.kill(pid, 0); From f37f2b7c626211332ee2fe1f25936ec3b08961ac Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 08:37:30 -0300 Subject: [PATCH 3/6] fix(android): keep the driver manual in budget and test only the emulator launch The tree-kill test matched `emulator -version` too, a plain run that asks for no tree kill; it now matches the `-avd` launch only. The manual's shutdown note joins its line so the manual stays at 150 lines. Co-Authored-By: Claude Opus 5.5 --- src/drivers/android/AGENTS.md | 3 +-- src/drivers/android/index.test.ts | 4 +++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/drivers/android/AGENTS.md b/src/drivers/android/AGENTS.md index 14eb8e45d..fc27aa8be 100644 --- a/src/drivers/android/AGENTS.md +++ b/src/drivers/android/AGENTS.md @@ -80,8 +80,7 @@ Reclaim — `reclaim`: Ownership gate: before any `emu kill` or snapshot load, `adb emu avd path` (5 s timeout, asked every time, never cached) must name this device's own AVD directory; unreachable, timed out or another path → nothing is sent (a snapshot reclaim then shuts down and wipes). -`shutdown`: gate, then `adb emu kill`, wait, SIGKILL. -The emulator alone is spawned with `killTree`, so a kill of its handle (that SIGKILL, a boot timeout) also ends its qemu child on Windows; elsewhere its process group. No adb command asks for it: an adb client can start the 5037 server as its child, so a kill ends that client alone. +`shutdown`: gate, then `adb emu kill`, wait, SIGKILL. The emulator alone is spawned with `killTree`, so a kill of its handle (that SIGKILL, a boot timeout) also ends its qemu child on Windows; elsewhere its process group. No adb command asks for it: an adb client can start the 5037 server as its child, so a kill ends that client alone. `destroy`: kills the emulator this process started, or after a restart each attached emulator whose bounded `emu avd path` names this AVD (any serial that cannot answer → refuse), then `avdmanager delete avd`, frees the port. `listManaged`: `/*.avd` + `adb devices` + `ro.boot.qemu.avd_name` per serial; only root members count. diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index 69f9225ea..eddf25950 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -524,7 +524,9 @@ describe("AndroidDriver", () => { await harness.driver.makeReady(harness.device); - const emulatorCalls = harness.runner.calls.filter((call) => call.command === binaries.emulator); + const emulatorCalls = harness.runner.calls.filter( + (call) => call.command === binaries.emulator && call.args.includes("-avd"), + ); const adbCalls = harness.runner.calls.filter((call) => call.command === binaries.adb); expect(emulatorCalls.map((call) => call.options.killTree)).toEqual([true]); expect(adbCalls.length).toBeGreaterThan(0); From 2cc287741beb6e58cb312313e58640acaeb1cabe Mon Sep 17 00:00:00 2001 From: Xavier Date: Sat, 31 Oct 2026 08:42:42 -0300 Subject: [PATCH 4/6] test(android): check every emulator launch asks for the tree kill A first boot launches the emulator twice (cold boot, then the reboot from the new baseline), and both ask for it. Co-Authored-By: Claude Opus 5.5 --- src/drivers/android/index.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/drivers/android/index.test.ts b/src/drivers/android/index.test.ts index eddf25950..ba4d440ec 100644 --- a/src/drivers/android/index.test.ts +++ b/src/drivers/android/index.test.ts @@ -528,7 +528,8 @@ describe("AndroidDriver", () => { (call) => call.command === binaries.emulator && call.args.includes("-avd"), ); const adbCalls = harness.runner.calls.filter((call) => call.command === binaries.adb); - expect(emulatorCalls.map((call) => call.options.killTree)).toEqual([true]); + expect(emulatorCalls.length).toBeGreaterThan(0); + expect(emulatorCalls.filter((call) => call.options.killTree !== true)).toEqual([]); expect(adbCalls.length).toBeGreaterThan(0); expect(adbCalls.filter((call) => call.options.killTree !== undefined)).toEqual([]); }); From 6490ada77f023bd7997fc460277f7b98045b07d4 Mon Sep 17 00:00:00 2001 From: Xavier Date: Wed, 4 Nov 2026 18:47:20 -0300 Subject: [PATCH 5/6] refactor(ports): move the tree-kill choice out of spawn Fallow's CRAP gate put `spawn` at 31.6 over its 30 limit once the `killTree` condition joined it; `killsTree` holds that choice. Co-Authored-By: Claude Opus 5.5 --- src/ports/process-runner.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/src/ports/process-runner.ts b/src/ports/process-runner.ts index 1d5c74a54..d45e9cbeb 100644 --- a/src/ports/process-runner.ts +++ b/src/ports/process-runner.ts @@ -2,7 +2,7 @@ import { spawn as spawnChildProcess, type ChildProcess } from "node:child_proces import { closeSync, openSync } from "node:fs"; import { constants } from "node:os"; -import { childLaunch } from "./windows-command.js"; +import { type ChildLaunch, childLaunch } from "./windows-command.js"; // `close` normally follows `exit` within the same tick, once the child's own stdio // pipes report EOF. But a child that forks a grandchild before it dies leaves that @@ -283,8 +283,7 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, - launch.windowsVerbatimArguments || - (process.platform === "win32" && options.killTree === true), + killsTree(launch, options), ); } @@ -558,6 +557,13 @@ class NodeStreamingProcessHandle implements StreamingProcessHandle { const TASKKILL_TIMEOUT_MS = 10_000; +/** why: on Windows a `.bat`/`.cmd` wrapper, or a child spawned with `killTree`, is killed as a whole tree. */ +function killsTree(launch: ChildLaunch, options: ProcessRunOptions): boolean { + return ( + launch.windowsVerbatimArguments || (process.platform === "win32" && options.killTree === true) + ); +} + /** * why: Windows has no process groups, and a batch file runs under a `cmd.exe` wrapper * (`windows-command.ts`): signalling the wrapper alone would leave the script's own processes, From 3113cabba435e0e102c0faaf5e194d4af0edcf8e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Tue, 17 Nov 2026 15:34:08 +0100 Subject: [PATCH 6/6] fix(ports): killChildren changes nothing off Windows, so a child's exit code stands there Co-Authored-By: Claude Opus 5.5 --- src/ports/node-process-runner.ts | 5 +++-- src/ports/process-runner.test.ts | 21 +++++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/src/ports/node-process-runner.ts b/src/ports/node-process-runner.ts index 785e03271..17039369d 100644 --- a/src/ports/node-process-runner.ts +++ b/src/ports/node-process-runner.ts @@ -581,8 +581,9 @@ function childStdio( } // why: a batch file's `cmd.exe` wrapper dies with its whole tree; a `killChildren` child with its -// own children only; any other child alone. +// own children only; any other child alone. Off Windows every child is `"child"`: its exit code +// stands, as the kill there is the process group's own signal. function windowsKillOf(wrapped: boolean, killChildren: boolean): WindowsKill { if (wrapped) return "tree"; - return killChildren ? "children" : "child"; + return killChildren && process.platform === "win32" ? "children" : "child"; } diff --git a/src/ports/process-runner.test.ts b/src/ports/process-runner.test.ts index 49f9b615a..59869f115 100644 --- a/src/ports/process-runner.test.ts +++ b/src/ports/process-runner.test.ts @@ -513,6 +513,27 @@ describe("NodeProcessRunner: spawnStreaming", () => { } }); + // why: `killChildren` is a Windows kill; elsewhere a child that answers SIGTERM with its own + // exit code keeps reporting it. + it.skipIf(process.platform === "win32")( + "reports the exit code of a killChildren child that exits on SIGTERM", + async () => { + const handle = new NodeProcessRunner().spawn( + process.execPath, + [ + "-e", + "process.on('SIGTERM', () => process.exit(7)); console.log('ready'); setInterval(() => {}, 1_000)", + ], + { killChildren: true }, + ); + for await (const line of handle.stdout) if (line === "ready") break; + + handle.kill("SIGTERM"); + + await expect(handle.wait()).resolves.toMatchObject({ code: 7 }); + }, + ); + it("kills the grandchildren too, because the signal goes to the process group", async () => { // The reason `kill` signals `-pid` rather than the child: a tool that forks (an // `adb`/`emulator` wrapper script, `simctl spawn`) leaves the work in a *grandchild*, and a