rnxsim 0.1.408 → 0.1.410

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 (69) hide show
  1. package/README.md +11 -10
  2. package/cli/bin.ts +16 -643
  3. package/cli/commands/assert.ts +6 -6
  4. package/cli/commands/box/rnx-command.ts +3 -11
  5. package/cli/commands/control.ts +3 -9
  6. package/cli/commands/daemon-mac-app.ts +5 -11
  7. package/cli/commands/daemon.ts +63 -113
  8. package/cli/drivers/playwright-provisioning.ts +33 -29
  9. package/cli/drivers/playwright-sim-host.ts +501 -0
  10. package/cli/drivers/playwright.ts +35 -522
  11. package/cli/hints.ts +2 -4
  12. package/cli/internal-child.ts +176 -0
  13. package/cli/maestro-js.ts +28 -39
  14. package/cli/main.ts +645 -0
  15. package/cli/outbound-endpoints.ts +8 -0
  16. package/cli/self-invocation.ts +34 -0
  17. package/dist-lib/agent-daemon-client.cjs +35 -25
  18. package/dist-lib/agent-events.cjs +1 -1
  19. package/dist-lib/agent-identity.cjs +1 -1
  20. package/dist-lib/agent-sessions.cjs +35 -25
  21. package/dist-lib/attached-projects.cjs +1 -1
  22. package/dist-lib/auth/shared-session.cjs +1 -1
  23. package/dist-lib/backend-origin.cjs +1 -1
  24. package/dist-lib/beta.cjs +1 -1
  25. package/dist-lib/beta.mjs +1 -1
  26. package/dist-lib/bridge-constants.cjs +1 -1
  27. package/dist-lib/bridge-contract-input.cjs +1 -1
  28. package/dist-lib/bridge-contract-input.mjs +1 -1
  29. package/dist-lib/bridge-contract.cjs +1 -1
  30. package/dist-lib/bridge-contract.mjs +1 -1
  31. package/dist-lib/capture-contract.cjs +1 -1
  32. package/dist-lib/capture-contract.mjs +1 -1
  33. package/dist-lib/cli-constants.cjs +1 -1
  34. package/dist-lib/cloud-contract.cjs +1 -4
  35. package/dist-lib/cloud-contract.mjs +1 -3
  36. package/dist-lib/config.cjs +1 -1
  37. package/dist-lib/detox/index.cjs +1 -1
  38. package/dist-lib/dev-bundle-resolution.cjs +1 -1
  39. package/dist-lib/home-paths.cjs +1 -1
  40. package/dist-lib/host/bridge-host.cjs +25 -15
  41. package/dist-lib/host/fetch-proxy-handler.cjs +1 -1
  42. package/dist-lib/host/fetch-proxy-overrides.cjs +1 -1
  43. package/dist-lib/host/fetch-proxy-overrides.mjs +1 -1
  44. package/dist-lib/host/replacement-module-handler.cjs +1 -1
  45. package/dist-lib/host/websocket-proxy.cjs +1 -1
  46. package/dist-lib/index.cjs +1 -1
  47. package/dist-lib/jump-to-source-babel.cjs +1 -1
  48. package/dist-lib/menu.cjs +1 -1
  49. package/dist-lib/menu.mjs +1 -1
  50. package/dist-lib/metro-fingerprint-registry.cjs +1 -1
  51. package/dist-lib/metro-fingerprint-registry.mjs +1 -1
  52. package/dist-lib/metro-production-bundle.cjs +1 -1
  53. package/dist-lib/metro-production-bundle.mjs +1 -1
  54. package/dist-lib/metro.cjs +1 -1
  55. package/dist-lib/profiles.cjs +1 -1
  56. package/dist-lib/public-brand.cjs +1 -1
  57. package/dist-lib/react-native-host-modules.cjs +1 -1
  58. package/dist-lib/react-native-host-modules.mjs +1 -1
  59. package/dist-lib/render-mode.cjs +1 -1
  60. package/dist-lib/scripts/dev-server-scanner.cjs +1 -1
  61. package/dist-lib/sdk.cjs +1 -1
  62. package/dist-lib/sdk.mjs +1 -1
  63. package/dist-lib/skills.cjs +134 -608
  64. package/dist-lib/vite.cjs +1 -1
  65. package/package.json +1 -1
  66. package/src/agent-daemon-client.ts +2 -2
  67. package/src/agent-sessions.ts +29 -24
  68. package/src/cloud-contract.ts +0 -1
  69. package/src/vite-plugin.ts +62 -0
