ravensight-playtest 0.20.1 → 0.21.1

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.
package/README.md CHANGED
@@ -383,6 +383,14 @@ libsecret on Linux). With no keychain available it falls back to a file with 060
383
383
  permissions under `RAVENSIGHT_HOME`, and says which store it used. In CI, set
384
384
  `RAVENSIGHT_TOKEN` and skip `login` entirely.
385
385
 
386
+ One token can cover one game, several games, or all of them: you choose on the
387
+ approval page, and "All my games" includes any game you add later. When this
388
+ folder is already linked to a game, `login` names it so you know which one to
389
+ tick, and warns if the new token still does not cover it. If `check` or `run`
390
+ says the linked game is not in the token's scope, it lists the games the token
391
+ does cover. To add the game, run `ravensight-playtest login` again and tick
392
+ every game the token should cover, including this one, or tick "All my games".
393
+
386
394
  ### logout
387
395
 
388
396
  Revokes the token on the server, then forgets it locally. No flags of its own. A
@@ -481,6 +489,19 @@ to a Godot project or a driver config gets no browser row. The fix is:
481
489
  npm i -D playwright && npx playwright install chromium
482
490
  ```
483
491
 
492
+ When this tool's own Playwright has no browser installed, `check` and `run` first
493
+ look for one the machine already has: a Chromium that another Playwright
494
+ installed (in `PLAYWRIGHT_BROWSERS_PATH` from your environment, read the way
495
+ Playwright reads it, or the default Playwright browser folder in your user
496
+ profile), then an installed Chrome. A browser inside your project folder is
497
+ never used, and a browser is started only when it stays inside its own browser
498
+ folder and its files and the folders above them belong to you (or the system)
499
+ and no one else can change them. `check` and `run` look in the same places. Each one is started once as a test,
500
+ and the first that starts and is recent enough is used. The
501
+ `browser` row then names the browser in use. Nothing is ever downloaded on its
502
+ own; when nothing on the machine works, the row says what was tried and gives
503
+ the install command.
504
+
484
505
  Past `--personas` in `POST /jobs`, requesting more than 100 personas or the same
485
506
  slug twice is refused with 400 `too_many_personas`, and a slug this game does
486
507
  not have is 400 `unknown_persona`; `run` checks the count against the same
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ravensight-playtest",
3
- "version": "0.20.1",
3
+ "version": "0.21.1",
4
4
  "description": "Local AI playtests and seeded game simulations with reports in Ravensight.",
5
5
  "license": "MIT",
6
6
  "homepage": "https://ravensight.io/docs/playtest/",
@@ -34,3 +34,54 @@ export function missingScopes(scopes, required = RUN_SCOPES) {
34
34
  export function missingScopeMessage(missing) {
35
35
  return `This login cannot run a playtest: its token does not have ${missing.join(', ')}. Log in again with "ravensight-playtest login" and approve the full set of playtest permissions. Nothing was registered or charged.`;
36
36
  }
37
+
38
+ /** How many of a token's games a message names before it counts the rest. */
39
+ const GAMES_NAMED = 5;
40
+
41
+ /** `Jump Bunny (g1)`, or just the id when the game has no name. */
42
+ const gameLabel = game => (game && game.name ? `${game.name} (${game.gameId})` : String(game && game.gameId));
43
+
44
+ /**
45
+ * The games a token covers, in words: `2 games: Jump Bunny (g1), Lab (g2)`.
46
+ *
47
+ * @param {Array<{gameId: string, name?: string}>} games
48
+ * @returns {string}
49
+ */
50
+ export function tokenGamesText(games) {
51
+ const list = Array.isArray(games) ? games : [];
52
+ if (list.length === 0) return 'no games';
53
+ const named = list.slice(0, GAMES_NAMED).map(gameLabel).join(', ');
54
+ const rest = list.length > GAMES_NAMED ? `, and ${list.length - GAMES_NAMED} more` : '';
55
+ return `${list.length} ${list.length === 1 ? 'game' : 'games'}: ${named}${rest}`;
56
+ }
57
+
58
+ /**
59
+ * Whether the token's game list leaves this game out. Null when that cannot be
60
+ * told: no game, or a whoami with no game list (an older server).
61
+ *
62
+ * A token approved for all games lists every game its user can see, so a game
63
+ * missing from the list is one the token cannot reach.
64
+ *
65
+ * @param {{games?: Array<{gameId: string}>}|null} whoami
66
+ * @param {string|null} gameId
67
+ * @returns {boolean|null}
68
+ */
69
+ export function gameOutOfScope(whoami, gameId) {
70
+ if (!gameId || !whoami || !Array.isArray(whoami.games)) return null;
71
+ return !whoami.games.some(game => game && game.gameId === gameId);
72
+ }
73
+
74
+ /**
75
+ * What to do when the linked game is outside the token's games. A customer
76
+ * read the old line as "tokens cover one game"; they cover any set, or all
77
+ * games, chosen on the approval page, so this says so and gives the command.
78
+ *
79
+ * @param {{gameId: string, games: Array<{gameId: string, name?: string}>, environment?: string|null}} facts
80
+ * @returns {{detail: string, fix: string, message: string}}
81
+ */
82
+ export function gameScopeHelp({ gameId, games, environment = null }) {
83
+ const where = environment ? ` (it is listed under the ${environment} environment)` : '';
84
+ const covers = `This login's token covers ${tokenGamesText(games)}. It does not cover ${gameId}.`;
85
+ const fix = `Run "ravensight-playtest login" and, on the approval page, tick every game this token should cover, including ${gameId}${where}, or tick "All my games". One token can cover several games or all of them. Or relink this folder to a covered game with "ravensight-playtest init --game <gameId> --force".`;
86
+ return { detail: covers, fix, message: `${covers} ${fix} Nothing was registered or charged.` };
87
+ }
package/src/cli.js CHANGED
@@ -264,6 +264,7 @@ export function buildProgram() {
264
264
  .option('--avoid <thing>', 'something every persona stays out of, such as "the settings menu"; up to five times', (v, list) => [...list, v], [])
265
265
  .option('--save <file>', 'a save file every persona starts from, at most 1 MiB; uploaded before the quote, free')
266
266
  .option('--save-target <where>', 'where the game reads the save: localstorage:<key>, godot:user://<path>, idbfs:/<mount>/<path>, or hook (the default: the game reads it through window.RavensightPlaytest.save)')
267
+ .option('--sessions <n>', 'play each persona as 2 or 3 sessions: the game is closed and started again on its own saved data between them, inside the same minutes and price; an uploaded web build only, each session at least 4 minutes')
267
268
  .requiredOption('--output <file>', 'save the original quote and immutable consent here')
268
269
  .option('--game <id>', 'game id, overriding this repo’s configuration')
269
270
  .addOption(new Option('--geri-provider <name>', "Geri's model provider: primary or alternate (ravensight.io/legal/subprocessors names both); unavailable choices are refused").choices(['primary', 'alternate']))
@@ -275,7 +276,7 @@ export function buildProgram() {
275
276
  const { hostedQuote, HOSTED_URL_REFUSAL } = await import('./commands/hosted.js');
276
277
  if (options.url !== undefined || options.buildUrl !== undefined) throw new CliError(HOSTED_URL_REFUSAL, ExitCode.ENVIRONMENT);
277
278
  return hostedQuote(flagsFrom(command.optsWithGlobals(), { build: options.build, profile: options.profile,
278
- persona: options.persona, personas: options.personas, tier: options.tier, minutes: options.minutes, start: options.start, focus: options.focus, avoid: options.avoid, save: options.save, saveTarget: options.saveTarget, output: options.output, game: options.game,
279
+ persona: options.persona, personas: options.personas, tier: options.tier, minutes: options.minutes, start: options.start, focus: options.focus, avoid: options.avoid, sessions: options.sessions, save: options.save, saveTarget: options.saveTarget, output: options.output, game: options.game,
279
280
  geriProvider: options.geriProvider,
280
281
  video: options.video }));
281
282
  }));
