From f1d775cbde1a244942291494f3126c82f7b0bd94 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 12:26:04 +0100 Subject: [PATCH 1/9] =?UTF-8?q?test:=20reproduce=20#1759=20=E2=80=94=20a?= =?UTF-8?q?=20child=20NodeProcessRunner.spawn=20logs=20to=20a=20file=20is?= =?UTF-8?q?=20not=20started=20detached=20on=20Windows?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/ports/child-window.test.ts | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/src/ports/child-window.test.ts b/src/ports/child-window.test.ts index 03c431293..fd1ab0dbf 100644 --- a/src/ports/child-window.test.ts +++ b/src/ports/child-window.test.ts @@ -93,3 +93,36 @@ describe("the children the ports start ask Windows for no console window", () => ); }); }); + +/** + * why: Node puts every child it does not start detached on Windows into a job that kills the + * child when Node exits, and the child shares Node's console. An emulator or adb server spawned + * that way dies with the daemon while its own children live on, holding the logon task's + * console open (#1759). Neither the job nor the console can be seen from a test off Windows, so + * this checks the option `spawn` hands Node with the platform set. + */ +describe("a child NodeProcessRunner.spawn logs to a file outlives the daemon on every platform", () => { + const original = Object.getOwnPropertyDescriptor(process, "platform"); + let directory: string | undefined; + + afterEach(async () => { + if (original !== undefined) Object.defineProperty(process, "platform", original); + vi.mocked(spawn).mockClear(); + if (directory !== undefined) await rm(directory, { force: true, recursive: true }); + directory = undefined; + }); + + it.each(["win32", "darwin", "linux"] as const)("is started detached on %s", async (platform) => { + directory = await mkdtemp(join(tmpdir(), "simlock-child-detach-")); + const file = join(directory, "child.log"); + Object.defineProperty(process, "platform", { value: platform }); + + await new NodeProcessRunner().spawn(...quiet, { stdio: { file } }).wait(); + + expect(vi.mocked(spawn)).toHaveBeenCalledWith( + process.execPath, + ["-e", ""], + expect.objectContaining({ detached: true }), + ); + }); +}); From 2b2d0b86a11a99b3d0230057eb1c9eef0283fe8d Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 13:03:43 +0100 Subject: [PATCH 2/9] fix(ports): a child that logs to a file is detached on Windows too (#1759) --- src/ports/node-process-runner.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/ports/node-process-runner.ts b/src/ports/node-process-runner.ts index 31e8793c4..09ecff71a 100644 --- a/src/ports/node-process-runner.ts +++ b/src/ports/node-process-runner.ts @@ -118,7 +118,9 @@ export class NodeProcessRunner implements ProcessRunner { const child = spawnChildProcess(launch.command, launch.args, { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), ...(options.env === undefined ? {} : { env: options.env }), - detached: process.platform !== "win32", + // why: a child that logs to a file is a long-lived one (emulator, adb server) that must outlive + // the daemon; on Windows only a detached child leaves Node's kill-on-exit job and console. + detached: process.platform !== "win32" || typeof options.stdio === "object", stdio: childStdio(options.stdio, logFd), // why: the daemon has no console, so on Windows a console program it starts (adb, the // emulator, node) would otherwise get a new, visible one. From 8ce27b75d55864ddd0ee09081f684eb5b5219c26 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 13:19:56 +0100 Subject: [PATCH 3/9] fix(ports): only a child that outlives the daemon is detached on Windows; the supervisor's daemon is not (#1759) --- src/daemon/service-main.test.ts | 1 + src/drivers/android/adb-server.test.ts | 1 + src/drivers/android/adb-server.ts | 1 + src/drivers/android/emulator.ts | 2 +- src/drivers/android/index-boot.test.ts | 1 + src/drivers/android/index-lifecycle.test.ts | 1 + src/ports/child-window.test.ts | 39 +++++++++++++-------- src/ports/node-process-runner.ts | 5 ++- src/ports/process-runner-types.ts | 8 +++++ 9 files changed, 41 insertions(+), 18 deletions(-) diff --git a/src/daemon/service-main.test.ts b/src/daemon/service-main.test.ts index 987e09932..83e61165d 100644 --- a/src/daemon/service-main.test.ts +++ b/src/daemon/service-main.test.ts @@ -147,6 +147,7 @@ describe("the Windows supervisor (#1698)", () => { const first = failed.runner.calls[0]; expect(first?.options.timeoutMs, "the daemon wait has no limit").toBeUndefined(); expect(first?.options.stdio).toEqual({ file: join(home, "daemon.log") }); + expect(first?.options.outlivesCaller, "ending the supervisor ends its daemon").toBeUndefined(); expect(first?.options.env).toMatchObject({ PATH: "saved", KEEP: "1", SIMLOCK_HOME: home }); expect(failed.logPaths[0]).toBe(join(home, "daemon.log")); expect( diff --git a/src/drivers/android/adb-server.test.ts b/src/drivers/android/adb-server.test.ts index fb48989bc..a97ba5791 100644 --- a/src/drivers/android/adb-server.test.ts +++ b/src/drivers/android/adb-server.test.ts @@ -83,6 +83,7 @@ describe("AdbServerSupervisor.start", () => { ANDROID_HOME: "/android-sdk", PATH: "/usr/bin", }, + outlivesCaller: true, stdio: { file: logPath }, }, }, diff --git a/src/drivers/android/adb-server.ts b/src/drivers/android/adb-server.ts index 027581238..823aad9d6 100644 --- a/src/drivers/android/adb-server.ts +++ b/src/drivers/android/adb-server.ts @@ -317,6 +317,7 @@ export class AdbServerSupervisor { ...SCOPED_ENVIRONMENT, ANDROID_ADB_SERVER_PORT: String(this.#options.port), }, + outlivesCaller: true, stdio: { file: this.#options.logPath }, }, ); diff --git a/src/drivers/android/emulator.ts b/src/drivers/android/emulator.ts index 6b8925029..fe4a29569 100644 --- a/src/drivers/android/emulator.ts +++ b/src/drivers/android/emulator.ts @@ -272,7 +272,7 @@ export class Emulator { // why: on Windows a kill otherwise ends `emulator.exe` alone, and its qemu child keeps // running with the guest's RAM. Not a tree or process-group kill: qemu's `netsimd` serves // every emulator. - { env: this.#env(data), killChildren: true, stdio: { file: logPath } }, + { env: this.#env(data), killChildren: true, outlivesCaller: true, stdio: { file: logPath } }, ); handle.unref(); // why: No announcement here, deliberately. adb answers `host:emulator:` by connecting diff --git a/src/drivers/android/index-boot.test.ts b/src/drivers/android/index-boot.test.ts index 9473e6673..516aed7e9 100644 --- a/src/drivers/android/index-boot.test.ts +++ b/src/drivers/android/index-boot.test.ts @@ -252,6 +252,7 @@ describe("AndroidDriver", () => { const adbCalls = harness.runner.calls.filter((call) => call.command === binaries.adb); expect(emulatorCalls.length).toBeGreaterThan(0); expect(emulatorCalls.filter((call) => call.options.killChildren !== true)).toEqual([]); + expect(emulatorCalls.filter((call) => call.options.outlivesCaller !== true)).toEqual([]); expect(adbCalls.length).toBeGreaterThan(0); expect(adbCalls.filter((call) => call.options.killChildren !== undefined)).toEqual([]); }); diff --git a/src/drivers/android/index-lifecycle.test.ts b/src/drivers/android/index-lifecycle.test.ts index bd217a5ab..4a359cff6 100644 --- a/src/drivers/android/index-lifecycle.test.ts +++ b/src/drivers/android/index-lifecycle.test.ts @@ -30,6 +30,7 @@ import { home } from "./test-index.js"; const emulatorOptions = { env: { ...scopedEnv, ANDROID_EMU_CRASH_REPORTING_DATABASE: `${avdDirectory}/emu-crash.db` }, killChildren: true, + outlivesCaller: true, stdio: { file: `${avdDirectory}/simlock_one/simlock.avd/emulator.log` }, } as const; diff --git a/src/ports/child-window.test.ts b/src/ports/child-window.test.ts index fd1ab0dbf..5460d3127 100644 --- a/src/ports/child-window.test.ts +++ b/src/ports/child-window.test.ts @@ -98,10 +98,11 @@ describe("the children the ports start ask Windows for no console window", () => * why: Node puts every child it does not start detached on Windows into a job that kills the * child when Node exits, and the child shares Node's console. An emulator or adb server spawned * that way dies with the daemon while its own children live on, holding the logon task's - * console open (#1759). Neither the job nor the console can be seen from a test off Windows, so - * this checks the option `spawn` hands Node with the platform set. + * console open (#1759). The supervisor's daemon must stay in that job, so that ending the + * supervisor ends it (ADR 0086 section 2). Neither the job nor the console can be seen from a + * test off Windows, so this checks the option `spawn` hands Node with the platform set. */ -describe("a child NodeProcessRunner.spawn logs to a file outlives the daemon on every platform", () => { +describe("a child that outlives its caller is detached on every platform, and one that does not is detached off Windows only", () => { const original = Object.getOwnPropertyDescriptor(process, "platform"); let directory: string | undefined; @@ -112,17 +113,27 @@ describe("a child NodeProcessRunner.spawn logs to a file outlives the daemon on directory = undefined; }); - it.each(["win32", "darwin", "linux"] as const)("is started detached on %s", async (platform) => { - directory = await mkdtemp(join(tmpdir(), "simlock-child-detach-")); - const file = join(directory, "child.log"); - Object.defineProperty(process, "platform", { value: platform }); + it.each([ + ["win32", true, true], + ["darwin", true, true], + ["linux", true, true], + ["win32", false, false], + ["darwin", false, true], + ["linux", false, true], + ] as const)( + "on %s, outlivesCaller %s is started detached: %s", + async (platform, outlivesCaller, detached) => { + directory = await mkdtemp(join(tmpdir(), "simlock-child-detach-")); + const file = join(directory, "child.log"); + Object.defineProperty(process, "platform", { value: platform }); - await new NodeProcessRunner().spawn(...quiet, { stdio: { file } }).wait(); + await new NodeProcessRunner().spawn(...quiet, { outlivesCaller, stdio: { file } }).wait(); - expect(vi.mocked(spawn)).toHaveBeenCalledWith( - process.execPath, - ["-e", ""], - expect.objectContaining({ detached: true }), - ); - }); + expect(vi.mocked(spawn)).toHaveBeenCalledWith( + process.execPath, + ["-e", ""], + expect.objectContaining({ detached }), + ); + }, + ); }); diff --git a/src/ports/node-process-runner.ts b/src/ports/node-process-runner.ts index 09ecff71a..907a4093b 100644 --- a/src/ports/node-process-runner.ts +++ b/src/ports/node-process-runner.ts @@ -118,9 +118,8 @@ export class NodeProcessRunner implements ProcessRunner { const child = spawnChildProcess(launch.command, launch.args, { ...(options.cwd === undefined ? {} : { cwd: options.cwd }), ...(options.env === undefined ? {} : { env: options.env }), - // why: a child that logs to a file is a long-lived one (emulator, adb server) that must outlive - // the daemon; on Windows only a detached child leaves Node's kill-on-exit job and console. - detached: process.platform !== "win32" || typeof options.stdio === "object", + // why: on Windows only a detached child leaves Node's kill-on-exit job (see `outlivesCaller`). + detached: process.platform !== "win32" || options.outlivesCaller === true, stdio: childStdio(options.stdio, logFd), // why: the daemon has no console, so on Windows a console program it starts (adb, the // emulator, node) would otherwise get a new, visible one. diff --git a/src/ports/process-runner-types.ts b/src/ports/process-runner-types.ts index 6450c2d0d..2a24c4f62 100644 --- a/src/ports/process-runner-types.ts +++ b/src/ports/process-runner-types.ts @@ -38,6 +38,14 @@ export interface ProcessRunOptions { * Windows, and on Windows also the child's own children (`emulator.exe` runs qemu), never theirs. */ readonly killChildren?: boolean; + /** + * why: a long-lived child the daemon starts for others to use (the emulator, Simlock's adb + * server) must outlive the daemon (ADR 0004, ADR 0019). Off Windows every child is detached + * already; on Windows only a detached child leaves Node's kill-on-exit job, which would end it + * with the daemon while its own children live on and hold the logon task's console open + * (#1759). The supervisor's daemon is not one: ending the supervisor ends it (ADR 0086 section 2). + */ + readonly outlivesCaller?: boolean; } export type LineEnd = "newline" | "carriage-return-too"; From f99e68d2578dce51d77b5980e9ff917a3206ed0f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 13:29:49 +0100 Subject: [PATCH 4/9] fix(ports): a detached child on Windows starts inside conhost --headless, so its qemu opens no window (#1759) --- src/ports/child-window.test.ts | 30 ++++++++++----- src/ports/node-process-runner.ts | 22 ++++++++--- src/ports/process-runner-types.ts | 5 ++- src/ports/process-tree-kill.ts | 29 ++++++++++----- src/ports/windows-command.test.ts | 61 ++++++++++++++++++++++++++++++- src/ports/windows-command.ts | 21 +++++++++++ 6 files changed, 141 insertions(+), 27 deletions(-) diff --git a/src/ports/child-window.test.ts b/src/ports/child-window.test.ts index 5460d3127..90788c21d 100644 --- a/src/ports/child-window.test.ts +++ b/src/ports/child-window.test.ts @@ -114,24 +114,34 @@ describe("a child that outlives its caller is detached on every platform, and on }); it.each([ - ["win32", true, true], - ["darwin", true, true], - ["linux", true, true], - ["win32", false, false], - ["darwin", false, true], - ["linux", false, true], + ["win32", true, true, true], + ["darwin", true, true, false], + ["linux", true, true, false], + ["win32", false, false, false], + ["darwin", false, true, false], + ["linux", false, true, false], ] as const)( - "on %s, outlivesCaller %s is started detached: %s", - async (platform, outlivesCaller, detached) => { + "on %s, outlivesCaller %s is started detached: %s, under conhost --headless: %s", + async (platform, outlivesCaller, detached, headless) => { directory = await mkdtemp(join(tmpdir(), "simlock-child-detach-")); const file = join(directory, "child.log"); Object.defineProperty(process, "platform", { value: platform }); + if (headless) { + // why: conhost.exe does not exist off Windows; the quiet program stands in for it. + const actual = + await vi.importActual("node:child_process"); + vi.mocked(spawn).mockImplementationOnce((( + _command: string, + _args: string[], + options: object, + ) => actual.spawn(...quiet, options)) as unknown as typeof spawn); + } await new NodeProcessRunner().spawn(...quiet, { outlivesCaller, stdio: { file } }).wait(); expect(vi.mocked(spawn)).toHaveBeenCalledWith( - process.execPath, - ["-e", ""], + headless ? expect.stringMatching(/conhost\.exe$/i) : process.execPath, + headless ? ["--headless", process.execPath, "-e", ""] : ["-e", ""], expect.objectContaining({ detached }), ); }, diff --git a/src/ports/node-process-runner.ts b/src/ports/node-process-runner.ts index 907a4093b..6e34d1936 100644 --- a/src/ports/node-process-runner.ts +++ b/src/ports/node-process-runner.ts @@ -10,7 +10,7 @@ import { runLimits, type WindowsKill, } from "./process-tree-kill.js"; -import { childLaunch } from "./windows-command.js"; +import { childLaunch, headlessLaunch } from "./windows-command.js"; import { InputStreamFailedError, ProcessSpawnError, @@ -112,7 +112,10 @@ export class NodeProcessRunner implements ProcessRunner { } #launch(command: string, args: readonly string[], options: ProcessRunOptions): NodeProcessHandle { - const launch = childLaunch(command, args); + const launch = + options.outlivesCaller === true + ? headlessLaunch(childLaunch(command, args)) + : childLaunch(command, args); const logFd = typeof options.stdio === "object" ? openSync(options.stdio.file, "a", 0o600) : undefined; const child = spawnChildProcess(launch.command, launch.args, { @@ -149,7 +152,11 @@ export class NodeProcessRunner implements ProcessRunner { options.lineEnd ?? "newline", this.exitDeferralCapMs, this.exitGraceMs, - windowsKillOf(launch.windowsVerbatimArguments, options.killChildren === true), + windowsKillOf( + launch.windowsVerbatimArguments, + options.killChildren === true, + options.outlivesCaller === true, + ), runLimits(options), ); } @@ -183,7 +190,7 @@ export class NodeProcessRunner implements ProcessRunner { options.onChunk, this.exitDeferralCapMs, this.exitGraceMs, - windowsKillOf(launch.windowsVerbatimArguments, false), + windowsKillOf(launch.windowsVerbatimArguments, false, false), ); if (options.input !== undefined) { // why: One shot, then closed (ADR 0005 ยง19c): a command reading stdin sees exactly this and @@ -589,8 +596,11 @@ function childStdio( // why: a batch file's `cmd.exe` wrapper dies with its whole tree; a `killChildren` child alone // off Windows (its process group would end what it started for others) and with its own children -// on Windows; any other child alone there, and off Windows its whole process group. -function windowsKillOf(wrapped: boolean, killChildren: boolean): WindowsKill { +// on Windows; any other child alone there, and off Windows its whole process group. A child that +// outlives its caller runs under a headless `conhost.exe` (`headlessLaunch`), so there the child +// Node sees is the wrapper and the wanted unit is one level further down. +function windowsKillOf(wrapped: boolean, killChildren: boolean, headless: boolean): WindowsKill { if (wrapped) return "tree"; + if (headless && process.platform === "win32") return killChildren ? "grandchildren" : "children"; return killChildren ? "children" : "child"; } diff --git a/src/ports/process-runner-types.ts b/src/ports/process-runner-types.ts index 2a24c4f62..992b14634 100644 --- a/src/ports/process-runner-types.ts +++ b/src/ports/process-runner-types.ts @@ -43,7 +43,10 @@ export interface ProcessRunOptions { * server) must outlive the daemon (ADR 0004, ADR 0019). Off Windows every child is detached * already; on Windows only a detached child leaves Node's kill-on-exit job, which would end it * with the daemon while its own children live on and hold the logon task's console open - * (#1759). The supervisor's daemon is not one: ending the supervisor ends it (ADR 0086 section 2). + * (#1759). On Windows it also runs under `conhost.exe --headless` (`headlessLaunch`), so the qemu + * of an emulator opens no window; `kill` still ends the wrapper's program and, with + * `killChildren`, that program's own children. The supervisor's daemon is not one: ending the + * supervisor ends it (ADR 0086 section 2). */ readonly outlivesCaller?: boolean; } diff --git a/src/ports/process-tree-kill.ts b/src/ports/process-tree-kill.ts index aac3609e9..5486cc177 100644 --- a/src/ports/process-tree-kill.ts +++ b/src/ports/process-tree-kill.ts @@ -14,7 +14,7 @@ export function runLimits({ }; } -export type WindowsKill = "child" | "children" | "tree"; +export type WindowsKill = "child" | "children" | "grandchildren" | "tree"; /** * why: Windows has no process groups, and a batch file runs under a `cmd.exe` wrapper @@ -36,19 +36,29 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS * `ParentProcessId`, and pids are reused, so a listed process counts as a child only when it * started after the child did. Should PowerShell fail, the child alone is killed. */ -function killWindowsProcessAndChildren( - child: ChildProcess, - pid: number, - signal: NodeJS.Signals, -): void { - const script = [ +export function windowsKillScript(pid: number, depth: 1 | 2): string { + return [ "$ErrorActionPreference = 'Stop'", `$parent = Get-CimInstance Win32_Process -Filter 'ProcessId = ${pid}'`, "if ($null -eq $parent) { exit 1 }", `$children = @(Get-CimInstance Win32_Process -Filter 'ParentProcessId = ${pid}' | Where-Object { $_.CreationDate -ge $parent.CreationDate })`, + ...(depth === 2 + ? [ + '$grandchildren = @(foreach ($c in $children) { Get-CimInstance Win32_Process -Filter "ParentProcessId = $($c.ProcessId)" | Where-Object { $_.CreationDate -ge $c.CreationDate } })', + ] + : ["$grandchildren = @()"]), `Stop-Process -Id ${pid} -Force`, - "foreach ($c in $children) { Stop-Process -Id $c.ProcessId -Force -ErrorAction SilentlyContinue }", + "foreach ($c in @($children) + @($grandchildren)) { Stop-Process -Id $c.ProcessId -Force -ErrorAction SilentlyContinue }", ].join("\n"); +} + +function killWindowsProcessAndChildren( + child: ChildProcess, + pid: number, + signal: NodeJS.Signals, + depth: 1 | 2, +): void { + const script = windowsKillScript(pid, depth); runWindowsKill(child, signal, "powershell.exe", [ "-NoProfile", "-NonInteractive", @@ -104,7 +114,8 @@ export function killProcessTree( if (process.platform === "win32") { if (windowsKill === "tree") killWindowsProcessTree(child, pid, signal); - else if (windowsKill === "children") killWindowsProcessAndChildren(child, pid, signal); + else if (windowsKill === "children") killWindowsProcessAndChildren(child, pid, signal, 1); + else if (windowsKill === "grandchildren") killWindowsProcessAndChildren(child, pid, signal, 2); else child.kill(signal); return; } diff --git a/src/ports/windows-command.test.ts b/src/ports/windows-command.test.ts index ed77e2ffe..57efe75da 100644 --- a/src/ports/windows-command.test.ts +++ b/src/ports/windows-command.test.ts @@ -5,7 +5,8 @@ import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { NodeProcessRunner, type ProcessHandle, type ProcessRunOptions } from "./index.js"; -import { childLaunch } from "./windows-command.js"; +import { windowsKillScript } from "./process-tree-kill.js"; +import { childLaunch, headlessLaunch } from "./windows-command.js"; const sdkmanager = String.raw`C:\Android\Sdk/cmdline-tools/latest/bin/sdkmanager.bat`; @@ -70,7 +71,65 @@ describe("childLaunch", () => { }); }); +// why: the launch a detached child gets is pure string work the runner's surface shows only on Windows. +describe("headlessLaunch", () => { + it.each([ + ["linux", "/sdk/emulator/emulator"], + ["darwin", "/sdk/emulator/emulator"], + ] as const)("leaves a command off Windows as it is (%s)", (platform, command) => { + const launch = { command, args: ["-avd", "x"], windowsVerbatimArguments: false }; + + expect(headlessLaunch(launch, platform, String.raw`C:\Windows`)).toBe(launch); + }); + + it("runs an .exe under conhost.exe --headless from the system folder", () => { + expect( + headlessLaunch( + { + command: String.raw`D:\Android\Sdk\emulator\emulator.exe`, + args: ["-avd", "simlock"], + windowsVerbatimArguments: false, + }, + "win32", + String.raw`C:\Windows`, + ), + ).toEqual({ + command: String.raw`C:\Windows\System32\conhost.exe`, + args: ["--headless", String.raw`D:\Android\Sdk\emulator\emulator.exe`, "-avd", "simlock"], + windowsVerbatimArguments: false, + }); + }); +}); + +// why: the PowerShell that ends a wrapper's tree cannot run off Windows; its depth decides +// whether qemu (the emulator's child) is ended with the emulator. +describe("windowsKillScript", () => { + it("ends the process and its children at depth 1, and their children too at depth 2", () => { + expect(windowsKillScript(42, 1)).toContain("$grandchildren = @()"); + expect(windowsKillScript(42, 2)).toContain("ParentProcessId = $($c.ProcessId)"); + expect(windowsKillScript(42, 2)).toContain("Stop-Process -Id 42 -Force"); + }); +}); + describe.runIf(process.platform === "win32")("NodeProcessRunner on Windows", () => { + /** + * why: a detached child of the daemon runs under a headless `conhost.exe` (#1759), so the child + * Node holds is the wrapper; killing it must still end the program under it (the emulator) and + * that program's child (qemu), and leave qemu's own child (netsimd) running. + */ + it("ends a detached killChildren child through its conhost wrapper: the program and its child, not the grandchild", async () => { + await withProcessChain( + { killChildren: true, outlivesCaller: true }, + async (handle, { child, grandchild }) => { + handle.kill("SIGKILL"); + + await expect(handle.wait()).resolves.toMatchObject({ code: null }); + await expect.poll(() => isAlive(child), { timeout: 10_000 }).toBe(false); + expect(isAlive(grandchild)).toBe(true); + }, + ); + }); + /** * why: the SDK's Gradle-generated batch files test `"x%~1"`, collect `%*` into a variable and * expand it on the `java` line, so cmd.exe parses every argument there twice more; this script diff --git a/src/ports/windows-command.ts b/src/ports/windows-command.ts index c5d7aac2c..ef663729b 100644 --- a/src/ports/windows-command.ts +++ b/src/ports/windows-command.ts @@ -58,3 +58,24 @@ export function childLaunch( windowsVerbatimArguments: true, }; } + +/** + * why: a detached child of the daemon (the emulator, Simlock's adb server) starts with no console + * of its own, and its qemu then opens a visible Windows Terminal window titled with the qemu path + * (#1759). Under `conhost.exe --headless` the child and everything it starts inherit a console + * that has no window, as the logon task's do (ADR 0086). The wrapper is the child Node sees; it + * exits when the program it runs exits. A batch-file launch is left as it is: none outlives its + * caller. + */ +export function headlessLaunch( + launch: ChildLaunch, + platform: NodeJS.Platform = process.platform, + systemRoot: string | undefined = process.env.SystemRoot, +): ChildLaunch { + if (platform !== "win32" || launch.windowsVerbatimArguments) return launch; + return { + command: win32.join(systemRoot ?? "C:\\Windows", "System32", "conhost.exe"), + args: ["--headless", launch.command, ...launch.args], + windowsVerbatimArguments: false, + }; +} From bb005da8effe6b501b443457fcd8fabb0d19e97e Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 13:30:14 +0100 Subject: [PATCH 5/9] refactor(ports): the launch choice is its own function (#1759) --- src/ports/node-process-runner.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/ports/node-process-runner.ts b/src/ports/node-process-runner.ts index 6e34d1936..709caccc2 100644 --- a/src/ports/node-process-runner.ts +++ b/src/ports/node-process-runner.ts @@ -10,7 +10,7 @@ import { runLimits, type WindowsKill, } from "./process-tree-kill.js"; -import { childLaunch, headlessLaunch } from "./windows-command.js"; +import { childLaunch, headlessLaunch, type ChildLaunch } from "./windows-command.js"; import { InputStreamFailedError, ProcessSpawnError, @@ -112,10 +112,7 @@ export class NodeProcessRunner implements ProcessRunner { } #launch(command: string, args: readonly string[], options: ProcessRunOptions): NodeProcessHandle { - const launch = - options.outlivesCaller === true - ? headlessLaunch(childLaunch(command, args)) - : childLaunch(command, args); + const launch = launchOf(command, args, options); const logFd = typeof options.stdio === "object" ? openSync(options.stdio.file, "a", 0o600) : undefined; const child = spawnChildProcess(launch.command, launch.args, { @@ -586,6 +583,15 @@ class NodeProcessHandle implements ProcessHandle { } } +function launchOf( + command: string, + args: readonly string[], + options: ProcessRunOptions, +): ChildLaunch { + const launch = childLaunch(command, args); + return options.outlivesCaller === true ? headlessLaunch(launch) : launch; +} + function childStdio( stdio: ProcessRunOptions["stdio"], logFd: number | undefined, From bdbf4d3b02a3b5be39c93695949ec827e672ab1b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 14:01:44 +0100 Subject: [PATCH 6/9] fix(android): reaping Simlock's adb server on Windows ends the adb under its conhost wrapper too (#1759) --- src/drivers/android/adb-server.test.ts | 10 ++++++++-- src/drivers/android/adb-server.ts | 4 ++-- src/ports/process-supervisor.test.ts | 26 ++++++++++++++++++++++++++ src/ports/process-supervisor.ts | 26 ++++++++++++++++++++++---- 4 files changed, 58 insertions(+), 8 deletions(-) diff --git a/src/drivers/android/adb-server.test.ts b/src/drivers/android/adb-server.test.ts index a97ba5791..881e9230d 100644 --- a/src/drivers/android/adb-server.test.ts +++ b/src/drivers/android/adb-server.test.ts @@ -140,6 +140,8 @@ describe("AdbServerSupervisor.start", () => { await harness.started; expect(harness.supervisor.signals).toEqual([{ pid: recordedPid, signal: "SIGTERM" }]); + // why: on Windows the recorded pid is the conhost wrapper's; its adb must end with it. + expect(harness.supervisor.treeSignals).toEqual([recordedPid]); expect(harness.runner.calls.map((call) => call.command)).toEqual([adb]); }, ); @@ -490,8 +492,12 @@ const ownServerCommand = `${adb} -P 5038 nodaemon server`; class SignallingSupervisor extends FakeProcessSupervisor { onSignal: ((pid: number, signal: NodeJS.Signals) => void) | undefined; - override signal(pid: number, signal: NodeJS.Signals): void { - super.signal(pid, signal); + override signal( + pid: number, + signal: NodeJS.Signals, + options?: { readonly tree?: boolean }, + ): void { + super.signal(pid, signal, options); this.onSignal?.(pid, signal); } } diff --git a/src/drivers/android/adb-server.ts b/src/drivers/android/adb-server.ts index 823aad9d6..7e97788e8 100644 --- a/src/drivers/android/adb-server.ts +++ b/src/drivers/android/adb-server.ts @@ -238,10 +238,10 @@ export class AdbServerSupervisor { return; } - this.#options.processSupervisor.signal(record.pid, "SIGTERM"); + this.#options.processSupervisor.signal(record.pid, "SIGTERM", { tree: true }); if (!(await this.#waitForExit(record.pid))) { if ((await this.#identify(record.pid)) === "own-server") { - this.#options.processSupervisor.signal(record.pid, "SIGKILL"); + this.#options.processSupervisor.signal(record.pid, "SIGKILL", { tree: true }); await this.#waitForExit(record.pid); } } diff --git a/src/ports/process-supervisor.test.ts b/src/ports/process-supervisor.test.ts index daa579bb8..1f26603a2 100644 --- a/src/ports/process-supervisor.test.ts +++ b/src/ports/process-supervisor.test.ts @@ -65,6 +65,32 @@ describe("NodeProcessSupervisor", () => { expect(kill).not.toHaveBeenCalled(); }); + it.each([ + ["win32", true, ["/pid", "4242", "/T", "/F"]], + ["win32", false, undefined], + ["linux", true, undefined], + ] as const)( + "on %s, a signal with tree %s ends the process and what it started through taskkill: %j", + (platform, tree, taskkillArgs) => { + const kill = vi.spyOn(process, "kill").mockImplementation(() => true); + const runner = new ScriptedProcessRunner([ + { + match: { args: [/.*/, /.*/, /.*/, /.*/], command: "taskkill" }, + result: { code: 0, stderr: "", stdout: "" }, + }, + ]); + + new NodeProcessSupervisor({ platform, processRunner: runner }).signal(4242, "SIGTERM", { + tree, + }); + + expect(runner.calls.map((call) => call.args)).toEqual( + taskkillArgs === undefined ? [] : [taskkillArgs], + ); + expect(kill).toHaveBeenCalledTimes(taskkillArgs === undefined ? 1 : 0); + }, + ); + it("treats signalling a process that is already gone as a no-op", async () => { const supervisor = nodeSupervisor(); const pid = await retiredPid(); diff --git a/src/ports/process-supervisor.ts b/src/ports/process-supervisor.ts index 2b12cdab0..daa4f3caf 100644 --- a/src/ports/process-supervisor.ts +++ b/src/ports/process-supervisor.ts @@ -10,8 +10,12 @@ import type { ProcessResult, ProcessRunner } from "./process-runner.js"; export interface ProcessSupervisor { /** True when a process with this pid exists and this user may signal it. */ isAlive(pid: number): boolean; - /** Best effort; a pid that is already gone is not an error. */ - signal(pid: number, signal: NodeJS.Signals): void; + /** + * why: best effort; a pid that is already gone is not an error. With `tree`, on Windows the + * process and what it started end together: a detached child there runs under a `conhost.exe` + * wrapper (`headlessLaunch`), and a recorded pid is the wrapper's, which ends alone otherwise. + */ + signal(pid: number, signal: NodeJS.Signals, options?: { readonly tree?: boolean }): void; /** * why: a recorded pid may since have been handed to another process, so a caller proves what * it is from its arguments before signalling it. They come back unquoted and joined by single @@ -83,11 +87,22 @@ export class NodeProcessSupervisor implements ProcessSupervisor { } } - signal(pid: number, signal: NodeJS.Signals): void { + signal(pid: number, signal: NodeJS.Signals, options?: { readonly tree?: boolean }): void { if (!isAddressablePid(pid)) { return; } + if (options?.tree === true && this.#options.platform === "win32") { + try { + this.#options.processRunner.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { + stdio: "ignore", + }); + return; + } catch { + // why: without taskkill the wrapper alone is ended, as before. + } + } + try { process.kill(pid, signal); } catch (error: unknown) { @@ -113,6 +128,8 @@ export interface SignalRecord { */ export class FakeProcessSupervisor implements ProcessSupervisor { readonly signals: SignalRecord[] = []; + /** why: the pids signalled with `tree`, kept apart so `signals` keeps one shape for every caller. */ + readonly treeSignals: number[] = []; readonly commandLineReads: number[] = []; readonly #live = new Set(); readonly #commandLines = new Map(); @@ -127,8 +144,9 @@ export class FakeProcessSupervisor implements ProcessSupervisor { return this.#live.has(pid); } - signal(pid: number, signal: NodeJS.Signals): void { + signal(pid: number, signal: NodeJS.Signals, options?: { readonly tree?: boolean }): void { this.signals.push({ pid, signal }); + if (options?.tree === true) this.treeSignals.push(pid); } markAlive(pid: number): void { From 7ffc38e10ede49352ac3b1fa561d9e11e1750a69 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 14:59:33 +0100 Subject: [PATCH 7/9] fix(ports): Simlock's adb server on Windows ends through a creation-time-guarded kill, and the docs say what a wrapper outlives (#1759) --- src/ports/process-runner-types.ts | 4 +- src/ports/process-supervisor.test.ts | 59 +++++++++++++++++++++------- src/ports/process-supervisor.ts | 25 +++++++++++- src/ports/process-tree-kill.ts | 34 ++++++++++------ src/ports/windows-command.ts | 4 +- 5 files changed, 96 insertions(+), 30 deletions(-) diff --git a/src/ports/process-runner-types.ts b/src/ports/process-runner-types.ts index 992b14634..2d2204008 100644 --- a/src/ports/process-runner-types.ts +++ b/src/ports/process-runner-types.ts @@ -35,7 +35,9 @@ export interface ProcessRunOptions { * grandchild can be a process others use (the first emulator's qemu starts the host's one * `netsimd`, and every emulator's network goes through it), and an `adb` client can start the * shared adb server, so no adb command sets this. With this, `kill` ends the child alone off - * Windows, and on Windows also the child's own children (`emulator.exe` runs qemu), never theirs. + * Windows, and on Windows also the child's own children (`emulator.exe` runs qemu). Under + * `outlivesCaller` the child is a `conhost.exe` wrapper, so that is the program and its children; + * the processes qemu starts (`netsimd`) are never ended. */ readonly killChildren?: boolean; /** diff --git a/src/ports/process-supervisor.test.ts b/src/ports/process-supervisor.test.ts index 1f26603a2..a23533bcd 100644 --- a/src/ports/process-supervisor.test.ts +++ b/src/ports/process-supervisor.test.ts @@ -66,31 +66,62 @@ describe("NodeProcessSupervisor", () => { }); it.each([ - ["win32", true, ["/pid", "4242", "/T", "/F"]], - ["win32", false, undefined], - ["linux", true, undefined], + ["win32", true, true], + ["win32", false, false], + ["linux", true, false], ] as const)( - "on %s, a signal with tree %s ends the process and what it started through taskkill: %j", - (platform, tree, taskkillArgs) => { + "on %s, a signal with tree %s ends the process and what it started through PowerShell: %s", + (platform, tree, throughPowerShell) => { const kill = vi.spyOn(process, "kill").mockImplementation(() => true); - const runner = new ScriptedProcessRunner([ - { - match: { args: [/.*/, /.*/, /.*/, /.*/], command: "taskkill" }, - result: { code: 0, stderr: "", stdout: "" }, - }, - ]); + const runner = new ScriptedProcessRunner( + throughPowerShell + ? [ + { + match: { args: [/.*/, /.*/, /.*/, /.*/], command: "powershell.exe" }, + result: { code: 0, stderr: "", stdout: "" }, + }, + ] + : [], + ); new NodeProcessSupervisor({ platform, processRunner: runner }).signal(4242, "SIGTERM", { tree, }); - expect(runner.calls.map((call) => call.args)).toEqual( - taskkillArgs === undefined ? [] : [taskkillArgs], + expect(runner.calls.map((call) => call.command)).toEqual( + throughPowerShell ? ["powershell.exe"] : [], ); - expect(kill).toHaveBeenCalledTimes(taskkillArgs === undefined ? 1 : 0); + expect(kill).toHaveBeenCalledTimes(throughPowerShell ? 0 : 1); + const encoded = runner.calls[0]?.args.at(-1); + if (encoded !== undefined) { + const script = Buffer.from(encoded, "base64").toString("utf16le"); + expect(script, "only processes that started after their parent are listed").toContain( + "Where-Object { $_.CreationDate -ge $parent.CreationDate }", + ); + expect(script, "grandchildren are ended too").toContain("$grandchildren"); + expect(script).toContain("ProcessId = 4242"); + } }, ); + it("ends the wrapper alone when the PowerShell call that ends its tree fails", async () => { + const kill = vi.spyOn(process, "kill").mockImplementation(() => true); + const runner = new ScriptedProcessRunner([ + { + match: { args: [/.*/, /.*/, /.*/, /.*/], command: "powershell.exe" }, + result: { code: 1, stderr: "gone", stdout: "" }, + }, + ]); + + new NodeProcessSupervisor({ platform: "win32", processRunner: runner }).signal( + 4242, + "SIGTERM", + { tree: true }, + ); + + await vi.waitFor(() => expect(kill).toHaveBeenCalledWith(4242, "SIGTERM")); + }); + it("treats signalling a process that is already gone as a no-op", async () => { const supervisor = nodeSupervisor(); const pid = await retiredPid(); diff --git a/src/ports/process-supervisor.ts b/src/ports/process-supervisor.ts index daa4f3caf..817466734 100644 --- a/src/ports/process-supervisor.ts +++ b/src/ports/process-supervisor.ts @@ -1,4 +1,5 @@ import type { ProcessResult, ProcessRunner } from "./process-runner.js"; +import { windowsKillCommand } from "./process-tree-kill.js"; /** * Liveness and signalling for a process addressed by pid rather than by a handle. @@ -94,15 +95,34 @@ export class NodeProcessSupervisor implements ProcessSupervisor { if (options?.tree === true && this.#options.platform === "win32") { try { - this.#options.processRunner.spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { + // why: depth 2 is the wrapper, its program and the program's children (the emulator's + // qemu), each only if it started after its parent did, as `windowsKillScript` checks. + const { command, args } = windowsKillCommand(pid, 2); + const killer = this.#options.processRunner.spawn(command, args, { stdio: "ignore", + timeoutMs: TREE_KILL_TIMEOUT_MS, }); + // why: the helper answers later than this call returns, so a failed or errored run ends the wrapper alone, as before. + const fallBack = () => { + try { + this.#signalAlone(pid, signal); + } catch { + // why: best effort, and nobody is waiting on this call any more. + } + }; + void killer.wait().then((result) => { + if (result.code !== 0) fallBack(); + }, fallBack); return; } catch { - // why: without taskkill the wrapper alone is ended, as before. + // why: without PowerShell the wrapper alone is ended, as before. } } + this.#signalAlone(pid, signal); + } + + #signalAlone(pid: number, signal: NodeJS.Signals): void { try { process.kill(pid, signal); } catch (error: unknown) { @@ -171,6 +191,7 @@ export class FakeProcessSupervisor implements ProcessSupervisor { /** why: PowerShell's first start on a cold host takes seconds, and `ps` answers in milliseconds; one bound covers both. */ const COMMAND_LINE_TIMEOUT_MS = 5_000; +const TREE_KILL_TIMEOUT_MS = 10_000; /** * why: Windows has no `ps`; `Win32_Process` holds the command line as the parent passed it. diff --git a/src/ports/process-tree-kill.ts b/src/ports/process-tree-kill.ts index 5486cc177..22d58e900 100644 --- a/src/ports/process-tree-kill.ts +++ b/src/ports/process-tree-kill.ts @@ -31,10 +31,11 @@ function killWindowsProcessTree(child: ChildProcess, pid: number, signal: NodeJS } /** - * why: `killChildren` (`ProcessRunOptions`): the child and the processes it started, never - * theirs, so `taskkill /T` does not fit. Windows keeps a dead parent's pid in its children's - * `ParentProcessId`, and pids are reused, so a listed process counts as a child only when it - * started after the child did. Should PowerShell fail, the child alone is killed. + * why: `killChildren` (`ProcessRunOptions`): the child and the processes it started, and with + * depth 2 theirs too, so `taskkill /T`, which follows parent pids to any depth, does not fit. + * Windows keeps a dead parent's pid in its children's `ParentProcessId`, and pids are reused, so + * a listed process counts as a child only when it started after its parent did. Should + * PowerShell fail, the child alone is killed. */ export function windowsKillScript(pid: number, depth: 1 | 2): string { return [ @@ -52,19 +53,30 @@ export function windowsKillScript(pid: number, depth: 1 | 2): string { ].join("\n"); } +/** why: the PowerShell call that runs `windowsKillScript`, for this module's kills and for the supervisor's, so both apply the same creation-time guard. */ +export function windowsKillCommand( + pid: number, + depth: 1 | 2, +): { readonly command: string; readonly args: readonly string[] } { + return { + command: "powershell.exe", + args: [ + "-NoProfile", + "-NonInteractive", + "-EncodedCommand", + Buffer.from(windowsKillScript(pid, depth), "utf16le").toString("base64"), + ], + }; +} + function killWindowsProcessAndChildren( child: ChildProcess, pid: number, signal: NodeJS.Signals, depth: 1 | 2, ): void { - const script = windowsKillScript(pid, depth); - runWindowsKill(child, signal, "powershell.exe", [ - "-NoProfile", - "-NonInteractive", - "-EncodedCommand", - Buffer.from(script, "utf16le").toString("base64"), - ]); + const { command, args } = windowsKillCommand(pid, depth); + runWindowsKill(child, signal, command, args); } function runWindowsKill( diff --git a/src/ports/windows-command.ts b/src/ports/windows-command.ts index ef663729b..adb49fe9e 100644 --- a/src/ports/windows-command.ts +++ b/src/ports/windows-command.ts @@ -64,8 +64,8 @@ export function childLaunch( * of its own, and its qemu then opens a visible Windows Terminal window titled with the qemu path * (#1759). Under `conhost.exe --headless` the child and everything it starts inherit a console * that has no window, as the logon task's do (ADR 0086). The wrapper is the child Node sees; it - * exits when the program it runs exits. A batch-file launch is left as it is: none outlives its - * caller. + * lives while any process on its console does, so it can outlive the program it runs (the + * emulator's `netsimd` holds it). A batch-file launch is left as it is: none outlives its caller. */ export function headlessLaunch( launch: ChildLaunch, From 990a6bd29bc70bf83ee393c65003e807a9e655cf Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 14:59:37 +0100 Subject: [PATCH 8/9] fix(android): a taken-over emulator is gone from adb before its device is deleted; a lingering conhost wrapper is ended after 30 s (#1759) --- src/drivers/android/emulator.ts | 29 +++++++- src/drivers/android/index-boot.test.ts | 73 +++++++++++++-------- src/drivers/android/index-lifecycle.test.ts | 46 +++++++++++++ 3 files changed, 118 insertions(+), 30 deletions(-) diff --git a/src/drivers/android/emulator.ts b/src/drivers/android/emulator.ts index fe4a29569..caed15768 100644 --- a/src/drivers/android/emulator.ts +++ b/src/drivers/android/emulator.ts @@ -30,6 +30,8 @@ export const COLD_BOOT_ESTIMATE_MS = 70_000; const PORT_POLL_INTERVAL_MS = 2_000; // why: how long an emulator that was asked to stop may take to exit, whatever the boot deadline is. const EMULATOR_EXIT_TIMEOUT_MS = 180_000; +// why: how long the process Node holds for an emulator may outlive the emulator once adb stopped listing it (see `shutdown`); the `emulator -kill` helpers sleep 20 s. +const WRAPPER_GRACE_MS = 30_000; // why: After this long without an answer from a serial, the emulator's own registration is // assumed lost and Simlock re-sends it. Long enough that a normally-booting emulator has // already attached, short enough that a lost announcement costs seconds, not the whole @@ -145,8 +147,7 @@ export class Emulator { const startedAt = this.#options.clock.now(); let remaining = serials; while (remaining.length > 0) { - const attached = (await this.#options.adbTools.scanSerials()).settledSerials; - remaining = remaining.filter((serial) => attached.includes(serial)); + remaining = await this.#stillAttached(remaining); if (remaining.length === 0) return; if (this.#options.clock.now() - startedAt >= EMULATOR_EXIT_TIMEOUT_MS) { throw new DriverCrashError( @@ -157,6 +158,15 @@ export class Emulator { } } + async #serialLeft(data: AndroidDriverData): Promise { + return (await this.#stillAttached([data.serial])).length === 0; + } + + async #stillAttached(serials: string[]): Promise { + const attached = (await this.#options.adbTools.scanSerials()).settledSerials; + return serials.filter((serial) => attached.includes(serial)); + } + #logPath(data: AndroidDriverData): string { return `${this.#options.adbTools.avdFolder(data)}/emulator.log`; } @@ -326,17 +336,30 @@ export class Emulator { } async shutdown(data: AndroidDriverData, handle: ProcessHandle | undefined): Promise { + let killed = false; if (data.port > 0 && (await this.#options.ownership.serialIsOwn(data))) { await this.#options.processRunner.run(this.#options.adb, ["-s", data.serial, "emu", "kill"], { env: this.#options.adbTools.env(), timeoutMs: OWNERSHIP_PROBE_TIMEOUT_MS, }); + killed = true; } if (handle === undefined) { + // why: an emulator of an earlier daemon has no handle to wait on, and adb lists its serial for + // a moment after the kill. The `destroy` that follows asks every listed serial for its AVD + // path, and one that no longer answers refuses the delete (#1759). + if (killed) await this.#waitForEmulatorsToExit(data, [data.serial]); return; } - const exited = await this.waitForExit(handle, EMULATOR_EXIT_TIMEOUT_MS); + // why: on Windows the handle is a `conhost.exe` wrapper (#1759), which lives while any process + // on its console does: the `emulator -kill` helpers for 20 s after qemu is gone, and for as long + // as another emulator runs, the `netsimd` qemu started. So a handle still running after the + // grace, with adb no longer listing the killed emulator, is the wrapper alone, and is ended. + let exited = await this.waitForExit(handle, WRAPPER_GRACE_MS); + if (!exited && !(killed && (await this.#serialLeft(data)))) { + exited = await this.waitForExit(handle, EMULATOR_EXIT_TIMEOUT_MS - WRAPPER_GRACE_MS); + } if (!exited) { handle.kill("SIGKILL"); await this.waitForExit(handle, SIGKILL_REAP_TIMEOUT_MS); diff --git a/src/drivers/android/index-boot.test.ts b/src/drivers/android/index-boot.test.ts index 516aed7e9..cdbee8f7c 100644 --- a/src/drivers/android/index-boot.test.ts +++ b/src/drivers/android/index-boot.test.ts @@ -462,34 +462,53 @@ describe("AndroidDriver", () => { expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0); }); - it("kills an emulator that has not exited 180 s after a shutdown, whatever the boot timeout is", async () => { - const harness = await provisionedHarness({ - afterwards: [ - copyPathExpectation("emulator-5586"), - processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), - ], - bootTimeoutMs: 600_000, - }); - const ready = await harness.driver.makeReady(harness.device); - const launch = harness.runner.calls.findLastIndex( - (call) => call.command === binaries.emulator && call.args.includes("-avd"), - ); - const running = harness.runner.handles[launch]; - if (running === undefined) throw new Error("no running emulator"); - const kill = vi.spyOn(running, "kill"); - - // why: The emulator ignores `emu kill`: only the timeout can end the wait. - harness.runner.ignoresEmuKill = true; - const armedBefore = harness.clock.pendingTimerCount; - const shutdown = harness.driver.shutdown(ready); - await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(armedBefore)); - expect(kill).not.toHaveBeenCalled(); - harness.clock.advance(180_000); - await shutdown; + it.each([ + ["adb still lists it", 180_000, "List of devices attached\nemulator-5586\tdevice\n"], + ["adb no longer lists it", 30_000, "List of devices attached\n"], + ] as const)( + "kills an emulator that has not exited after a shutdown, whatever the boot timeout is: %s, at %s ms", + async (_listing, killedAfterMs, devices) => { + const harness = await provisionedHarness({ + afterwards: [ + copyPathExpectation("emulator-5586"), + processResult(binaries.adb, ["-s", "emulator-5586", "emu", "kill"]), + processResult(binaries.adb, ["devices"], devices), + ], + bootTimeoutMs: 600_000, + }); + const ready = await harness.driver.makeReady(harness.device); + const launch = harness.runner.calls.findLastIndex( + (call) => call.command === binaries.emulator && call.args.includes("-avd"), + ); + const running = harness.runner.handles[launch]; + if (running === undefined) throw new Error("no running emulator"); + const kill = vi.spyOn(running, "kill"); + + // why: The emulator ignores `emu kill`: only the timeout can end the wait. + harness.runner.ignoresEmuKill = true; + const armedBefore = harness.clock.pendingTimerCount; + const shutdown = harness.driver.shutdown(ready); + await vi.waitFor(() => expect(harness.clock.pendingTimerCount).toBeGreaterThan(armedBefore)); + expect(kill).not.toHaveBeenCalled(); + harness.clock.advance(29_999); + await Promise.resolve(); + expect(kill, "nothing is ended inside the 30 s grace").not.toHaveBeenCalled(); + harness.clock.advance(1); + for (let tick = 0; tick < 100; tick += 1) await Promise.resolve(); + if (killedAfterMs === 180_000) { + expect(kill, "adb still lists the emulator, so it keeps the 180 s").not.toHaveBeenCalled(); + harness.clock.advance(150_000); + } else { + expect(kill, "adb lists it no more, so the wrapper alone is ended").toHaveBeenCalledWith( + "SIGKILL", + ); + } + await shutdown; - expect(kill).toHaveBeenCalledWith("SIGKILL"); - expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0); - }); + expect(kill).toHaveBeenCalledWith("SIGKILL"); + expect(harness.clock.pendingTimerCount, "timers still armed after shutdown").toBe(0); + }, + ); it("leaves no timer armed when waiting for the emulator to exit fails", async () => { const harness = await provisionedHarness({ diff --git a/src/drivers/android/index-lifecycle.test.ts b/src/drivers/android/index-lifecycle.test.ts index 4a359cff6..4b24e816f 100644 --- a/src/drivers/android/index-lifecycle.test.ts +++ b/src/drivers/android/index-lifecycle.test.ts @@ -498,6 +498,52 @@ describe("AndroidDriver console ports across a restart", () => { expect(await filesystem.exists(`${avdDirectory}/${running.deviceId}`)).toBe(true); }); + it("shuts a discovered emulator down and deletes its AVD although adb lists its serial for a moment after the kill", async () => { + const filesystem = await androidFilesystem(); + const host = new EmulatorHost(filesystem); + const before = await createDriver(filesystem, host.runner(), { ids: ["one"] }); + const spec = await before.resolveSpec({ model: "Pixel 5", platform: "android" }); + const running = await before.makeReady(await before.provision(spec)); + const inner = host.runner(); + // why: the emulator is gone at the kill, but adb keeps listing its serial for two listings, and a path asked of it fails. + let killed = false; + let staleListings = 2; + const runner: ProcessRunner = { + ...inner, + run: async (command, args, options) => { + if (command === binaries.adb && killed && staleListings > 0) { + if (args[0] === "devices") { + staleListings -= 1; + return ok(`List of devices attached\n${running.address}\tdevice\n`); + } + if (args.join(" ").endsWith("emu avd path")) { + return { code: 1, stderr: "error: closed", stdout: "" }; + } + } + const result = await inner.run(command, args, options); + if (command === binaries.adb && args.includes("kill")) killed = true; + return result; + }, + }; + const clock = new FakeClock(); + const after = await createDriver(filesystem, runner, { clock }); + await after.listManaged(); + // why: the registry keeps the ready device's stored data, port and serial included, across the restart. + const orphan = running; + + const shutDown = after.shutdown(orphan); + const state = promiseState(shutDown); + for (let step = 0; step < 10 && state.state === "pending"; step += 1) { + for (let tick = 0; tick < 100; tick += 1) await Promise.resolve(); + if (clock.pendingTimerCount > 0) clock.advance(2_000); + } + expect(state.state, "shutdown returns once adb stops listing the serial").toBe("fulfilled"); + expect(staleListings, "shutdown waited out the two stale listings").toBe(0); + await expect(after.destroy(orphan)).resolves.toBeUndefined(); + + expect(await filesystem.exists(`${avdDirectory}/${running.deviceId}`)).toBe(false); + }); + it("refuses to delete the AVD when an attached emulator cannot say which AVD it runs", async () => { const filesystem = await androidFilesystem(); const host = new EmulatorHost(filesystem); From 61fb99009525ee37343c298139d1c39b768bb53f Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 19 Nov 2026 15:18:54 +0100 Subject: [PATCH 9/9] fix(supervisor): a Windows tree kill that found the wrapper gone signals nothing (#1759) --- src/ports/process-supervisor.test.ts | 45 ++++++++++++++++++---------- src/ports/process-supervisor.ts | 4 +-- 2 files changed, 31 insertions(+), 18 deletions(-) diff --git a/src/ports/process-supervisor.test.ts b/src/ports/process-supervisor.test.ts index a23533bcd..28f4ea422 100644 --- a/src/ports/process-supervisor.test.ts +++ b/src/ports/process-supervisor.test.ts @@ -104,23 +104,36 @@ describe("NodeProcessSupervisor", () => { }, ); - it("ends the wrapper alone when the PowerShell call that ends its tree fails", async () => { - const kill = vi.spyOn(process, "kill").mockImplementation(() => true); - const runner = new ScriptedProcessRunner([ - { - match: { args: [/.*/, /.*/, /.*/, /.*/], command: "powershell.exe" }, - result: { code: 1, stderr: "gone", stdout: "" }, - }, - ]); - - new NodeProcessSupervisor({ platform: "win32", processRunner: runner }).signal( - 4242, - "SIGTERM", - { tree: true }, - ); + it.each([ + { + name: "never finishes", + result: { code: null, stderr: "", stdout: "", endedBy: "timeout" as const }, + signalled: true, + }, + { + name: "exits because the wrapper is already gone", + result: { code: 1, stderr: "gone", stdout: "" }, + signalled: false, + }, + ])( + "when the PowerShell call that ends its tree $name, the wrapper is signalled: $signalled", + async ({ result, signalled }) => { + const kill = vi.spyOn(process, "kill").mockImplementation(() => true); + const runner = new ScriptedProcessRunner([ + { match: { args: [/.*/, /.*/, /.*/, /.*/], command: "powershell.exe" }, result }, + ]); + + new NodeProcessSupervisor({ platform: "win32", processRunner: runner }).signal( + 4242, + "SIGTERM", + { tree: true }, + ); - await vi.waitFor(() => expect(kill).toHaveBeenCalledWith(4242, "SIGTERM")); - }); + await vi.waitFor(() => expect(runner.calls).toHaveLength(1)); + await new Promise((resolve) => setImmediate(resolve)); + expect(kill).toHaveBeenCalledTimes(signalled ? 1 : 0); + }, + ); it("treats signalling a process that is already gone as a no-op", async () => { const supervisor = nodeSupervisor(); diff --git a/src/ports/process-supervisor.ts b/src/ports/process-supervisor.ts index 817466734..0c4b620a8 100644 --- a/src/ports/process-supervisor.ts +++ b/src/ports/process-supervisor.ts @@ -102,7 +102,7 @@ export class NodeProcessSupervisor implements ProcessSupervisor { stdio: "ignore", timeoutMs: TREE_KILL_TIMEOUT_MS, }); - // why: the helper answers later than this call returns, so a failed or errored run ends the wrapper alone, as before. + // why: the helper answers later than this call returns, so a run that never finished (spawn error, timeout, killed) ends the wrapper alone, as before. A numeric exit, including the script's exit 1 for a wrapper already gone, sends nothing: that pid may be reused by now. const fallBack = () => { try { this.#signalAlone(pid, signal); @@ -111,7 +111,7 @@ export class NodeProcessSupervisor implements ProcessSupervisor { } }; void killer.wait().then((result) => { - if (result.code !== 0) fallBack(); + if (result.code === null || result.endedBy !== undefined) fallBack(); }, fallBack); return; } catch {