@@ -0,0 +1,501 @@
1
+ // the detached browser host, as CJS source.
2
+ //
3
+ // it resolves playwright from the absolute path the driver hands it, launches
4
+ // Chrome for Testing, opens the target url, then keeps itself (and therefore
5
+ // the browser) alive until the browser disconnects. all inputs arrive through
6
+ // the environment.
7
+ //
8
+ // it stays a source string rather than a module of its own: playwright is
9
+ // resolved from the user's project at runtime and is not a dependency here, so
10
+ // there are no types for any of this, and a typed rewrite would be `unknown`
11
+ // casts end to end. cli/internal-child.ts runs it through node:vm with a real
12
+ // require, in a child process the CLI spawns as itself.
13
+ import { DISPOSABLE_BROWSER_CACHE_DIR_NAMES } from '../../src/browser-cache'
14
+
15
+ export const PLAYWRIGHT_SIM_HOST = `
16
+ const modulePath = process.env.SOOTSIM_PW_MODULE;
17
+ const url = process.env.SOOTSIM_PW_URL;
18
+ // the WS bridge port the sim page must register with, injected below as
19
+ // window.__sootsimBridgePort so the page skips its shell-port heuristic (which
20
+ // assumes the default offset and breaks when the dev bridge drifted).
21
+ const bridgePort = process.env.SOOTSIM_PW_BRIDGE_PORT || '';
22
+ const headless = process.env.SOOTSIM_PW_HEADLESS === '1';
23
+ const callerUserDataDir = process.env.SOOTSIM_PW_USERDATADIR || '';
24
+ // pid of the session that launched us (its topmost non-init ancestor). when
25
+ // that process exits we tear Chrome down — see startOwnerWatch below. it is a
26
+ // required lifetime bound: an invalid value aborts before Chrome launches.
27
+ // SOOTSIM_PW_OWNER_POLL_MS is a test-only override of the 5s poll interval;
28
+ // production never sets it.
29
+ const ownerPid = Number(process.env.SOOTSIM_PW_OWNER_PID || 0);
30
+ const ownerPollMs = Number(process.env.SOOTSIM_PW_OWNER_POLL_MS || 5000);
31
+ // optional CDP port — exposes Chrome's remote-debugging endpoint so a
32
+ // bridge-driven sim can also be cpu-profiled (rnx perf cpu --cdp-port).
33
+ // playwright keeps its own pipe connection; the port is an additional endpoint.
34
+ const cdpPort = process.env.SOOTSIM_PW_CDP_PORT || '';
35
+ // extra chromium launch args, space-separated. a linux GPU runner injects
36
+ // '--use-angle=vulkan --enable-features=Vulkan' here so chrome binds the
37
+ // real GPU instead of silently falling back to swiftshader software
38
+ // rendering (which pegs cores and produces ~1fps canvas capture).
39
+ const extraChromeArgs = (process.env.SOOTSIM_PW_CHROME_ARGS || '')
40
+ .split(' ')
41
+ .filter(Boolean);
42
+ // Local CanvasKit work must never fall back to Playwright's software
43
+ // renderer. CI may use the bundled browser for non-interactive coverage, but
44
+ // local test drives fail closed unless the hardware-backed test browser is
45
+ // proven after launch.
46
+ const hardwareGpuRequired = process.env.CI !== '1' && process.env.CI !== 'true';
47
+ const softwareRendererPattern = /swiftshader|software(?: rasterizer)?|llvmpipe|lavapipe|softpipe/i;
48
+ // page viewport as '<w>x<h>'. the caller sizes it from the device profile;
49
+ // the fallback is phone-shaped because the page hosts a phone sim — the
50
+ // playwright default (1280x720 desktop) letterboxes the device frame.
51
+ const viewportSpec = /^(\\d+)x(\\d+)$/.exec(process.env.SOOTSIM_PW_VIEWPORT || '');
52
+ const viewport = viewportSpec
53
+ ? { width: Number(viewportSpec[1]), height: Number(viewportSpec[2]) }
54
+ : { width: 600, height: 900 };
55
+ // device pixels per css pixel. playwright's default is 1, which makes the
56
+ // engine allocate its canvas backing store at HALF the resolution a normal
57
+ // retina-mac chrome would (dpr 2) — the sim looks visibly soft. default to 2
58
+ // so a driver-launched sim matches what the user sees in their own browser.
59
+ const deviceScaleFactor = Number(process.env.SOOTSIM_PW_DSF || 2);
60
+ const closeTimeoutMs = Number(process.env.SOOTSIM_PW_CLOSE_TIMEOUT_MS || 2500);
61
+ const connectAckFile = process.env.SOOTSIM_PW_CONNECTED_ACK_FILE || '';
62
+ const disposableBrowserCacheDirs = new Set(${JSON.stringify(
63
+ DISPOSABLE_BROWSER_CACHE_DIR_NAMES,
64
+ )});
65
+ const { existsSync, mkdtempSync, readdirSync, rmSync, unlinkSync } = require('fs');
66
+ const { execSync } = require('child_process');
67
+ const { tmpdir } = require('os');
68
+ const { join } = require('path');
69
+ // chrome tree reaper — playwright's browser.close() and even SIGKILLing the
70
+ // root chrome process do NOT reliably take down the helper tree (gpu, renderer,
71
+ // network/storage utilities). they reparent to launchd/init and survive, each
72
+ // one busy enough to peg CPU at 100%+. close() only reaches the root.
73
+ //
74
+ // the prior approach was \`pgrep -f ms-playwright/[c]hromium\`. it never matched
75
+ // system Chrome, so the reaper was a no-op in the common case and every
76
+ // aborted/closed \`rnx open\` leaked a renderer + gpu helper burning 100%+
77
+ // CPU until manually killed (multiple incidents 2026-06).
78
+ //
79
+ // fix: identify our chrome tree by its UNIQUE user-data-dir. every helper a
80
+ // chrome root spawns inherits \`--user-data-dir=<dir>\` in its cmdline, so
81
+ // \`pgrep -f <profileDir>\` finds exactly the tree we launched and nothing else
82
+ // — Chrome for Testing and bundled playwright chromium alike. as a side benefit we
83
+ // no longer need the launch / launchPersistentContext fork: we ALWAYS use a
84
+ // profile dir (mkdtemp'd if the caller didn't pass one, then removed at exit).
85
+ const reapEnabled = process.platform !== 'win32';
86
+ let profileDir = callerUserDataDir;
87
+ let ephemeralProfile = false;
88
+ if (!profileDir) {
89
+ profileDir = mkdtempSync(join(tmpdir(), 'rnx-playwright-host-'));
90
+ ephemeralProfile = true;
91
+ }
92
+ // browser HTTP caches are acceleration data, not profile identity. give each
93
+ // host a bounded temporary cache so persistent named profiles retain cookies
94
+ // and storage without multiplying a private cache for every profile.
95
+ const diskCacheDir = mkdtempSync(join(tmpdir(), 'rnx-playwright-cache-'));
96
+ const chromePidsByProfile = () => {
97
+ if (!reapEnabled) return [];
98
+ try {
99
+ return execSync('pgrep -f ' + profileDir + ' || true', { stdio: ['ignore', 'pipe', 'ignore'] })
100
+ .toString().split('\\n').filter(Boolean).map((p) => Number(p))
101
+ .filter((p) => p && p !== process.pid);
102
+ } catch { return []; }
103
+ };
104
+ const chromeCommandsByProfile = () => {
105
+ if (!reapEnabled) return [];
106
+ const pids = chromePidsByProfile();
107
+ if (pids.length === 0) return [];
108
+ try {
109
+ return execSync('ps -p ' + pids.join(',') + ' -o command=', {
110
+ stdio: ['ignore', 'pipe', 'ignore'],
111
+ }).toString().split('\\n').filter(Boolean);
112
+ } catch { return []; }
113
+ };
114
+ const assertNoUnsafeSwiftShaderFlag = () => {
115
+ if (!hardwareGpuRequired) return;
116
+ const unsafe = chromeCommandsByProfile().find((command) =>
117
+ command.includes('--enable-unsafe-swiftshader') ||
118
+ /--use-angle=(?:swiftshader|swiftshader-webgl)(?:\\s|$)/i.test(command)
119
+ );
120
+ if (unsafe) {
121
+ throw new Error(
122
+ '[playwright-driver] refused software-rendering Chrome: launched process contains a SwiftShader flag'
123
+ );
124
+ }
125
+ };
126
+ const killTree = (pid) => {
127
+ let kids = [];
128
+ try {
129
+ kids = execSync('pgrep -P ' + pid + ' || true', { stdio: ['ignore', 'pipe', 'ignore'] })
130
+ .toString().split('\\n').filter(Boolean);
131
+ } catch {}
132
+ for (const k of kids) killTree(Number(k));
133
+ try { process.kill(pid, 'SIGKILL'); } catch {}
134
+ };
135
+ const reapChrome = () => { for (const pid of chromePidsByProfile()) killTree(pid); };
136
+ const removeDisposableCaches = (root) => {
137
+ let children = [];
138
+ try { children = readdirSync(root, { withFileTypes: true }); } catch { return; }
139
+ for (const child of children) {
140
+ if (!child.isDirectory() || child.isSymbolicLink()) continue;
141
+ const childPath = join(root, child.name);
142
+ if (disposableBrowserCacheDirs.has(child.name)) {
143
+ try { rmSync(childPath, { recursive: true, force: true }); } catch {}
144
+ continue;
145
+ }
146
+ removeDisposableCaches(childPath);
147
+ }
148
+ };
149
+ const cleanupProfile = () => {
150
+ try { rmSync(diskCacheDir, { recursive: true, force: true }); } catch {}
151
+ if (ephemeralProfile) {
152
+ try { rmSync(profileDir, { recursive: true, force: true }); } catch {}
153
+ return;
154
+ }
155
+ removeDisposableCaches(profileDir);
156
+ };
157
+ (async () => {
158
+ const pw = require(modulePath);
159
+ let context;
160
+ let keepAlive = null;
161
+ let connectTimer = null;
162
+ let connectAckPoll = null;
163
+ let ownerWatch = null;
164
+ let connected = false;
165
+ let shuttingDown = false;
166
+ const clearConnectTimer = () => {
167
+ if (connectTimer) {
168
+ clearTimeout(connectTimer);
169
+ connectTimer = null;
170
+ }
171
+ if (connectAckPoll) {
172
+ clearInterval(connectAckPoll);
173
+ connectAckPoll = null;
174
+ }
175
+ };
176
+ const markConnected = () => {
177
+ connected = true;
178
+ clearConnectTimer();
179
+ };
180
+ const ackFileExists = () => {
181
+ if (!connectAckFile) return false;
182
+ try { return existsSync(connectAckFile); } catch { return false; }
183
+ };
184
+ const bounded = async (label, work, timeoutMs) => {
185
+ let timer = null;
186
+ try {
187
+ const timeout = new Promise((resolve) => {
188
+ timer = setTimeout(() => resolve({ timedOut: true }), timeoutMs);
189
+ });
190
+ if (typeof timer.unref === 'function') timer.unref();
191
+ const result = await Promise.race([
192
+ Promise.resolve().then(work).then(
193
+ () => ({ timedOut: false }),
194
+ (error) => ({ timedOut: false, error }),
195
+ ),
196
+ timeout,
197
+ ]);
198
+ if (result && result.timedOut) {
199
+ process.stderr.write('[shutdown-timeout] ' + label + ' exceeded ' + timeoutMs + 'ms\\n');
200
+ return false;
201
+ }
202
+ if (result && result.error) {
203
+ process.stderr.write('[shutdown-error] ' + label + ': ' + String((result.error && result.error.message) || result.error) + '\\n');
204
+ return false;
205
+ }
206
+ return true;
207
+ } finally {
208
+ if (timer) clearTimeout(timer);
209
+ }
210
+ };
211
+ const browserProcess = () => {
212
+ if (context && typeof context.browser === 'function') {
213
+ try {
214
+ const b = context.browser();
215
+ if (b && typeof b.process === 'function') return b.process();
216
+ } catch {}
217
+ }
218
+ return null;
219
+ };
220
+ const processIsAlive = (proc) => {
221
+ if (!proc || !proc.pid) return false;
222
+ try {
223
+ process.kill(proc.pid, 0);
224
+ return true;
225
+ } catch (err) {
226
+ return err && err.code === 'EPERM';
227
+ }
228
+ };
229
+ const terminateBrowserProcess = async () => {
230
+ const proc = browserProcess();
231
+ if (!proc || !proc.pid || !processIsAlive(proc)) return;
232
+ try { proc.kill('SIGTERM'); } catch {}
233
+ await bounded('browser process exit after SIGTERM', async () => {
234
+ while (processIsAlive(proc)) {
235
+ await new Promise((resolve) => setTimeout(resolve, 50));
236
+ }
237
+ }, 600);
238
+ if (!processIsAlive(proc)) return;
239
+ try { proc.kill('SIGKILL'); } catch {}
240
+ };
241
+ const shutdown = async (code = 0) => {
242
+ if (shuttingDown) return;
243
+ shuttingDown = true;
244
+ clearConnectTimer();
245
+ if (keepAlive) clearInterval(keepAlive);
246
+ if (ownerWatch) clearInterval(ownerWatch);
247
+ const timeoutMs = Number.isFinite(closeTimeoutMs) && closeTimeoutMs > 0 ? closeTimeoutMs : 2500;
248
+ if (context) await bounded('context.close', () => context.close(), timeoutMs);
249
+ await terminateBrowserProcess();
250
+ // close() + root-SIGKILL above handle the graceful case; the helper tree
251
+ // (gpu/renderer/utilities) reparents and survives every one of those, so
252
+ // we always sweep by our unique profile dir as the load-bearing teardown.
253
+ reapChrome();
254
+ cleanupProfile();
255
+ if (connectAckFile) {
256
+ try { unlinkSync(connectAckFile); } catch {}
257
+ }
258
+ process.exit(code);
259
+ };
260
+ process.once('SIGTERM', () => { void shutdown(0); });
261
+ process.once('SIGINT', () => { void shutdown(0); });
262
+ // the launch-failure path at the bottom of this script exits without going
263
+ // through shutdown(); the exit hook (sync sweep) still reaps the tree.
264
+ process.on('exit', () => { reapChrome(); cleanupProfile(); });
265
+ // owner-liveness watchdog — the load-bearing fix for leaked Chrome hosts.
266
+ // we are spawned detached + unref'd so \`rnx open\` returns immediately,
267
+ // which means nothing in the OS process tree ties Chrome's lifetime to the
268
+ // session that asked for it. once the sim connects, the connect-timeout
269
+ // safety net is cleared, so absent an explicit \`rnx close\` (or the
270
+ // daemon's idle reaper closing the sim socket) the host would hold Chrome
271
+ // open forever after its owner exits. poll the owning session's pid and tear
272
+ // down when it's gone. ESRCH (kill throws) = owner exited; EPERM = alive but
273
+ // not signalable by us, which still counts as alive.
274
+ const startOwnerWatch = () => {
275
+ if (!Number.isInteger(ownerPid) || ownerPid <= 1) {
276
+ throw new Error('[playwright-driver] missing valid owning process; refusing unsupervised browser host');
277
+ }
278
+ const intervalMs = Number.isFinite(ownerPollMs) && ownerPollMs > 0 ? ownerPollMs : 5000;
279
+ ownerWatch = setInterval(() => {
280
+ try {
281
+ process.kill(ownerPid, 0);
282
+ } catch (err) {
283
+ if (err && err.code === 'EPERM') return;
284
+ process.stderr.write('[owner-gone] owning process ' + ownerPid + ' exited; closing playwright host\\n');
285
+ void shutdown(0);
286
+ }
287
+ }, intervalMs);
288
+ if (typeof ownerWatch.unref === 'function') ownerWatch.unref();
289
+ };
290
+ startOwnerWatch();
291
+ // Local rendering uses Playwright's full Chrome for Testing app. On macOS its
292
+ // com.google.chrome.for.testing identity cannot intercept open/quit events for
293
+ // the user's com.google.Chrome browser. CI may use chromium_headless_shell;
294
+ // local rendering fails closed because that shell has no GPU and silently
295
+ // chooses SwiftShader. NOTE: this is NOT enough to make \`rnx perf cpu\`
296
+ // work — that profiles the tenant *worker*, and the JS Self-Profiler API
297
+ // cannot be constructed in a dedicated worker (see
298
+ // worker-handlers/cpu-profile.ts). cpu-profile needs a CDP-based profiler
299
+ // instead.
300
+ if (
301
+ hardwareGpuRequired &&
302
+ extraChromeArgs.some((arg) =>
303
+ arg === '--enable-unsafe-swiftshader' ||
304
+ /^--use-angle=(?:swiftshader|swiftshader-webgl)$/i.test(arg)
305
+ )
306
+ ) {
307
+ throw new Error('[playwright-driver] refused SwiftShader launch arguments');
308
+ }
309
+ // one browser path per environment: the full, separately identified test app
310
+ // locally; chromium_headless_shell on CI. never launch a branded user browser.
311
+ const channelsToTry = hardwareGpuRequired ? ['chromium'] : [null];
312
+ const launchWith = async (channel) => {
313
+ const opts = channel
314
+ ? { headless, channel, viewport, deviceScaleFactor }
315
+ : { headless, viewport, deviceScaleFactor };
316
+ // playwright injects --force-color-profile=srgb by default, which reads
317
+ // visibly washed-out next to a normal chrome window on a wide-gamut mac
318
+ // display. strip it so driver-launched sims color-match the user's own
319
+ // browser (real incident 2026-07-09: "low res and whitewashed" sim).
320
+ opts.ignoreDefaultArgs = ['--force-color-profile=srgb'];
321
+ // headless chromium backgrounds/occludes the renderer and throttles rAF +
322
+ // timers to ~1fps, which silently starves combined/video frame capture
323
+ // (was 47 frames over 63s -> frozen-looking mp4). keep the render loop at
324
+ // full rate so the recorder captures real motion. document.hidden stays
325
+ // false in headless, so assertTabVisibleForCapture never caught this — it
326
+ // has to be fixed at the launch flags.
327
+ opts.args = [
328
+ // the compositor renders through skia graphite on webgpu, so a launch
329
+ // without navigator.gpu boots to a fatal instead of a sim.
330
+ '--enable-unsafe-webgpu',
331
+ '--disk-cache-dir=' + diskCacheDir,
332
+ '--disk-cache-size=67108864',
333
+ '--disable-background-timer-throttling',
334
+ '--disable-backgrounding-occluded-windows',
335
+ '--disable-renderer-backgrounding',
336
+ ];
337
+ if (channel) {
338
+ // the full test browser can bind the real platform GPU — force the native
339
+ // ANGLE backend and strip playwright's --enable-unsafe-swiftshader
340
+ // default arg. without both, headless chrome silently falls back to
341
+ // swiftshader software rendering for the CanvasKit/WebGL canvas and
342
+ // pegs every core. SOOTSIM_PW_CHROME_ARGS is appended later, so an
343
+ // env-injected --use-angle=... still overrides (last flag wins).
344
+ const angle = process.platform === 'darwin' ? 'metal'
345
+ : process.platform === 'linux' ? 'vulkan' : 'default';
346
+ opts.args.unshift(
347
+ '--use-angle=' + angle,
348
+ '--enable-gpu',
349
+ '--enable-gpu-rasterization',
350
+ '--enable-zero-copy',
351
+ '--ignore-gpu-blocklist',
352
+ );
353
+ opts.ignoreDefaultArgs.push('--enable-unsafe-swiftshader');
354
+ } else {
355
+ // playwright's bundled software chromium exposes no navigator.gpu until
356
+ // Vulkan is named explicitly, and webgpu is the only backend there is.
357
+ opts.args.push('--enable-features=Vulkan');
358
+ }
359
+ if (cdpPort) opts.args.push('--remote-debugging-port=' + cdpPort);
360
+ if (extraChromeArgs.length) opts.args.push(...extraChromeArgs);
361
+ // headed: size the OS window to the (phone-shaped) viewport too, plus
362
+ // room for chrome's own toolbar, so the window isn't desktop-shaped
363
+ // around a letterboxed page.
364
+ if (!headless) opts.args.push('--window-size=' + viewport.width + ',' + (viewport.height + 88));
365
+ // ALWAYS persistent: every chrome process inherits --user-data-dir=<dir>
366
+ // in its cmdline, which is how reapChrome() finds the whole tree (root +
367
+ // helpers) on shutdown. without a unique dir there is no way to attribute
368
+ // an orphaned helper back to us, which is the leak we just fixed.
369
+ return await pw.chromium.launchPersistentContext(profileDir, opts);
370
+ };
371
+ let launchErr = null;
372
+ let launchedChannel = null;
373
+ for (const channel of channelsToTry) {
374
+ try {
375
+ context = await launchWith(channel);
376
+ launchedChannel = channel || 'chromium';
377
+ launchErr = null;
378
+ break;
379
+ } catch (err) {
380
+ launchErr = err;
381
+ const msg = err && err.message ? String(err.message) : '';
382
+ const isMissingChannel =
383
+ /not found at/i.test(msg) ||
384
+ /not installed/i.test(msg) ||
385
+ /Chromium distribution/i.test(msg);
386
+ if (!isMissingChannel) throw err; // unexpected failure: bubble up
387
+ if (channel) {
388
+ const next = hardwareGpuRequired
389
+ ? '; bundled Chromium is disabled for local GPU work\\n'
390
+ : ', falling back to bundled chromium\\n';
391
+ process.stderr.write('[playwright-driver] channel "' + channel + '" not available' + next);
392
+ }
393
+ }
394
+ }
395
+ if (launchErr) throw launchErr;
396
+ if (launchedChannel) {
397
+ process.stderr.write('[playwright-driver] launched ' + launchedChannel + '\\n');
398
+ }
399
+ // grant camera up front so the sim's Camera app reaches the host webcam
400
+ // through getUserMedia, mirroring a real iOS simulator where the camera just
401
+ // works. without this the unhandled chrome permission prompt auto-denies and
402
+ // CameraApp renders its "Camera Access Required" placeholder.
403
+ await context.grantPermissions(['camera']);
404
+ const hostMeta = {
405
+ sootsimHostDriver: 'playwright',
406
+ sootsimHostPid: process.pid,
407
+ sootsimHostOwnerPid: ownerPid,
408
+ sootsimHostStartedAt: Date.now(),
409
+ };
410
+ // inject the resolved bridge port (numeric literal) BEFORE the page runs, so
411
+ // the shell/engine talk to the daemon this driver owns. addInitScript runs
412
+ // ahead of every page script, and the vite dev plugin only fills the value in
413
+ // when it is still unset, so this one wins. plain assignment, NOT
414
+ // defineProperty: other injectors also assign to it, and a non-writable
415
+ // property would throw at that assignment and crash boot.
416
+ const bridgePortInject = bridgePort
417
+ ? 'window.__sootsimBridgePort = ' + Number(bridgePort) + ';'
418
+ : '';
419
+ await context.addInitScript({
420
+ content: 'Object.defineProperty(window, "__sootsimHostMeta", { value: ' + JSON.stringify(hostMeta) + ', configurable: true });' + bridgePortInject,
421
+ });
422
+ await context.exposeBinding('__sootsimHostClose', async () => {
423
+ await shutdown(0);
424
+ });
425
+ const connectTimeoutMs = Number(process.env.SOOTSIM_PW_CONNECT_TIMEOUT_MS || 120000);
426
+ if (connectAckFile) {
427
+ connectAckPoll = setInterval(() => {
428
+ if (ackFileExists()) markConnected();
429
+ }, 500);
430
+ if (typeof connectAckPoll.unref === 'function') connectAckPoll.unref();
431
+ }
432
+ connectTimer = setTimeout(() => {
433
+ if (ackFileExists()) {
434
+ markConnected();
435
+ return;
436
+ }
437
+ if (connected) return;
438
+ process.stderr.write('[connect-timeout] sim did not register with the bridge within ' + connectTimeoutMs + 'ms; closing playwright host\\n');
439
+ void shutdown(2);
440
+ }, Number.isFinite(connectTimeoutMs) && connectTimeoutMs > 0 ? connectTimeoutMs : 120000);
441
+ if (typeof connectTimer.unref === 'function') connectTimer.unref();
442
+ const page = await context.newPage();
443
+ if (hardwareGpuRequired) {
444
+ assertNoUnsafeSwiftShaderFlag();
445
+ const gpu = await page.evaluate(() => {
446
+ const canvas = document.createElement('canvas');
447
+ const gl =
448
+ canvas.getContext('webgl2', { powerPreference: 'high-performance' }) ||
449
+ canvas.getContext('webgl', { powerPreference: 'high-performance' });
450
+ if (!gl) return { renderer: null, vendor: null };
451
+ const info = gl.getExtension('WEBGL_debug_renderer_info');
452
+ return {
453
+ renderer: info ? String(gl.getParameter(info.UNMASKED_RENDERER_WEBGL)) : null,
454
+ vendor: info ? String(gl.getParameter(info.UNMASKED_VENDOR_WEBGL)) : null,
455
+ };
456
+ });
457
+ if (!gpu.renderer) {
458
+ throw new Error(
459
+ '[playwright-driver] could not prove a hardware WebGL renderer; refusing local render-heavy launch'
460
+ );
461
+ }
462
+ if (softwareRendererPattern.test(gpu.renderer)) {
463
+ throw new Error('[playwright-driver] refused software WebGL renderer: ' + gpu.renderer);
464
+ }
465
+ assertNoUnsafeSwiftShaderFlag();
466
+ process.stderr.write(
467
+ '[playwright-driver] hardware WebGL renderer: ' + gpu.renderer +
468
+ (gpu.vendor ? ' (' + gpu.vendor + ')' : '') + '\\n'
469
+ );
470
+ }
471
+ // surface page-side failures (engine boot crash, failed WS registration)
472
+ // to stderr so a sim that never connects produces a real diagnostic
473
+ // instead of a silent "timed out waiting for opened sim to connect".
474
+ page.on('pageerror', (e) => {
475
+ process.stderr.write('[pageerror] ' + ((e && e.stack) || e) + '\\n');
476
+ });
477
+ page.on('console', (m) => {
478
+ if (m.type() === 'error') {
479
+ process.stderr.write('[console.error] ' + m.text() + '\\n');
480
+ }
481
+ });
482
+ page.on('crash', () => process.stderr.write('[page] renderer crashed\\n'));
483
+ try {
484
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });
485
+ } catch (err) {
486
+ process.stderr.write('[goto] ' + String((err && err.message) || err) + '\\n');
487
+ }
488
+ keepAlive = setInterval(() => {}, 1 << 30);
489
+ // browser disconnect (e.g. user killed chrome from outside) → tear down.
490
+ // we are persistent-only now, so .browser() is the only handle to it.
491
+ try {
492
+ const b = context.browser && context.browser();
493
+ if (b && typeof b.on === 'function') b.on('disconnected', () => { void shutdown(0); });
494
+ } catch {}
495
+ context.on('close', () => { void shutdown(0); });
496
+ page.on('close', () => { void shutdown(0); });
497
+ })().catch((err) => {
498
+ process.stderr.write(String((err && err.stack) || err) + '\\n');
499
+ process.exit(1);
500
+ });
501
+ `