From 0167112bf835bc9b7641977fe273b65aefe05362 Mon Sep 17 00:00:00 2001 From: Nate Moore Date: Fri, 30 Oct 2026 11:26:27 -0700 Subject: [PATCH] Make close() exit a web process A worker's own close() ended it without the kernel hearing, so the process hung. As in a worker, the current task still runs to its end and nothing queued after it does; the process then exits 0. --- packages/kernel/src/runtime/globals.ts | 12 ++++++++++-- packages/kernel/tests/process-runtime.spec.ts | 12 ++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/kernel/src/runtime/globals.ts b/packages/kernel/src/runtime/globals.ts index e30ae2f..e8b9675 100644 --- a/packages/kernel/src/runtime/globals.ts +++ b/packages/kernel/src/runtime/globals.ts @@ -20,14 +20,22 @@ export function installNodeGlobals(timers: Timers, process: GuestProcess): void } /** Web-shaped timers that still hold the loop, so a pending timer keeps the process - * alive: they return the numeric id, which clearTimeout already accepts. */ -export function installWebGlobals(timers: Timers): void { + * alive: they return the numeric id, which clearTimeout already accepts. close() exits + * the process: the worker's own would end it without the kernel ever hearing. */ +export function installWebGlobals(timers: Timers, process: GuestProcess): void { const byId = (start: (fn: () => void, ms?: unknown, ...args: unknown[]) => Timeout) => (fn: () => void, ms?: unknown, ...args: unknown[]): number => Number(start(fn, ms, ...args)); + let closing = false; Object.assign(globalThis, { setTimeout: byId(timers.setTimeout), clearTimeout: timers.clearTimeout, setInterval: byId(timers.setInterval), clearInterval: timers.clearInterval, + // As in a worker, the current task runs to its end and nothing queued after it does. + close(): void { + if (closing) return; + closing = true; + queueMicrotask(() => process.exit(0)); + }, }); } diff --git a/packages/kernel/tests/process-runtime.spec.ts b/packages/kernel/tests/process-runtime.spec.ts index e464f4f..cd1cd77 100644 --- a/packages/kernel/tests/process-runtime.spec.ts +++ b/packages/kernel/tests/process-runtime.spec.ts @@ -124,3 +124,15 @@ test("the worker scope belongs to the guest: its postMessage cannot reach the ke expect(out, runtime).toEqual({ code: 0, signal: null, stdout: "still talking to the kernel 0\n", stderr: "" }); } }); + +test("web: close() ends the process after the current task, as it ends a worker", async ({ page }) => { + const out = await web(page, { + "/app/main.mjs": [ + "setTimeout(() => console.log('queued timer ran'), 0);", + "console.log('before close');", + "close();", + "console.log('rest of the task');", + ].join("\n"), + }); + expect(out).toEqual({ code: 0, signal: null, stdout: "before close\nrest of the task\n", stderr: "" }); +}); -- knotmirror 0.0.1