@waffle-os/runtime 0.0.145 → 0.0.146

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/README.md +32 -0
  2. package/browser/command-input.ts +86 -0
  3. package/browser/command-owner.ts +5 -0
  4. package/browser/display/guest.ts +2 -18
  5. package/browser/display/surface-info.ts +19 -0
  6. package/browser/operations/cells.ts +90 -0
  7. package/browser/operations/guest.ts +94 -0
  8. package/browser/operations/owner.ts +201 -0
  9. package/browser/operations/protocol.ts +16 -0
  10. package/browser/operations/types.ts +41 -0
  11. package/browser/operations/writer.ts +106 -0
  12. package/browser/preview1-worker.ts +8 -1
  13. package/browser/process-broker.ts +372 -22
  14. package/browser/process-start.ts +5 -2
  15. package/browser/run-command.ts +388 -0
  16. package/browser/shared-fs.ts +20 -3
  17. package/browser/worker-memory.ts +6 -0
  18. package/browser/worker.ts +121 -27
  19. package/dist/browser/command-input.js +82 -0
  20. package/dist/browser/command-owner.js +2 -0
  21. package/dist/browser/display/guest.js +2 -18
  22. package/dist/browser/display/surface-info.js +18 -0
  23. package/dist/browser/operations/cells.js +80 -0
  24. package/dist/browser/operations/guest.js +67 -0
  25. package/dist/browser/operations/owner.js +175 -0
  26. package/dist/browser/operations/protocol.js +0 -0
  27. package/dist/browser/operations/types.js +0 -0
  28. package/dist/browser/operations/writer.js +98 -0
  29. package/dist/browser/preview1-worker.js +4 -0
  30. package/dist/browser/process-broker.js +317 -18
  31. package/dist/browser/process-start.js +3 -0
  32. package/dist/browser/run-command.js +377 -0
  33. package/dist/browser/shared-fs.js +8 -3
  34. package/dist/browser/worker-memory.js +10 -1
  35. package/dist/browser/worker.js +83 -28
  36. package/dist/fs/client.js +81 -18
  37. package/dist/fs/resolve-observation.js +11 -0
  38. package/dist/fs/service.js +51 -4
  39. package/dist/proc/command-transfer.js +72 -0
  40. package/dist/proc/directory.js +9 -1
  41. package/dist/proc/intrinsics/host.js +4 -1
  42. package/dist/proc/intrinsics.js +1 -0
  43. package/dist/proc/pipes.js +37 -4
  44. package/dist/proc/registry.js +25 -14
  45. package/dist/proc/start-command.js +101 -0
  46. package/dist/proc/supervisor.js +34 -10
  47. package/dist/proc/worker-broker.js +86 -31
  48. package/dist/proc/worker-client.js +67 -31
  49. package/dist/programs/collection.js +2 -0
  50. package/dist/runtime.js +14 -1
  51. package/dist/tooling/program/program-transformer.json +1 -1
  52. package/fs/client.ts +113 -17
  53. package/fs/resolve-observation.ts +25 -0
  54. package/fs/service.ts +63 -4
  55. package/index.ts +5 -0
  56. package/package.json +9 -1
  57. package/proc/command-transfer.ts +96 -0
  58. package/proc/directory.ts +10 -1
  59. package/proc/intrinsics/host.ts +5 -1
  60. package/proc/intrinsics.ts +1 -0
  61. package/proc/pipes.ts +39 -6
  62. package/proc/registry.ts +52 -17
  63. package/proc/start-command.ts +157 -0
  64. package/proc/supervisor.ts +34 -9
  65. package/proc/worker-broker.ts +100 -38
  66. package/proc/worker-client.ts +84 -31
  67. package/programs/collection.ts +4 -0
  68. package/runtime.ts +44 -3
  69. package/scripts/test-browser.ts +49 -29
  70. package/tests/browser-controls-discovery.test.ts +2 -10
  71. package/tests/browser-matrix.test.ts +105 -59
  72. package/tests/browser-navigation.test.ts +1 -1
  73. package/tests/browser-runner-lifecycle.ts +23 -13
  74. package/tests/command-input.test.ts +40 -0
  75. package/tests/command-scope.test.ts +422 -0
  76. package/tests/filesystem-client-intrinsics.test.ts +2 -0
  77. package/tests/filesystem-refcount.test.ts +2 -0
  78. package/tests/filesystem-resolve-observation.test.ts +185 -0
  79. package/tests/fixtures/command-bounded-admission.ts +31 -0
  80. package/tests/fixtures/command-disposal.ts +47 -0
  81. package/tests/fixtures/command-guests.ts +123 -0
  82. package/tests/fixtures/operation-fs-worker.ts +114 -0
  83. package/tests/fixtures/operation-observer-worker.ts +41 -0
  84. package/tests/fixtures/operation-page.ts +522 -0
  85. package/tests/fixtures/process-start-worker.ts +32 -0
  86. package/tests/link-browser-runner.ts +95 -22
  87. package/tests/node-exports.test.ts +29 -0
  88. package/tests/operation-diagnostics-browser.ts +192 -0
  89. package/tests/operation-diagnostics.test.ts +291 -0
  90. package/tests/page-runner/browser-controls-process-fixture.ts +24 -0
  91. package/tests/page-runner/browser-controls-runner.test.ts +20 -0
  92. package/tests/page-runner/browser-controls-runner.ts +1 -0
  93. package/tests/page-runner/browser-controls-suite.ts +20 -3
  94. package/tests/page-runner/control-run.ts +9 -1
  95. package/tests/page-runner/driver.ts +2 -0
  96. package/tests/page-runner/playwright-driver.ts +1 -1
  97. package/tests/page-runner/suite-host.ts +26 -1
  98. package/tests/page-runner/suite-startup.test.ts +39 -0
  99. package/tests/page-runner/threads-runtime-browser.test.ts +4 -6
  100. package/tests/page-runner/threads-runtime-suite.test.ts +14 -5
  101. package/tests/page-runner/worker-capability-controls.ts +174 -15
  102. package/tests/pipe-reader-reuse-races.test.ts +44 -0
  103. package/tests/process-start-browser-runner.ts +12 -4
  104. package/tests/process-start-browser.ts +66 -5
  105. package/tests/program-build-tools.test.ts +1 -1
  106. package/tests/runtime-facade.test.ts +5 -0
  107. package/tests/start-command.test.ts +109 -0
  108. package/tests/threads-guest-fixture.ts +1 -1
  109. package/tests/threads-guest-module.ts +6 -3
  110. package/tests/threads-guest.test.ts +25 -0
  111. package/tests/threads-runtime-browser-runner.ts +36 -13
  112. package/tests/threads-runtime-browser.ts +231 -92
  113. package/tests/threads-runtime-cases.ts +18 -1
  114. package/tests/threads-runtime-cleanup.ts +5 -1
  115. package/tests/threads-runtime-fd-browser.ts +247 -0
  116. package/tests/threads-runtime-fd-control.ts +3 -385
  117. package/tests/threads-runtime-fd-descriptors.test.ts +15 -13
  118. package/tests/threads-runtime-fd-module.ts +13 -2
  119. package/tests/threads-runtime-fd-service.ts +23 -2
  120. package/tests/threads-runtime-growth-worker.ts +61 -0
  121. package/tests/threads-runtime-host.ts +17 -4
  122. package/tests/threads-runtime-modules.ts +23 -5
  123. package/tests/threads-runtime-regression-controls.ts +386 -0
  124. package/tests/threads-runtime-regression-modules.ts +242 -0
  125. package/tests/threads-runtime-service-barrier.ts +8 -1
  126. package/tests/webkit-diagnostics.ts +125 -0
  127. package/tests/webkit-error-output.test.ts +118 -0
  128. package/tests/worker-memory-bootstrap.test.ts +19 -1
  129. package/tests/worker-memory-broker.test.ts +16 -8
  130. package/tooling/ci-paths.test.ts +329 -61
  131. package/tooling/private-authority.ts +14 -0
  132. package/tooling/program/program-transformer.json +1 -1
  133. package/tooling/tarball-smoke.ts +3 -1
