peachsim 0.1.1667 → 0.1.1674

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 (204) hide show
  1. package/README.md +1 -1
  2. package/cli/bridge-flow-runner.ts +4 -1
  3. package/cli/commands/coverage-swift.ts +291 -0
  4. package/cli/commands/coverage.ts +168 -24
  5. package/cli/commands/diagnose.ts +1 -19
  6. package/cli/commands/inspect/settling.ts +37 -4
  7. package/cli/commands/react.ts +3 -18
  8. package/cli/commands/screenshot.ts +1 -1
  9. package/cli/commands/screenshots-capture.ts +1 -1
  10. package/cli/drivers/playwright-provisioning.ts +1 -4
  11. package/cli/drivers/playwright.ts +15 -1
  12. package/cli/scene-video.ts +1 -1
  13. package/cli/ui.ts +20 -0
  14. package/cli/ws-bridge.ts +7 -36
  15. package/detox/frame-identity.cjs +21 -0
  16. package/detox/frame-identity.d.cts +6 -0
  17. package/detox/index.ts +39 -33
  18. package/detox/jest-environment.cjs +4 -1
  19. package/detox/jest-setup-after-env.cjs +0 -4
  20. package/detox/navigation-lifecycle.ts +2 -2
  21. package/detox/proof-observer.ts +126 -0
  22. package/dist-lib/agent-daemon-client.cjs +29 -1
  23. package/dist-lib/agent-events.cjs +1 -1
  24. package/dist-lib/attached-projects.cjs +10 -1
  25. package/dist-lib/auth/shared-session.cjs +1 -1
  26. package/dist-lib/backend-origin.cjs +1 -1
  27. package/dist-lib/beta.cjs +1 -1
  28. package/dist-lib/beta.mjs +1 -1
  29. package/dist-lib/bridge-constants.cjs +1 -1
  30. package/dist-lib/bridge-contract-input.cjs +1 -1
  31. package/dist-lib/bridge-contract-input.mjs +1 -1
  32. package/dist-lib/bridge-contract.cjs +1 -1
  33. package/dist-lib/bridge-contract.mjs +1 -1
  34. package/dist-lib/bundle-channel.cjs +557 -158
  35. package/dist-lib/capture-contract.cjs +1 -1
  36. package/dist-lib/capture-contract.mjs +1 -1
  37. package/dist-lib/cloud-contract.cjs +1 -1
  38. package/dist-lib/cloud-contract.mjs +1 -1
  39. package/dist-lib/cloud-test-args.cjs +1 -1
  40. package/dist-lib/cloud-test-args.mjs +1 -1
  41. package/dist-lib/cloud.cjs +1 -1
  42. package/dist-lib/cloud.mjs +1 -1
  43. package/dist-lib/config.cjs +1 -1
  44. package/dist-lib/config.mjs +1 -1
  45. package/dist-lib/detox/index.cjs +5098 -7344
  46. package/dist-lib/detox/jest-environment.cjs +4 -1
  47. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  48. package/dist-lib/expo-swift-bundle.cjs +602 -152
  49. package/dist-lib/expo-swift-metadata.cjs +1 -1
  50. package/dist-lib/expo-swift-metadata.mjs +1 -1
  51. package/dist-lib/home-paths.cjs +1 -1
  52. package/dist-lib/host/bridge-host.cjs +688 -194
  53. package/dist-lib/host/fetch-proxy-handler.cjs +6 -3
  54. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  55. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  56. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  57. package/dist-lib/host/websocket-proxy.cjs +1 -1
  58. package/dist-lib/index.cjs +247 -11
  59. package/dist-lib/jump-to-source-babel.cjs +1 -1
  60. package/dist-lib/jump-to-source-native.cjs +1 -1
  61. package/dist-lib/kotlin-host.cjs +1 -1
  62. package/dist-lib/menu.cjs +1 -1
  63. package/dist-lib/menu.mjs +1 -1
  64. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  65. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  66. package/dist-lib/metro-production-bundle.cjs +10 -1
  67. package/dist-lib/metro-production-bundle.mjs +12 -1
  68. package/dist-lib/metro.cjs +155 -5
  69. package/dist-lib/native-app-identity-project.cjs +43 -5
  70. package/dist-lib/native-app-identity-project.mjs +43 -5
  71. package/dist-lib/native-app-identity.cjs +1 -1
  72. package/dist-lib/native-app-identity.mjs +1 -1
  73. package/dist-lib/native-firebase-metadata.cjs +1 -1
  74. package/dist-lib/native-firebase-metadata.mjs +1 -1
  75. package/dist-lib/plist.cjs +1 -1
  76. package/dist-lib/plist.mjs +1 -1
  77. package/dist-lib/profiles.cjs +21 -1
  78. package/dist-lib/public-brand.cjs +1 -1
  79. package/dist-lib/public-origins-lib-esm.json +73 -27
  80. package/dist-lib/public-origins-lib-static.json +1 -1
  81. package/dist-lib/public-origins-lib.json +563 -183
  82. package/dist-lib/react-native-host-modules.cjs +1 -1
  83. package/dist-lib/react-native-host-modules.mjs +1 -1
  84. package/dist-lib/reap-browser.cjs +964 -0
  85. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  86. package/dist-lib/sdk.cjs +38 -5
  87. package/dist-lib/sdk.mjs +38 -5
  88. package/dist-lib/skills.cjs +1031 -530
  89. package/dist-lib/swift-compile.cjs +298 -86
  90. package/dist-lib/swift-compile.mjs +298 -86
  91. package/dist-lib/swift-package.cjs +53 -4
  92. package/dist-lib/swift-package.mjs +52 -4
  93. package/dist-lib/swift-submit.cjs +2 -2
  94. package/dist-lib/swift-submit.mjs +2 -2
  95. package/dist-lib/swift-toolchain.cjs +25 -44
  96. package/dist-lib/swift.cjs +1 -1
  97. package/dist-lib/vite-swift.cjs +603 -114
  98. package/dist-lib/vite.cjs +65 -3
  99. package/dist-lib/worklet-executable.cjs +1 -1
  100. package/dist-lib/worklet-executable.mjs +1 -1
  101. package/dist-types/packages/peach-engine/src/engine/clipboardContract.d.ts +7 -0
  102. package/dist-types/packages/peach-engine/src/engine/glass-material.d.ts +1 -1
  103. package/dist-types/packages/peach-engine/src/engine/image-loader.d.ts +2 -0
  104. package/dist-types/packages/peach-engine/src/engine/inspect-outline.d.ts +2 -1
  105. package/dist-types/packages/peach-engine/src/engine/liquid-glass.d.ts +1 -0
  106. package/dist-types/packages/peach-engine/src/engine/paint-boundary.d.ts +4 -1
  107. package/dist-types/packages/peach-engine/src/render-worker/host-service-protocol.d.ts +7 -0
  108. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime-kind.d.ts +24 -0
  109. package/dist-types/packages/peach-engine/src/render-worker/worklet-runtime.d.ts +4 -2
  110. package/dist-types/packages/peach-engine/src/rolldown-bundle-inventory.d.ts +1 -1
  111. package/dist-types/packages/peach-engine/src/settings/devices.d.ts +1 -0
  112. package/dist-types/packages/peach-globals/src/clipboardBridgeContract.d.ts +18 -0
  113. package/dist-types/packages/peach-globals/src/compositorBridgeContract.d.ts +10 -1
  114. package/dist-types/packages/peach-globals/src/index.d.ts +2 -2
  115. package/dist-types/packages/peach-globals/src/nodeContract.d.ts +1 -0
  116. package/dist-types/packages/peach-kit/src/capabilities.d.ts +1 -0
  117. package/package.json +1 -1
  118. package/runtime-companion.json +1 -1
  119. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CFString.h +2 -0
  120. package/sdk/ios/System/Library/Frameworks/CoreFoundation.framework/Headers/CoreFoundation.h +54 -0
  121. package/sdk/ios/System/Library/Frameworks/Foundation.framework/Headers/Foundation.h +23 -4
  122. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStore.h +439 -0
  123. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreCopySpecific.h +216 -0
  124. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCDynamicStoreKey.h +267 -0
  125. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetwork.h +204 -0
  126. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConfiguration.h +1393 -0
  127. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkConnection.h +568 -0
  128. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCNetworkReachability.h +369 -0
  129. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferences.h +473 -0
  130. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesPath.h +179 -0
  131. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCPreferencesSetSpecific.h +95 -0
  132. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SCSchemaDefinitions.h +2395 -0
  133. package/sdk/ios/System/Library/Frameworks/SystemConfiguration.framework/Headers/SystemConfiguration.h +184 -0
  134. package/sdk/ios/usr/include/_ctype.h +388 -0
  135. package/sdk/ios/usr/include/_inttypes.h +296 -0
  136. package/sdk/ios/usr/include/_locale.h +83 -0
  137. package/sdk/ios/usr/include/_locale_posix2008.h +65 -0
  138. package/sdk/ios/usr/include/_time.h +207 -0
  139. package/sdk/ios/usr/include/ctype.h +70 -0
  140. package/sdk/ios/usr/include/dispatch/dispatch.h +69 -6
  141. package/sdk/ios/usr/include/inttypes.h +35 -0
  142. package/sdk/ios/usr/include/libkern/OSByteOrder.h +315 -0
  143. package/sdk/ios/usr/include/libkern/machine/OSByteOrder.h +147 -0
  144. package/sdk/ios/usr/include/locale.h +59 -0
  145. package/sdk/ios/usr/include/runetype.h +118 -0
  146. package/sdk/ios/usr/include/setjmp.h +99 -0
  147. package/sdk/ios/usr/include/sys/_types/_clock_t.h +32 -0
  148. package/sdk/ios/usr/include/sys/_types/_ct_rune_t.h +33 -0
  149. package/sdk/ios/usr/include/sys/_types/_rune_t.h +32 -0
  150. package/sdk/ios/usr/include/sys/_types/_time_t.h +32 -0
  151. package/sdk/ios/usr/include/sys/_types/_wint_t.h +33 -0
  152. package/sdk/ios/usr/include/sys/cdefs.h +2 -0
  153. package/sdk/ios/usr/include/time.h +67 -2
  154. package/src/bridge-contract.ts +42 -0
  155. package/src/chromium-admission.ts +196 -0
  156. package/src/host/bridge-host.ts +6 -43
  157. package/src/host/rolldown-bundle-forward.ts +4 -1
  158. package/src/launch-deadline.ts +74 -0
  159. package/src/nitro-adapter.lock.json +3 -3
  160. package/src/profiles.ts +21 -0
  161. package/src/react-native-coverage/capability-reference-resolution.ts +402 -0
  162. package/src/react-native-coverage/capability-source-references.ts +1296 -0
  163. package/src/react-native-coverage/native-typescript-parser.ts +74 -0
  164. package/src/react-native-coverage/project-aliases.ts +207 -0
  165. package/src/react-native-coverage/verified-reach.ts +47 -0
  166. package/src/reap-browser.ts +1019 -0
  167. package/src/skills/builtin/a11y-review.ts +1 -1
  168. package/src/skills/builtin/perf-profile.ts +1 -1
  169. package/src/skills/builtin/screenshot-all.ts +1 -1
  170. package/src/skills/builtin/visual-diff.ts +1 -1
  171. package/src/swift-compile.ts +109 -57
  172. package/src/swift-coverage/indexdump.ts +80 -0
  173. package/src/swift-coverage/indexing.ts +147 -0
  174. package/src/swift-coverage/package.ts +230 -0
  175. package/src/swift-coverage/provenance.ts +47 -0
  176. package/src/swift-coverage/reader.ts +81 -0
  177. package/src/swift-coverage/source.ts +252 -0
  178. package/src/swift-coverage/types.ts +58 -0
  179. package/src/swift-coverage/xcode-assets.ts +175 -0
  180. package/src/swift-coverage/xcode-bridging.ts +160 -0
  181. package/src/swift-coverage/xcode-packages.ts +251 -0
  182. package/src/swift-coverage/xcode-strings.ts +78 -0
  183. package/src/swift-coverage/xcode.ts +656 -0
  184. package/src/swift-distribution.lock.json +8 -8
  185. package/src/swift-host.ts +21 -1
  186. package/src/swift-objc-compile.ts +7 -3
  187. package/src/swift-objc-import.ts +191 -27
  188. package/src/swift-objc-metadata.ts +2 -2
  189. package/src/swift-objc-standin.ts +9 -2
  190. package/src/swift-package-manifest.ts +134 -13
  191. package/src/swift-package.ts +69 -4
  192. package/src/swift-standins.ts +4 -1
  193. package/src/swift-submit.ts +2 -1
  194. package/src/swift-toolchain.ts +36 -61
  195. package/src/worker-system-chunks.ts +3 -10
  196. package/src/xcode-project.ts +5 -5
  197. package/detox/attempt-events.cjs +0 -914
  198. package/detox/attempt-events.d.cts +0 -113
  199. package/detox/motion-change.cjs +0 -524
  200. package/detox/motion-change.d.cts +0 -140
  201. package/detox/motion-leg-starts.cjs +0 -20
  202. package/detox/motion-leg-starts.d.cts +0 -8
  203. package/detox/proof-frame.cjs +0 -190
  204. package/detox/record-block-execution.cjs +0 -78
