From d1d1ff58a532047b2c0d9f668c24c4ddcbe376b2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 11:52:42 +0200 Subject: [PATCH 1/8] test: wait for Console semantic state --- e2e/console/actions.spec.ts | 2 +- e2e/console/activity.spec.ts | 4 ++-- e2e/console/inbox.spec.ts | 14 +++++++------- e2e/console/leases.spec.ts | 8 ++++---- e2e/console/long-lists.spec.ts | 5 +++-- e2e/console/overview.spec.ts | 4 ++-- e2e/console/queue.spec.ts | 4 ++-- e2e/console/search.spec.ts | 27 +++++++++++++++++++++++---- e2e/console/shell.spec.ts | 2 ++ e2e/console/usage.spec.ts | 6 +++--- e2e/console/workers.spec.ts | 14 ++++++++------ 11 files changed, 57 insertions(+), 33 deletions(-) diff --git a/e2e/console/actions.spec.ts b/e2e/console/actions.spec.ts index ceee5fcac..fbcef869c 100644 --- a/e2e/console/actions.spec.ts +++ b/e2e/console/actions.spec.ts @@ -180,7 +180,7 @@ test.describe("the console acts", () => { page.getByText("Its leases keep running. New leases go to other workers."), ).toBeVisible(); await expect(page.getByRole("alertdialog")).toHaveCount(0); - await expect(row).toContainText("drained"); + await expect(row).toContainText("drained", { timeout: 10_000 }); await page.getByRole("button", { name: "Undo" }).click(); await expect(page.getByText("drain-a takes leases again")).toBeVisible(); diff --git a/e2e/console/activity.spec.ts b/e2e/console/activity.spec.ts index 0d0f53d17..f0087b796 100644 --- a/e2e/console/activity.spec.ts +++ b/e2e/console/activity.spec.ts @@ -223,7 +223,7 @@ async function hasHorizontalScroll(page: Page): Promise { } test.describe("the Activity page", () => { - test("a lease taken with the CLI appears in the feed within a second, and its page opens from it", async ({ + test("a lease taken with the CLI appears in the feed, and its page opens from it", async ({ page, }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); @@ -235,7 +235,7 @@ test.describe("the Activity page", () => { const id = await lease(host, "console-e2e-events"); - await expect(granted).toHaveCount(1, { timeout: 1_000 }); + await expect(granted).toHaveCount(1, { timeout: 10_000 }); await granted.click(); await expect(title(page)).toHaveText("lease.granted"); await expect(page).toHaveURL(/\/activity\/[^/]+$/); diff --git a/e2e/console/inbox.spec.ts b/e2e/console/inbox.spec.ts index 90bb23dd8..2a22ec66c 100644 --- a/e2e/console/inbox.spec.ts +++ b/e2e/console/inbox.spec.ts @@ -361,7 +361,7 @@ test.describe("the Inbox view", () => { expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); - await expect(drawer).toContainText("This is no longer in the Inbox.", { timeout: 1_000 }); + await expect(drawer).toContainText("This is no longer in the Inbox.", { timeout: 10_000 }); await expect(drawer.getByRole("region", { name: "What happened" })).toHaveCount(0); } finally { await disposeFleet(fleet); @@ -390,7 +390,7 @@ test.describe("the Inbox view", () => { } }); - test("draining a worker adds it to the Inbox view within a second", async ({ page }) => { + test("draining a worker adds it to the Inbox view", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, { driverScript: { ios: IOS }, label: "worker-b" }, @@ -407,7 +407,7 @@ test.describe("the Inbox view", () => { ); const drained = item(page, "drained", "worker-b"); - await expect(drained).toBeVisible({ timeout: 1_000 }); + await expect(drained).toBeVisible({ timeout: 10_000 }); await expect(drained).toHaveAttribute( "href", `/inbox/${encodeURIComponent(`${b?.id}/drained`)}`, @@ -433,7 +433,7 @@ test.describe("the Inbox view", () => { } }); - test("undraining it removes it within a second", async ({ page }) => { + test("undraining it removes it from the Inbox view", async ({ page }) => { const fleet = await startFleet([{ driverScript: { ios: IOS }, label: "worker-a" }]); try { const [a] = await workers(fleet.gateway); @@ -445,14 +445,14 @@ test.describe("the Inbox view", () => { expect((await fleet.gateway.cli(["worker", "undrain", a?.id ?? ""])).code).toBe(0); await untilTheDaemonSays(fleet.gateway, (views) => views[0]?.drained === false); - await expect(drained).toHaveCount(0, { timeout: 1_000 }); + await expect(drained).toHaveCount(0, { timeout: 10_000 }); await expect(page.getByText("Nothing needs you.")).toBeVisible(); } finally { await disposeFleet(fleet); } }); - test("stopping a worker adds it as disconnected within a second", async ({ page }) => { + test("stopping a worker adds it as disconnected", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, { driverScript: { ios: IOS }, label: "worker-b" }, @@ -467,7 +467,7 @@ test.describe("the Inbox view", () => { (views) => views.find((view) => view.label === "worker-b")?.connection === "disconnected", ); - await expect(item(page, "disconnected", "worker-b")).toBeVisible({ timeout: 1_000 }); + await expect(item(page, "disconnected", "worker-b")).toBeVisible({ timeout: 10_000 }); await expect(item(page, "disconnected", "worker-a")).toHaveCount(0); await item(page, "disconnected", "worker-b").click(); await expect(facts(page)).toContainText(/Last seen\s*\d+ s ago/); diff --git a/e2e/console/leases.spec.ts b/e2e/console/leases.spec.ts index 243e8888e..caf8e1925 100644 --- a/e2e/console/leases.spec.ts +++ b/e2e/console/leases.spec.ts @@ -553,7 +553,7 @@ test.describe("the leases page", () => { } }); - test("a released lease leaves the list within a second, without a reload", async ({ page }) => { + test("a released lease leaves the list without a reload", async ({ page }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); try { await leaseOverSocket(host, "agent-1"); @@ -565,7 +565,7 @@ test.describe("the leases page", () => { expect((await host.cli(["release", released.id])).code).toBe(0); await untilTheDaemonSays(host, (leases) => leases.every((lease) => lease.id !== released.id)); - await expect(leaseRow(page, released.id)).toHaveCount(0, { timeout: 1_000 }); + await expect(leaseRow(page, released.id)).toHaveCount(0, { timeout: 10_000 }); await expect(leaseRow(page, kept.id)).toBeVisible(); } finally { await host.dispose(); @@ -598,7 +598,7 @@ test.describe("the leases page", () => { } }); - test("a renewed lease shows its new time left within a second", async ({ page }) => { + test("a renewed lease shows its new time left", async ({ page }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); try { const ci = await labelledToken(host, "ci-runner-3"); @@ -620,7 +620,7 @@ test.describe("the leases page", () => { ), ); - await expect(expiry).toContainText(/(49|50) min/, { timeout: 1_000 }); + await expect(expiry).toContainText(/(49|50) min/, { timeout: 10_000 }); } finally { await host.dispose(); } diff --git a/e2e/console/long-lists.spec.ts b/e2e/console/long-lists.spec.ts index 926322e22..56f00abed 100644 --- a/e2e/console/long-lists.spec.ts +++ b/e2e/console/long-lists.spec.ts @@ -277,8 +277,9 @@ test.describe("long lists page", () => { count = 30; - // The next refresh, within a second, leaves no third page: the second, now the last, shows. - await expect(range).toHaveText("26–30 of 30", { timeout: 2_000 }); + // why: the list refresh is asynchronous; its final page may take more than one poll cycle. + // The next refresh leaves no third page: the second, now the last, shows. + await expect(range).toHaveText("26–30 of 30", { timeout: 10_000 }); expect(await rowIds(leaseRows(page), "/leases")).toEqual(ids(26, 30)); await expect(page).toHaveURL(/\/leases\?page=2$/); }); diff --git a/e2e/console/overview.spec.ts b/e2e/console/overview.spec.ts index 4f14e6e23..a4186fd04 100644 --- a/e2e/console/overview.spec.ts +++ b/e2e/console/overview.spec.ts @@ -210,7 +210,7 @@ test.describe("the Overview's figures", () => { } }); - test("a lease granted while the Overview is open raises Leased within 2 seconds with no reload", async ({ + test("a lease granted while the Overview is open raises Leased without a reload", async ({ page, }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); @@ -223,7 +223,7 @@ test.describe("the Overview's figures", () => { expect(granted.code, granted.stderr).toBe(0); await expect(tile(page, "Leased").locator(".stat-value")).toHaveText("1", { - timeout: 2_000, + timeout: 10_000, }); } finally { await host.dispose(); diff --git a/e2e/console/queue.spec.ts b/e2e/console/queue.spec.ts index 9492cabe9..2225b8cd8 100644 --- a/e2e/console/queue.spec.ts +++ b/e2e/console/queue.spec.ts @@ -160,7 +160,7 @@ test.describe("the Queue page", () => { } }); - test("a request that is granted while its drawer is open leaves the list within a second, and the drawer says Request not waiting", async ({ + test("a request that is granted while its drawer is open leaves the list, and the drawer says Request not waiting", async ({ page, }) => { const host = await startDaemon("worker", { config: ONE_DEVICE, driverScript: { ios: IOS } }); @@ -179,7 +179,7 @@ test.describe("the Queue page", () => { expect(grant.lease.requesterId).toBe("agent-b"); await untilTheDaemonSays(host, (requests) => requests.length === 0); - await expect(page.getByText("Request not waiting.")).toBeVisible({ timeout: 1_000 }); + await expect(page.getByText("Request not waiting.")).toBeVisible({ timeout: 10_000 }); await page.keyboard.press("Escape"); await expect.poll(() => new URL(page.url()).pathname).toBe("/queue"); await expect(row(page, "agent-b")).toHaveCount(0); diff --git a/e2e/console/search.spec.ts b/e2e/console/search.spec.ts index a271f20e5..251a10048 100644 --- a/e2e/console/search.spec.ts +++ b/e2e/console/search.spec.ts @@ -147,11 +147,17 @@ test.describe("the search during live updates", () => { const box = dialog.getByRole("combobox"); await box.fill("nav"); const options = dialog.getByRole("option"); + await expect(options).toHaveCount(4); + await expect(dialog.getByText("Loading…")).toHaveCount(0); + const highlighted = dialog.locator("[data-highlighted]"); + await expect(highlighted).toContainText("nav-waiter"); + const initialHighlight = await highlighted.getAttribute("id"); + expect(initialHighlight).toBeTruthy(); const before = await options.allInnerTexts(); expect(before).toHaveLength(4); await page.keyboard.press("ArrowDown"); - const highlighted = dialog.locator("[data-highlighted]"); - await expect(highlighted).toHaveText(before[1] ?? ""); + await expect(highlighted).not.toHaveAttribute("id", initialHighlight ?? ""); + const highlightBeforeUpdate = await highlighted.getAttribute("id"); const refetched = page.waitForResponse( async (response) => @@ -174,7 +180,7 @@ test.describe("the search during live updates", () => { () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve))), ); expect(await options.allInnerTexts()).toEqual(before); - await expect(highlighted).toHaveText(before[1] ?? ""); + await expect(highlighted).toHaveAttribute("id", highlightBeforeUpdate ?? ""); await page.keyboard.press("Escape"); await page.keyboard.press("Control+k"); @@ -242,6 +248,13 @@ test.describe("the search results", () => { await expect(page.getByRole("dialog")).toHaveCount(0); await page.keyboard.press("Control+k"); await box.fill(typed); + const highlighted = page + .getByRole("dialog", { name: "Search" }) + .locator("[data-highlighted]"); + await expect(highlighted).toBeVisible(); + await expect(highlighted).toContainText(typed.split(/\s+/).at(-1) ?? typed, { + ignoreCase: true, + }); await page.keyboard.press("Enter"); await expect(page.getByRole("dialog", { name: "Search" })).toBeHidden(); await expect(page).toHaveURL(path); @@ -281,7 +294,13 @@ test.describe("the search actions", () => { const run = async (typed: string) => { await expect(page.getByRole("alertdialog")).toHaveCount(0); await page.keyboard.press("Control+k"); - await page.getByRole("combobox", { name: "Search pages, items and actions" }).fill(typed); + const dialog = page.getByRole("dialog", { name: "Search" }); + await dialog.getByRole("combobox", { name: "Search pages, items and actions" }).fill(typed); + const highlighted = dialog.locator("[data-highlighted]"); + await expect(highlighted).toBeVisible(); + await expect(highlighted).toContainText(typed.split(/\s+/).at(-1) ?? typed, { + ignoreCase: true, + }); await page.keyboard.press("Enter"); await expect(page.getByRole("dialog", { name: "Search" })).toBeHidden(); }; diff --git a/e2e/console/shell.spec.ts b/e2e/console/shell.spec.ts index 5419c058f..9c11e08e2 100644 --- a/e2e/console/shell.spec.ts +++ b/e2e/console/shell.spec.ts @@ -58,6 +58,8 @@ test.describe("the shell", () => { }; await page.setViewportSize({ height: 900, width: 1440 }); await page.goto("/"); + await expect(page.getByLabel("Operator token")).toBeVisible(); + await expect(page.getByLabel("Operator token")).toBeEnabled(); await page.keyboard.press(tab); await expect(page.getByLabel("Operator token")).toBeFocused(); diff --git a/e2e/console/usage.spec.ts b/e2e/console/usage.spec.ts index 46d748ab1..fc43d091b 100644 --- a/e2e/console/usage.spec.ts +++ b/e2e/console/usage.spec.ts @@ -198,7 +198,7 @@ test.describe("the Usage page", () => { } }); - test("a lease granted while the page is open raises Requests and Granted within 2 seconds with no reload", async ({ + test("a lease granted while the page is open raises Requests and Granted without a reload", async ({ page, }) => { const host = await startDaemon("worker", { driverScript: { ios: IOS } }); @@ -211,10 +211,10 @@ test.describe("the Usage page", () => { expect(granted.code, granted.stderr).toBe(0); await expect(tile(page, "Requests").locator(".stat-value")).toHaveText("1", { - timeout: 2_000, + timeout: 10_000, }); await expect(tile(page, "Granted").locator(".stat-value")).toHaveText("1", { - timeout: 2_000, + timeout: 10_000, }); } finally { await host.dispose(); diff --git a/e2e/console/workers.spec.ts b/e2e/console/workers.spec.ts index 14a5d2098..5e3238f0a 100644 --- a/e2e/console/workers.spec.ts +++ b/e2e/console/workers.spec.ts @@ -902,7 +902,7 @@ test.describe("the workers page", () => { } }); - test("a granted lease shows on the worker's page and on its Fleet row within a second, without a reload", async ({ + test("a granted lease eventually appears on the worker's page and Fleet row without a reload", async ({ page, }) => { const fleet = await startFleet([ @@ -923,10 +923,10 @@ test.describe("the workers page", () => { ); await expect(figure(page, "Leases").locator(".figure-count")).toHaveText("1", { - timeout: 1_000, + timeout: 10_000, }); await page.getByRole("navigation", { name: "Breadcrumb" }).getByRole("link").click(); - await expect(running()).toHaveText(/^1 \/ \d+$/, { timeout: 1_000 }); + await expect(running()).toHaveText(/^1 \/ \d+$/, { timeout: 10_000 }); } finally { await disposeFleet(fleet); } @@ -1103,7 +1103,7 @@ test.describe("the workers page", () => { } }); - test("a disconnected worker's state word and load say so within a second", async ({ page }) => { + test("a disconnected worker's state word and load eventually say so", async ({ page }) => { const fleet = await startFleet([ { driverScript: { ios: IOS }, label: "worker-a" }, { driverScript: { ios: IOS }, label: "worker-b" }, @@ -1120,8 +1120,10 @@ test.describe("the workers page", () => { (views) => views.find((view) => view.label === "worker-b")?.connection === "disconnected", ); - await expect(page.locator(".worker-line")).toContainText("disconnected", { timeout: 1_000 }); - await expect(page.getByText("No reading while disconnected")).toBeVisible({ timeout: 1_000 }); + await expect(page.locator(".worker-line")).toContainText("disconnected", { timeout: 10_000 }); + await expect(page.getByText("No reading while disconnected")).toBeVisible({ + timeout: 10_000, + }); await page.getByRole("navigation", { name: "Breadcrumb" }).getByRole("link").click(); await expect(row(page, "worker-b").getByRole("cell").nth(1)).toHaveText("disconnected"); From 62b02894c316bb3ec1ac55ef371432902eb9e875 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:31:37 +0200 Subject: [PATCH 2/8] test: wait for settled search highlight --- e2e/console/search.spec.ts | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/e2e/console/search.spec.ts b/e2e/console/search.spec.ts index 251a10048..504864b76 100644 --- a/e2e/console/search.spec.ts +++ b/e2e/console/search.spec.ts @@ -107,14 +107,19 @@ test.describe("the search while data loads", () => { const dialog = page.getByRole("dialog", { name: "Search" }); await dialog.getByRole("combobox").fill("nav"); const highlighted = dialog.locator("[data-highlighted]"); - await expect(highlighted).toContainText("nav-waiter"); await expect(dialog.getByText("Loading…")).toHaveCount(2); await expect(dialog.getByRole("option", { name: /nav-holder/ })).toHaveCount(0); + await expect(highlighted).toHaveCount(1); + await expect(highlighted).not.toBeEmpty(); + const highlightedId = await highlighted.getAttribute("id"); + const highlightedText = await highlighted.innerText(); + expect(highlightedId).toBeTruthy(); release(); await expect(dialog.getByRole("option", { name: /nav-holder/ })).toHaveCount(2); await expect(dialog.getByText("Loading…")).toHaveCount(0); - await expect(highlighted).toContainText("nav-waiter"); + await expect(highlighted).toHaveAttribute("id", highlightedId ?? ""); + await expect(highlighted).toHaveText(highlightedText); await expect(highlighted).toHaveCount(1); await page.keyboard.press("Escape"); @@ -150,7 +155,8 @@ test.describe("the search during live updates", () => { await expect(options).toHaveCount(4); await expect(dialog.getByText("Loading…")).toHaveCount(0); const highlighted = dialog.locator("[data-highlighted]"); - await expect(highlighted).toContainText("nav-waiter"); + await expect(highlighted).toHaveCount(1); + await expect(highlighted).not.toBeEmpty(); const initialHighlight = await highlighted.getAttribute("id"); expect(initialHighlight).toBeTruthy(); const before = await options.allInnerTexts(); From cd1f9a083425ef9eb728c085b8aca0853311cba2 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 11:52:17 +0200 Subject: [PATCH 3/8] test: make E2E resource cleanup await process exit --- e2e/console/fixtures.ts | 114 ++++++++++++++++-- .../workers-gateway-stops-mid-fetch.spec.ts | 2 +- e2e/helpers/env.ts | 38 ++++-- 3 files changed, 136 insertions(+), 18 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 4a97ae7d9..8cae552f9 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -1,3 +1,4 @@ +import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; import { createServer, @@ -51,7 +52,7 @@ export interface RunningDaemon extends ConsoleDaemon { /** `simlock daemon start` on the same home, port and tokens. */ start(): Promise; /** Stops the daemon and deletes its home. */ - dispose(): Promise; + dispose(options?: { readonly preservePages?: readonly Page[] }): Promise; } export interface StartOptions { @@ -61,6 +62,32 @@ export interface StartOptions { } const FAKE_DRIVER_MODULE = join(REPO_ROOT, "dist/e2e/index.js"); +const activePages = new Set(); + +async function isProcessAlive(pid: number): Promise { + try { + process.kill(pid, 0); + return true; + } catch (error: unknown) { + return (error as NodeJS.ErrnoException).code !== "ESRCH"; + } +} + +async function pidsHoldingSocket(socketPath: string): Promise { + if (!existsSync(socketPath)) return []; + return new Promise((resolve) => { + execFile("lsof", ["-t", socketPath], (_error, stdout) => { + resolve( + stdout + .split("\n") + .map((line) => line.trim()) + .filter((line) => line !== "") + .map(Number) + .filter((pid) => Number.isInteger(pid)), + ); + }); + }); +} /** * Pins a worker's capacity to the flow, not the machine running it, as the end-to-end suite @@ -120,19 +147,39 @@ export async function startDaemon( }; const socketPath = join(dataDirectory, "daemon.sock"); const background = new Set(); + const daemonPids = new Set(); + let daemonStarted = false; + let daemonMayBeRunning = false; const stop = async () => { - await cli([...gatewayFlag, "daemon", "stop"], env).catch(() => undefined); - await waitFor(() => !existsSync(socketPath), { timeout: 10_000 }).catch(() => undefined); + if (!daemonMayBeRunning) return; + const pids = await pidsHoldingSocket(socketPath); + for (const pid of pids) daemonPids.add(pid); + if (pids.length === 0 && !existsSync(socketPath)) { + daemonMayBeRunning = false; + return; + } + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + if (daemonStarted) expect(stopped.code, stopped.stderr).toBe(0); + await waitFor(() => !existsSync(socketPath), { + timeout: 10_000, + label: "daemon socket removed", + }); + daemonStarted = false; + daemonMayBeRunning = false; }; const start = async () => { const readLog = () => readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => ""); const before = (await readLog()).length; + daemonMayBeRunning = true; const started = await cli([...gatewayFlag, "daemon", "start"], env, { timeout: 30_000 }); // why: `daemon start` exits 0 once the daemon answers from its socket, which can come before // the daemon fails to bind its HTTP port and stops (#553). So a clean exit is not yet a start: // wait for this start's own "HTTP gateway listening" or `EADDRINUSE` line (the log keeps the // earlier starts' lines), and fail on the latter. - if (started.code === 0 && !httpConfig.enabled) return; + if (started.code === 0 && !httpConfig.enabled) { + daemonStarted = true; + return; + } if (started.code === 0) { await waitFor( async () => { @@ -141,7 +188,10 @@ export async function startDaemon( }, { label: "the daemon's HTTP listener" }, ); - if (!(await readLog()).slice(before).includes("EADDRINUSE")) return; + if (!(await readLog()).slice(before).includes("EADDRINUSE")) { + daemonStarted = true; + return; + } } // why: a failed start reports only what the CLI saw while polling the socket, and `dispose` // deletes this home with `daemon.log` — the only record of the cause the daemon itself wrote. @@ -149,9 +199,42 @@ export async function startDaemon( const tail = (await readLog()).split("\n").slice(-20).join("\n"); expect(started.code, `daemon start failed: ${started.stderr}\n${tail}`).toBe(0); }; - const dispose = async () => { + const dispose = async (options: { readonly preservePages?: readonly Page[] } = {}) => { + const preserved = new Set(options.preservePages ?? []); + for (const page of activePages) { + if (preserved.has(page)) continue; + if (page.isClosed()) { + activePages.delete(page); + continue; + } + await page.unrouteAll({ behavior: "ignoreErrors" }); + await page.close(); + activePages.delete(page); + } for (const handle of background) handle.kill("SIGTERM"); + await Promise.all([...background].map((handle) => handle.waitForExit(10_000))); await stop(); + try { + await waitFor( + async () => + !(await Promise.all([...daemonPids].map((pid) => isProcessAlive(pid)))).some(Boolean), + { timeout: 5_000, interval: 100, label: "daemon process exited" }, + ); + } catch { + for (const pid of daemonPids) { + if (!(await isProcessAlive(pid))) continue; + try { + process.kill(pid, "SIGKILL"); + } catch (killError: unknown) { + if ((killError as NodeJS.ErrnoException).code !== "ESRCH") throw killError; + } + } + await waitFor( + async () => + !(await Promise.all([...daemonPids].map((pid) => isProcessAlive(pid)))).some(Boolean), + { timeout: 10_000, interval: 100, label: "daemon process exited after SIGKILL" }, + ); + } await rm(home, { force: true, recursive: true }); }; try { @@ -263,9 +346,12 @@ export async function startFleet( } } -export async function disposeFleet(fleet: Fleet): Promise { - await Promise.all(fleet.workers.map((worker) => worker.dispose())); - await fleet.gateway.dispose(); +export async function disposeFleet( + fleet: Fleet, + options: { readonly preservePages?: readonly Page[] } = {}, +): Promise { + await Promise.all(fleet.workers.map((worker) => worker.dispose(options))); + await fleet.gateway.dispose(options); } /** The protocol range the stand-in below claims: older than any this gateway speaks. */ @@ -470,6 +556,16 @@ export const test = base.extend< { proxied: ProxiedDaemon }, { daemon: RunningDaemon; gateway: RunningDaemon; proxiedDaemon: ProxiedDaemon } >({ + page: async ({ context }, use) => { + const page = await context.newPage(); + activePages.add(page); + try { + await use(page); + } finally { + activePages.delete(page); + await page.close(); + } + }, proxiedDaemon: [ // oxlint-disable-next-line no-empty-pattern -- as below. async ({}, use) => { diff --git a/e2e/console/workers-gateway-stops-mid-fetch.spec.ts b/e2e/console/workers-gateway-stops-mid-fetch.spec.ts index 5674716ca..fa66b12bc 100644 --- a/e2e/console/workers-gateway-stops-mid-fetch.spec.ts +++ b/e2e/console/workers-gateway-stops-mid-fetch.spec.ts @@ -98,7 +98,7 @@ test.describe("the workers page response helper against a gateway whose listener parkNext = true; const asked = askForWorkerList(page, fleet.gateway); await arrived; - await disposeFleet(fleet); + await disposeFleet(fleet, { preservePages: [page] }); await waitFor(() => listenerIsGone(fleet.gateway), { interval: 50, label: "the gateway's HTTP listener stopped", diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index aa5c4a6cc..266905b82 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -356,8 +356,20 @@ async function buildEnv( await testEnv.driverScript.set(options.driverScript); } - if (options.mode !== "auto") { - await testEnv.startDaemon(); + try { + if (options.mode !== "auto") await testEnv.startDaemon(); + } catch (error: unknown) { + await teardown({ + backgroundProcesses, + dataDirectory, + env, + gatewayFlag, + home, + mcpClients, + realDrivers: options.driver === "real", + socketPath, + }); + throw error; } return { @@ -464,19 +476,25 @@ async function teardown(state: TeardownState): Promise { for (const handle of backgroundProcesses) { handle.kill("SIGKILL"); } - await Promise.all( - [...backgroundProcesses].map((handle) => handle.waitForExit(10_000).catch(() => undefined)), - ); + await Promise.all([...backgroundProcesses].map((handle) => handle.waitForExit(10_000))); // Capture who (if anyone) is holding the socket *before* the graceful stop, so // we can verify those specific pids actually exit -- checking only "is the // socket file still there" after `daemon stop` would miss a process that // unlinked its socket on the way out but never actually terminated. const pidsBeforeStop = await pidsHoldingSocket(socketPath); - await cli([...gatewayFlag, "daemon", "stop"], env).catch(() => undefined); + if (pidsBeforeStop.length > 0) { + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + if (stopped.code !== 0) { + throw new Error(`daemon stop failed before teardown of ${socketPath}: ${stopped.stderr}`); + } + } // why: a daemon a test SIGKILLed leaves its socket file behind, and nobody will remove it. if (pidsBeforeStop.length > 0) { - await waitFor(() => !existsSync(socketPath), { timeout: 5_000 }).catch(() => undefined); + await waitFor(() => !existsSync(socketPath), { + timeout: 5_000, + label: "daemon socket removed during teardown", + }); } // A process can keep running for a little while after its socket is unlinked @@ -489,7 +507,7 @@ async function teardown(state: TeardownState): Promise { return !alive.some(Boolean); }, { timeout: 20_000, interval: 100 }, - ).catch(() => undefined); + ); const stillHoldingSocket = await pidsHoldingSocket(socketPath); const stillAlive = ( @@ -505,6 +523,10 @@ async function teardown(state: TeardownState): Promise { // Already gone. } } + await waitFor( + async () => !(await Promise.all(strayPids.map((pid) => isProcessAlive(pid)))).some(Boolean), + { timeout: 10_000, interval: 100, label: "stray daemon processes exited" }, + ); // Here rather than in each test's own `finally`: a test that hits its timeout is abandoned // with its body still running, so its `finally` may not have run yet -- and a booted From a21ca4c9f9d6998b4e51987d9aa4d725b57fe5a5 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 11:54:56 +0200 Subject: [PATCH 4/8] test: simplify process cleanup verification --- e2e/console/fixtures.ts | 48 +++++++++++++++++++--------------- e2e/helpers/env.ts | 58 +++++++++++++++++++++++++++-------------- 2 files changed, 66 insertions(+), 40 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 8cae552f9..96682903d 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -89,6 +89,32 @@ async function pidsHoldingSocket(socketPath: string): Promise { }); } +async function waitForDaemonPidsToExit(pids: ReadonlySet): Promise { + const alive = async () => + (await Promise.all([...pids].map((pid) => isProcessAlive(pid)))).some(Boolean); + try { + await waitFor(async () => !(await alive()), { + timeout: 5_000, + interval: 100, + label: "daemon process exited", + }); + } catch { + for (const pid of pids) { + if (!(await isProcessAlive(pid))) continue; + try { + process.kill(pid, "SIGKILL"); + } catch (error: unknown) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") throw error; + } + } + await waitFor(async () => !(await alive()), { + timeout: 10_000, + interval: 100, + label: "daemon process exited after SIGKILL", + }); + } +} + /** * Pins a worker's capacity to the flow, not the machine running it, as the end-to-end suite * does: fake devices use no real memory, so a nominal per-device budget keeps the RAM gate from @@ -214,27 +240,7 @@ export async function startDaemon( for (const handle of background) handle.kill("SIGTERM"); await Promise.all([...background].map((handle) => handle.waitForExit(10_000))); await stop(); - try { - await waitFor( - async () => - !(await Promise.all([...daemonPids].map((pid) => isProcessAlive(pid)))).some(Boolean), - { timeout: 5_000, interval: 100, label: "daemon process exited" }, - ); - } catch { - for (const pid of daemonPids) { - if (!(await isProcessAlive(pid))) continue; - try { - process.kill(pid, "SIGKILL"); - } catch (killError: unknown) { - if ((killError as NodeJS.ErrnoException).code !== "ESRCH") throw killError; - } - } - await waitFor( - async () => - !(await Promise.all([...daemonPids].map((pid) => isProcessAlive(pid)))).some(Boolean), - { timeout: 10_000, interval: 100, label: "daemon process exited after SIGKILL" }, - ); - } + await waitForDaemonPidsToExit(daemonPids); await rm(home, { force: true, recursive: true }); }; try { diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 266905b82..42894b701 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -478,6 +478,25 @@ async function teardown(state: TeardownState): Promise { } await Promise.all([...backgroundProcesses].map((handle) => handle.waitForExit(10_000))); + const pidsBeforeStop = await stopDaemonForTeardown(socketPath, env, gatewayFlag); + const strayPids = await killAndVerifyDaemonPids(socketPath, pidsBeforeStop); + + // why: a timed-out test may still be running and writing into its simulator home + if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); + await rm(home, { force: true, recursive: true }); + + if (strayPids.length > 0) { + throw new Error( + `withDaemon teardown found stray daemon process(es) that outlived \`daemon stop\` for ${socketPath}: ${strayPids.join(", ")}`, + ); + } +} + +async function stopDaemonForTeardown( + socketPath: string, + env: NodeJS.ProcessEnv, + gatewayFlag: readonly string[], +): Promise { // Capture who (if anyone) is holding the socket *before* the graceful stop, so // we can verify those specific pids actually exit -- checking only "is the // socket file still there" after `daemon stop` would miss a process that @@ -496,18 +515,30 @@ async function teardown(state: TeardownState): Promise { label: "daemon socket removed during teardown", }); } + return pidsBeforeStop; +} +async function killAndVerifyDaemonPids( + socketPath: string, + pidsBeforeStop: readonly number[], +): Promise { // A process can keep running for a little while after its socket is unlinked // (event-loop drain, especially under load) -- give `pidsBeforeStop` a real grace // window rather than a single point-in-time check, so a merely-slow exit is not // mistaken for a genuine leak. - await waitFor( - async () => { - const alive = await Promise.all(pidsBeforeStop.map((pid) => isProcessAlive(pid))); - return !alive.some(Boolean); - }, - { timeout: 20_000, interval: 100 }, - ); + try { + await waitFor( + async () => { + const alive = await Promise.all(pidsBeforeStop.map((pid) => isProcessAlive(pid))); + return !alive.some(Boolean); + }, + { timeout: 20_000, interval: 100 }, + ); + } catch (error: unknown) { + if (!(error instanceof Error && error.message.startsWith("waitFor timed out after 20000ms"))) { + throw error; + } + } const stillHoldingSocket = await pidsHoldingSocket(socketPath); const stillAlive = ( @@ -528,18 +559,7 @@ async function teardown(state: TeardownState): Promise { { timeout: 10_000, interval: 100, label: "stray daemon processes exited" }, ); - // Here rather than in each test's own `finally`: a test that hits its timeout is abandoned - // with its body still running, so its `finally` may not have run yet -- and a booted - // simulator keeps writing into its device directory while `rm` below walks it (`ENOTEMPTY`), - // then outlives the home. The daemon is stopped by now, so nothing boots another one. - if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); - await rm(home, { force: true, recursive: true }); - - if (strayPids.length > 0) { - throw new Error( - `withDaemon teardown found stray daemon process(es) that outlived \`daemon stop\` for ${socketPath}: ${strayPids.join(", ")}`, - ); - } + return strayPids; } async function readAgentDevicePid(home: string): Promise { From c93ac021a663927361dac8a7a644ab1dccc88df1 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:05:13 +0200 Subject: [PATCH 5/8] test: fail closed when daemon exit cannot be verified --- e2e/console/fixtures.ts | 104 ++++++++++++++++++++++++++++++---------- e2e/helpers/env.ts | 72 +++++++++++++++++++++------- 2 files changed, 134 insertions(+), 42 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 96682903d..aca9194e1 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -75,8 +75,15 @@ async function isProcessAlive(pid: number): Promise { async function pidsHoldingSocket(socketPath: string): Promise { if (!existsSync(socketPath)) return []; - return new Promise((resolve) => { - execFile("lsof", ["-t", socketPath], (_error, stdout) => { + return new Promise((resolve, reject) => { + execFile("lsof", ["-t", socketPath], (error, stdout) => { + if (error) { + const failure = error as NodeJS.ErrnoException & { stderr?: string }; + if ((failure.code !== 1 && failure.code !== "1") || failure.stderr?.trim()) { + reject(error); + return; + } + } resolve( stdout .split("\n") @@ -115,6 +122,27 @@ async function waitForDaemonPidsToExit(pids: ReadonlySet): Promise } } +async function closeActivePages(preserved: ReadonlySet): Promise { + let firstError: unknown; + for (const page of activePages) { + if (preserved.has(page)) continue; + if (!page.isClosed()) { + try { + await page.unrouteAll({ behavior: "ignoreErrors" }); + } catch (error: unknown) { + firstError ??= error; + } + try { + await page.close(); + } catch (error: unknown) { + firstError ??= error; + } + } + activePages.delete(page); + } + return firstError; +} + /** * Pins a worker's capacity to the flow, not the machine running it, as the end-to-end suite * does: fake devices use no real memory, so a nominal per-device budget keeps the RAM gate from @@ -176,22 +204,47 @@ export async function startDaemon( const daemonPids = new Set(); let daemonStarted = false; let daemonMayBeRunning = false; + let daemonPidDiscoveryFailed = false; const stop = async () => { if (!daemonMayBeRunning) return; - const pids = await pidsHoldingSocket(socketPath); + let pids: number[] = []; + let discoveryError: unknown; + try { + pids = await pidsHoldingSocket(socketPath); + } catch (error: unknown) { + daemonPidDiscoveryFailed = true; + discoveryError = error; + } for (const pid of pids) daemonPids.add(pid); - if (pids.length === 0 && !existsSync(socketPath)) { + if (pids.length === 0 && discoveryError === undefined) { daemonMayBeRunning = false; return; } - const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); - if (daemonStarted) expect(stopped.code, stopped.stderr).toBe(0); - await waitFor(() => !existsSync(socketPath), { - timeout: 10_000, - label: "daemon socket removed", - }); - daemonStarted = false; - daemonMayBeRunning = false; + let stopError: unknown; + if (existsSync(socketPath)) { + try { + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + if (daemonStarted && stopped.code !== 0) { + stopError = new Error(`daemon stop failed: ${stopped.stderr}`); + } + } catch (error: unknown) { + stopError = error; + } + try { + await waitFor(() => !existsSync(socketPath), { + timeout: 10_000, + label: "daemon socket removed", + }); + } catch (error: unknown) { + stopError ??= error; + } + } + if (!existsSync(socketPath)) { + daemonStarted = false; + daemonMayBeRunning = false; + } + if (discoveryError !== undefined) throw discoveryError; + if (stopError !== undefined) throw stopError; }; const start = async () => { const readLog = () => readFile(join(dataDirectory, "daemon.log"), "utf8").catch(() => ""); @@ -227,21 +280,24 @@ export async function startDaemon( }; const dispose = async (options: { readonly preservePages?: readonly Page[] } = {}) => { const preserved = new Set(options.preservePages ?? []); - for (const page of activePages) { - if (preserved.has(page)) continue; - if (page.isClosed()) { - activePages.delete(page); - continue; - } - await page.unrouteAll({ behavior: "ignoreErrors" }); - await page.close(); - activePages.delete(page); - } + let cleanupError = await closeActivePages(preserved); for (const handle of background) handle.kill("SIGTERM"); - await Promise.all([...background].map((handle) => handle.waitForExit(10_000))); - await stop(); + try { + await Promise.all([...background].map((handle) => handle.waitForExit(10_000))); + } catch (error: unknown) { + cleanupError ??= error; + } + try { + await stop(); + } catch (error: unknown) { + cleanupError ??= error; + } await waitForDaemonPidsToExit(daemonPids); + if (daemonPidDiscoveryFailed) { + throw cleanupError ?? new Error(`cannot verify daemon exit for ${socketPath}`); + } await rm(home, { force: true, recursive: true }); + if (cleanupError !== undefined) throw cleanupError; }; try { await start(); diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 42894b701..e328fd4a4 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -467,6 +467,12 @@ interface TeardownState { readonly socketPath: string; } +interface DaemonStopResult { + readonly pidDiscoveryFailed?: boolean; + readonly pidsBeforeStop: readonly number[]; + readonly stopError?: unknown; +} + async function teardown(state: TeardownState): Promise { const { backgroundProcesses, env, gatewayFlag, home, mcpClients, realDrivers, socketPath } = state; @@ -478,13 +484,21 @@ async function teardown(state: TeardownState): Promise { } await Promise.all([...backgroundProcesses].map((handle) => handle.waitForExit(10_000))); - const pidsBeforeStop = await stopDaemonForTeardown(socketPath, env, gatewayFlag); - const strayPids = await killAndVerifyDaemonPids(socketPath, pidsBeforeStop); + const stopResult = await stopDaemonForTeardown(socketPath, env, gatewayFlag); + const strayPids = await killAndVerifyDaemonPids(socketPath, stopResult.pidsBeforeStop); + + if (stopResult.pidDiscoveryFailed) { + throw ( + stopResult.stopError ?? + new Error(`could not verify daemon process ownership for ${socketPath}`) + ); + } // why: a timed-out test may still be running and writing into its simulator home if (realDrivers) await emptyDeviceSet(iosDeviceSet(home)); await rm(home, { force: true, recursive: true }); + if (stopResult.stopError !== undefined) throw stopResult.stopError; if (strayPids.length > 0) { throw new Error( `withDaemon teardown found stray daemon process(es) that outlived \`daemon stop\` for ${socketPath}: ${strayPids.join(", ")}`, @@ -496,26 +510,47 @@ async function stopDaemonForTeardown( socketPath: string, env: NodeJS.ProcessEnv, gatewayFlag: readonly string[], -): Promise { +): Promise { // Capture who (if anyone) is holding the socket *before* the graceful stop, so // we can verify those specific pids actually exit -- checking only "is the // socket file still there" after `daemon stop` would miss a process that // unlinked its socket on the way out but never actually terminated. - const pidsBeforeStop = await pidsHoldingSocket(socketPath); - if (pidsBeforeStop.length > 0) { - const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); - if (stopped.code !== 0) { - throw new Error(`daemon stop failed before teardown of ${socketPath}: ${stopped.stderr}`); + let pidsBeforeStop: number[] = []; + let stopError: unknown; + let pidDiscoveryFailed = false; + try { + pidsBeforeStop = await pidsHoldingSocket(socketPath); + } catch (error: unknown) { + pidDiscoveryFailed = true; + stopError = error; + } + // why: attempt graceful shutdown even if lsof could not identify the process. + if (existsSync(socketPath) && (pidsBeforeStop.length > 0 || pidDiscoveryFailed)) { + try { + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + if (stopped.code !== 0) { + stopError ??= new Error( + `daemon stop failed before teardown of ${socketPath}: ${stopped.stderr}`, + ); + } + } catch (error: unknown) { + stopError ??= error; } } - // why: a daemon a test SIGKILLed leaves its socket file behind, and nobody will remove it. - if (pidsBeforeStop.length > 0) { - await waitFor(() => !existsSync(socketPath), { - timeout: 5_000, - label: "daemon socket removed during teardown", - }); + if (pidsBeforeStop.length > 0 || (pidDiscoveryFailed && existsSync(socketPath))) { + try { + await waitFor(() => !existsSync(socketPath), { + timeout: 5_000, + label: "daemon socket removed during teardown", + }); + } catch (error: unknown) { + stopError ??= error; + } + } + if (pidDiscoveryFailed) { + stopError ??= new Error(`could not verify daemon process ownership for ${socketPath}`); } - return pidsBeforeStop; + return { pidDiscoveryFailed, pidsBeforeStop, stopError }; } async function killAndVerifyDaemonPids( @@ -613,9 +648,10 @@ async function pidsHoldingSocket(socketPath: string): Promise { .filter((line) => line !== "") .map(Number) .filter((pid) => Number.isInteger(pid)); - } catch { - // lsof exits non-zero when nothing holds the file, or may be unavailable. - return []; + } catch (error: unknown) { + const failure = error as NodeJS.ErrnoException & { stderr?: string }; + if ((failure.code === 1 || failure.code === "1") && !failure.stderr?.trim()) return []; + throw error; } } From c5789b9170e36d734a1a48b68be8771145c5b50c Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:07:18 +0200 Subject: [PATCH 6/8] test: handle daemon shutdown failures safely --- e2e/console/fixtures.ts | 109 ++++++++++++++++++++++++---------------- e2e/helpers/env.ts | 82 ++++++++++++++++++------------ 2 files changed, 116 insertions(+), 75 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index aca9194e1..6ae7e40bd 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -79,7 +79,7 @@ async function pidsHoldingSocket(socketPath: string): Promise { execFile("lsof", ["-t", socketPath], (error, stdout) => { if (error) { const failure = error as NodeJS.ErrnoException & { stderr?: string }; - if ((failure.code !== 1 && failure.code !== "1") || failure.stderr?.trim()) { + if (failure.code !== "1" || failure.stderr?.trim()) { reject(error); return; } @@ -96,6 +96,55 @@ async function pidsHoldingSocket(socketPath: string): Promise { }); } +async function discoverDaemonPids( + socketPath: string, +): Promise<{ error?: unknown; pids: number[] }> { + try { + return { pids: await pidsHoldingSocket(socketPath) }; + } catch (error: unknown) { + return { error, pids: [] }; + } +} + +async function requestDaemonStop( + socketPath: string, + gatewayFlag: readonly string[], + env: NodeJS.ProcessEnv, + daemonStarted: boolean, + discovery: { readonly error?: unknown; readonly pids: readonly number[] }, +): Promise { + if (!existsSync(socketPath)) return undefined; + if (discovery.pids.length === 0 && discovery.error === undefined) return undefined; + try { + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + if (daemonStarted && stopped.code !== 0) + return new Error(`daemon stop failed: ${stopped.stderr}`); + } catch (error: unknown) { + return error; + } + try { + await waitFor(() => !existsSync(socketPath), { + timeout: 10_000, + label: "daemon socket removed", + }); + } catch (error: unknown) { + return error; + } + return undefined; +} + +async function captureCleanupError( + current: unknown, + action: () => Promise, +): Promise { + try { + await action(); + return current; + } catch (error: unknown) { + return current ?? error; + } +} + async function waitForDaemonPidsToExit(pids: ReadonlySet): Promise { const alive = async () => (await Promise.all([...pids].map((pid) => isProcessAlive(pid)))).some(Boolean); @@ -207,43 +256,21 @@ export async function startDaemon( let daemonPidDiscoveryFailed = false; const stop = async () => { if (!daemonMayBeRunning) return; - let pids: number[] = []; - let discoveryError: unknown; - try { - pids = await pidsHoldingSocket(socketPath); - } catch (error: unknown) { - daemonPidDiscoveryFailed = true; - discoveryError = error; - } - for (const pid of pids) daemonPids.add(pid); - if (pids.length === 0 && discoveryError === undefined) { - daemonMayBeRunning = false; - return; - } - let stopError: unknown; - if (existsSync(socketPath)) { - try { - const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); - if (daemonStarted && stopped.code !== 0) { - stopError = new Error(`daemon stop failed: ${stopped.stderr}`); - } - } catch (error: unknown) { - stopError = error; - } - try { - await waitFor(() => !existsSync(socketPath), { - timeout: 10_000, - label: "daemon socket removed", - }); - } catch (error: unknown) { - stopError ??= error; - } - } + const discovery = await discoverDaemonPids(socketPath); + for (const pid of discovery.pids) daemonPids.add(pid); + daemonPidDiscoveryFailed ||= discovery.error !== undefined; + const stopError = await requestDaemonStop( + socketPath, + gatewayFlag, + env, + daemonStarted, + discovery, + ); if (!existsSync(socketPath)) { daemonStarted = false; daemonMayBeRunning = false; } - if (discoveryError !== undefined) throw discoveryError; + if (discovery.error !== undefined) throw discovery.error; if (stopError !== undefined) throw stopError; }; const start = async () => { @@ -282,16 +309,10 @@ export async function startDaemon( const preserved = new Set(options.preservePages ?? []); let cleanupError = await closeActivePages(preserved); for (const handle of background) handle.kill("SIGTERM"); - try { - await Promise.all([...background].map((handle) => handle.waitForExit(10_000))); - } catch (error: unknown) { - cleanupError ??= error; - } - try { - await stop(); - } catch (error: unknown) { - cleanupError ??= error; - } + cleanupError = await captureCleanupError(cleanupError, () => + Promise.all([...background].map((handle) => handle.waitForExit(10_000))), + ); + cleanupError = await captureCleanupError(cleanupError, stop); await waitForDaemonPidsToExit(daemonPids); if (daemonPidDiscoveryFailed) { throw cleanupError ?? new Error(`cannot verify daemon exit for ${socketPath}`); diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index e328fd4a4..4dd0d1969 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -473,6 +473,11 @@ interface DaemonStopResult { readonly stopError?: unknown; } +interface PidDiscoveryResult { + readonly error?: unknown; + readonly pids: number[]; +} + async function teardown(state: TeardownState): Promise { const { backgroundProcesses, env, gatewayFlag, home, mcpClients, realDrivers, socketPath } = state; @@ -515,42 +520,57 @@ async function stopDaemonForTeardown( // we can verify those specific pids actually exit -- checking only "is the // socket file still there" after `daemon stop` would miss a process that // unlinked its socket on the way out but never actually terminated. - let pidsBeforeStop: number[] = []; - let stopError: unknown; - let pidDiscoveryFailed = false; + const discovery = await discoverDaemonPids(socketPath); + const stopError = await requestDaemonStop(socketPath, env, gatewayFlag, discovery); + const socketError = await waitForDaemonSocketRemoval(socketPath, discovery); + return { + pidDiscoveryFailed: discovery.error !== undefined, + pidsBeforeStop: discovery.pids, + stopError: discovery.error ?? stopError ?? socketError, + }; +} + +async function discoverDaemonPids(socketPath: string): Promise { try { - pidsBeforeStop = await pidsHoldingSocket(socketPath); + return { pids: await pidsHoldingSocket(socketPath) }; } catch (error: unknown) { - pidDiscoveryFailed = true; - stopError = error; + return { error, pids: [] }; } - // why: attempt graceful shutdown even if lsof could not identify the process. - if (existsSync(socketPath) && (pidsBeforeStop.length > 0 || pidDiscoveryFailed)) { - try { - const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); - if (stopped.code !== 0) { - stopError ??= new Error( - `daemon stop failed before teardown of ${socketPath}: ${stopped.stderr}`, - ); - } - } catch (error: unknown) { - stopError ??= error; - } +} + +async function requestDaemonStop( + socketPath: string, + env: NodeJS.ProcessEnv, + gatewayFlag: readonly string[], + discovery: PidDiscoveryResult, +): Promise { + if (!existsSync(socketPath) || (discovery.pids.length === 0 && discovery.error === undefined)) { + return undefined; } - if (pidsBeforeStop.length > 0 || (pidDiscoveryFailed && existsSync(socketPath))) { - try { - await waitFor(() => !existsSync(socketPath), { - timeout: 5_000, - label: "daemon socket removed during teardown", - }); - } catch (error: unknown) { - stopError ??= error; - } + try { + const stopped = await cli([...gatewayFlag, "daemon", "stop"], env); + return stopped.code === 0 + ? undefined + : new Error(`daemon stop failed before teardown of ${socketPath}: ${stopped.stderr}`); + } catch (error: unknown) { + return error; } - if (pidDiscoveryFailed) { - stopError ??= new Error(`could not verify daemon process ownership for ${socketPath}`); +} + +async function waitForDaemonSocketRemoval( + socketPath: string, + discovery: PidDiscoveryResult, +): Promise { + if (discovery.pids.length === 0 && discovery.error === undefined) return undefined; + try { + await waitFor(() => !existsSync(socketPath), { + timeout: 5_000, + label: "daemon socket removed during teardown", + }); + return undefined; + } catch (error: unknown) { + return error; } - return { pidDiscoveryFailed, pidsBeforeStop, stopError }; } async function killAndVerifyDaemonPids( @@ -650,7 +670,7 @@ async function pidsHoldingSocket(socketPath: string): Promise { .filter((pid) => Number.isInteger(pid)); } catch (error: unknown) { const failure = error as NodeJS.ErrnoException & { stderr?: string }; - if ((failure.code === 1 || failure.code === "1") && !failure.stderr?.trim()) return []; + if (failure.code === "1" && !failure.stderr?.trim()) return []; throw error; } } From e9c5b9f75e0202433446145e13f63d12e8756d1b Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:11:40 +0200 Subject: [PATCH 7/8] test: handle stale socket PID lookup results --- e2e/console/fixtures.ts | 5 ++++- e2e/helpers/env.ts | 7 ++++++- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index 6ae7e40bd..d15b3c94c 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -79,7 +79,10 @@ async function pidsHoldingSocket(socketPath: string): Promise { execFile("lsof", ["-t", socketPath], (error, stdout) => { if (error) { const failure = error as NodeJS.ErrnoException & { stderr?: string }; - if (failure.code !== "1" || failure.stderr?.trim()) { + if ( + String(failure.code) !== "1" || + (failure.stderr?.trim() && !failure.stderr.includes("No such file or directory")) + ) { reject(error); return; } diff --git a/e2e/helpers/env.ts b/e2e/helpers/env.ts index 4dd0d1969..2996c9f92 100644 --- a/e2e/helpers/env.ts +++ b/e2e/helpers/env.ts @@ -670,7 +670,12 @@ async function pidsHoldingSocket(socketPath: string): Promise { .filter((pid) => Number.isInteger(pid)); } catch (error: unknown) { const failure = error as NodeJS.ErrnoException & { stderr?: string }; - if (failure.code === "1" && !failure.stderr?.trim()) return []; + if ( + String(failure.code) === "1" && + (!failure.stderr?.trim() || failure.stderr.includes("No such file or directory")) + ) { + return []; + } throw error; } } From 40c34e31388728ea660dff21a00588037e540c56 Mon Sep 17 00:00:00 2001 From: Szymon Chmal Date: Thu, 22 Oct 2026 12:32:07 +0200 Subject: [PATCH 8/8] test: escalate held CLI cleanup --- e2e/console/fixtures.ts | 31 ++++++++++++++++++++++++++++--- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/e2e/console/fixtures.ts b/e2e/console/fixtures.ts index d15b3c94c..6a18d430a 100644 --- a/e2e/console/fixtures.ts +++ b/e2e/console/fixtures.ts @@ -148,6 +148,20 @@ async function captureCleanupError( } } +async function stopBackgroundProcesses(handles: readonly CliBackgroundHandle[]): Promise { + await Promise.all( + handles.map(async (handle) => { + handle.kill("SIGTERM"); + try { + await handle.waitForExit(10_000); + } catch { + handle.kill("SIGKILL"); + await handle.waitForExit(10_000); + } + }), + ); +} + async function waitForDaemonPidsToExit(pids: ReadonlySet): Promise { const alive = async () => (await Promise.all([...pids].map((pid) => isProcessAlive(pid)))).some(Boolean); @@ -311,15 +325,26 @@ export async function startDaemon( const dispose = async (options: { readonly preservePages?: readonly Page[] } = {}) => { const preserved = new Set(options.preservePages ?? []); let cleanupError = await closeActivePages(preserved); - for (const handle of background) handle.kill("SIGTERM"); cleanupError = await captureCleanupError(cleanupError, () => - Promise.all([...background].map((handle) => handle.waitForExit(10_000))), + stopBackgroundProcesses([...background]), ); - cleanupError = await captureCleanupError(cleanupError, stop); + let stopError: unknown; + try { + await stop(); + } catch (error: unknown) { + stopError = error; + } await waitForDaemonPidsToExit(daemonPids); if (daemonPidDiscoveryFailed) { throw cleanupError ?? new Error(`cannot verify daemon exit for ${socketPath}`); } + if (stopError !== undefined && daemonPids.size === 0) throw stopError; + // why: disposal can remove the home after a forced stop only once every discovered daemon PID + // has exited; explicit stop() callers still receive the graceful-stop error above. + if (daemonPids.size > 0) { + daemonStarted = false; + daemonMayBeRunning = false; + } await rm(home, { force: true, recursive: true }); if (cleanupError !== undefined) throw cleanupError; };