@@ -3,6 +3,29 @@ import { join } from "node:path";
3
3
  import { withStorageCleanup } from "../storage-allocation.js";
4
4
  import { runControlProcess } from "./browser-controls-runner.js";
5
5
  import { checkControl } from "./browser-controls-suite.js";
6
+ import { captureWebKitDiagnostics } from "../webkit-diagnostics.js";
7
+
8
+ function nativeDiagnostics(): void {
9
+ const {
10
+ debug,
11
+ }: {
12
+ debug(namespace: string): (message: string) => void;
13
+ } = require("playwright-core/lib/utilsBundle");
14
+ debug("pw:protocol")("PROTOCOL_BEFORE_CAPTURE");
15
+ const restore = captureWebKitDiagnostics();
16
+ try {
17
+ const browser = debug("pw:browser");
18
+ const payload = "é".repeat(20_000);
19
+ browser(`[pid=123][err] NATIVE_RETAINED ${payload}`);
20
+ browser(`[pid=123][out] NATIVE_OVER_LIMIT ${payload}`);
21
+ browser("[pid=123][err] NATIVE_DROPPED");
22
+ browser("[pid=123] <process did exit: exitCode=0, signal=null>");
23
+ console.error("NON_NATIVE_FAILURE");
24
+ } finally {
25
+ restore();
26
+ }
27
+ debug("pw:browser")("BROWSER_LOGGING_RESTORED");
28
+ }
6
29
 
