rnxsim 0.1.408 → 0.1.409

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