@@ -292,6 +293,7 @@ export function buildProgram() {
292
293
  .option('--avoid <thing>', 'something every persona stays out of, such as "the settings menu"; up to five times', (v, list) => [...list, v], [])
293
294
  .option('--save <file>', 'a save file every persona starts from, at most 1 MiB; uploaded before the quote, free')
294
295
  .option('--save-target <where>', 'where the game reads the save: localstorage:<key>, godot:user://<path>, idbfs:/<mount>/<path>, or hook (the default: the game reads it through window.RavensightPlaytest.save)')
296
+ .option('--sessions <n>', 'play each persona as 2 or 3 sessions: the game is closed and started again on its own saved data between them, inside the same minutes and price; an uploaded web build only, each session at least 4 minutes')
295
297
  .option('--game <id>', 'game id, overriding this repo’s configuration')
296
298
  .option('--video', 'save a video of each persona\'s game session in its report')
297
299
  .option('--wait', 'stay until the report is ready, printing each phase change (with or without a saved quote)')
@@ -305,12 +307,12 @@ export function buildProgram() {
305
307
  const { hostedRun, hostedRunDirect, HOSTED_URL_REFUSAL } = await import('./commands/hosted.js');
306
308
  if (options.url !== undefined || options.buildUrl !== undefined) throw new CliError(HOSTED_URL_REFUSAL, ExitCode.ENVIRONMENT);
307
309
  if (filename) {
308
- const extra = ['build', 'nativeBuild', 'persona', 'personas', 'tier', 'minutes', 'start', 'save', 'saveTarget', 'game', 'video'].filter(name => options[name] !== undefined).concat(['focus', 'avoid'].filter(name => options[name]?.length));
310
+ const extra = ['build', 'nativeBuild', 'persona', 'personas', 'tier', 'minutes', 'start', 'sessions', 'save', 'saveTarget', 'game', 'video'].filter(name => options[name] !== undefined).concat(['focus', 'avoid'].filter(name => options[name]?.length));
309
311
  if (extra.length) throw new CliError(`A saved quote already fixes its build, personas and options. Drop --${extra.map(name => name.replace(/[A-Z]/g, c => `-${c.toLowerCase()}`)).join(', --')}, or run "hosted run" without a quote file.`);
310
312
  return hostedRun(filename, flagsFrom(command.optsWithGlobals(), { wait: options.wait, waitForCapacity: options.waitForCapacity,
311
313
  evenIfUnknown: options.evenIfUnknown }));
312
314
  }
313
- return hostedRunDirect(flagsFrom(command.optsWithGlobals(), { build: options.build, nativeBuild: options.nativeBuild, persona: options.persona, personas: options.personas, tier: options.tier, minutes: options.minutes, start: options.start, focus: options.focus, avoid: options.avoid, save: options.save, saveTarget: options.saveTarget, game: options.game,
315
+ return hostedRunDirect(flagsFrom(command.optsWithGlobals(), { build: options.build, nativeBuild: options.nativeBuild, persona: options.persona, personas: options.personas, tier: options.tier, minutes: options.minutes, start: options.start, focus: options.focus, avoid: options.avoid, sessions: options.sessions, save: options.save, saveTarget: options.saveTarget, game: options.game,
314
316
  video: options.video, wait: options.wait, waitForCapacity: options.waitForCapacity, evenIfUnknown: options.evenIfUnknown }));
315
317
  }));
316
318
  common(hosted.command('status [run-id]'))
@@ -951,8 +953,14 @@ export function report(error) {
951
953
  // cannot probe for a game's existence. That means the message alone can
952
954
  // never tell a developer which of the two it was, so name both.
953
955
  if (error.status === 404 && /\/api\/v1\/games\//.test(error.path || '')) {
956
+ const raw = (/\/api\/v1\/games\/([^/?#]+)/.exec(error.path || '') || [])[1];
957
+ let game = raw;
958
+ try { game = raw && decodeURIComponent(raw); } catch { /* shown as sent */ }
954
959
  ui.info('That game, job or run is not visible to this token.');
955
- ui.info('Run ravensight-playtest check to confirm the game is linked, or log in again.');
960
+ // The likeliest cause is a token approved for other games. One token can
961
+ // cover several games or all of them; the approval page is where.
962
+ ui.info(`If the token does not cover ${game || 'this game'}, run "ravensight-playtest login" and tick it, or "All my games", on the approval page.`);
963
+ ui.info('Run ravensight-playtest check to see the games this token covers.');
956
964
  return ExitCode.FAILURE;
957
965
  }
958
966
  return ExitCode.FAILURE;
@@ -5,7 +5,7 @@ import { ApiError } from '../api/errors.js';
5
5
  import { resolveApiUrl, paths } from '../paths.js';
6
6
  import { resolveToken, looksLikeIngestKey, looksLikeMcpToken } from '../auth/session.js';
7
7
  import { backendName } from '../auth/keychain.js';
8
- import { missingScopes } from '../auth/scopes.js';
8
+ import { missingScopes, gameScopeHelp } from '../auth/scopes.js';
9
9
  import { loadConfig } from '../config.js';
10
10
  import { packs } from '../packs/index.js';
11
11
  import { verifyPack } from '../packs/signature.js';
@@ -21,6 +21,7 @@ import { inspectNativeBuild, probeAutomation, platformWords } from '../run/drive
21
21
  import { CHECK_PLAYTEST_IDENTITY, DEFAULT_VIEWPORT, WEB_OBSERVATION_MAX_CHARS, injectPlaytestIdentity, measureSnapshot, readSnapshot } from '../run/drivers/web.js';
22
22
  import { inspectReadiness } from '../run/readiness.js';
23
23
  import { isGodotProject } from '../run/drivers/godot-project.js';
24
+ import { browserReuseInputs, launchChromium } from '../run/browserSource.js';
24
25
  import path from 'node:path';
25
26
  import { readFileSync } from 'node:fs';
26
27
  import { createRequire } from 'node:module';
@@ -193,10 +194,32 @@ export function heavyReasons(measure) {
193
194
  return reasons;
194
195
  }
195
196
 
197
+ /**
198
+ * What was tried before a missing browser was reported, in one clause.
199
+ *
200
+ * @param {Array<{kind: string, executablePath?: string, outcome: string, detail?: string}>} tried
201
+ * @returns {string}
202
+ */
203
+ export function reuseSummary(tried) {
204
+ const folders = tried.filter(entry => entry.kind === 'folder');
205
+ const chrome = tried.find(entry => entry.kind === 'chrome');
206
+ const parts = [];
207
+ parts.push(folders.length === 0
208
+ ? 'no other Playwright Chromium was found on this machine'
209
+ : `${folders.length} other Playwright ${folders.length === 1 ? 'browser' : 'browsers'} on this machine could not be used (${folders.map(entry => `${entry.executablePath}: ${entry.outcome}${entry.outcome === 'not started' && entry.detail ? `, because ${entry.detail}` : ''}`).join('; ')})`);
210
+ if (chrome) parts.push(chrome.outcome === 'too old' ? 'the installed Chrome is too old for this tool' : 'no installed Chrome started');
211
+ return `${parts.join(', and ')}. Nothing was downloaded`;
212
+ }
213
+
196
214
  /**
197
215
  * Import Playwright, launch headless Chromium, close it. The same three steps
198
216
  * a web run starts with, so a pass here means the run will get a browser.
199
217
  *
218
+ * The launch is the run's own (../run/browserSource.js): when this tool's
219
+ * Playwright has no browser build, a Chromium already on the machine (another
220
+ * Playwright's, or an installed Chrome) is tried, and the detail names the one
221
+ * that started. Nothing is downloaded.
222
+ *
200
223
  * With a `url`, the browser also loads that first screen and measures it
201
224
  * (see {@link measureFirstScreen}); a page that does not load is reported
202
225
  * in `firstScreen`, never as a failed browser.
@@ -205,18 +228,21 @@ export function heavyReasons(measure) {
205
228
  * @param {{url?: string|null, timeoutMs?: number}} [options]
206
229
  * @returns {Promise<{ok: boolean, detail: string, firstScreen?: Object}>}
207
230
  */
208
- export async function probeBrowser(importer, { url = null, timeoutMs } = {}) {
231
+ export async function probeBrowser(importer, { url = null, timeoutMs, reuse = {} } = {}) {
209
232
  const load = importer || (specifier => import(specifier));
210
233
  let browser = null;
211
234
  try {
212
235
  const playwright = await load('playwright');
213
- browser = await playwright.chromium.launch({ headless: true });
236
+ const launched = await launchChromium(playwright, { headless: true }, reuse);
237
+ browser = launched.browser;
214
238
  const version = typeof browser.version === 'function' ? browser.version() : '';
215
- const detail = `chromium ${version}`.trim() + ' launched headless';
239
+ const detail = `chromium ${version}`.trim() + ' launched headless'
240
+ + (launched.source.kind === 'own' ? '' : `, using ${launched.source.label} because this tool's own Playwright has no browser installed`);
216
241
  if (!url) return { ok: true, detail };
217
242
  return { ok: true, detail, firstScreen: await measureFirstScreen(browser, url, { timeoutMs }) };
218
243
  } catch (error) {
219
- return { ok: false, detail: String(error && error.message ? error.message : error).split('\n')[0] };
244
+ const detail = String(error && error.message ? error.message : error).split('\n')[0];
245
+ return { ok: false, detail: Array.isArray(error && error.reuse) ? `${detail}; ${reuseSummary(error.reuse)}` : detail };
220
246
  } finally {
221
247
  if (browser) {
222
248
  try {
@@ -526,11 +552,15 @@ export async function runChecks(flags = {}, deps = {}) {
526
552
  } else {
527
553
  inScope = Boolean(scoped);
528
554
  facts.project.in_scope = inScope;
555
+ // Out of scope says which games the token does cover and how to add this
556
+ // one: a customer read the bare "not in this token's scope" as "a token
557
+ // covers one game" and stopped there.
558
+ const help = inScope ? null : gameScopeHelp({ gameId, games: whoami.games || [], environment });
529
559
  rows.push(row(
530
560
  'project binding',
531
561
  inScope ? 'pass' : 'fail',
532
- inScope ? `linked to ${linked}, in the token's scope` : `linked to ${linked}, which is not in this token's scope`,
533
- inScope ? null : 'run ravensight-playtest login again and approve this game, or relink with init --game <gameId> --force'
562
+ inScope ? `linked to ${linked}, in the token's scope` : `linked to ${linked}, which is not in this token's scope. ${help.detail}`,
563
+ inScope ? null : help.fix
534
564
  ));
535
565
  }
536
566
  }
@@ -708,7 +738,7 @@ export async function runChecks(flags = {}, deps = {}) {
708
738
  const browserNeed = browserSeverity(flags, await configForBrowser(flags), { godotRepo: await isGodotProject(repoRoot).catch(() => false) });
709
739
  if (browserNeed) {
710
740
  const firstScreenUrl = plan.driverName === 'playwright_web' && /^https?:\/\//i.test(String(plan.target || '')) ? plan.target : null;
711
- const probe = await probeBrowser(deps.importer, { url: firstScreenUrl, timeoutMs: deps.firstScreenTimeoutMs });
741
+ const probe = await probeBrowser(deps.importer, { url: firstScreenUrl, timeoutMs: deps.firstScreenTimeoutMs, reuse: browserReuseInputs(repoRoot, deps.browserReuse) });
712
742
  rows.push(row(
713
743
  'browser',
714
744
  probe.ok ? 'pass' : browserNeed,
@@ -18,12 +18,12 @@ import { ANDROID_FORMAT, ANDROID_UNAVAILABLE, ANDROID_UNAVAILABLE_CODE, androidP
18
18
  /** Machine output names a Geri provider by its role, never by the server's wire id. */
19
19
  const printJson = value => ui.json(providerRoles(value));
20
20
 
21
- /** --tier, --minutes, --start, --focus and --avoid as the quote request takes them. */
21
+ /** --tier, --minutes, --start, --focus, --avoid and --sessions as the quote request takes them. */
22
22
  export function scopeFrom(flags = {}) {
23
23
  const minutes = flags.minutes === undefined ? undefined : Number(flags.minutes);
24
- const named = flags.start !== undefined || (flags.focus || []).length || (flags.avoid || []).length;
24
+ const named = flags.start !== undefined || (flags.focus || []).length || (flags.avoid || []).length || flags.sessions !== undefined;
25
25
  return { ...(flags.tier ? { tier: flags.tier } : {}), ...(minutes !== undefined ? { minutes } : {}),
26
- ...(named ? { focus: focusFor({ start: flags.start, focus: flags.focus || [], avoid: flags.avoid || [] }) } : {}) };
26
+ ...(named ? { focus: focusFor({ start: flags.start, focus: flags.focus || [], avoid: flags.avoid || [], sessions: flags.sessions }) } : {}) };
27
27
  }
28
28
 
29
29
  /**
@@ -77,6 +77,7 @@ export function assertNativeRunFlags(flags = {}) {
77
77
  if (flags.start !== undefined || flags.save !== undefined || flags.saveTarget !== undefined) {
78
78
  throw new CliError(ANDROID_FOCUS_REFUSAL, ExitCode.ENVIRONMENT);
79
79
  }
80
+ if (flags.sessions !== undefined) throw new CliError('A cloud playtest of an Android build plays as one session: drop --sessions. Nothing was uploaded or charged.', ExitCode.ENVIRONMENT);
80
81
  }
81
82
 
82
83
  /**
@@ -6,6 +6,8 @@ import { CLI_VERSION, CLIENT_NAME } from '../version.js';
6
6
  import { ui } from '../ui/index.js';
7
7
  import { openInBrowser } from '../dashboard.js';
8
8
  import { ExitCode } from '../errors.js';
9
+ import { loadConfig } from '../config.js';
10
+ import { gameOutOfScope, gameScopeHelp } from '../auth/scopes.js';
9
11
 
10
12
  /**
11
13
  * `ravensight-playtest login`
@@ -27,6 +29,15 @@ export async function login(flags = {}, deps = {}) {
27
29
  const api = deps.api || createClient({ apiUrl, ...(deps.clientOptions || {}) });
28
30
 
29
31
  const started = await api.cli.deviceCode({ client: CLIENT_NAME, clientVersion: CLI_VERSION });
32
+ // The game this folder is linked to, so the approval step can name it. The
33
+ // approval page has no way to preselect a game, so the words do it.
34
+ let linked = null;
35
+ try {
36
+ const config = await loadConfig({ repoRoot: flags.repoRoot });
37
+ if (config && config.game_id) linked = { gameId: config.game_id, environment: config.environment || null };
38
+ } catch {
39
+ // An unreadable config is reported by the commands that need it.
40
+ }
30
41
 
31
42
  if (flags.json) {
32
43
  ui.json({
@@ -38,6 +49,9 @@ export async function login(flags = {}, deps = {}) {
38
49
  ui.blank();
39
50
  ui.info(`Open ${started.verification_uri}`);
40
51
  ui.info(`and enter the code: ${started.user_code}`);
52
+ if (linked) {
53
+ ui.info(`This folder is linked to ${linked.gameId}${linked.environment ? ` (${linked.environment})` : ''}. Tick it on the approval page, with any other games this token should cover, or tick "All my games".`);
54
+ }
41
55
  ui.blank();
42
56
  if (!flags.noBrowser) await openInBrowser(started.verification_uri, deps);
43
57
  }
@@ -59,8 +73,12 @@ export async function login(flags = {}, deps = {}) {
59
73
 
60
74
  const { backend } = await setStoredToken(host, minted.token);
61
75
 
76
+ // Null when the server sent no game list (it cannot be told), true or false otherwise. An empty
77
+ // list is a token that reaches no game: a token for all games lists every game its user can see.
78
+ const games = Array.isArray(minted.games) ? minted.games : null;
79
+ const inScope = linked && games ? !gameOutOfScope({ games }, linked.gameId) : null;
62
80
  if (flags.json) {
63
- ui.json({ ok: true, host, backend, scopes: minted.scopes, games: minted.games });
81
+ ui.json({ ok: true, host, backend, scopes: minted.scopes, games: minted.games, ...(linked ? { linked_game: linked.gameId, linked_game_in_scope: inScope } : {}) });
64
82
  return ExitCode.OK;
65
83
  }
66
84
 
@@ -69,18 +87,25 @@ export async function login(flags = {}, deps = {}) {
69
87
  if (backend === 'file') {
70
88
  ui.warn('No OS keychain was available, so the token is in a 0600 file under your home directory.');
71
89
  }
72
- if (minted.games && minted.games.length > 0) {
90
+ if (games && games.length > 0) {
73
91
  ui.blank();
74
92
  ui.info('Games this token can see:');
75
- ui.table(minted.games, [
93
+ ui.table(games, [
76
94
  { key: 'gameId', label: 'GAME ID' },
77
95
  { key: 'name', label: 'NAME' }
78
96
  ]);
79
- } else {
80
- ui.info('This token is scoped to every game you can see.');
97
+ } else if (games) {
98
+ ui.warn('This token does not reach any game yet. Run "ravensight-playtest login" again and tick a game, or tick "All my games", on the approval page.');
99
+ }
100
+ if (linked && inScope === false && games.length > 0) {
101
+ const help = gameScopeHelp({ gameId: linked.gameId, games, environment: linked.environment });
102
+ ui.blank();
103
+ ui.warn(`This folder is linked to ${linked.gameId}, which this token does not cover.`);
104
+ ui.info(help.fix);
81
105
  }
82
106
  ui.blank();
83
- ui.info('Next: ravensight-playtest init --game <gameId>');
107
+ if (games && games.length === 0) ui.info('Next: ravensight-playtest login, and tick a game');
108
+ else ui.info(linked && inScope !== false ? 'Next: ravensight-playtest check' : 'Next: ravensight-playtest init --game <gameId>');
84
109
  return ExitCode.OK;
85
110
  }
86
111
 
@@ -31,10 +31,11 @@ import { capabilityNoteLines } from '../run/readiness.js';
31
31
  import { readBridgeConfig } from "../run/drivers/stdio.js";
32
32
  import { WEBDRIVER_NAMES, readDriverConfig } from '../run/drivers/webdriver.js';
33
33
  import { BROWSER_FIX, automationChecks, probeBrowser, browserFixFor, playwrightVersion } from './check.js';
34
+ import { browserReuseInputs } from '../run/browserSource.js';
34
35
  import { runPersona, MIN_SESSION_ACTIONS } from '../run/personaLoop.js';
35
36
  import { playedToBudget } from '../run/intent.js';
36
37
  import { runModelBudgetUsd } from '../run/budgetReserve.js';
37
- import { missingScopeMessage, missingScopes } from '../auth/scopes.js';
38
+ import { gameOutOfScope, gameScopeHelp, missingScopeMessage, missingScopes } from '../auth/scopes.js';
38
39
  import { tracesWanted } from '../run/acceptance.js';
39
40
  import { cleanCommit } from '../run/replay.js';
40
41
  import { loadLocalBrief, localBriefProblems } from '../briefLocal.js';
@@ -199,7 +200,9 @@ async function run(flags, injected, deps, log) {
199
200
  options.live = liveView.on;
200
201
  // A dry upload already says it sends nothing; one more line naming it would only repeat that.
201
202
  if (liveView.reason !== 'dry_upload') log(liveLine(liveView));
202
- const scopeRefusal = await tokenScopeRefusal(api);
203
+ // The config's environment describes the config's game only, not a --game given instead.
204
+ const linkedConfig = context.config && context.config.game_id === gameId ? context.config : null;
205
+ const scopeRefusal = await tokenScopeRefusal(api, { gameId, environment: (linkedConfig && linkedConfig.environment) || null });
203
206
  if (scopeRefusal !== null) {
204
207
  log(scopeRefusal.message);
205
208
  return scopeRefusal.code;
@@ -269,7 +272,7 @@ async function run(flags, injected, deps, log) {
269
272
  log(noGodot);
270
273
  return EXIT.ENVIRONMENT;
271
274
  }
272
- const noBrowser = await browserRefusal({ driverName, injected });
275
+ const noBrowser = await browserRefusal({ driverName, injected, repoRoot });
273
276
  if (noBrowser) {
274
277
  log(noBrowser);
275
278
  return EXIT.ENVIRONMENT;
@@ -953,7 +956,7 @@ export async function playPersonaRun({
953
956
  const runTarget = entry.target || target;
954
957
  let driver;
955
958
  try {
956
- driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null, start: options.startFrom || null, launchArgs: launchArgsOf(options), slowMotion: slowMotionPlan(options) }));
959
+ driver = await makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null, start: options.startFrom || null, launchArgs: launchArgsOf(options), slowMotion: slowMotionPlan(options), repoRoot }));
957
960
  } catch (error) {
958
961
  // A driver that cannot even be built (the browser package missing, say) is
959
962
  // what a new machine hits first. The run is completed as failed now, with
@@ -1046,7 +1049,7 @@ export async function playPersonaRun({
1046
1049
  edgePass: options.noEdgePass !== true,
1047
1050
  replayFindings: options.noReplay !== true,
1048
1051
  // A web run's findings are replayed in a second browser of the same kind, on the same target, with no recording; a local Unreal run's in a fresh launch of the same build.
1049
- ...(driverName === 'playwright_web' || (DESKTOP_NATIVE_DRIVERS.includes(driverName) && options.driverMode === 'native') ? { replayDriver: () => makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null })) } : {}),
1052
+ ...(driverName === 'playwright_web' || (DESKTOP_NATIVE_DRIVERS.includes(driverName) && options.driverMode === 'native') ? { replayDriver: () => makeDriver(driverName, driverOptions({ headless, driverName, target: runTarget, directory, entry, jobId, keyModifier: options.keyModifier, godotPath: options.godotPath, realtime: options.realtime, phone: options.phone, native: options.nativePlan, mode: options.driverMode, nativeLock, liveSite: options.liveSite || null, apiUrl, network: options.network || null, repoRoot })) } : {}),
1050
1053
  // A run sold by the minute stops on the clock (../run/playClock.js).
1051
1054
  playClock: playClockFor(options, entry),
1052
1055
  ...(options.phone === true && driverName === 'playwright_web' ? { viewport: PHONE_VIEWPORT } : {}),
@@ -1791,18 +1794,20 @@ export async function godotRefusal({ driverName, godotPath, projectDir, injected
1791
1794
  * answer is the same one, with the one line that installs this tool's own
1792
1795
  * browser.
1793
1796
  *
1794
- * @param {{driverName: string, injected?: Object}} input
1797
+ * @param {{driverName: string, injected?: Object, repoRoot?: string}} input
1795
1798
  * @returns {Promise<string|null>}
1796
1799
  */
1797
- export async function browserRefusal({ driverName, injected = {} }) {
1800
+ export async function browserRefusal({ driverName, injected = {}, repoRoot = process.cwd() }) {
1798
1801
  if (driverName !== 'playwright_web') return null;
1799
1802
  // A test with its own driver has no use for a real browser.
1800
1803
  const probe = injected.browserProbe || (injected.driverFactory ? null : probeBrowser);
1801
1804
  if (!probe) return null;
1802
- const result = await probe(injected.importer);
1805
+ // The same places `check` searches, so the two never disagree about the browser.
1806
+ const result = await probe(injected.importer, { reuse: browserReuseInputs(repoRoot, injected.browserReuse) });
1803
1807
  if (result.ok) return null;
1804
1808
  const fix = browserFixFor(result.detail, injected.playwrightVersion !== undefined ? injected.playwrightVersion : playwrightVersion());
1805
- return `The browser a web run needs could not start (${String(result.detail || 'it did not launch').slice(0, 240)}). Install it with this one line, then run again: ${fix}\nNothing was registered or charged.`;
1809
+ // Long enough to keep what was tried before the install line (../run/browserSource.js), as `check` shows it.
1810
+ return `The browser a web run needs could not start (${String(result.detail || 'it did not launch').slice(0, 800)}). Install it with this one line, then run again: ${fix}\nNothing was registered or charged.`;
1806
1811
  }
1807
1812
 
1808
1813
  /**
@@ -1818,9 +1823,10 @@ export async function browserRefusal({ driverName, injected = {} }) {
1818
1823
  * none, or a network failure, leaves the server's own checks in charge.
1819
1824
  *
1820
1825
  * @param {Object} api
1826
+ * @param {{gameId?: string|null, environment?: string|null}} [target] the game the run is for
1821
1827
  * @returns {Promise<{code: number, message: string}|null>}
1822
1828
  */
1823
- export async function tokenScopeRefusal(api) {
1829
+ export async function tokenScopeRefusal(api, { gameId = null, environment = null } = {}) {
1824
1830
  if (!api || !api.cli || typeof api.cli.whoami !== 'function') return null;
1825
1831
  let whoami;
1826
1832
  try {
@@ -1832,7 +1838,12 @@ export async function tokenScopeRefusal(api) {
1832
1838
  return null;
1833
1839
  }
1834
1840
  const missing = missingScopes(whoami && whoami.scopes);
1835
- return missing && missing.length > 0 ? { code: EXIT.AUTH, message: missingScopeMessage(missing) } : null;
1841
+ if (missing && missing.length > 0) return { code: EXIT.AUTH, message: missingScopeMessage(missing) };
1842
+ // The game itself: a token approved for other games is refused here, with
1843
+ // the games it does cover and the login that adds this one, rather than as
1844
+ // the server's bare "not found" after the run has been set up.
1845
+ if (gameOutOfScope(whoami, gameId)) return { code: EXIT.AUTH, message: gameScopeHelp({ gameId, games: whoami.games, environment }).message };
1846
+ return null;
1836
1847
  }
1837
1848
 
1838
1849
  export async function resolveSetup(deps, options, log) {
@@ -1899,7 +1910,7 @@ export function sessionsFor(options = {}, maxActions = 0, log = () => {}) {
1899
1910
  return Math.min(asked, fits);
1900
1911
  }
1901
1912
 
1902
- export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null, network = null, start = null, launchArgs = [], slowMotion = null }) {
1913
+ export function driverOptions({ headless, driverName, target, directory, entry, jobId, keyModifier, godotPath, realtime, phone = false, native = null, mode = 'webdriver', nativeLock, liveSite = null, apiUrl = null, network = null, start = null, launchArgs = [], slowMotion = null, repoRoot = null, browserReuse = null }) {
1903
1914
  // Only the browser driver sends key chords with a modifier.
1904
1915
  const modifier = driverName === 'playwright_web' ? resolveKeyModifier(keyModifier).modifier : null;
1905
1916
  const godot = driverName === 'godot_driver'
@@ -1922,6 +1933,8 @@ export function driverOptions({ headless, driverName, target, directory, entry,
1922
1933
  ...(driverName === 'playwright_web' && network && !liveSite ? { network } : {}),
1923
1934
  // The Ravensight ingest origins the game's own SDK session can go to: the SDKs' default and this run's API (../run/sdkSession.js).
1924
1935
  ...(driverName === 'playwright_web' && apiUrl ? { ingestOrigins: ingestOriginsFor(apiUrl) } : {}),
1936
+ // Where a browser already on the machine may be found: the same inputs `check` and the preflight use (../run/browserSource.js).
1937
+ ...(driverName === 'playwright_web' && repoRoot ? { browserReuse: browserReuseInputs(repoRoot, browserReuse) } : {}),
1925
1938
  ...godot,
1926
1939
  // The SDK pause hook for native desktop builds, bridges whose config opts
1927
1940
  // in, and native mobile builds on an emulator or simulator (contract
@@ -94,13 +94,15 @@ export async function readHostedQuote(filename) {
94
94
  */
95
95
  export const TIERS = Object.freeze(['jam', 'small', 'medium', 'large']);
96
96
  const plainLine = value => typeof value === 'string' && value.trim().length > 0 && value.length <= 200 && !/[\u0000-\u001f\u007f]/.test(value);
97
- /** The focus block: a start query or hash, and up to five focus and avoid lines. */
98
- export function focusFor({ start, focus = [], avoid = [] } = {}) {
97
+ /** The focus block: a start query or hash, up to five focus and avoid lines, and the sessions a persona plays (2 or 3). */
98
+ export function focusFor({ start, focus = [], avoid = [], sessions } = {}) {
99
99
  if (start !== undefined && start !== null && start !== '' && (typeof start !== 'string' || !/^[?#][^\s\\]{0,199}$/.test(start))) fail('Choose --start as a query or hash on the build, such as ?level=3 or #boss.');
100
100
  for (const [name, list] of [['--focus', focus], ['--avoid', avoid]]) {
101
101
  if (!Array.isArray(list) || list.length > 5 || !list.every(plainLine)) fail(`Give ${name} at most five times, each plain text of at most 200 characters.`);
102
102
  }
103
- return { ...(start ? { start } : {}), focus: focus.map(x => x.trim()), avoid: avoid.map(x => x.trim()) };
103
+ const n = sessions === undefined || sessions === null ? 1 : Number(sessions);
104
+ if (!Number.isSafeInteger(n) || n < 1 || n > 3) fail('Choose --sessions as 1, 2 or 3.');
105
+ return { ...(start ? { start } : {}), focus: focus.map(x => x.trim()), avoid: avoid.map(x => x.trim()), ...(n > 1 ? { sessions: n } : {}) };
104
106
  }
105
107
 
106
108
  /** Why a cloud playtest of an Android build takes no --start, --save or --save-target. Its --focus and --avoid goals are taken. */
@@ -157,6 +159,7 @@ function requestFor({ buildId, profileVersion, personas, controllers = COMBINED,
157
159
  // An Android build plays on a device with its network off and has no web address: no start and no save. Its goals,
158
160
  // --focus and --avoid, are taken as on any combined playtest (the server's focus block).
159
161
  if (profile.driver === ANDROID_DRIVER && focus !== undefined && (focus.start || focus.save)) fail(ANDROID_FOCUS_REFUSAL);
162
+ if (profile.driver === ANDROID_DRIVER && focus?.sessions) fail('A cloud playtest of an Android build plays as one session: drop --sessions. Nothing was charged.');
160
163
  return { kind: 'recorded_graphical', buildId, personas: [...list], controllers: [...controllers],
161
164
  driver: profile.driver, runLength: 'standard', profileVersion, includeVideo, includeTranscript,
162
165
  ...(standardProvider === undefined ? {} : { standardProvider }),
@@ -270,6 +273,7 @@ export function hostedQuoteLines(offer) {
270
273
  ...(focus.save ? [`Start from the save file: ${printable(String(focus.save.name))} (${Number(focus.save.bytes) || 0} bytes), ${focus.save.target?.kind === 'hook' ? 'read by the game through the playtest save hook' : focus.save.target?.kind === 'local_storage' ? 'placed in local storage before the game loads' : 'placed in the game\'s browser file storage before the game loads'}.`] : []),
271
274
  ...(focus.focus?.length ? [`Focus: ${focus.focus.map(printable).join('; ')}`] : []),
272
275
  ...(focus.avoid?.length ? [`Avoid: ${focus.avoid.map(printable).join('; ')}`] : []),
276
+ ...(Number.isSafeInteger(focus.sessions) && focus.sessions > 1 ? [`Sessions: ${focus.sessions} per persona, the game closed and started again on its own saved data between them, inside the same minutes and price.`] : []),
273
277
  ...(r.standardProvider ? [`Geri's model provider: ${providerLabel(r.standardProvider)}; policy ${q.standardProviderPolicyHash}.`] : []),
274
278
  ...personaPrices(q, r).map(row => `${row.persona}${row.persona === ALWAYS_INCLUDED_PERSONA ? ' (always included)' : ''}: ${money(row.priceCents)}.`),
275
279
  ...(q.setupFeeCents ? [`Includes a non-refundable setup fee: ${money(q.setupFeeCents)} (${money(q.setupFeeCents / r.personas.length)} a persona). It is kept even when a persona is refunded, unless it never got a machine.`] : []),
@@ -34,7 +34,9 @@ export function hostedPlaytestStatus(admission, job = null, runs = [], now = Dat
34
34
  let detail = 'Waiting for hosted capacity.';
35
35
 
36
36
  if (CANCELED.has(jobState) || CANCELED.has(admissionState)) {
37
- phase = 'canceled'; label = 'Canceled'; detail = 'The hosted run was canceled.';
37
+ phase = 'canceled'; label = 'Canceled';
38
+ // A cancel the platform made itself (no machine could be started) says why, in the server's own words.
39
+ detail = (admission.canceledBy === 'platform' && boundedReason(admission.cancelReason)) || 'The hosted run was canceled.';
38
40
  } else if (FAILED.has(jobState) || FAILED.has(admissionState) || job?.summary_report === 'failed') {
39
41
  phase = 'failed'; label = 'Failed'; detail = 'The hosted run stopped before a report was ready.';
40
42
  } else if (job?.summary_report === 'ready' || admissionState === 'recorded_closed') {
@@ -0,0 +1,361 @@
1
+ /**
2
+ * Which Chromium a web run starts, when the CLI's own Playwright has none.
3
+ *
4
+ * The CLI's Playwright wants the one browser build it was released with. A
5
+ * workspace that already runs Playwright usually has a Chromium of its own in
6
+ * the shared browser folder, often one revision away, and a customer was told
7
+ * to download another build while one sat on the disk. So when the CLI's own
8
+ * launch says its executable is missing, this looks for a Chromium the machine
9
+ * already has and launches that instead:
10
+ *
11
+ * 1. the Playwright browser folders: an absolute PLAYWRIGHT_BROWSERS_PATH from
12
+ * the process environment, and the default cache in the user's profile;
13
+ * 2. an installed Chrome, through Playwright's `channel: 'chrome'`.
14
+ *
15
+ * Never the workspace: a cloned repository could ship a planted "chrome" in
16
+ * its node_modules, and `check` must not run a binary the repository supplied.
17
+ * For the same reason a reused binary is resolved through its symlinks and
18
+ * started only when it and every folder above it belong to this user (or
19
+ * root) and no one else can write to them ({@link trustedExecutable}).
20
+ *
21
+ * Each candidate is launched with the run's own options, which is the probe:
22
+ * one that starts and reports a Chrome major version no more than
23
+ * {@link MAX_MAJORS_BEHIND} behind the CLI's Playwright is used, an older one
24
+ * is closed and skipped. Nothing is ever downloaded or installed here, and
25
+ * only local binaries are started. The winner is remembered for the process so
26
+ * every later launch goes straight to it.
27
+ */
28
+ import path from 'node:path';
29
+ import os from 'node:os';
30
+ import { readdir, stat, readFile, realpath } from 'node:fs/promises';
31
+ import { createRequire } from 'node:module';
32
+
33
+ /** How many Chrome major versions below the CLI's own build a reused browser may be. Playwright supports a stable Chrome this far behind its bundled build. */
34
+ export const MAX_MAJORS_BEHIND = 3;
35
+
36
+ /** At most this many folder candidates are launched, so a cache full of old builds cannot slow `check` down. */
37
+ export const MAX_FOLDER_PROBES = 4;
38
+
39
+ /** What Playwright says when its browser build is not on the disk. Anything else is a real failure and is not papered over. */
40
+ const MISSING_BROWSER = /Executable doesn't exist|is not found at|download new browsers/i;
41
+
42
+ /**
43
+ * Whether a launch error means the browser build is missing.
44
+ * @param {unknown} error
45
+ * @returns {boolean}
46
+ */
47
+ export function isMissingBrowser(error) {
48
+ return MISSING_BROWSER.test(String(error && error.message ? error.message : error || ''));
49
+ }
50
+
51
+ /** The executable inside one revision folder, newest layout first, for each platform. */
52
+ const LAYOUTS = {
53
+ darwin: {
54
+ chromium: [
55
+ 'chrome-mac-arm64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',
56
+ 'chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',
57
+ 'chrome-mac/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing',
58
+ 'chrome-mac/Chromium.app/Contents/MacOS/Chromium'
59
+ ],
60
+ shell: [
61
+ 'chrome-headless-shell-mac-arm64/chrome-headless-shell',
62
+ 'chrome-headless-shell-mac-x64/chrome-headless-shell',
63
+ 'chrome-mac/headless_shell'
64
+ ]
65
+ },
66
+ linux: {
67
+ chromium: ['chrome-linux64/chrome', 'chrome-linux/chrome'],
68
+ shell: ['chrome-headless-shell-linux64/chrome-headless-shell', 'chrome-linux/headless_shell']
69
+ },
70
+ win32: {
71
+ chromium: ['chrome-win64/chrome.exe', 'chrome-win/chrome.exe'],
72
+ shell: ['chrome-headless-shell-win64/chrome-headless-shell.exe', 'chrome-win/headless_shell.exe']
73
+ }
74
+ };
75
+
76
+ /**
77
+ * The browser folders to search, in order, without duplicates: an absolute
78
+ * PLAYWRIGHT_BROWSERS_PATH, then the platform's default cache in the user's
79
+ * profile. Never a folder inside the workspace.
80
+ *
81
+ * The env path is read from the process environment only, never from the
82
+ * repo's config. A relative value is resolved the way Playwright resolves it,
83
+ * against INIT_CWD or else the current folder, so this searches the folder
84
+ * Playwright itself would use. "0" means the workspace's node_modules and is
85
+ * never followed, and a folder that lands inside the workspace (a relative
86
+ * value run from the project, or an absolute one pointing into it) is left
87
+ * out: a cloned repository must not supply the binary that runs.
88
+ *
89
+ * @param {{env?: Object, home?: string, platform?: string, repoRoot?: string, cwd?: string}} [where]
90
+ * @returns {string[]}
91
+ */
92
+ export function registryDirs({ env = process.env, home = os.homedir(), platform = process.platform, repoRoot = process.cwd(), cwd = process.cwd() } = {}) {
93
+ const dirs = [];
94
+ const set = env.PLAYWRIGHT_BROWSERS_PATH;
95
+ const inside = (dir, root) => {
96
+ const relative = path.relative(path.resolve(root), path.resolve(dir));
97
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
98
+ };
99
+ if (set && set !== '0') {
100
+ const resolved = path.isAbsolute(set) ? path.resolve(set) : path.resolve(env.INIT_CWD || cwd, set);
101
+ if (!inside(resolved, repoRoot)) dirs.push(resolved);
102
+ }
103
+ if (platform === 'darwin') dirs.push(path.join(home, 'Library', 'Caches', 'ms-playwright'));
104
+ else if (platform === 'win32') dirs.push(path.join(env.LOCALAPPDATA || path.join(home, 'AppData', 'Local'), 'ms-playwright'));
105
+ else dirs.push(path.join(env.XDG_CACHE_HOME || path.join(home, '.cache'), 'ms-playwright'));
106
+ return [...new Set(dirs)];
107
+ }
108
+
109
+ /**
110
+ * Whether a found browser may be started: its symlinks resolved, the resolved
111
+ * executable still inside its own (resolved) revision folder, then it and
112
+ * every folder above it, up to the root of the disk, owned by this user or
113
+ * root and writable by no group and no one else. A link that leads out of its
114
+ * revision folder is refused. Windows has no such modes; there only the
115
+ * profile cache and the env path are searched, and the path is still resolved
116
+ * and held to its revision folder.
117
+ *
118
+ * @param {string} executablePath
119
+ * @param {{fs?: {realpath: Function, stat: Function}, uid?: number|null, platform?: string, root?: string}} [seams] root: the revision folder it was found in
120
+ * @returns {Promise<{ok: true, realPath: string}|{ok: false, reason: string}>}
121
+ */
122
+ export async function trustedExecutable(executablePath, { fs = { realpath, stat }, uid = typeof process.getuid === 'function' ? process.getuid() : null, platform = process.platform, root = null } = {}) {
123
+ let real;
124
+ let realRoot = null;
125
+ try {
126
+ real = await fs.realpath(executablePath);
127
+ if (root) realRoot = await fs.realpath(root);
128
+ } catch (error) {
129
+ return { ok: false, reason: `could not be resolved (${error && error.code ? error.code : 'error'})` };
130
+ }
131
+ if (realRoot) {
132
+ const relative = path.relative(realRoot, real);
133
+ if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative)) {
134
+ return { ok: false, reason: `it leads out of its browser folder, to ${real}` };
135
+ }
136
+ }
137
+ if (platform === 'win32' || uid === null) return { ok: true, realPath: real };
138
+ let current = real;
139
+ for (;;) {
140
+ let info;
141
+ try {
142
+ info = await fs.stat(current);
143
+ } catch (error) {
144
+ return { ok: false, reason: `${current} could not be read (${error && error.code ? error.code : 'error'})` };
145
+ }
146
+ if (info.uid !== uid && info.uid !== 0) return { ok: false, reason: `${current} belongs to another user` };
147
+ if ((info.mode & 0o022) !== 0) return { ok: false, reason: `${current} can be changed by other users` };
148
+ const parent = path.dirname(current);
149
+ if (parent === current) break;
150
+ current = parent;
151
+ }
152
+ return { ok: true, realPath: real };
153
+ }
154
+
155
+ /**
156
+ * The Chromium the CLI's own Playwright was released with, or null when that
157
+ * cannot be read (no Playwright, or a layout this does not know).
158
+ *
159
+ * @param {{resolve?: (id: string) => string, read?: (file: string) => Promise<string>}} [seams]
160
+ * @returns {Promise<{revision: number, major: number|null}|null>}
161
+ */
162
+ export async function expectedChromium({ resolve = createRequire(import.meta.url).resolve, read = file => readFile(file, 'utf8') } = {}) {
163
+ try {
164
+ const core = path.dirname(resolve('playwright-core/package.json'));
165
+ const manifest = JSON.parse(await read(path.join(core, 'browsers.json')));
166
+ const entry = (manifest.browsers || []).find(browser => browser.name === 'chromium');
167
+ if (!entry) return null;
168
+ const major = Number(String(entry.browserVersion || '').split('.')[0]);
169
+ return { revision: Number(entry.revision), major: Number.isFinite(major) && major > 0 ? major : null };
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ const exists = async (file, fs) => {
176
+ try {
177
+ await fs.stat(file);
178
+ return true;
179
+ } catch {
180
+ return false;
181
+ }
182
+ };
183
+
184
+ /**
185
+ * Finished Chromium installs in the browser folders, best first: the CLI's own
186
+ * revision, then newer ones nearest first, then older ones nearest first. A
187
+ * full Chromium comes before a headless shell of the same revision, and a
188
+ * shell is left out when the run is not headless.
189
+ *
190
+ * @param {{dirs: string[], platform?: string, expected?: {revision: number}|null, headless?: boolean, fs?: {readdir: Function, stat: Function}}} options
191
+ * @returns {Promise<Array<{executablePath: string, revision: number, kind: 'chromium'|'shell', dir: string, root: string}>>}
192
+ */
193
+ export async function folderCandidates({ dirs, platform = process.platform, expected = null, headless = true, fs = { readdir, stat } }) {
194
+ const layout = LAYOUTS[platform] || LAYOUTS.linux;
195
+ const found = [];
196
+ const seen = new Set();
197
+ for (const dir of dirs) {
198
+ let names;
199
+ try {
200
+ names = await fs.readdir(dir);
201
+ } catch {
202
+ continue;
203
+ }
204
+ for (const name of names) {
205
+ const match = /^chromium(_headless_shell)?-(\d+)$/.exec(name);
206
+ if (!match) continue;
207
+ const kind = match[1] ? 'shell' : 'chromium';
208
+ if (kind === 'shell' && !headless) continue;
209
+ const root = path.join(dir, name);
210
+ // Playwright writes this marker last; a folder without it is a download that never finished.
211
+ if (!(await exists(path.join(root, 'INSTALLATION_COMPLETE'), fs))) continue;
212
+ for (const relative of layout[kind]) {
213
+ const executablePath = path.join(root, relative);
214
+ if (seen.has(executablePath)) break;
215
+ if (await exists(executablePath, fs)) {
216
+ seen.add(executablePath);
217
+ found.push({ executablePath, revision: Number(match[2]), kind, dir, root });
218
+ break;
219
+ }
220
+ }
221
+ }
222
+ }
223
+ const want = expected && Number.isFinite(expected.revision) ? expected.revision : null;
224
+ const rank = candidate => {
225
+ if (want === null) return [1, -candidate.revision];
226
+ if (candidate.revision === want) return [0, 0];
227
+ return candidate.revision > want ? [1, candidate.revision - want] : [2, want - candidate.revision];
228
+ };
229
+ return found.sort((a, b) => {
230
+ const [ga, da] = rank(a);
231
+ const [gb, db] = rank(b);
232
+ return ga - gb || da - db || (a.kind === b.kind ? 0 : a.kind === 'chromium' ? -1 : 1);
233
+ });
234
+ }
235
+
236
+ const majorOf = browser => {
237
+ const version = browser && typeof browser.version === 'function' ? String(browser.version() || '') : '';
238
+ const major = Number(version.split('.')[0]);
239
+ return Number.isFinite(major) && major > 0 ? major : null;
240
+ };
241
+
242
+ const closeQuietly = async browser => {
243
+ try {
244
+ await browser.close();
245
+ } catch {
246
+ // It launched; that it will not close changes nothing here.
247
+ }
248
+ };
249
+
250
+ /** How long one candidate may take to start before it is given up on. */
251
+ export const PROBE_LAUNCH_TIMEOUT_MS = 10000;
252
+
253
+ /**
254
+ * The reuse inputs `check`, the run's preflight and the web driver all pass,
255
+ * so the three search the same places and never disagree.
256
+ *
257
+ * @param {string} repoRoot
258
+ * @param {Object|null} [overrides] test seams
259
+ * @returns {Object}
260
+ */
261
+ export function browserReuseInputs(repoRoot, overrides = null) {
262
+ return { repoRoot, ...(overrides || {}) };
263
+ }
264
+
265
+ /** What `check` and a run say about the browser in use. */
266
+ const describe = (kind, detail) => ({
267
+ own: 'the Chromium of this tool\'s own Playwright',
268
+ folder: `the Playwright Chromium already on this machine at ${detail}`,
269
+ chrome: 'the Chrome installed on this machine'
270
+ })[kind];
271
+
272
+ /** Remembered per process: once a reused browser launched, later launches go straight to it. */
273
+ const processCache = { chosen: null };
274
+
275
+ /**
276
+ * Launch Chromium with these options, reusing a browser the machine already
277
+ * has when the CLI's own Playwright has none.
278
+ *
279
+ * Throws the CLI's own launch error, unchanged except for a `reuse` field
280
+ * listing what was tried, when nothing could be used: the error is what the
281
+ * install command is chosen from, and a run must still fail on it.
282
+ *
283
+ * @param {any} playwright the loaded playwright module
284
+ * @param {Object} [options] chromium.launch options
285
+ * @param {Object} [deps] seams: dirs, platform, expected, fs, cache, repoRoot, env, home
286
+ * @returns {Promise<{browser: any, source: {kind: 'own'|'folder'|'chrome', label: string, executablePath?: string, channel?: string}}>}
287
+ */
288
+ export async function launchChromium(playwright, options = {}, deps = {}) {
289
+ const cache = deps.cache || processCache;
290
+ const headless = options.headless !== false;
291
+ // A headless shell chosen for a headless run cannot open a window, so a remembered choice holds for the same mode only.
292
+ if (cache.chosen && cache.chosen.headless === headless) {
293
+ const browser = await playwright.chromium.launch({ ...options, ...cache.chosen.overrides });
294
+ return { browser, source: cache.chosen.source };
295
+ }
296
+ let ownError;
297
+ try {
298
+ const browser = await playwright.chromium.launch(options);
299
+ return { browser, source: { kind: 'own', label: describe('own') } };
300
+ } catch (error) {
301
+ if (!isMissingBrowser(error)) throw error;
302
+ ownError = error;
303
+ }
304
+
305
+ const expected = deps.expected !== undefined ? deps.expected : await expectedChromium();
306
+ const dirs = deps.dirs || registryDirs({ env: deps.env, home: deps.home, platform: deps.platform, repoRoot: deps.repoRoot, cwd: deps.cwd });
307
+ const folders = await folderCandidates({ dirs, platform: deps.platform, expected, headless, fs: deps.fs });
308
+ const attempts = [
309
+ ...folders.slice(0, MAX_FOLDER_PROBES).map(found => ({
310
+ check: found.executablePath,
311
+ root: found.root,
312
+ overrides: { executablePath: found.executablePath },
313
+ source: { kind: 'folder', label: describe('folder', found.executablePath), executablePath: found.executablePath, revision: found.revision }
314
+ })),
315
+ { overrides: { channel: 'chrome' }, source: { kind: 'chrome', label: describe('chrome'), channel: 'chrome' } }
316
+ ];
317
+
318
+ const tried = [];
319
+ for (const attempt of attempts) {
320
+ if (attempt.check) {
321
+ const trusted = await trustedExecutable(attempt.check, { fs: deps.fs, uid: deps.uid, platform: deps.platform, root: attempt.root });
322
+ if (!trusted.ok) {
323
+ tried.push({ ...attempt.source, outcome: 'not started', detail: trusted.reason });
324
+ continue;
325
+ }
326
+ // The resolved path is what starts, so a link swapped after the check changes nothing.
327
+ attempt.overrides = { executablePath: trusted.realPath };
328
+ if (trusted.realPath !== attempt.check) {
329
+ attempt.source = { ...attempt.source, executablePath: trusted.realPath, label: `${attempt.source.label}, which leads to ${trusted.realPath}` };
330
+ }
331
+ }
332
+ let browser;
333
+ try {
334
+ // A short limit: a candidate that hangs must not cost the full default each.
335
+ browser = await playwright.chromium.launch({ ...options, timeout: PROBE_LAUNCH_TIMEOUT_MS, ...attempt.overrides });
336
+ } catch (error) {
337
+ tried.push({ ...attempt.source, outcome: 'did not start', detail: String(error && error.message ? error.message : error).split('\n')[0] });
338
+ continue;
339
+ }
340
+ const major = majorOf(browser);
341
+ if (major === null) {
342
+ await closeQuietly(browser);
343
+ tried.push({ ...attempt.source, outcome: 'version unknown', detail: 'it started but did not report a Chrome version, so it could not be judged' });
344
+ continue;
345
+ }
346
+ if (expected && expected.major && major < expected.major - MAX_MAJORS_BEHIND) {
347
+ await closeQuietly(browser);
348
+ tried.push({ ...attempt.source, outcome: 'too old', detail: `Chrome ${major}, and this tool's Playwright needs ${expected.major - MAX_MAJORS_BEHIND} or newer` });
349
+ continue;
350
+ }
351
+ cache.chosen = { overrides: attempt.overrides, source: attempt.source, headless };
352
+ return { browser, source: attempt.source };
353
+ }
354
+ ownError.reuse = tried;
355
+ throw ownError;
356
+ }
357
+
358
+ /** Forget the remembered browser. Tests only. */
359
+ export function resetChosenBrowser(cache = processCache) {
360
+ cache.chosen = null;
361
+ }
@@ -24,6 +24,7 @@ import { recordingLimits, recordingViewport, recordingDirectory, recordingMetada
24
24
  import path from 'node:path';
25
25
  import { gameRefusal, runnerGone } from '../gameRefusal.js';
26
26
  import { createAvoidGuard } from '../avoid.js';
27
+ import { launchChromium } from '../browserSource.js';
27
28
  import { classifyRequest, createSafetyCounts, networkRules, isIngestCall } from '../livesite/network.js';
28
29
  // A run's network access to the game's listed servers (the platform's docs/playtest-network/CONTRACT.md).
29
30
  import { createEgress, egressBrowserArgs, hostLabel, parseEntries } from '../egress.js';
@@ -1290,6 +1291,7 @@ export function browserLaunchArgs({ video, liveSite, headless = false }) {
1290
1291
  /**
1291
1292
  * @param {Object} opts
1292
1293
  * @param {(specifier: string) => Promise<any>} [opts.importer] test seam
1294
+ * @param {Object} [opts.browserReuse] test seams for finding a Chromium the machine already has (../browserSource.js)
1293
1295
  * @param {boolean} [opts.headless]
1294
1296
  * @param {{token?: string, runId?: string, jobId?: string, persona?: string}} [opts.playtest]
1295
1297
  * the run's playtest identity, handed to the page so the game's own SDK
@@ -1500,7 +1502,7 @@ function maskShare(mask) {
1500
1502
  return mask.length ? n / mask.length : 1;
1501
1503
  }
1502
1504
 
1503
- export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null, ingestOrigins = null, network = null, egressTest = null } = {}) {
1505
+ export function createWebDriver({ importer, headless = true, playtest = null, platform = process.platform, modifier = null, recording = {}, now = () => Date.now(), inspectVideo = probeVideo, freezeTime = true, touch = false, frameStrip = true, liveSite = null, ingestOrigins = null, network = null, egressTest = null, browserReuse = null } = {}) {
1504
1506
  const editModifier = modifier === 'Meta' || modifier === 'Control' ? modifier : platformModifier(platform);
1505
1507
  // What the brief asks the run to stay out of (../avoid.js): an input on such a control is never sent (setAvoid).
1506
1508
  let avoidGuard = createAvoidGuard([]);
@@ -3233,7 +3235,8 @@ export function createWebDriver({ importer, headless = true, playtest = null, pl
3233
3235
  const proxy = await egress.start();
3234
3236
  launchArgs.push(...egressBrowserArgs(proxy.url, { direct: buildHostsOf(url) }), ...testArgs);
3235
3237
  }
3236
- browser = await playwright.chromium.launch({ headless, ...(launchArgs.length ? { args: launchArgs } : {}) });
3238
+ // The CLI's own Chromium, or one the machine already has when that build is missing (../browserSource.js).
3239
+ browser = (await launchChromium(playwright, { headless, ...(launchArgs.length ? { args: launchArgs } : {}) }, browserReuse || {})).browser;
3237
3240
  const contextBase = { viewport, ...(touch ? { hasTouch: true, isMobile: true, deviceScaleFactor: 1, userAgent: PHONE_USER_AGENT } : {}) };
3238
3241
  // A live site's sign-in happens first, in a context of its own with no recording of any kind; the
3239
3242
  // recorded context starts from its cookies and storage, so it never shows the form being filled.