7
30
  async function interruptControl(signal: "SIGINT" | "SIGTERM"): Promise<void> {
8
31
  const received = Promise.withResolvers<void>();
@@ -51,6 +74,7 @@ if (mode === "supervise") {
51
74
  mode,
52
75
  async () => {
53
76
  if (mode === "verdict-failure") throw new TypeError("CONTROL_ASSERTION");
77
+ if (mode === "native-diagnostics") nativeDiagnostics();
54
78
  if (mode === "interrupted-SIGINT") await interruptControl("SIGINT");
55
79
  if (mode === "interrupted-SIGTERM") await interruptControl("SIGTERM");
56
80
  },
@@ -103,6 +103,10 @@ const fixture = join(import.meta.dir, "browser-controls-process-fixture.ts");
103
103
  async function synthetic(root: string, mode: string) {
104
104
  const resultPath = join(root, "result.json");
105
105
  const child = Bun.spawn([process.execPath, fixture, "supervise", mode, resultPath], {
106
+ env:
107
+ mode === "native-diagnostics"
108
+ ? { ...process.env, DEBUG: "pw:protocol", DEBUG_COLORS: "1" }
109
+ : process.env,
106
110
  timeout: 4000,
107
111
  stdout: "pipe",
108
112
  stderr: "pipe",
@@ -128,6 +132,22 @@ async function synthetic(root: string, mode: string) {
128
132
  }
129
133
  }
130
134
 
135
+ test("native capture bounds browser output and keeps launcher and control diagnostics", async () => {
136
+ await temporary(async (root) => {
137
+ const { code, stderr } = await synthetic(root, "native-diagnostics");
138
+ expect(code).toBe(0);
139
+ expect(Buffer.byteLength(stderr)).toBeLessThan(64 * 1024);
140
+ expect(stderr).toContain("PROTOCOL_BEFORE_CAPTURE");
141
+ expect(stderr).toContain("NATIVE_RETAINED");
142
+ expect(stderr).not.toContain("NATIVE_OVER_LIMIT");
143
+ expect(stderr).not.toContain("NATIVE_DROPPED");
144
+ expect(stderr.match(/native stdout\/stderr truncated/g)).toHaveLength(1);
145
+ expect(stderr).toContain("<process did exit: exitCode=0, signal=null>");
146
+ expect(stderr).toContain("NON_NATIVE_FAILURE");
147
+ expect(stderr).not.toContain("BROWSER_LOGGING_RESTORED");
148
+ });
149
+ });
150
+
131
151
  async function assertProcessOutcome(mode: string, expected: number): Promise<void> {
132
152
  await temporary(async (root) => {
133
153
  const { code, stdout, stderr, summary } = await synthetic(root, mode);
@@ -5,6 +5,7 @@ import { writeResult } from "./result-file.js";
5
5
 
6
6
  function spawnControls(command: string[], controlsPath: string) {
7
7
  return Bun.spawn(command.concat(["--result", controlsPath]), {
8
+ env: process.env,
8
9
  stdin: "ignore",
9
10
  stdout: "inherit",
10
11
  stderr: "pipe",
@@ -1,7 +1,11 @@
1
1
  import { keyPressControl } from "./key-press-controls.js";
2
2
  import { ControlRun } from "./control-run.js";
3
3
  import { fixtureCapabilityControl, fixtureControlModes } from "./fixture-capability-controls.js";
4
- import { workerCapabilityControl, workerControlModes } from "./worker-capability-controls.js";
4
+ import {
5
+ webKitWorkerVerificationModes,
6
+ workerCapabilityControl,
7
+ workerControlModes,
8
+ } from "./worker-capability-controls.js";
5
9
  import { retainedWorkerControl, retainedWorkerControlModes } from "./retained-worker-controls.js";
6
10
  import { peerControl, peerControlModes } from "./peer-controls.js";
7
11
  import { buildFrameworkBootstrap } from "../../build.js";
@@ -27,6 +31,7 @@ import { bounded } from "./driver.js";
27
31
  import { storageWorker } from "./storage-worker.js";
28
32
  import { withStorageCleanup } from "../storage-allocation.js";
29
33
  import { browserBundle, engines } from "../browser-runner-lifecycle.js";
34
+ import { captureWebKitDiagnostics } from "../webkit-diagnostics.js";
30
35
  function hangWorker(): void {
31
36
  globalThis.onmessage = () => {};
32
37
  }
@@ -301,7 +306,11 @@ async function engineControls(
301
306
  () => fixtureCapabilityControl(engine, mode, root),
302
307
  results,
303
308
  );
304
- for (const mode of workerControlModes.filter(
309
+ const workerModes =
310
+ engine === "webkit"
311
+ ? workerControlModes.concat(webKitWorkerVerificationModes)
312
+ : workerControlModes;
313
+ for (const mode of workerModes.filter(
305
314
  (mode) => !selected || `worker-capability-${mode}`.includes(selected),
306
315
  ))
307
316
  await checkControl(
@@ -379,6 +388,14 @@ async function engineControls(
379
388
  results,
380
389
  );
381
390
  }
391
+ async function runEngine(engine: string, root: string, results: ControlResults): Promise<void> {
392
+ const restore = engine === "webkit" ? captureWebKitDiagnostics() : undefined;
393
+ try {
394
+ await engineControls(engine, root, results);
395
+ } finally {
396
+ restore?.();
397
+ }
398
+ }
382
399
  async function main(controls: ControlRun): Promise<void> {
383
400
  controls.throwIfInterrupted();
384
401
  const args = process.argv.slice(2),
@@ -406,7 +423,7 @@ async function main(controls: ControlRun): Promise<void> {
406
423
  await buildFrameworkBootstrap();
407
424
  root = await mkdtemp(join(process.env.STORAGE_SCRATCH_ROOT ?? tmpdir(), "pr-results-"));
408
425
  await mkdir(root, { recursive: true });
409
- for (const engine of requested) await engineControls(engine, root, results);
426
+ for (const engine of requested) await runEngine(engine, root, results);
410
427
  },
411
428
  async () => {
412
429
  if (root) await rm(root, { recursive: true, force: true });
@@ -1,3 +1,5 @@
1
+ import { boundWebKitLogReplay } from "../webkit-diagnostics.js";
2
+
1
3
  type ControlResult = {
2
4
  engine: string;
3
5
  control: string;
@@ -29,7 +31,13 @@ export class ControlRun {
29
31
  this.throwIfInterrupted();
30
32
  this.results.push({ engine, control, status: "pass" });
31
33
  } catch (error) {
32
- this.results.push({ engine, control, status: "fail", error: String(error) });
34
+ const detail = String(error);
35
+ this.results.push({
36
+ engine,
37
+ control,
38
+ status: "fail",
39
+ error: engine === "webkit" ? boundWebKitLogReplay(detail) : detail,
40
+ });
33
41
  }
34
42
  console.log(JSON.stringify(this.results[this.results.length - 1]));
35
43
  }
@@ -89,6 +89,8 @@ export interface Driver {
89
89
  handles(signal: AbortSignal): Promise<string[]>;
90
90
  url(signal: AbortSignal): Promise<string>;
91
91
  script(source: string, signal: AbortSignal): Promise<unknown>;
92
+ /** Optional read-only check while the session is still live. Stop must settle admitted work. */
93
+ verifyBeforeStop?(signal: AbortSignal): Promise<void>;
92
94
  stop(): Promise<DriverCleanup>;
93
95
  readonly uncertain: boolean;
94
96
  }
@@ -96,7 +96,7 @@ export class PlaywrightDriver implements Driver {
96
96
  })),
97
97
  };
98
98
  }
99
- private current(): Page {
99
+ protected current(): Page {
100
100
  if (!this.page) throw new Error("No page");
101
101
  return this.page;
102
102
  }
@@ -358,6 +358,31 @@ async function stopDriver(driver: Driver, ms: number): Promise<DriverCleanup> {
358
358
  };
359
359
  }
360
360
  }
361
+ async function verifyAndStopDriver(
362
+ driver: Driver,
363
+ cleanupMs: number,
364
+ collector: Collector,
365
+ ): Promise<DriverCleanup> {
366
+ const verify = driver.verifyBeforeStop?.bind(driver);
367
+ if (!verify) return stopDriver(driver, cleanupMs);
368
+ const cancel = new AbortController();
369
+ const verification = Promise.resolve().then(() => verify(cancel.signal));
370
+ try {
371
+ await bounded(verification, 5000, "driver cleanup verification");
372
+ } catch (error) {
373
+ collector.fail("cleanup-verification", String(error));
374
+ cancel.abort(error);
375
+ }
376
+ const cleanup = await stopDriver(driver, cleanupMs);
377
+ if (cancel.signal.aborted) {
378
+ // Browser closure cancels admitted Playwright calls. Join their verifier independently.
379
+ const settled = Promise.allSettled([verification]);
380
+ await bounded(settled, 1000, "driver cleanup verification settlement").catch((error) => {
381
+ collector.fail("cleanup-verification", String(error));
382
+ });
383
+ }
384
+ return cleanup;
385
+ }
361
386
  async function stopCollector(
362
387
  server: ReturnType<typeof Bun.serve>,
363
388
  stopped: boolean,
@@ -537,7 +562,7 @@ export async function runPageSuite<R>(
537
562
  joinPreparation(preparation, cleanupMs),
538
563
  consumers.join(cleanupMs),
539
564
  driver
540
- ? stopDriver(driver, cleanupMs).then((result) => {
565
+ ? verifyAndStopDriver(driver, cleanupMs, collector).then((result) => {
541
566
  driverCleanup = result;
542
567
  })
543
568
  : undefined,
@@ -61,3 +61,42 @@ for (const safari of [true, false]) {
61
61
  }
62
62
  });
63
63
  }
64
+
65
+ test("cleanup verification failure survives an unconfirmed driver stop", async () => {
66
+ const root = await mkdtemp(join(process.env.STORAGE_SCRATCH_ROOT ?? tmpdir(), "startup-"));
67
+ const driver = new FakeDriver("pass", { list: ["control"], result: true });
68
+ const release = Promise.withResolvers<void>();
69
+ const stopping = release.promise.then(driver.stop.bind(driver));
70
+ driver.start = async () => {
71
+ throw new Error("startup failed");
72
+ };
73
+ driver.stop = () => stopping;
74
+ Object.assign(driver, {
75
+ async verifyBeforeStop() {
76
+ throw new Error("root worker missing during verification");
77
+ },
78
+ });
79
+ try {
80
+ const result = await runPageSuite(adapter, () => driver, {
81
+ scratchRoot: root,
82
+ resultPath: join(root, "result.json"),
83
+ port: "ephemeral",
84
+ cleanupTimeoutMs: 100,
85
+ });
86
+ expect(result.exit).toBe(2);
87
+ expect(result.cleanup.session).toEqual({
88
+ status: "unconfirmed",
89
+ detail: "Error: driver teardown timed out",
90
+ });
91
+ expect(result.failures).toContainEqual(
92
+ expect.objectContaining({
93
+ category: "cleanup-verification",
94
+ detail: "Error: root worker missing during verification",
95
+ }),
96
+ );
97
+ } finally {
98
+ release.resolve();
99
+ await stopping;
100
+ await rm(root, { recursive: true, force: true });
101
+ }
102
+ });
@@ -30,15 +30,13 @@ for (const tamper of [false, true]) {
30
30
  });
31
31
  if (tamper)
32
32
  assets["/threads.wasm"] = new Blob(["changed bytes"], { type: "application/wasm" });
33
+ const resultsDir = process.env.THREAD_RUNTIME_RESULTS_DIR;
33
34
  const result = await runPageSuite(
34
35
  adapter,
35
36
  (path) => (driver = new PlaywrightDriver("chromium", path)),
36
37
  {
37
- resultPath: process.env.THREAD_RUNTIME_RESULTS_DIR
38
- ? join(
39
- process.env.THREAD_RUNTIME_RESULTS_DIR,
40
- `typed-page-${tamper ? "tamper" : "complete"}.json`,
41
- )
38
+ resultPath: resultsDir
39
+ ? join(resultsDir, `typed-page-${tamper ? "tamper" : "complete"}.json`)
42
40
  : join(root, "result.json"),
43
41
  scratchRoot: root,
44
42
  port: "ephemeral",
@@ -59,7 +57,7 @@ for (const tamper of [false, true]) {
59
57
  }
60
58
  expect(result.cleanup.scratch.status).toBe("confirmed");
61
59
  expect(result.cleanup.server.status).toBe("confirmed");
62
- expect(await readdir(root)).toEqual([]);
60
+ expect(await readdir(root)).toEqual(resultsDir ? [] : ["result.json"]);
63
61
  } finally {
64
62
  await driver?.stop();
65
63
  await rm(root, { recursive: true, force: true });
@@ -6,8 +6,10 @@ import { runPageSuite } from "@waffle-os/runtime/testing/page-runner";
6
6
  import { parseRuntimeThreadCommand } from "../threads-runtime-browser-runner.js";
7
7
  import {
8
8
  runtimeThreadCases,
9
+ runtimeThreadRegressions,
9
10
  stockThreadCase,
10
11
  isRuntimeThreadCase,
12
+ type BrowserRuntimeThreadCase,
11
13
  } from "../threads-runtime-cases.js";
12
14
  import {
13
15
  threadsRuntimeAdapter,
@@ -61,23 +63,30 @@ function adapter() {
61
63
  return threadsRuntimeAdapter("", { fixtureSha256, assets: {} });
62
64
  }
63
65
 
64
- test("browser CLI defaults to all nine, preserves focused selectors and dispatches native first", () => {
66
+ test("browser CLI defaults to the full matrix, supports focused cases and dispatches native first", () => {
67
+ const cases =
68
+ Array.from<BrowserRuntimeThreadCase>(runtimeThreadCases).concat(runtimeThreadRegressions);
65
69
  expect(parseRuntimeThreadCommand([])).toEqual({
66
70
  kind: "browser",
67
71
  engines: ["chromium"],
68
- cases: runtimeThreadCases,
72
+ cases,
69
73
  });
70
74
  expect(parseRuntimeThreadCommand(["chromium", "firefox", "webkit"])).toEqual({
71
75
  kind: "browser",
72
76
  engines: ["chromium", "firefox", "webkit"],
73
- cases: runtimeThreadCases,
77
+ cases,
74
78
  });
75
- for (const selected of runtimeThreadCases)
79
+ for (const selected of cases)
76
80
  expect(parseRuntimeThreadCommand(["--case", selected, "webkit"])).toEqual({
77
81
  kind: "browser",
78
82
  engines: ["webkit"],
79
83
  cases: [selected],
80
84
  });
85
+ expect(parseRuntimeThreadCommand(["--case", "growth", "--case", "join"])).toEqual({
86
+ kind: "browser",
87
+ engines: ["chromium"],
88
+ cases: ["growth", "join"],
89
+ });
81
90
  expect(parseRuntimeThreadCommand(["ios-safari", "--result", "/result.json"])).toEqual({
82
91
  kind: "native",
83
92
  args: ["--result", "/result.json"],
@@ -87,7 +96,7 @@ test("browser CLI defaults to all nine, preserves focused selectors and dispatch
87
96
  ["--case", "unknown"],
88
97
  ["chromium", "--result", "/result.json"],
89
98
  ["safari"],
90
- ["--case", "pair", "--case", "repeat"],
99
+ ["--case", "pair", "--case", "pair"],
91
100
  ])
92
101
  expect(() => parseRuntimeThreadCommand(args)).toThrow();
93
102
  });
@@ -1,9 +1,12 @@
1
1
  import { runPageSuite, type SuiteAdapter } from "@waffle-os/runtime/testing/page-runner";
2
2
  import { PlaywrightDriver } from "@waffle-os/runtime/testing/page-runner/playwright";
3
3
  import { browserBundle } from "../browser-runner-lifecycle.js";
4
+ import { observeWebKitPage } from "../webkit-diagnostics.js";
4
5
  import { tmpdir } from "node:os";
5
6
  import { join } from "node:path";
7
+ import type { DriverCleanup } from "./driver.js";
6
8
  import { record } from "./protocol.js";
9
+ import type { SuiteResult } from "./suite-host.js";
7
10
 
8
11
  export const workerControlModes = [
9
12
  "success",
@@ -19,8 +22,25 @@ export const workerControlModes = [
19
22
  "controller-mismatch",
20
23
  "absent-current",
21
24
  ];
25
+ export const webKitWorkerVerificationModes = [
26
+ "verification-navigation-held",
27
+ "verification-slow-native-close",
28
+ "verification-startup-failure",
29
+ ];
30
+ function holdsVerificationNavigation(mode: string): boolean {
31
+ return mode === "verification-navigation-held" || mode === "verification-slow-native-close";
32
+ }
22
33
  const installingWorker = `const identity = crypto.randomUUID(); self.addEventListener('message', e => e.ports[0]?.postMessage(identity)); self.addEventListener('install', e => e.waitUntil(self.skipWaiting())); self.addEventListener('activate', e => e.waitUntil(self.clients.claim()));`;
23
34
  const foreignWorker = `const identity = crypto.randomUUID(); self.addEventListener('install', e => e.waitUntil(self.skipWaiting())); self.addEventListener('activate', e => e.waitUntil(self.clients.claim())); self.addEventListener('message', e => e.ports[0]?.postMessage(identity));`;
35
+ const cleanupStepPrefix = "worker capability verification: ";
36
+ const verificationTimeout = "driver cleanup verification timed out";
37
+ const startupFailure = "Control failed startup after allocating the browser";
38
+ const missingRoot = "No active root Worker in verification document";
39
+ const verificationPage = `<!doctype html><script>
40
+ Object.defineProperty(ServiceWorkerRegistration.prototype, "unregister", {
41
+ value() { throw new Error("Verification document attempted to unregister a worker"); },
42
+ });
43
+ </script>`;
24
44
  function assert(value: unknown, detail: string): asserts value {
25
45
  if (!value) throw new Error(detail);
26
46
  }
@@ -30,12 +50,62 @@ class ControlDriver extends PlaywrightDriver {
30
50
  rootIdentity = "";
31
51
  foreignIdentity = "";
32
52
  verified = false;
53
+ verificationNavigationHeld = false;
54
+ nativeCloses = 0;
55
+ private diagnostics?: ReturnType<typeof observeWebKitPage>;
33
56
  constructor(
34
- engine: "chromium" | "webkit",
57
+ private readonly controlEngine: "chromium" | "webkit",
35
58
  scratch: string,
36
59
  readonly mode: string,
60
+ private readonly startupFailureOrigin?: string,
37
61
  ) {
38
- super(engine, scratch);
62
+ super(controlEngine, scratch);
63
+ }
64
+ override async start(signal: AbortSignal): Promise<void> {
65
+ await super.start(signal);
66
+ if (this.controlEngine !== "webkit") return;
67
+ if (this.mode === "in-flight-loss" || webKitWorkerVerificationModes.includes(this.mode))
68
+ this.observeVerification();
69
+ if (holdsVerificationNavigation(this.mode))
70
+ await this.current().route("**/verify.html", () => {
71
+ this.verificationNavigationHeld = true;
72
+ });
73
+ if (this.mode === "verification-slow-native-close") this.delayNativeClose();
74
+ if (this.startupFailureOrigin) {
75
+ this.origin = this.startupFailureOrigin;
76
+ throw new Error(startupFailure);
77
+ }
78
+ }
79
+ private delayNativeClose(): void {
80
+ const context = this.current().context();
81
+ const browser = context.browser();
82
+ assert(browser, "Expected WebKit launcher for persistent context");
83
+ const closeContext = context.close.bind(context);
84
+ const closeBrowser = browser.close.bind(browser);
85
+ context.close = async (options) => {
86
+ await Bun.sleep(4250);
87
+ await closeContext(options);
88
+ this.nativeCloses++;
89
+ };
90
+ browser.close = async (options) => {
91
+ await Bun.sleep(3650);
92
+ await closeBrowser(options);
93
+ this.nativeCloses++;
94
+ };
95
+ }
96
+ private observeVerification(): void {
97
+ const page = this.current();
98
+ const diagnostics = observeWebKitPage(page, `worker-capability-${this.mode}`);
99
+ this.diagnostics = diagnostics;
100
+ page.on("console", (message) => {
101
+ const text = message.text();
102
+ if (message.type() === "debug" && text.startsWith(cleanupStepPrefix))
103
+ diagnostics.enter(text.slice(cleanupStepPrefix.length));
104
+ });
105
+ }
106
+ get browserStopped(): boolean {
107
+ const page = this.current();
108
+ return page.isClosed() && page.context().browser()?.isConnected() === false;
39
109
  }
40
110
  override async navigate(url: string, signal: AbortSignal): Promise<void> {
41
111
  const parsed = new URL(url);
@@ -74,7 +144,9 @@ class ControlDriver extends PlaywrightDriver {
74
144
  }
75
145
  if (this.mode === "in-flight-loss") {
76
146
  await this.stage("in-flight", signal);
147
+ this.diagnostics?.enter("navigate away from initiating document");
77
148
  await super.navigate(this.origin + "/foreign.html", signal);
149
+ this.diagnostics?.enter("discarded initiating document");
78
150
  throw new Error("Control lost initiating document before settlement");
79
151
  }
80
152
  await this.stage("registered", signal);
@@ -130,27 +202,56 @@ class ControlDriver extends PlaywrightDriver {
130
202
  "Stale A worker identity was not retained",
131
203
  );
132
204
  }
133
- override async stop() {
134
- const signal = AbortSignal.timeout(5000);
135
- let failure: unknown;
205
+ override stop(): Promise<DriverCleanup> {
206
+ this.diagnostics?.shutdown("runner cleanup");
207
+ return super.stop();
208
+ }
209
+ async verifyBeforeStop(signal: AbortSignal): Promise<void> {
210
+ if (!this.origin) return;
211
+ const fail = () => this.diagnostics?.fail();
212
+ signal.addEventListener("abort", fail, { once: true });
136
213
  try {
137
- if (this.origin) await this.verifyCleanup(signal);
214
+ await this.verifyCleanup(signal);
138
215
  } catch (error) {
139
- failure = error;
216
+ if (!signal.aborted) fail();
217
+ throw error;
218
+ } finally {
219
+ signal.removeEventListener("abort", fail);
140
220
  }
141
- const cleanup = await super.stop();
142
- if (failure) throw failure;
143
- return cleanup;
144
221
  }
145
222
  private async verifyCleanup(signal: AbortSignal): Promise<void> {
146
- await super.navigate(this.origin + "/foreign.html", signal);
223
+ this.diagnostics?.enter("navigate to verification document");
224
+ await super.navigate(this.origin + "/verify.html", signal);
225
+ this.diagnostics?.enter("start verification script");
147
226
  const foreign = ["collision-before", "collision-after", "replacement", "in-place"].includes(
148
227
  this.mode,
149
228
  );
150
229
  const value = await this.script(
151
- `return (async () => { const regs = await navigator.serviceWorker.getRegistrations(); const root = regs.find(r=>r.scope===location.origin+'/'); const owned = regs.find(r=>r.scope===${JSON.stringify(this.scope)}); const ch = new MessageChannel(); const id = new Promise(r=>ch.port1.onmessage=e=>r(e.data)); root.active.postMessage('id',[ch.port2]); const rootIdentity = await id; let foreignIdentity = null; if(${foreign} && owned?.active) { const other = new MessageChannel(); const value = new Promise(resolve=>other.port1.onmessage=e=>resolve(e.data)); owned.active.postMessage('id',[other.port2]); foreignIdentity = await value; } const result = {root:rootIdentity, foreignIdentity, current:owned?.active?.scriptURL ?? null}; for(const r of regs) await r.unregister(); return result; })()`,
230
+ `return (async () => {
231
+ const step = ${this.diagnostics ? `name => console.debug(${JSON.stringify(cleanupStepPrefix)} + name)` : "() => {}"};
232
+ step("enumerate registrations");
233
+ const regs = await navigator.serviceWorker.getRegistrations();
234
+ const root = regs.find(r => r.scope === location.origin + "/");
235
+ const owned = regs.find(r => r.scope === ${JSON.stringify(this.scope)});
236
+ if (!root?.active) throw new Error(${JSON.stringify(missingRoot)});
237
+ const ch = new MessageChannel();
238
+ const id = new Promise(r => ch.port1.onmessage = e => r(e.data));
239
+ step("await root worker identity");
240
+ root.active.postMessage("id", [ch.port2]);
241
+ const rootIdentity = await id;
242
+ let foreignIdentity = null;
243
+ if (${foreign} && owned?.active) {
244
+ const other = new MessageChannel();
245
+ const value = new Promise(resolve => other.port1.onmessage = e => resolve(e.data));
246
+ owned.active.postMessage("id", [other.port2]);
247
+ foreignIdentity = await value;
248
+ }
249
+ step("verify worker identities");
250
+ return {root: rootIdentity, foreignIdentity, current: owned?.active?.scriptURL ?? null};
251
+ })()`,
152
252
  signal,
153
253
  );
254
+ signal.throwIfAborted();
154
255
  assert(record(value) && value.root === this.rootIdentity, "Foreign root active Worker changed");
155
256
  const unknownOperation = this.mode === "in-flight-loss";
156
257
  assert(
@@ -170,21 +271,71 @@ class ControlDriver extends PlaywrightDriver {
170
271
  this.verified = true;
171
272
  }
172
273
  }
274
+ function assertVerificationFailure(driver: ControlDriver, result: SuiteResult): void {
275
+ const held = holdsVerificationNavigation(driver.mode);
276
+ assert(!driver.verified && result.exit === 2, "Verification failure did not fail the suite");
277
+ assert(driver.browserStopped, "Verification failure left the WebKit browser connected");
278
+ const failure = result.failures.find(({ category }) => category === "cleanup-verification");
279
+ assert(
280
+ failure?.detail.includes(held ? verificationTimeout : missingRoot) &&
281
+ !result.failures.some(({ detail }) => detail.includes("verification settlement timed out")),
282
+ `Wrong verification failure: ${JSON.stringify(result.failures)}`,
283
+ );
284
+ if (held) {
285
+ assert(
286
+ driver.verificationNavigationHeld &&
287
+ result.runComplete &&
288
+ result.cleanup.storage.status === "confirmed" &&
289
+ result.outcomes.worker?.status === "pass",
290
+ "Verification hold did not follow a completed worker case",
291
+ );
292
+ if (driver.mode === "verification-slow-native-close")
293
+ assert(driver.nativeCloses === 2, "Suite returned before both real close calls settled");
294
+ } else {
295
+ assert(
296
+ result.failures.some(
297
+ ({ category, detail }) => category === "host" && detail.includes(startupFailure),
298
+ ),
299
+ `Original startup failure was lost: ${JSON.stringify(result.failures)}`,
300
+ );
301
+ }
302
+ }
173
303
  export async function workerCapabilityControl(
174
304
  engine: "chromium" | "webkit",
175
305
  mode: string,
176
306
  root: string,
177
307
  ): Promise<void> {
178
308
  let driver: ControlDriver | undefined;
309
+ let startupOrigin: string | undefined;
179
310
  const script = mode === "nested-script" ? "/assets/owned-sw.js" : "/owned-sw.js";
180
311
  const a: SuiteAdapter<{ mode: string }> = {
181
312
  suite: "worker-capability",
182
- inventory: () => [{ id: "worker", label: mode, request: () => ({ mode }) }],
313
+ inventory: () => [
314
+ {
315
+ id: "worker",
316
+ label: mode,
317
+ request: () => ({ mode: holdsVerificationNavigation(mode) ? "success" : mode }),
318
+ },
319
+ ],
183
320
  serviceWorker: { caseId: "worker", script },
321
+ fixture:
322
+ mode === "verification-startup-failure"
323
+ ? {
324
+ caseId: "worker",
325
+ create: () => ({
326
+ async start({ origin }) {
327
+ startupOrigin = origin;
328
+ return [];
329
+ },
330
+ async close() {},
331
+ }),
332
+ }
333
+ : undefined,
184
334
  policy: { listIds: () => ["worker"], check() {} },
185
335
  assets: async () => ({
186
336
  "/page.js": await browserBundle(join(import.meta.dir, "worker-capability-control-page.ts")),
187
337
  "/foreign.html": new Blob(["<!doctype html>"], { type: "text/html" }),
338
+ "/verify.html": new Blob([verificationPage], { type: "text/html" }),
188
339
  "/root-sw.js": foreignWorker,
189
340
  "/foreign-sw.js": foreignWorker,
190
341
  [script]:
@@ -196,15 +347,23 @@ export async function workerCapabilityControl(
196
347
  };
197
348
  const result = await runPageSuite(
198
349
  a,
199
- (scratch) => (driver = new ControlDriver(engine, scratch, mode)),
350
+ (scratch) => (driver = new ControlDriver(engine, scratch, mode, startupOrigin)),
200
351
  {
201
352
  scratchRoot: process.env.STORAGE_SCRATCH_ROOT ?? tmpdir(),
202
353
  resultPath: join(root, `worker-${engine}-${mode}.json`),
203
354
  port: "ephemeral",
204
355
  },
205
356
  );
357
+ const { session, launcher, server, scratch } = result.cleanup;
358
+ assert(
359
+ [session, launcher, server, scratch].every((step) => step.status === "confirmed"),
360
+ `Worker capability browser teardown unconfirmed: ${JSON.stringify(result.cleanup)}`,
361
+ );
362
+ assert(driver, "Worker capability driver did not start");
363
+ if (webKitWorkerVerificationModes.includes(mode))
364
+ return assertVerificationFailure(driver, result);
206
365
  assert(
207
- driver?.verified,
366
+ driver.verified,
208
367
  `Worker cleanup control not verified: ${JSON.stringify(result.failures)}`,
209
368
  );
210
369
  assert(