ravensight-playtest 0.20.0 → 0.20.2

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.0",
3
+ "version": "0.20.2",
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
@@ -951,8 +951,14 @@ export function report(error) {
951
951
  // cannot probe for a game's existence. That means the message alone can
952
952
  // never tell a developer which of the two it was, so name both.
953
953
  if (error.status === 404 && /\/api\/v1\/games\//.test(error.path || '')) {
954
+ const raw = (/\/api\/v1\/games\/([^/?#]+)/.exec(error.path || '') || [])[1];
955
+ let game = raw;
956
+ try { game = raw && decodeURIComponent(raw); } catch { /* shown as sent */ }
954
957
  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.');
958
+ // The likeliest cause is a token approved for other games. One token can
959
+ // cover several games or all of them; the approval page is where.
960
+ 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.`);
961
+ ui.info('Run ravensight-playtest check to see the games this token covers.');
956
962
  return ExitCode.FAILURE;
957
963
  }
958
964
  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,
@@ -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
@@ -99,13 +99,25 @@ export function modeOutcomes(runs = [], controllers = ['standard', 'jev'], admis
99
99
  state: run?.state || 'not_started',
100
100
  reason: run?.state_reason ? boundedReason(run.state_reason) : null,
101
101
  reportValid: report ? report.valid === true : false,
102
- findings: report && Number.isSafeInteger(report.findings_count) ? report.findings_count : null,
102
+ findings: findingCount(report),
103
103
  wouldContinue: report && typeof report.would_continue === 'boolean' ? report.would_continue : null,
104
104
  recording: run?.recording?.status || null
105
105
  };
106
106
  });
107
107
  }
108
108
 
109
+ // The severities that are problems. A report's `findings_count` also counts what worked (severity praise), so a run with nothing
110
+ // wrong read "1 finding" on the release 20 paid proofs (Dojo Duel and Coin Yard, whose reports held 0).
111
+ const PROBLEM_SEVERITIES = ['blocker', 'major', 'minor', 'cosmetic'];
112
+
113
+ /** How many problems a run's report holds: the sum of its severity counts, or its findings count when it has none. Null with no report. */
114
+ export function findingCount(report) {
115
+ if (!report) return null;
116
+ const counts = report.severity_counts;
117
+ if (counts && typeof counts === 'object' && PROBLEM_SEVERITIES.every(k => Number.isSafeInteger(counts[k]) && counts[k] >= 0)) return PROBLEM_SEVERITIES.reduce((n, k) => n + counts[k], 0);
118
+ return Number.isSafeInteger(report.findings_count) ? report.findings_count : null;
119
+ }
120
+
109
121
  /** "Geri: completed, 4 findings, video saved." or "speedrunner: queued, position 2, ..." */
110
122
  export function modeLine(row, now = Date.now()) {
111
123
  if (row.queue && row.state === 'queued') return `${row.name}: ${queueLine(row.queue, now).replace(/^Queued/, 'queued')}`;
@@ -16,7 +16,7 @@
16
16
  // (the platform repo, infrastructure/hosted-playtest/direct-runner/lib/anygame/genre.mjs).
17
17
  // The 2D kinds and styles (a real-time strategy game, tower defense, point and click, and styles such as fighting or a sliding
18
18
  // puzzle) live in the genre2d file, so the kinds others add here and those stay apart.
19
- import { KINDS_2D, KIND_IDS_2D, ALIASES_2D, STYLES_2D, STYLE_ASKS, styleAsk, parseStyle, styleFits, describeStyle, styleOver } from './genre2d.js';
19
+ import { KINDS_2D, KIND_IDS_2D, ALIASES_2D, STYLES_2D, STYLE_ASKS, styleAsk, parseStyle, styleFits, describeStyle, styleOver, screenStyle, styleKind } from './genre2d.js';
20
20
 
21
21
  export const DEFAULT_KIND = 'unknown';
22
22
  // Looks in a row that must agree before the kind is settled, and looks after which the question is dropped.
@@ -180,11 +180,32 @@ export function parseKind(v, { three = false } = {}) {
180
180
  return null;
181
181
  }
182
182
 
183
- /** `is3d`: whether the page now shows a 3D scene (a measured 3D pose); a word both kinds of game are called by follows it. */
184
- export function createGenre({ hint = null, is3d = () => false } = {}) {
183
+ // On a page that listens for touch alone the kind's advice speaks of the stick and fingers, never of keys (the release 20
184
+ // paid proof Thumb Ship was told "hold keys to move" on a touch-only phone game).
185
+ const TOUCH_WORDS = [[/\bhold keys to move\b/g, 'hold the on screen stick or a finger to move']];
186
+ const forTouch = text => TOUCH_WORDS.reduce((t, [re, to]) => t.replace(re, to), String(text));
187
+
188
+ /**
189
+ * `is3d`: whether the page now shows a 3D scene (a measured 3D pose); a word both kinds of game are called by follows it.
190
+ * `touch`: whether the page in play listens for touch alone, so the advice names no keys.
191
+ */
192
+ export function createGenre({ hint = null, is3d = () => false, touch = () => false } = {}) {
185
193
  let settled = parseKind(hint), settledAt = settled ? 0 : null, source = settled ? 'the job' : null;
186
- let last = null, streak = 0, asks = 0, style2d = null, described = null, styleAsks = 0, hintSeen3d = false;
194
+ let last = null, streak = 0, asks = 0, style2d = null, described = null, onScreen = null, styleAsks = 0, hintSeen3d = false;
187
195
  const votes = {};
196
+ const touchNow = () => { try { return Boolean(touch()); } catch { return false; } };
197
+ /**
198
+ * A style that fits one kind only (fighting is real-time action) settles that kind on the first reading of it, without
199
+ * waiting for a second look in a row: the style was named in the planner's own description or on the game's own screen.
200
+ * On the release 20 paid proof Dojo Duel settled at step 23 of 35 on two looks, and its combos went out unspaced until then.
201
+ */
202
+ function settleByStyle(step) {
203
+ if (settled || !last || streak < 1) return false;
204
+ const st = [style2d, described, onScreen].find(x => x && styleKind(x) === last);
205
+ if (!st) return false;
206
+ settled = last; settledAt = step; source = 'the playtester\'s reading of the screen, with its style';
207
+ return true;
208
+ }
188
209
  const three = () => { try { return Boolean(is3d()); } catch { return false; } };
189
210
  // The job's word is read before the page is seen; once the page shows a 3D scene it is read again, once ("rts" on a 3D map).
190
211
  function hintOn3d() {
@@ -209,16 +230,24 @@ export function createGenre({ hint = null, is3d = () => false } = {}) {
209
230
  settled = kind; settledAt = step; source = 'the playtester\'s reading of the screen';
210
231
  return true;
211
232
  }
212
- return false;
233
+ return settleByStyle(step);
213
234
  }
214
235
 
215
236
  /**
216
237
  * The planner's own description of the game (its "about"): a style it names there is kept when the kind answer named none
217
238
  * (genre2d describeStyle). A later description replaces an earlier one; one that names no style changes nothing.
218
239
  */
219
- function describe(text) {
240
+ function describe(text, step = 0) {
220
241
  const st = describeStyle(text);
221
242
  if (st) described = st;
243
+ return settleByStyle(step);
244
+ }
245
+
246
+ /** What the game's own screen says (the planner's copy of it): a style it names (genre2d screenStyle) is kept as a description's is. */
247
+ function screen(text, step = 0) {
248
+ const st = screenStyle(text);
249
+ if (st) onScreen = st;
250
+ return settleByStyle(step);
222
251
  }
223
252
 
224
253
  const kind = () => { hintOn3d(); return settled || DEFAULT_KIND; };
@@ -243,22 +272,23 @@ export function createGenre({ hint = null, is3d = () => false } = {}) {
243
272
  /** The play style as lines for the plan, once a kind is settled; [] for the default. */
244
273
  /** The 2D style kept for the settled kind, or null (the genre2d file). */
245
274
  // The kind answer's own style first, then one the planner's description named (describe).
246
- const style2dNow = () => (!settled ? null : style2d && styleFits(style2d, settled) ? style2d : described && styleFits(described, settled) ? described : null);
275
+ const style2dNow = () => (!settled ? null : [style2d, described, onScreen].find(st => st && styleFits(st, settled)) || null);
247
276
 
248
277
  function lines() {
249
278
  hintOn3d();
250
279
  if (!settled) return [];
251
280
  const s = style(), st = style2dNow();
252
- return [`This is ${s.label}. How to play it: ${s.pacing} ${s.waits} ${s.replan} Progress here is: ${s.progress}.`, ...(st ? [STYLES_2D[st].line] : [])];
281
+ const out = [`This is ${s.label}. How to play it: ${s.pacing} ${s.waits} ${s.replan} Progress here is: ${s.progress}.`, ...(st ? [STYLES_2D[st].line] : [])];
282
+ return touchNow() ? out.map(forTouch) : out;
253
283
  }
254
284
 
255
285
  /** What the executor is told about this kind of game (one or two sentences). */
256
- const helperLine = () => { hintOn3d(); return settled ? [style().helper, style2dNow() ? STYLES_2D[style2dNow()].helper : ''].filter(Boolean).join(' ') : ''; };
286
+ const helperLine = () => { hintOn3d(); const line = settled ? [style().helper, style2dNow() ? STYLES_2D[style2dNow()].helper : ''].filter(Boolean).join(' ') : ''; return touchNow() ? forTouch(line) : line; };
257
287
 
258
288
  function digest() {
259
289
  const s = style();
260
290
  return { kind: kind(), style2d: style2dNow(), label: s.label, settledAtStep: settledAt, source, votes: { ...votes }, style: { pacing: s.pacing, waits: s.waits, replan: s.replan, progress: s.progress, fast: s.fast }, needsSound: Boolean(s.needsSound) };
261
291
  }
262
292
 
263
- return { read, describe, ask, lines, helperLine, kind, style, style2d: style2dNow, digest, get settled() { hintOn3d(); return Boolean(settled); } };
293
+ return { read, describe, screen, ask, lines, helperLine, kind, style, style2d: style2dNow, digest, get settled() { hintOn3d(); return Boolean(settled); } };
264
294
  }
@@ -123,6 +123,71 @@ export function describeStyle(text) {
123
123
  return best;
124
124
  }
125
125
 
126
+ // What a fighting game's own screen says before play: a combo of punches and kicks. On the release 20 paid proof Dojo Duel's
127
+ // title read "J punches, K kicks, hold L to block. Combo: J, J, K, each a quarter to half a second after the last." and the
128
+ // style settled only at step 23 of 35, after 3 of its 4 combo tries were planned. Only words a fighting game's screen shows
129
+ // together count: a combo with a punch or a kick named beside it.
130
+ const ON_SCREEN = [
131
+ ['fighting', t => /\bcombos?\b/.test(t) && /\b(?:punch(?:es)?|kicks?)\b/.test(t)]
132
+ ];
133
+
134
+ /** A 2D style named by what the game's own screen says (the planner's copy of it), or null. Stricter than describeStyle. */
135
+ export function screenStyle(text) {
136
+ const t = String(text ?? '').toLowerCase();
137
+ if (!t.trim()) return null;
138
+ for (const [id, cue] of ON_SCREEN) if (cue(t)) return id;
139
+ return null;
140
+ }
141
+
142
+ /** The one kind a style fits, or null when it fits several or any (racing, roguelike). */
143
+ export const styleKind = style => (STYLES_2D[style]?.kinds.length === 1 ? STYLES_2D[style].kinds[0] : null);
144
+
145
+ // The gap between combo presses when the game does not say: the fighting line's own "about 350 ms apart".
146
+ export const COMBO_GAP_MS = 350;
147
+ // What counts as a press in a combo, and how many: a tap (held this long at most), two to six of them.
148
+ export const COMBO_TAP_MS = 200;
149
+ export const COMBO_PRESSES = [2, 6];
150
+ const FRACTION_MS = { quarter: 250, third: 333, half: 500 };
151
+
152
+ /**
153
+ * The time a game gives between combo presses, from its own words: `{ min, max }` in ms, or null when the text names none.
154
+ * Reads "a quarter to half a second", "0.25 to 0.55 s", "250 to 550 ms" and "between 250 and 550 milliseconds".
155
+ */
156
+ export function comboWindow(text) {
157
+ const t = String(text ?? '').toLowerCase().replace(/\s+/g, ' ');
158
+ if (!t.trim()) return null;
159
+ const ok = (min, max) => (Number.isFinite(min) && Number.isFinite(max) && min >= 50 && max <= 2000 && max > min ? { min: Math.round(min), max: Math.round(max) } : null);
160
+ const words = /\b(?:an? |one )?(quarter|third|half)(?: of)?(?: an? second)? ?(?:to|and|or|-) ?(?:an? |one )?(quarter|third|half)(?: of)? an? second\b/.exec(t);
161
+ if (words) { const w = ok(FRACTION_MS[words[1]], FRACTION_MS[words[2]]); if (w) return w; }
162
+ const nums = /\b(\d+(?:\.\d+)?) ?(?:to|and|-) ?(\d+(?:\.\d+)?) ?(ms|milliseconds?|s|secs?|seconds?)\b/.exec(t);
163
+ if (nums) {
164
+ const k = /^m/.test(nums[3]) ? 1 : 1000;
165
+ const w = ok(Number(nums[1]) * k, Number(nums[2]) * k);
166
+ if (w) return w;
167
+ }
168
+ return null;
169
+ }
170
+
171
+ /**
172
+ * A combo the planner wrote as one timed sequence of key taps, played inside the window the game gives between presses:
173
+ * the steps with each press `gap` ms after the last, where `gap` is the middle of `window` (COMBO_GAP_MS when the game
174
+ * gave none). Answers null when the sequence is not a combo (a click or a move in it, a key held, two keys at once, too
175
+ * few or too many presses) or when every gap already sits inside the window.
176
+ */
177
+ export function spaceCombo(steps, window = null) {
178
+ if (!Array.isArray(steps)) return null;
179
+ const n = steps.length;
180
+ if (n < COMBO_PRESSES[0] || n > COMBO_PRESSES[1]) return null;
181
+ if (!steps.every(s => s && typeof s === 'object' && typeof s.key === 'string' && s.key.trim() && !s.key.includes('+') && s.click === undefined && s.move === undefined && Number.isFinite(Number(s.at)) && !(Number(s.holdMs) > COMBO_TAP_MS))) return null;
182
+ const at = steps.map(s => Number(s.at));
183
+ for (let i = 1; i < n; i++) if (!(at[i] > at[i - 1])) return null;
184
+ const win = window && Number.isFinite(window.min) && Number.isFinite(window.max) ? window : { min: Math.round(COMBO_GAP_MS * 0.75), max: Math.round(COMBO_GAP_MS * 1.5) };
185
+ const gaps = at.slice(1).map((v, i) => v - at[i]);
186
+ if (gaps.every(g => g >= win.min && g <= win.max)) return null;
187
+ const gap = window ? Math.round((win.min + win.max) / 2) : COMBO_GAP_MS;
188
+ return steps.map((s, i) => ({ ...s, at: i * gap }));
189
+ }
190
+
126
191
  /** What a settled kind is called and how it is paced under a style that changes them (a roguelike played in turns), or null. */
127
192
  export const styleOver = (style, kind) => STYLES_2D[style]?.over?.[kind] || null;
128
193
 
@@ -130,7 +130,8 @@ export function createLocalAnyGame({ briefText = '', controls = null, touch = fa
130
130
  let overSaid = false;
131
131
  const book = createControlBook({ touch, given: controls });
132
132
  // `is3d`: the page has shown a 3D scene (a measured pose), so "rts" or "racing" names the 3D kind (./genre.js).
133
- const genre = createGenre({ is3d });
133
+ // `touch`: a run played with a finger is never told to hold keys to move.
134
+ const genre = createGenre({ is3d, touch: () => touch });
134
135
  const briefLanguage = detectLanguage(briefText);
135
136
  const report = reportLanguage(briefText, { explicit: reportLanguageHint });
136
137
  let sound = null, soundTest = null;
@@ -443,27 +443,33 @@ export function world3dFindings(steps, { won = false } = {}) {
443
443
  } else i = Math.max(i + 1, j);
444
444
  }
445
445
 
446
- // Fell out of the world: below the level's lowest point, still going down at the end of play, and far below it.
447
- const posedSteps = list.filter(posed);
448
- const last = posedSteps.at(-1);
449
- if (last && last.after.floorY !== null) {
450
- const floorY = last.after.floorY, y = p => p.pos[1];
451
- const firstBelow = posedSteps.findIndex(t => y(t.after) < floorY - L.fallBelow);
452
- const tail = firstBelow >= 0 ? posedSteps.slice(firstBelow) : [];
453
- const stayed = tail.length && tail.every(t => y(t.after) < floorY - L.fallBelow);
454
- const falling = tail.length >= 2 && y(tail.at(-1).after) < y(tail.at(-2).after);
446
+ // Fell out of the world: below the level's lowest point, still going down at the end of play (or when the run loaded the game
447
+ // again because of it, a step of kind `restart`), and far below it. The first such fall is the finding.
448
+ const segments = [];
449
+ let seg = [];
450
+ for (const t of list) {
451
+ if (t.kind === 'restart') { if (seg.length) segments.push({ steps: seg, restartAt: t.step }); seg = []; continue; }
452
+ if (posed(t)) seg.push(t);
453
+ }
454
+ if (seg.length) segments.push({ steps: seg, restartAt: null });
455
+ for (const { steps: posedSteps, restartAt } of segments) {
456
+ const last = posedSteps.at(-1);
457
+ if (!last || last.after.floorY === null) continue;
458
+ const floorY = last.after.floorY;
459
+ const tail = fallTail(posedSteps.map(t => t.after), floorY);
460
+ if (!tail) continue;
461
+ const f = posedSteps[posedSteps.length - tail.length];
455
462
  // Play reached the game: an input it received came at or before the fall, so the pose is not the page's word alone.
456
- const played = tail.length > 0 && list.some(t => t.step <= tail[0].step && (t.received === true || t.captured === true));
457
- if (stayed && falling && played && y(last.after) < floorY - L.fallDepth) {
458
- const f = tail[0];
459
- out.push({
460
- kind: 'fell_out', key: 'world3d:fell', atStep: f.step, severity: 'major', category: 'bug',
461
- title: 'The player fell out of the world',
462
- description: `At step ${f.step} the player (${f.after.subject === 'camera' ? 'the camera' : `"${f.after.subject}"`}) went below the lowest point of the level (height ${floorY.toFixed(1)}) and never came back: at the end of play, step ${last.step}, it was at height ${y(last.after).toFixed(1)} and still falling. Nothing put it back on the level.`,
463
- steps: [list[list.indexOf(f) - 1], f, last].filter(Boolean).map(t => t.step), shots: shots([f, last]),
464
- facts: { floorY, at: f.after.pos, endY: y(last.after) }
465
- });
466
- }
463
+ if (!list.some(t => t.step <= f.step && (t.received === true || t.captured === true))) continue;
464
+ const endY = last.after.pos[1];
465
+ out.push({
466
+ kind: 'fell_out', key: 'world3d:fell', atStep: f.step, severity: 'major', category: 'bug',
467
+ title: 'The player fell out of the world',
468
+ description: `At step ${f.step} the player (${f.after.subject === 'camera' ? 'the camera' : `"${f.after.subject}"`}) went below the lowest point of the level (height ${floorY.toFixed(1)}) and never came back: ${restartAt === null ? `at the end of play, step ${last.step}, it was at height ${endY.toFixed(1)} and still falling. Nothing put it back on the level.` : `at step ${last.step} it was at height ${endY.toFixed(1)} and still falling, and nothing had put it back on the level, so the run loaded the game again at step ${restartAt}.`}`,
469
+ steps: [list[list.indexOf(f) - 1], f, last].filter(Boolean).map(t => t.step), shots: shots([f, last]),
470
+ facts: { floorY, at: f.after.pos, endY, ...(restartAt === null ? {} : { restartAt }), toStep: last.step }
471
+ });
472
+ break;
467
473
  }
468
474
 
469
475
  // The camera inside a solid: the first input the page received after which the camera was inside a box the game draws as solid.
@@ -533,6 +539,33 @@ export function world3dFindings(steps, { won = false } = {}) {
533
539
  return out;
534
540
  }
535
541
 
542
+ /**
543
+ * The poses of a fall out of the world at the end of `poses` (in order, each with `pos`), or null: below `floorY` by more
544
+ * than fallBelow from the first of them on, still going down at the last, and more than fallDepth below at the last.
545
+ */
546
+ function fallTail(poses, floorY) {
547
+ if (!Number.isFinite(floorY)) return null;
548
+ const y = p => p.pos[1];
549
+ const first = poses.findIndex(p => y(p) < floorY - L.fallBelow);
550
+ const tail = first >= 0 ? poses.slice(first) : [];
551
+ if (tail.length < 2 || !tail.every(p => y(p) < floorY - L.fallBelow)) return null;
552
+ if (!(y(tail.at(-1)) < y(tail.at(-2))) || !(y(tail.at(-1)) < floorY - L.fallDepth)) return null;
553
+ return tail;
554
+ }
555
+
556
+ /**
557
+ * Whether the poses measured since the game was last loaded show the player falling out of the world now (the fall rule of
558
+ * world3dFindings, as play goes): a run that sees it loads the game again instead of walking on in the void. `{ floorY, y, from }`
559
+ * (`from` the index of the first pose below the level) or null. Only a measured pose counts; a picture never does.
560
+ */
561
+ export function fallingOut(poses) {
562
+ const list = (Array.isArray(poses) ? poses : []).filter(p => p && Array.isArray(p.pos) && Number.isFinite(p.pos[1]));
563
+ const last = list.at(-1);
564
+ if (!last || !Number.isFinite(last.floorY)) return null;
565
+ const tail = fallTail(list, last.floorY);
566
+ return tail ? { floorY: last.floorY, y: last.pos[1], from: list.length - tail.length } : null;
567
+ }
568
+
536
569
  /**
537
570
  * Movement inputs of `among` that something stopped: held long enough, received, and moved the player less than blockedShare of
538
571
  * the run's usual distance for that time (the median over the run's movement inputs that moved), one a place (places at least
@@ -4,14 +4,14 @@
4
4
  "language": "2b95828c77a8e82440c53d330381b7ba830796312d2ae9b7edc8fd95ff72e1ef",
5
5
  "memory": "76ad175baeb3f066ff566f76460d4b414c545f683fe4fe0ab16b0125a63d3fce",
6
6
  "controlbook": "1b388c0dd0c60f332131a095cf89eb4ee181671c60a2b4e45750a0a918c6ea9e",
7
- "genre": "b3344e6b8d4f56e1b415becc635dca60c110e16b8f289aecad6a6b4bd25a925a",
8
- "genre2d": "da57ee8e4886e64bb399cc786f6cc979383b071e23f0ac6e5e098edce0d9e2b7",
7
+ "genre": "5b26e7a610622599f8e0b2dcdeff3748e00e47f89a3be282abafac359a73443c",
8
+ "genre2d": "e8d8c607f61d1049a8a031263ac464dc15db2988a88fb0796bca05ab5da1ef4e",
9
9
  "sound": "bc1264cb971417f4c6c6966ecba217721e59bc30dc069b48ade0bf8174e1444e",
10
10
  "gamenotes": "f0ab9c9be900c17824d6e37beeead7210bfe280573860e4d0ecd4ac2edd36678",
11
11
  "claimwords": "6cd99897a09dae67d0b657a110476fb0f8b27ae4124da9c60b79b2b0d28133b7",
12
12
  "events": "8b1cbb4cf48b1e1e1f1de064e2f3cbf4ecd8473d4a518c20caa3c8953a3a1708",
13
13
  "eventclaims": "11dfdd3e0928447ce3e21408c7b2f9eedb499e92ada39ca8b48222646cadc23b",
14
14
  "egress": "65053e3fc47f9746f9662da8a5bfa2c31b7252d8c66528849fd0bf0b0006dd80",
15
- "scene3d": "9d2cdbc47985935e1e81993d196bae0e1c2b7046a666113d5bb75f4ed2314a4e"
15
+ "scene3d": "43d4ed85c9f2e0b2de93507b270c979e6e2b898d22902e34e381523b1d33486e"
16
16
  }
17
17
  }
@@ -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.