@@ -0,0 +1,1019 @@
1
+ // canonical playwright chrome reaper for any launcher that can be killed
2
+ // mid-run (the wave kicker, deploy/runtime validators, probe loops).
3
+ //
4
+ // playwright's `browser.close()` does NOT reliably reap the chrome process tree
5
+ // when the launching node process is killed (a TaskStop SIGTERM, or — under
6
+ // OOM — `close()` hangs and node gets SIGKILLed): chrome's gpu/renderer/network
7
+ // children reparent to init and survive. a launcher run repeatedly inside a
8
+ // long-lived agent session accumulates them — one 4h session leaked ~200
9
+ // chromes and drove the machine to 0.2GB-free swap-thrash, which then MIMICS
10
+ // every Zero infra failure (zero-cache timeouts, CVR resets, replica drift)
11
+ // and burns a night on confounded RCAs. install this on every launcher.
12
+ //
13
+ // the prior implementation tracked chrome by `pgrep -f ms-playwright/chromium`
14
+ // — that filter never matched a system Chrome launch and so was a no-op in the
15
+ // default path, leaking the renderer + gpu tree on every aborted launch and
16
+ // pegging CPU box-wide (real-world incident 2026-06-20). the fix: track the
17
+ // browser's own root pid through BrowserServer.process() or Chromium's
18
+ // SystemInfo.getProcessInfo CDP endpoint, then recursively SIGKILL its tree.
19
+ // playwright Browser does not expose process(), so a Browser launch must use
20
+ // the CDP path; a persistent context reaches the Browser through browser().
21
+ //
22
+ // CAUTION for manual cleanup: do NOT reap a stray canvas with
23
+ // `pgrep -f sootsim-playwright-host` (or any shared profile-prefix match). that
24
+ // mkdtemp prefix is shared by EVERY agent's playwright-driver canvas, so a
25
+ // naive kill hits co-tenant sessions' live sims, not just yours (near-incident
26
+ // 2026-07-08: a cleanup pass targeted another session's active verify canvas).
27
+ // this reaper and the CLI driver both key on the UNIQUE mkdtemp'd profile dir
28
+ // plus an owner-pid watchdog precisely to avoid that. if a launcher used
29
+ // launchReaped it already self-reaps on exit; if you must reap by hand, match
30
+ // your own launch's full profile dir, never the prefix.
31
+ //
32
+ // DO NOT retry-loop a launcher against a wedged or slow target. each aborted /
33
+ // timed-out `peach open` (or any launch) spawns a fresh browser tree — under
34
+ // the bundled chromium_headless_shell that is a software-render process per
35
+ // attempt, and a pile of them pegs every core faster than the reaper can catch
36
+ // them (incident 2026-07-08: repeated `peach open` retries against a wedged
37
+ // mobile stack spawned headless_shells that outran the reap and drove a load
38
+ // emergency). a connect-timeout means STOP and diagnose (load, stack health,
39
+ // does the bundle/engine even boot), never retry the open; reuse ONE persistent
40
+ // sim tab + reload, and launch GPU Chrome for Testing, not headless_shell.
41
+
42
+ import * as childProcess from 'node:child_process'
43
+ import { execFileSync, execSync } from 'node:child_process'
44
+ import { randomUUID } from 'node:crypto'
45
+ import * as fs from 'node:fs'
46
+ import * as os from 'node:os'
47
+ import * as path from 'node:path'
48
+ import { acquireChromiumAdmission, readChromiumQueue } from './chromium-admission.ts'
49
+ import { startLaunchDeadline } from './launch-deadline.ts'
50
+ import { listProcessChildren } from './process-group.ts'
51
+
52
+ export type BrowserLaunchRuntime = {
53
+ platform: NodeJS.Platform
54
+ env: Readonly<Record<string, string | undefined>>
55
+ }
56
+
57
+ // keep chromium's main process in the caller's cgroup with its children.
58
+ export const LINUX_CHROME_SCOPE_ENV = {
59
+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/nonexistent/chrome-session-bus',
60
+ }
61
+
62
+ export type BrowserLaunchPolicy = {
63
+ runtime?: BrowserLaunchRuntime
64
+ processCommand?: (pid: number) => string
65
+ processIdentity?: (pid: number) => string | null
66
+ admission?: ChromiumLaunchAdmission
67
+ }
68
+
69
+ export type ChromiumLaunchAdmission = {
70
+ signal: AbortSignal
71
+ acquire: () => Promise<() => void>
72
+ }
73
+
74
+ export function reserveChromiumAdmission(signal?: AbortSignal): Promise<() => void> {
75
+ return acquireChromiumAdmission({
76
+ fs,
77
+ os,
78
+ path,
79
+ childProcess,
80
+ label: process.argv.slice(1, 3).join(' '),
81
+ readQueue: readChromiumQueue,
82
+ signal,
83
+ })
84
+ }
85
+
86
+ type BrowserCdpSession = {
87
+ send: (method: string) => Promise<unknown>
88
+ detach?: () => Promise<void>
89
+ }
90
+
91
+ const discoveredChromePids = new WeakMap<object, number>()
92
+ type TrackedProcess = {
93
+ pid: number
94
+ identity: string
95
+ readIdentity: (pid: number) => string | null
96
+ }
97
+
98
+ const discoveredChromeProcesses = new WeakMap<object, TrackedProcess>()
99
+ const reapPids = new Map<number, TrackedProcess>()
100
+ let installed = false
101
+
102
+ // shape just enough of playwright's Browser to read its root chrome pid. we
103
+ // keep this loose so launchReaped's generic stays compatible with both Browser
104
+ // and BrowserContext returns (the latter is what launchPersistentContext gives).
105
+ type WithProcess = {
106
+ process?: () => { pid?: number } | null
107
+ on?: (event: string, fn: () => void) => unknown
108
+ browser?: () => WithProcess | null
109
+ close?: () => Promise<void> | void
110
+ kill?: () => Promise<void> | void
111
+ newBrowserCDPSession?: () => Promise<BrowserCdpSession>
112
+ }
113
+
114
+ function currentRuntime(): BrowserLaunchRuntime {
115
+ return { platform: process.platform, env: process.env }
116
+ }
117
+
118
+ function processCommand(pid: number): string {
119
+ return execFileSync('/bin/ps', ['-p', String(pid), '-o', 'command='], {
120
+ encoding: 'utf8',
121
+ }).trim()
122
+ }
123
+
124
+ function processIdentity(pid: number): string | null {
125
+ try {
126
+ const identity = execFileSync(
127
+ '/bin/ps',
128
+ ['-p', String(pid), '-o', 'lstart=', '-o', 'command='],
129
+ { encoding: 'utf8' },
130
+ ).trim()
131
+ return identity || null
132
+ } catch {
133
+ return null
134
+ }
135
+ }
136
+
137
+ // only GPU-less Linux hosts that identify themselves may use Playwright's
138
+ // software-only chromium_headless_shell: the remote Linux builder, GitHub Actions Linux runners, the
139
+ // cf-factory container, whose image sets CONTRAST_CF_FACTORY_CONTAINER, and a
140
+ // run whose compositor draws in the native linux host
141
+ // (PEACH_NATIVE_COMPOSITOR=1, packages/peach-desktop/node), where chrome draws
142
+ // no part of the simulator. generic CI flags on a developer machine do not
143
+ // weaken the hardware-GPU requirement, and an unrecognized host never falls
144
+ // back to software rendering.
145
+ export function softwareChromeAllowed(
146
+ runtime: BrowserLaunchRuntime = currentRuntime(),
147
+ ): boolean {
148
+ if (runtime.platform !== 'linux') return false
149
+ return (
150
+ runtime.env.CONTRAST_REMOTE_BUILD === 'linux' ||
151
+ (runtime.env.GITHUB_ACTIONS === 'true' && runtime.env.RUNNER_OS === 'Linux') ||
152
+ runtime.env.CONTRAST_CF_FACTORY_CONTAINER === '1' ||
153
+ runtime.env.PEACH_NATIVE_COMPOSITOR === '1'
154
+ )
155
+ }
156
+
157
+ function isSoftwareRendererArgument(value: unknown): boolean {
158
+ const arg = String(value)
159
+ return (
160
+ /^--disable-gpu(?:=.*)?$/i.test(arg) ||
161
+ /^--enable-unsafe-swiftshader(?:=.*)?$/i.test(arg) ||
162
+ /^--use-angle=(?:swiftshader|swiftshader-webgl)$/i.test(arg) ||
163
+ /^--use-gl=swiftshader$/i.test(arg)
164
+ )
165
+ }
166
+
167
+ function softwareRendererArgumentInText(command: string): string | null {
168
+ const unsafe = command.match(
169
+ /(?:^|\s)(--disable-gpu(?:=[^\s]+)?|--enable-unsafe-swiftshader(?:=[^\s]+)?|--use-angle=(?:swiftshader|swiftshader-webgl)|--use-gl=swiftshader)(?=\s|$)/i,
170
+ )
171
+ return unsafe?.[1] ?? null
172
+ }
173
+
174
+ function expectedAngle(platform: NodeJS.Platform): string {
175
+ if (platform === 'darwin') return 'metal'
176
+ if (platform === 'linux') return 'vulkan'
177
+ return 'default'
178
+ }
179
+
180
+ // validate the argv Chrome actually received. this catches launch wrappers or
181
+ // Playwright defaults that mutate the options after gpuChromeLaunchOptions.
182
+ export function assertGpuBrowserCommand(
183
+ command: string,
184
+ runtime: BrowserLaunchRuntime = currentRuntime(),
185
+ ): void {
186
+ if (softwareChromeAllowed(runtime)) return
187
+ const unsafe = softwareRendererArgumentInText(command)
188
+ if (unsafe) {
189
+ throw new Error(
190
+ `[reap-browser] refused software-rendering Chrome process argument ${unsafe}`,
191
+ )
192
+ }
193
+ const angle = expectedAngle(runtime.platform)
194
+ const args = command.split(/\s+/)
195
+ if (!args.includes(`--use-angle=${angle}`) || !args.includes('--enable-gpu')) {
196
+ throw new Error(
197
+ `[reap-browser] Chrome process did not retain the required ${angle} GPU arguments`,
198
+ )
199
+ }
200
+ for (const name of ['--enable-features=', '--disable-features=']) {
201
+ const lists = args
202
+ .filter((arg) => arg.startsWith(name))
203
+ .map((arg) => arg.slice(name.length).split(',').filter(Boolean))
204
+ const kept = new Set(lists.at(-1) ?? [])
205
+ const dropped = lists
206
+ .slice(0, -1)
207
+ .flat()
208
+ .filter((feature) => !kept.has(feature))
209
+ if (dropped.length > 0) {
210
+ throw new Error(
211
+ `[reap-browser] Chrome keeps only its last ${name.slice(0, -1)} switch, which dropped ${dropped.join(',')}; add them to the merged list in packages/peachsim/src/reap-browser.ts`,
212
+ )
213
+ }
214
+ }
215
+ if (
216
+ runtime.platform === 'darwin' &&
217
+ command.includes('/Applications/Google Chrome.app/')
218
+ ) {
219
+ throw new Error(
220
+ "[reap-browser] refused the user's installed Google Chrome; use Playwright channel chromium",
221
+ )
222
+ }
223
+ }
224
+
225
+ function collectGpuRendererStrings(info: unknown): string[] {
226
+ if (!info || typeof info !== 'object') return []
227
+ const record = info as Record<string, unknown>
228
+ const gpu = record.gpu
229
+ if (!gpu || typeof gpu !== 'object') return []
230
+ const gpuRecord = gpu as Record<string, unknown>
231
+ const values: string[] = []
232
+ const aux = gpuRecord.auxAttributes
233
+ if (aux && typeof aux === 'object') {
234
+ for (const value of Object.values(aux)) {
235
+ if (typeof value === 'string') values.push(value)
236
+ }
237
+ }
238
+ const devices = gpuRecord.devices
239
+ if (Array.isArray(devices)) {
240
+ for (const device of devices) {
241
+ if (!device || typeof device !== 'object') continue
242
+ for (const value of Object.values(device)) {
243
+ if (typeof value === 'string') values.push(value)
244
+ }
245
+ }
246
+ }
247
+ return values
248
+ }
249
+
250
+ function browserProcessPid(info: unknown): number | null {
251
+ if (!info || typeof info !== 'object') return null
252
+ const record = info as Record<string, unknown>
253
+ if (!Array.isArray(record.processInfo)) return null
254
+ for (const entry of record.processInfo) {
255
+ if (!entry || typeof entry !== 'object') continue
256
+ const processInfo = entry as Record<string, unknown>
257
+ if (
258
+ processInfo.type === 'browser' &&
259
+ typeof processInfo.id === 'number' &&
260
+ Number.isInteger(processInfo.id) &&
261
+ processInfo.id > 0
262
+ ) {
263
+ return processInfo.id
264
+ }
265
+ }
266
+ return null
267
+ }
268
+
269
+ // validate the renderer Chrome reports over CDP, not only its requested flags.
270
+ // metal is mandatory on local macOS because a valid-looking argv can still
271
+ // initialize ANGLE's CPU renderer.
272
+ export function assertGpuRendererInfo(
273
+ info: unknown,
274
+ runtime: BrowserLaunchRuntime = currentRuntime(),
275
+ ): void {
276
+ if (softwareChromeAllowed(runtime)) return
277
+ const renderers = collectGpuRendererStrings(info)
278
+ const summary = renderers.join(' | ')
279
+ if (!summary || /swiftshader|llvmpipe|software rasterizer/i.test(summary)) {
280
+ throw new Error(
281
+ `[reap-browser] Chrome reported a software renderer${summary ? `: ${summary}` : ''}`,
282
+ )
283
+ }
284
+ if (runtime.platform === 'darwin' && !/metal/i.test(summary)) {
285
+ throw new Error(
286
+ `[reap-browser] Chrome did not report an ANGLE Metal renderer: ${summary}`,
287
+ )
288
+ }
289
+ }
290
+
291
+ function rootChromePid(b: unknown): number | null {
292
+ if (b && typeof b === 'object') {
293
+ const discovered = discoveredChromePids.get(b)
294
+ if (discovered !== undefined) return discovered
295
+ }
296
+ const w = b as WithProcess
297
+ // direct: BrowserServer exposes .process() → ChildProcess (with .pid)
298
+ if (w && typeof w.process === 'function') {
299
+ try {
300
+ const p = w.process()
301
+ if (p && typeof p.pid === 'number' && p.pid > 0) return p.pid
302
+ } catch {}
303
+ }
304
+ // indirect: a BrowserContext from launchPersistentContext keeps its browser
305
+ // handle on .browser(); reach through it to the chrome root.
306
+ if (w && typeof w.browser === 'function') {
307
+ try {
308
+ const child = w.browser()
309
+ if (child) return rootChromePid(child)
310
+ } catch {}
311
+ }
312
+ return null
313
+ }
314
+
315
+ // recursively SIGKILL pid and all its descendants. chrome's helpers
316
+ // (gpu/renderer/utility) are not all children of one pid and some spawn after
317
+ // launch, so we walk the tree at reap time to catch them all. postorder: kill
318
+ // children BEFORE the root so reparenting can't strand them.
319
+ export function killTree(pid: number): void {
320
+ let kids: number[] = []
321
+ try {
322
+ kids = listProcessChildren([pid])
323
+ } catch {
324
+ // no children
325
+ }
326
+ for (const k of kids) killTree(k)
327
+ try {
328
+ process.kill(pid, 'SIGKILL')
329
+ } catch {
330
+ // already dead
331
+ }
332
+ }
333
+
334
+ function killOwnedTree(tracked: TrackedProcess): void {
335
+ if (tracked.readIdentity(tracked.pid) !== tracked.identity) return
336
+ killTree(tracked.pid)
337
+ }
338
+
339
+ function trackReapPid(
340
+ pid: number,
341
+ readIdentity: (pid: number) => string | null = processIdentity,
342
+ ): TrackedProcess | null {
343
+ const identity = readIdentity(pid)
344
+ if (identity === null) return null
345
+ const current = reapPids.get(pid)
346
+ if (current?.identity === identity && current.readIdentity === readIdentity) {
347
+ return current
348
+ }
349
+ const tracked = { pid, identity, readIdentity }
350
+ reapPids.set(pid, tracked)
351
+ installReaper()
352
+ return tracked
353
+ }
354
+
355
+ function untrackReapPid(tracked: TrackedProcess): void {
356
+ if (reapPids.get(tracked.pid) === tracked) reapPids.delete(tracked.pid)
357
+ }
358
+
359
+ function browserControl(b: unknown): WithProcess | null {
360
+ const candidate = b as WithProcess
361
+ if (!candidate || typeof candidate !== 'object') return null
362
+ if (
363
+ typeof candidate.newBrowserCDPSession === 'function' ||
364
+ typeof candidate.process === 'function'
365
+ ) {
366
+ return candidate
367
+ }
368
+ if (typeof candidate.browser !== 'function') return null
369
+ try {
370
+ const browser = candidate.browser()
371
+ return browser ? browserControl(browser) : null
372
+ } catch {
373
+ return null
374
+ }
375
+ }
376
+
377
+ function registerChromePid(
378
+ browser: unknown,
379
+ control: WithProcess,
380
+ pid: number,
381
+ readIdentity: (pid: number) => string | null = processIdentity,
382
+ ): void {
383
+ if (browser && typeof browser === 'object') discoveredChromePids.set(browser, pid)
384
+ discoveredChromePids.set(control, pid)
385
+ const tracked = trackReapPid(pid, readIdentity)
386
+ if (tracked === null) return
387
+ if (browser && typeof browser === 'object') {
388
+ discoveredChromeProcesses.set(browser, tracked)
389
+ }
390
+ discoveredChromeProcesses.set(control, tracked)
391
+ }
392
+
393
+ async function discoverChromePid(browser: unknown): Promise<number | null> {
394
+ const known = rootChromePid(browser)
395
+ if (known !== null) return known
396
+ const control = browserControl(browser)
397
+ if (!control || typeof control.newBrowserCDPSession !== 'function') return null
398
+ const session = await control.newBrowserCDPSession()
399
+ try {
400
+ const pid = browserProcessPid(await session.send('SystemInfo.getProcessInfo'))
401
+ if (pid === null) return null
402
+ registerChromePid(browser, control, pid)
403
+ return pid
404
+ } finally {
405
+ await session.detach?.()
406
+ }
407
+ }
408
+
409
+ async function rejectLaunchedBrowser(browser: unknown): Promise<void> {
410
+ const tracked =
411
+ browser && typeof browser === 'object'
412
+ ? discoveredChromeProcesses.get(browser)
413
+ : undefined
414
+ if (tracked) {
415
+ killOwnedTree(tracked)
416
+ untrackReapPid(tracked)
417
+ return
418
+ }
419
+ const candidate = browser as WithProcess
420
+ if (candidate && typeof candidate.close === 'function') {
421
+ try {
422
+ await candidate.close()
423
+ } catch {}
424
+ }
425
+ }
426
+
427
+ async function validateLaunchedGpuBrowser<B>(
428
+ browser: B,
429
+ runtime: BrowserLaunchRuntime,
430
+ rendererTarget?: (browser: B) => Promise<unknown>,
431
+ commandForPid: (pid: number) => string = processCommand,
432
+ readIdentity: (pid: number) => string | null = processIdentity,
433
+ ): Promise<void> {
434
+ if (softwareChromeAllowed(runtime)) return
435
+ const root = rootChromePid(browser)
436
+ const launchedControl = browserControl(browser)
437
+ if (root !== null && launchedControl) {
438
+ registerChromePid(browser, launchedControl, root, readIdentity)
439
+ }
440
+ if (root !== null && (runtime.platform === 'darwin' || runtime.platform === 'linux')) {
441
+ assertGpuBrowserCommand(commandForPid(root), runtime)
442
+ }
443
+
444
+ const rendererBrowser = rendererTarget ? await rendererTarget(browser) : browser
445
+ const control = browserControl(rendererBrowser)
446
+ if (control && typeof control.newBrowserCDPSession === 'function') {
447
+ const session = await control.newBrowserCDPSession()
448
+ try {
449
+ const pid = browserProcessPid(await session.send('SystemInfo.getProcessInfo'))
450
+ if (pid === null) {
451
+ throw new Error('[reap-browser] Chrome did not report its browser process id')
452
+ }
453
+ registerChromePid(browser, control, pid, readIdentity)
454
+ if (rendererBrowser && typeof rendererBrowser === 'object') {
455
+ discoveredChromePids.set(rendererBrowser, pid)
456
+ }
457
+ if (runtime.platform === 'darwin' || runtime.platform === 'linux') {
458
+ assertGpuBrowserCommand(commandForPid(pid), runtime)
459
+ }
460
+ assertGpuRendererInfo(await session.send('SystemInfo.getInfo'), runtime)
461
+ return
462
+ } finally {
463
+ await session.detach?.()
464
+ }
465
+ }
466
+
467
+ throw new Error('[reap-browser] could not validate the launched Chrome GPU renderer')
468
+ }
469
+
470
+ // claim before launching and handle SIGINT, SIGTERM and SIGHUP. the owner
471
+ // closes the browser after its asynchronous cleanup; signal termination does
472
+ // not run the process-exit sweep.
473
+ let signalShutdownClaimed = false
474
+ export function claimSignalShutdown(): void {
475
+ signalShutdownClaimed = true
476
+ }
477
+
478
+ function installReaper(): void {
479
+ if (installed) return
480
+ installed = true
481
+ const reap = () => {
482
+ for (const tracked of reapPids.values()) killOwnedTree(tracked)
483
+ }
484
+ // node runs every listener for a signal in ONE synchronous pass, so a
485
+ // process.exit(0) in here terminates the process before any later listener
486
+ // runs and before any awaited work in one gets a turn of the event loop. that
487
+ // silently destroyed the evidence of every killed wave: the driver's own
488
+ // handler is registered after this one, so it never ran, and the run ended at
489
+ // exit 0 with no closeout, no verdict, and a leaked wave lock. reaping first
490
+ // would be just as wrong for a claimed shutdown, since closeout still needs
491
+ // the browser for its final capture. the exit sweep below covers both cases,
492
+ // including the driver's hard-exit fallback.
493
+ if (!signalShutdownClaimed) {
494
+ process.on('SIGTERM', () => {
495
+ reap()
496
+ process.exit(0)
497
+ })
498
+ process.on('SIGINT', () => {
499
+ reap()
500
+ process.exit(0)
501
+ })
502
+ }
503
+ process.on('exit', reap)
504
+ }
505
+
506
+ // wrap a `chromium.launch(...)` so its chrome tree is force-reaped if this
507
+ // process is killed mid-run, AND hand back a `reapNow()` that force-reaps THIS
508
+ // launch's tree on demand. tracks by the browser's own root pid — works for
509
+ // Chrome for Testing, bundled playwright chromium, AND launchPersistentContext
510
+ // (we reach through context.browser()). when the root
511
+ // pid can't be obtained (very old playwright, unusual launcher), launch still
512
+ // returns successfully — the wrapper just installs no reaper, and the caller's
513
+ // browser.close() / process exit is the only teardown (same as no wrap).
514
+ //
515
+ // const { browser, reapNow } = await launchReapedScoped(() => chromium.launch())
516
+ export async function launchReapedScoped<T>(
517
+ launch: () => Promise<T>,
518
+ readIdentity: (pid: number) => string | null = processIdentity,
519
+ admission?: ChromiumLaunchAdmission,
520
+ ): Promise<{ browser: T; reapNow: () => void }> {
521
+ // every reaped launch takes a host-wide chromium slot until it closes
522
+ const releaseAdmission = await (admission
523
+ ? admission.acquire()
524
+ : reserveChromiumAdmission())
525
+ let browser: T
526
+ try {
527
+ admission?.signal.throwIfAborted()
528
+ browser = await launch()
529
+ if (admission?.signal.aborted) {
530
+ await rejectLaunchedBrowser(browser)
531
+ admission.signal.throwIfAborted()
532
+ }
533
+ } catch (err) {
534
+ releaseAdmission()
535
+ throw err
536
+ }
537
+ const mine = new Set<TrackedProcess>()
538
+ let closed = false
539
+ const reapNow = () => {
540
+ closed = true
541
+ for (const tracked of mine) {
542
+ killOwnedTree(tracked)
543
+ untrackReapPid(tracked)
544
+ }
545
+ mine.clear()
546
+ admission?.signal.removeEventListener('abort', reapNow)
547
+ releaseAdmission()
548
+ }
549
+ // subscribe before asynchronous pid discovery: a browser can disconnect
550
+ // during CDP discovery while its launching process remains alive.
551
+ const evented = browserControl(browser) ?? (browser as WithProcess)
552
+ if (typeof evented.on === 'function') {
553
+ const disconnectEvent =
554
+ typeof evented.newBrowserCDPSession === 'function' ? 'disconnected' : 'close'
555
+ evented.on(disconnectEvent, reapNow)
556
+ }
557
+ admission?.signal.addEventListener('abort', reapNow, { once: true })
558
+ if (admission?.signal.aborted) reapNow()
559
+
560
+ let root = rootChromePid(browser)
561
+ if (root === null && !closed) {
562
+ try {
563
+ root = await discoverChromePid(browser)
564
+ } catch {
565
+ root = null
566
+ }
567
+ }
568
+ if (root != null) {
569
+ const tracked = trackReapPid(root, readIdentity)
570
+ if (tracked !== null) mine.add(tracked)
571
+ }
572
+ if (closed) {
573
+ reapNow()
574
+ admission?.signal.throwIfAborted()
575
+ throw new Error('[reap-browser] browser disconnected during launch')
576
+ }
577
+ return { browser, reapNow }
578
+ }
579
+
580
+ // const browser = await launchReaped(() => chromium.launch({ headless: true }))
581
+ export async function launchReaped<T>(
582
+ launch: () => Promise<T>,
583
+ readIdentity: (pid: number) => string | null = processIdentity,
584
+ admission?: ChromiumLaunchAdmission,
585
+ ): Promise<T> {
586
+ const { browser } = await launchReapedScoped(launch, readIdentity, admission)
587
+ return browser
588
+ }
589
+
590
+ // force the platform-native ANGLE backend so real Chrome actually binds the
591
+ // GPU. headless Chrome for Testing still picks SwiftShader for WebGL/CanvasKit
592
+ // workloads unless --use-angle points at a real backend, and playwright
593
+ // additionally injects --enable-unsafe-swiftshader as a default arg, which lets
594
+ // that fallback happen silently. three of those software-rendering chromes
595
+ // pegged the box at load 54-148 on 2026-07-05 (the factory
596
+ // headless-runtime-host path). same recipe as
597
+ // packages/peach-engine/test/playwright-shared-browser.ts gpuArgsForPlatform.
598
+ // exported for launchers that can't route through platformChromeLaunch (the root
599
+ // playwright.config.ts builds static launchOptions) but must apply the same
600
+ // GPU-or-fail-loud policy.
601
+ export function gpuChromeArgs(platform: NodeJS.Platform = process.platform): string[] {
602
+ const angle = expectedAngle(platform)
603
+ return [
604
+ // sootsim's compositor renders through skia graphite on webgpu, so a launch
605
+ // without navigator.gpu cannot present a frame at all. chrome enables webgpu
606
+ // by default on gpu-backed macOS but not on every headless configuration,
607
+ // and every caller that renders a sim was passing this by hand. own it here
608
+ // so a launcher cannot silently come up without the only backend there is.
609
+ '--enable-unsafe-webgpu',
610
+ `--use-angle=${angle}`,
611
+ '--enable-gpu',
612
+ '--enable-gpu-rasterization',
613
+ '--enable-zero-copy',
614
+ '--ignore-gpu-blocklist',
615
+ ]
616
+ }
617
+
618
+ // chrome keeps only the LAST --enable-features / --disable-features value on
619
+ // its command line, and playwright appends caller args after its own switches,
620
+ // so any caller feature switch silently replaced playwright's whole list. every
621
+ // launch therefore emits one merged switch per name: playwright's defaults,
622
+ // the caller's features, and ours. assertGpuBrowserCommand reads the launched
623
+ // argv and fails loudly when the last switch drops a feature an earlier one
624
+ // named, so a playwright upgrade that adds a default cannot silently re-enable
625
+ // it here. keep these two lists equal to the installed playwright's chromiumSwitches
626
+ // (node_modules/playwright-core/lib/coreBundle.js, search disabledFeatures).
627
+ const PLAYWRIGHT_DISABLED_FEATURES = [
628
+ 'AimEnabled',
629
+ 'AvoidUnnecessaryBeforeUnloadCheckSync',
630
+ 'BlockOriginHeaderModificationOnRedirect',
631
+ 'BoundaryEventDispatchTracksNodeRemoval',
632
+ 'DestroyProfileOnBrowserClose',
633
+ 'DialMediaRouteProvider',
634
+ 'GlobalMediaControls',
635
+ 'HttpsUpgrades',
636
+ 'LensOverlay',
637
+ 'MediaRouter',
638
+ 'PaintHolding',
639
+ 'ThirdPartyStoragePartitioning',
640
+ 'Translate',
641
+ 'AutoDeElevate',
642
+ 'RenderDocument',
643
+ 'OptimizationHints',
644
+ 'msForceBrowserSignIn',
645
+ 'msEdgeUpdateLaunchServicesPreferredVersion',
646
+ ]
647
+ const PLAYWRIGHT_ENABLED_FEATURES = ['CDPScreenshotNewSurface']
648
+ // chrome fetches network time from google right after startup and, when that
649
+ // response lands about half a second in, rebuilds every certificate verifier.
650
+ // the rebuild marks every http/2 and quic session as going away, and a request
651
+ // bound to one of those sessions at that instant fails with net::ERR_FAILED,
652
+ // which chrome never retries for a module script: a first navigation whose
653
+ // module graph spans that moment loses one random module and never mounts.
654
+ // --disable-background-networking does not cover the time fetch. an automation
655
+ // browser has no use for network time.
656
+ // a react-native-webview page whose framing refusal the sim lifts is a
657
+ // fulfilled response, which chrome files under the public address space, so
658
+ // local network access checks then block that page's navigation to any local
659
+ // origin, a hop no WKWebView ever refuses.
660
+ const DISABLED_FEATURES = ['NetworkTimeServiceQuerying', 'LocalNetworkAccessChecks']
661
+
662
+ // the one --disable-features switch every sim browser launch ends with:
663
+ // playwright's defaults plus ours, since chrome keeps only the last one.
664
+ export function chromeDisabledFeaturesSwitch(): string {
665
+ return `--disable-features=${[...new Set([...PLAYWRIGHT_DISABLED_FEATURES, ...DISABLED_FEATURES])].join(',')}`
666
+ }
667
+
668
+ function mergeFeatureSwitches(args: string[], enabled: string[] = []): string[] {
669
+ const enable = new Set([...PLAYWRIGHT_ENABLED_FEATURES, ...enabled])
670
+ const disable = new Set([...PLAYWRIGHT_DISABLED_FEATURES, ...DISABLED_FEATURES])
671
+ const rest: string[] = []
672
+ for (const arg of args) {
673
+ const match = /^--(enable|disable)-features=(.*)$/.exec(arg)
674
+ if (!match) {
675
+ rest.push(arg)
676
+ continue
677
+ }
678
+ for (const feature of match[2].split(',')) {
679
+ if (feature) (match[1] === 'enable' ? enable : disable).add(feature)
680
+ }
681
+ }
682
+ return [
683
+ ...rest,
684
+ `--enable-features=${[...enable].join(',')}`,
685
+ `--disable-features=${[...disable].join(',')}`,
686
+ ]
687
+ }
688
+
689
+ // Static Playwright configs cannot route their implicit browser launch through
690
+ // launchReapedChrome. Keep the exact GPU/fail-loud launch options here so those
691
+ // configs do not duplicate the unsafe-default stripping literal or drift from
692
+ // the explicit launcher policy.
693
+ export function gpuChromeLaunchOptions(
694
+ opts: Record<string, unknown> = {},
695
+ runtime: BrowserLaunchRuntime = currentRuntime(),
696
+ ): Record<string, unknown> {
697
+ const callerArgs = Array.isArray(opts.args) ? opts.args : []
698
+ const unsafe = callerArgs.find(isSoftwareRendererArgument)
699
+ if (unsafe !== undefined) {
700
+ throw new Error(
701
+ `[reap-browser] refused software-rendering Chrome launch argument ${String(unsafe)}`,
702
+ )
703
+ }
704
+ if (opts.executablePath !== undefined) {
705
+ throw new Error(
706
+ '[reap-browser] executablePath bypasses Playwright Chrome for Testing and is not allowed',
707
+ )
708
+ }
709
+ if (opts.ignoreDefaultArgs === true) {
710
+ throw new Error(
711
+ '[reap-browser] ignoreDefaultArgs=true bypasses required Chrome launch defaults',
712
+ )
713
+ }
714
+ const managedGpuArgs = new Set([
715
+ '--enable-unsafe-webgpu',
716
+ '--enable-gpu',
717
+ '--enable-gpu-rasterization',
718
+ '--enable-zero-copy',
719
+ '--ignore-gpu-blocklist',
720
+ ])
721
+ const unmanagedCallerArgs = callerArgs.filter((arg) => {
722
+ const value = String(arg)
723
+ return !managedGpuArgs.has(value) && !value.startsWith('--use-angle=')
724
+ })
725
+ const callerIgnored = Array.isArray(opts.ignoreDefaultArgs)
726
+ ? opts.ignoreDefaultArgs
727
+ : []
728
+ const ignoredDefaults = [
729
+ ...new Set([...callerIgnored, '--disable-gpu', '--enable-unsafe-swiftshader']),
730
+ ]
731
+ // full chrome on linux asks the user's systemd over the session bus to move
732
+ // its main process into a transient app scope (user.slice, CPUWeight 100)
733
+ // while its children stay in the caller's cgroup, which starves the main
734
+ // process inside a protected compute scope. an unreachable session bus keeps
735
+ // the whole tree where the caller put it.
736
+ const env =
737
+ runtime.platform === 'linux'
738
+ ? {
739
+ ...(opts.env ?? runtime.env),
740
+ ...LINUX_CHROME_SCOPE_ENV,
741
+ }
742
+ : opts.env
743
+ return {
744
+ ...opts,
745
+ ...(env ? { env } : {}),
746
+ // playwright's `chromium` channel is the full Google Chrome for Testing
747
+ // app, not chromium_headless_shell. on macOS it has bundle id
748
+ // com.google.chrome.for.testing, so automation cannot become the target of
749
+ // Dock open/quit events intended for the user's com.google.Chrome browser.
750
+ channel: 'chromium',
751
+ args: mergeFeatureSwitches([
752
+ ...unmanagedCallerArgs,
753
+ ...gpuChromeArgs(runtime.platform),
754
+ ]),
755
+ ignoreDefaultArgs: ignoredDefaults,
756
+ }
757
+ }
758
+
759
+ // playwright's own launch timeout is a wall-clock timer that keeps running
760
+ // while the load governor holds the browser, so the launch runs without it
761
+ // (`timeout: 0`) under a deadline that does not advance during a hold. on
762
+ // expiry the chrome this launch spawned is killed, which rejects the launch.
763
+ const DEFAULT_LAUNCH_TIMEOUT_MS = 180_000
764
+
765
+ export async function launchWithPauseAwareDeadline<B>(
766
+ launch: (opts: Record<string, unknown>) => Promise<B>,
767
+ opts: Record<string, unknown>,
768
+ ): Promise<B> {
769
+ const budget =
770
+ typeof opts.timeout === 'number' ? opts.timeout : DEFAULT_LAUNCH_TIMEOUT_MS
771
+ if (budget === 0) return launch(opts)
772
+ // a unique switch marks this launch's own chrome, so a concurrent launch in
773
+ // this process is never killed by this deadline
774
+ const marker = `--peach-launch-id=${randomUUID()}`
775
+ let expired = false
776
+ // what the expiry sweep saw, so the timeout error reports it
777
+ const cleanupAttempted: number[] = []
778
+ const lookupFailed: number[] = []
779
+ let sweepFailure: string | undefined
780
+ const cancel = startLaunchDeadline(budget, () => {
781
+ expired = true
782
+ let children: number[] = []
783
+ try {
784
+ children = listProcessChildren([process.pid])
785
+ } catch (err) {
786
+ sweepFailure = err instanceof Error ? err.message : String(err)
787
+ }
788
+ for (const pid of children) {
789
+ let marked: boolean
790
+ try {
791
+ marked = processCommand(pid).includes(marker)
792
+ } catch {
793
+ // already gone, or ps could not answer: ownership is unknown
794
+ lookupFailed.push(pid)
795
+ continue
796
+ }
797
+ if (!marked) continue
798
+ cleanupAttempted.push(pid)
799
+ killTree(pid)
800
+ }
801
+ })
802
+ try {
803
+ const args = Array.isArray(opts.args) ? opts.args : []
804
+ return await launch({ ...opts, args: [...args, marker], timeout: 0 })
805
+ } catch (err) {
806
+ if (!expired) throw err
807
+ const observed = [
808
+ sweepFailure
809
+ ? `child listing failed: ${sweepFailure}`
810
+ : cleanupAttempted.length > 0
811
+ ? `marked child pid(s) ${cleanupAttempted.join(', ')} observed, kill attempted (outcome not checked)`
812
+ : lookupFailed.length > 0
813
+ ? 'no marked child confirmed'
814
+ : 'no marked child observed',
815
+ lookupFailed.length > 0
816
+ ? `command lookup failed for pid(s) ${lookupFailed.join(', ')}, ownership unknown`
817
+ : undefined,
818
+ ]
819
+ .filter(Boolean)
820
+ .join('; ')
821
+ throw new Error(
822
+ `[reap-browser] browser launch timed out after ${budget}ms; ${observed}`,
823
+ { cause: err },
824
+ )
825
+ } finally {
826
+ cancel()
827
+ }
828
+ }
829
+
830
+ // build a launch thunk that requires GPU-backed Chrome for Testing (the
831
+ // `chromium` channel -> Metal) locally. this is Playwright's full browser app,
832
+ // with a different macOS identity from the user's Chrome. GitHub Actions Linux
833
+ // runners instead select Playwright's bundled chromium_headless_shell and its
834
+ // sanctioned SwiftShader renderer directly: a GPU-first launch is not viable
835
+ // on dedicated CPU-only runners and can succeed while exposing no WebGL2
836
+ // context. the shell's software-Skia path has no GPU and pegs every core
837
+ // (~2.4x cpu, the documented machine-freeze risk). any
838
+ // render-heavy local launcher wants this: sootsim's CanvasKit/WebGL canvas, and
839
+ // the factory headless-runtime-host that renders + screenshots a project's live
840
+ // app runtime. shared by both launchReapedChrome and
841
+ // launchReapedChromeScoped so platform selection lives in one place.
842
+ function platformChromeLaunch<B>(
843
+ launch: (opts: Record<string, unknown>) => Promise<B>,
844
+ opts: Record<string, unknown>,
845
+ rendererTarget?: (browser: B) => Promise<unknown>,
846
+ policy: BrowserLaunchPolicy = {},
847
+ ): () => Promise<B> {
848
+ return async () => {
849
+ const runtime = policy.runtime ?? currentRuntime()
850
+ if (softwareChromeAllowed(runtime)) {
851
+ return launchWithPauseAwareDeadline(launch, chromeLaunchOptions(opts, runtime))
852
+ }
853
+ const gpuOptions = chromeLaunchOptions(opts, runtime)
854
+ let browser: B
855
+ try {
856
+ browser = await launchWithPauseAwareDeadline(launch, gpuOptions)
857
+ } catch (err) {
858
+ const msg = err instanceof Error ? err.message : String(err)
859
+ const missing =
860
+ /not found at|not installed|Chromium distribution|Executable doesn't exist|No such file/i.test(
861
+ msg,
862
+ )
863
+ if (!missing) throw err
864
+ throw new Error(
865
+ '[reap-browser] Playwright Chrome for Testing is required for local GPU browser work. Run `bun scripts/ops/install-playwright-browsers.ts chromium`.',
866
+ { cause: err },
867
+ )
868
+ }
869
+ try {
870
+ await validateLaunchedGpuBrowser(
871
+ browser,
872
+ runtime,
873
+ rendererTarget,
874
+ policy.processCommand,
875
+ policy.processIdentity,
876
+ )
877
+ } catch (err) {
878
+ await rejectLaunchedBrowser(browser)
879
+ throw err
880
+ }
881
+ return browser
882
+ }
883
+ }
884
+
885
+ // the GitHub Actions Linux implementation must not inherit a Chrome for
886
+ // Testing channel or executable override from its caller. select Playwright's
887
+ // bundled software Chromium and explicitly retain its sanctioned WebGL2-capable
888
+ // SwiftShader renderer instead.
889
+ export function softwareChromeLaunchOptions(
890
+ opts: Record<string, unknown>,
891
+ runtime: BrowserLaunchRuntime = currentRuntime(),
892
+ ): Record<string, unknown> {
893
+ if (opts.ignoreDefaultArgs === true) {
894
+ throw new Error(
895
+ '[reap-browser] ignoreDefaultArgs=true bypasses required Chrome launch defaults',
896
+ )
897
+ }
898
+ if (runtime.platform === 'linux') {
899
+ // native dawn's driver selectors exclude chromium's bundled swiftshader.
900
+ // isolate the browser child; keep the native host's loader and environment.
901
+ const env: Record<string, unknown> = Object.assign(
902
+ {},
903
+ opts.env ?? runtime.env,
904
+ LINUX_CHROME_SCOPE_ENV,
905
+ )
906
+ delete env.VK_DRIVER_FILES
907
+ delete env.VK_ICD_FILENAMES
908
+ opts = { ...opts, env }
909
+ }
910
+ const callerArgs = Array.isArray(opts.args) ? opts.args.map(String) : []
911
+ if (runtime.platform === 'linux' && runtime.env.PEACH_NATIVE_COMPOSITOR === '1') {
912
+ // native workers own the gpu; chromium presents their bitmaps and DOM.
913
+ const native: Record<string, unknown> = {
914
+ ...opts,
915
+ args: [...callerArgs, '--disable-gpu'],
916
+ }
917
+ delete native.channel
918
+ delete native.executablePath
919
+ return native
920
+ }
921
+ const unmanagedCallerArgs = callerArgs.filter((arg) => {
922
+ return (
923
+ !arg.startsWith('--use-angle=') &&
924
+ arg !== '--enable-gpu' &&
925
+ arg !== '--enable-gpu-rasterization' &&
926
+ arg !== '--enable-zero-copy' &&
927
+ arg !== '--ignore-gpu-blocklist' &&
928
+ arg !== '--disable-gpu-watchdog' &&
929
+ arg !== '--enable-skia-graphite' &&
930
+ !/^--enable-unsafe-webgpu(?:=.*)?$/i.test(arg) &&
931
+ !/^--enable-unsafe-swiftshader(?:=.*)?$/i.test(arg)
932
+ )
933
+ })
934
+ const software: Record<string, unknown> = {
935
+ ...opts,
936
+ // playwright's bundled software chromium exposes no navigator.gpu without
937
+ // --enable-unsafe-webgpu plus the Vulkan feature, and the compositor's only
938
+ // backend is webgpu. emitted here rather than per caller so a hosted-linux
939
+ // launch and a local gpu launch agree on what a sim needs.
940
+ args: mergeFeatureSwitches(
941
+ [
942
+ ...unmanagedCallerArgs,
943
+ '--use-angle=swiftshader',
944
+ '--enable-unsafe-swiftshader',
945
+ '--enable-unsafe-webgpu',
946
+ // without Skia Graphite as chromium's own compositor, SwiftShader has no
947
+ // shared-image backing for a WebGPU canvas swap chain at any size: the
948
+ // first configured canvas fails "Could not find SharedImageBackingFactory"
949
+ // and chromium destroys the device mid-capture. compute-only WebGPU
950
+ // still works, so an adapter probe cannot see this.
951
+ '--enable-skia-graphite',
952
+ // the GPU watchdog kills the GPU process when a task outlives its
953
+ // timeout, and SwiftShader precompiling Graphite pipelines on two CPU
954
+ // cores can legitimately outlive it. the cost: a genuinely wedged GPU
955
+ // process now holds its job until the job's own timeout instead of
956
+ // dying fast.
957
+ '--disable-gpu-watchdog',
958
+ ],
959
+ ['Vulkan'],
960
+ ),
961
+ }
962
+ delete software.channel
963
+ delete software.executablePath
964
+ return software
965
+ }
966
+
967
+ export function chromeLaunchOptions(
968
+ opts: Record<string, unknown> = {},
969
+ runtime: BrowserLaunchRuntime = currentRuntime(),
970
+ ): Record<string, unknown> {
971
+ if (signalShutdownClaimed) {
972
+ // the owner needs the browser alive until its asynchronous cleanup finishes.
973
+ opts = { ...opts, handleSIGINT: false, handleSIGTERM: false, handleSIGHUP: false }
974
+ }
975
+ return softwareChromeAllowed(runtime)
976
+ ? softwareChromeLaunchOptions(opts, runtime)
977
+ : gpuChromeLaunchOptions(opts, runtime)
978
+ }
979
+
980
+ // prefer GPU-backed Chrome, reaped. pass the raw `chromium.launch` (or a
981
+ // `(o) => chromium.launchPersistentContext(dir, o)` closure) as `launch`.
982
+ export async function launchReapedChrome<B>(
983
+ launch: (opts: Record<string, unknown>) => Promise<B>,
984
+ opts: Record<string, unknown> = {},
985
+ rendererTarget?: (browser: B) => Promise<unknown>,
986
+ policy: BrowserLaunchPolicy = {},
987
+ ): Promise<B> {
988
+ return launchReaped(
989
+ platformChromeLaunch(launch, opts, rendererTarget, policy),
990
+ policy.processIdentity,
991
+ policy.admission,
992
+ )
993
+ }
994
+
995
+ // same GPU-Chrome preference as launchReapedChrome, but returns the scoped
996
+ // `reapNow()` for launchers with a mid-run teardown (relaunch/dispose) that must
997
+ // force-kill THIS launch's chrome tree on demand instead of only at process exit.
998
+ export async function launchReapedChromeScoped<B>(
999
+ launch: (opts: Record<string, unknown>) => Promise<B>,
1000
+ opts: Record<string, unknown> = {},
1001
+ rendererTarget?: (browser: B) => Promise<unknown>,
1002
+ policy: BrowserLaunchPolicy = {},
1003
+ ): Promise<{ browser: B; reapNow: () => void }> {
1004
+ return launchReapedScoped(
1005
+ platformChromeLaunch(launch, opts, rendererTarget, policy),
1006
+ policy.processIdentity,
1007
+ policy.admission,
1008
+ )
1009
+ }
1010
+
1011
+ // reap every tracked chrome tree NOW, on demand. for launchers with a mid-run
1012
+ // teardown path (e.g. a force-kill in closeBrowsers()) that can't wait for the
1013
+ // SIGTERM/exit handlers. idempotent — already-dead pids are no-ops — and only
1014
+ // touches chromes THIS process spawned via launchReaped (a `chromium.launch()`
1015
+ // not wrapped by launchReaped is untracked and never killed by this function).
1016
+ export function reapSpawnedNow(): void {
1017
+ for (const tracked of reapPids.values()) killOwnedTree(tracked)
1018
+ reapPids.clear()
1019
+ }