ravensight-playtest 0.19.0 → 0.20.0

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/src/run/args.js CHANGED
@@ -12,6 +12,8 @@
12
12
 
13
13
  import { startProblems } from './startFrom.js';
14
14
  import { sessionProblems } from './sessions.js';
15
+ import { launchArgProblems } from './launchArgs.js';
16
+ import { slowMotionProblems } from './slowMotion.js';
15
17
 
16
18
  /** Options that take a value. */
17
19
  const VALUED = new Map([
@@ -43,6 +45,8 @@ const VALUED = new Map([
43
45
  ['--godot-path', 'godotPath'],
44
46
  ['--cli', 'cli'],
45
47
  ['--max-actions', 'maxActions'],
48
+ // Slow motion through the SDK pause hook (./slowMotion.js): the share of its speed the game runs at while the persona decides.
49
+ ['--time-scale', 'timeScale'],
46
50
  ['--concurrency', 'concurrency'],
47
51
  ['--quality', 'quality'],
48
52
  ['--key-modifier', 'keyModifier'],
@@ -62,7 +66,9 @@ const REPEATED = new Map([
62
66
  ['--focus', 'focus'],
63
67
  ['--avoid', 'avoid'],
64
68
  // A save file a native local run starts from, up to eight (./startFrom.js).
65
- ['--save', 'save']
69
+ ['--save', 'save'],
70
+ // An argument handed to a native build this machine starts, never through a shell (./launchArgs.js).
71
+ ['--launch-arg', 'launchArg']
66
72
  ]);
67
73
 
68
74
  /** Options that are just present or absent. */
@@ -104,6 +110,8 @@ const BOOLEAN = new Map([
104
110
  // godot_driver only: let the game run in real time between actions instead
105
111
  // of pausing it while the persona thinks.
106
112
  ['--realtime', 'realtime'],
113
+ // Keep a --realtime action game at full speed: no slow motion (./slowMotion.js).
114
+ ['--no-slow-motion', 'noSlowMotion'],
107
115
  // Native drivers only: register without the free automation probe first.
108
116
  ['--skip-preflight', 'skipPreflight'],
109
117
  // Resume only: replay an interrupted run from the start instead of writing a
@@ -123,7 +131,7 @@ const BOOLEAN = new Map([
123
131
  ]);
124
132
 
125
133
  /** Options whose value is a number. */
126
- const NUMERIC = new Set(['maxActions', 'concurrency', 'minutes', 'sessions']);
134
+ const NUMERIC = new Set(['maxActions', 'concurrency', 'minutes', 'sessions', 'timeScale']);
127
135
 
128
136
  /**
129
137
  * @param {string[]} argv the leftovers commander handed over
@@ -275,7 +283,8 @@ export function scopeProblems(options = {}, driverName = '') {
275
283
  if (typeof options.start !== 'string' || !/^[?#][^\s\\]{0,199}$/.test(options.start)) problems.push('Choose --start as a query or hash on the build, such as ?level=3 or #boss.');
276
284
  else if (driverName && driverName !== 'playwright_web') problems.push(`--start opens a web build at a query or hash, and this run uses ${driverName}. A native run starts from --save or --start-spec.`);
277
285
  }
278
- problems.push(...startProblems(options, driverName), ...sessionProblems(options, driverName));
286
+ problems.push(...startProblems(options, driverName), ...sessionProblems(options, driverName), ...launchArgProblems(options, driverName));
287
+ problems.push(...slowMotionProblems(options, driverName));
279
288
  return problems;
280
289
  }
281
290
 
@@ -23,7 +23,7 @@ export const MAX_GAME_ARG_CHARS = 1024;
23
23
  export function gameArgs(args) {
24
24
  if (args === undefined || args === null) return [];
25
25
  if (!Array.isArray(args) || args.length > MAX_GAME_ARGS || !args.every(arg => typeof arg === 'string' && arg.length <= MAX_GAME_ARG_CHARS && !arg.includes('\0'))) {
26
- throw new Error(`native.args must be a list of at most ${MAX_GAME_ARGS} strings.`);
26
+ throw new Error(`The game's arguments (native.args and --launch-arg together) must be a list of at most ${MAX_GAME_ARGS} strings, each at most ${MAX_GAME_ARG_CHARS} characters.`);
27
27
  }
28
28
  return [...args];
29
29
  }
@@ -333,4 +333,62 @@ export function describeEnd({ exited, crash, lastError = null, recent = [] }) {
333
333
  return { kind: 'exited', message: `The game process stopped during play (${status}); it left no crash report, so the game itself quit${exited.code && lastError ? `. The last error it printed: ${String(lastError).slice(0, 300)}` : ''}`, ...tail };
334
334
  }
335
335
 
336
- export default { gameEnvironment, screenPoint, gamePixel, lookSteps, captureWindow, launchGame, stopGame, startFrameRecorder, runScreenshot, viewText, describeEnd, abnormalExit, DESKTOP_LOCK };
336
+ /** How long a game is given to quit after Command-Q between sessions, then after a stop signal. */
337
+ export const QUIT_WAIT_MS = 10000;
338
+ export const TERM_WAIT_MS = 5000;
339
+
340
+ /**
341
+ * Quit a game the way a player does, between two sessions of a run
342
+ * (../../sessions.js): Command-Q first, its own Quit, so a game that saves on
343
+ * quit saves; then a polite stop signal (SIGTERM, which SDL and Unreal read
344
+ * as a quit); then a kill. Answers how it went: quit, stop_signal, killed or
345
+ * already_gone.
346
+ *
347
+ * @param {{exitPromise: Promise<unknown>, kill: (signal: string) => unknown}} game
348
+ * @param {{exited: () => unknown, commandQ?: (() => Promise<unknown>)|null, quitWaitMs?: number, termWaitMs?: number}} options
349
+ */
350
+ export async function quitLikeAPlayer(game, { exited, commandQ = null, quitWaitMs = QUIT_WAIT_MS, termWaitMs = TERM_WAIT_MS }) {
351
+ const grace = ms => new Promise(resolve => setTimeout(resolve, ms).unref?.());
352
+ const gone = ms => Promise.race([game.exitPromise.then(() => true), grace(ms).then(() => false)]);
353
+ if (exited()) return 'already_gone';
354
+ if (commandQ) {
355
+ await commandQ().catch(() => null);
356
+ if (await gone(quitWaitMs)) return 'quit';
357
+ }
358
+ game.kill('SIGTERM');
359
+ if (await gone(termWaitMs)) return 'stop_signal';
360
+ game.kill('SIGKILL');
361
+ await gone(2000);
362
+ return 'killed';
363
+ }
364
+
365
+ /**
366
+ * The pause hook's summary across a run's sessions: the first launch's answer, with the times the game resumed
367
+ * by itself added up over every launch, and an end said when a launch's channel closed early.
368
+ */
369
+ export function sessionTimeSummary(earlier = [], current = null) {
370
+ const all = [...earlier, ...(current ? [current] : [])].filter(Boolean);
371
+ if (!all.length) return null;
372
+ if (all.length === 1) return all[0];
373
+ const first = all.find(entry => entry.hook) || all[0];
374
+ const sum = key => all.reduce((total, entry) => total + (Number.isFinite(entry[key]) ? entry[key] : 0), 0);
375
+ const ended = all.find(entry => entry.ended);
376
+ const { ended: _ended, ...rest } = first;
377
+ const slowMotion = sessionSlowMotion(all);
378
+ return { ...rest, ...(first.hook ? { auto_resumed: sum('auto_resumed'), auto_resume_refused: sum('auto_resume_refused') } : {}), ...(ended ? { ended: ended.ended } : {}), ...(slowMotion ? { slow_motion: slowMotion } : {}) };
379
+ }
380
+
381
+ /** Slow motion across sessions (../../slowMotion.js): the first launch that slowed the game, with the slowed time of every launch added up. */
382
+ function sessionSlowMotion(all) {
383
+ const records = all.map(entry => entry.slow_motion).filter(record => record && typeof record === 'object');
384
+ if (!records.length) return null;
385
+ const base = records.find(record => record.status === 'on') || records[0];
386
+ const timed = records.filter(record => Number.isFinite(record.slowed_wall_ms));
387
+ if (!timed.length) return base;
388
+ const { measured_scale: _measured, ...kept } = base;
389
+ const gameMs = timed.reduce((total, record) => total + (Number.isFinite(record.slowed_game_ms) ? record.slowed_game_ms : 0), 0);
390
+ const wallMs = timed.reduce((total, record) => total + record.slowed_wall_ms, 0);
391
+ return { ...kept, slowed_game_ms: gameMs, slowed_wall_ms: wallMs, ...(wallMs > 0 ? { measured_scale: Math.round((gameMs / wallMs) * 1000) / 1000 } : {}) };
392
+ }
393
+
394
+ export default { quitLikeAPlayer, sessionTimeSummary, gameEnvironment, screenPoint, gamePixel, lookSteps, captureWindow, launchGame, stopGame, startFrameRecorder, runScreenshot, viewText, describeEnd, abnormalExit, DESKTOP_LOCK };
@@ -13,6 +13,12 @@
13
13
  // feeds the world watch (../../world3d.js). What the game prints is read for
14
14
  // its errors (./output.js), and when it dies, the report macOS left says why.
15
15
  // No automation server, no network, nothing outside this run.
16
+ //
17
+ // A run that starts from a save or plays several sessions gives the game a
18
+ // home folder of its own (./runHome.js) with the saves in it, and the start
19
+ // spec in its environment (RAVENSIGHT_PLAYTEST_START, first launch only).
20
+ // Between sessions the game is quit the way a player quits it (relaunch)
21
+ // and started again on the same home.
16
22
  import { spawn } from 'node:child_process';
17
23
  import { randomBytes } from 'node:crypto';
18
24
  import fs from 'node:fs/promises';
@@ -35,7 +41,9 @@ import { describeGame, inspectDesktopApp } from './app.js';
35
41
  import { startDesktopHelper } from './helper.js';
36
42
  import { actionKeyCodes } from './keys.js';
37
43
  import { createOutputTail } from './output.js';
38
- import { bundleOf, crashWait, captureWindow, launchThroughLaunchServices, DESKTOP_LOCK, describeEnd, gameEnvironment, launchGame, lookSteps, MODEL_LONG_EDGE, RECORD_INTERVAL_MS, runScreenshot, screenPoint, startFrameRecorder, stopGame as stopProcess, viewText } from './common.js';
44
+ import { createRunHome, needsRunHome, startAnswerOf } from './runHome.js';
45
+ import { START_ENV } from '../../startFrom.js';
46
+ import { bundleOf, crashWait, quitLikeAPlayer, QUIT_WAIT_MS, TERM_WAIT_MS, sessionTimeSummary, captureWindow, launchThroughLaunchServices, DESKTOP_LOCK, describeEnd, gameEnvironment, launchGame, lookSteps, MODEL_LONG_EDGE, RECORD_INTERVAL_MS, runScreenshot, screenPoint, startFrameRecorder, stopGame as stopProcess, viewText } from './common.js';
39
47
 
40
48
  export const DRIVER_NAME = 'desktop_driver';
41
49
  /** The most notches one scroll turns the wheel. */
@@ -60,9 +68,18 @@ export function createDesktopAppDriver({
60
68
  native: plan = {}, startHelper = startDesktopHelper, spawnGame = spawn, lock = lockDevice, inspect = inspectDesktopApp,
61
69
  digest = buildDigest, windowCapture = captureWindow, encode = encodeFrames, now = Date.now, platform = process.platform,
62
70
  settleMs = 200, windowTimeoutMs = 90000, helloTimeoutMs = 10000, recordIntervalMs = RECORD_INTERVAL_MS,
63
- playtest = null, pauseHook = true, timeControl: makeTimeControl = createTimeControl, home = os.homedir(), crashWaitMs = 6000,
64
- findCrashImpl = findCrash, launchServices = true, launchApp = launchThroughLaunchServices
71
+ playtest = null, pauseHook = true, slowMotion = null, timeControl: givenTimeControl = createTimeControl, home = os.homedir(), crashWaitMs = 6000,
72
+ findCrashImpl = findCrash, launchServices = true, launchApp = launchThroughLaunchServices,
73
+ makeRunHome = createRunHome, quitWaitMs = QUIT_WAIT_MS, termWaitMs = TERM_WAIT_MS
65
74
  } = {}) {
75
+ // The time control is made again for each session's launch, with the options of the first (relaunch).
76
+ let timeOptions = null;
77
+ // Slow motion asked for after a hello (an action game, ../../slowMotion.js) is asked of each relaunch's hook again.
78
+ let slowAsked = null;
79
+ const makeTimeControl = options => { timeOptions = options; return givenTimeControl(options); };
80
+ // Where the run starts (../../startFrom.js): a home of the run's own, with the saves in it, and the start spec.
81
+ const start = plan.start && ((plan.start.saves && plan.start.saves.length) || plan.start.spec) ? plan.start : null;
82
+ let runHome = null, launchToken = null, timeSummaries = [];
66
83
  let metadata, runDirectory, signal, unlock, helper, game, source, window, frame, pendingFrame, startedAt, stopPromise, access;
67
84
  let step = 0, shots = 0, gameEnded = null, exited = null, launched = false, pointerAt = null;
68
85
  let recorder = null;
@@ -84,7 +101,7 @@ export function createDesktopAppDriver({
84
101
  await stopPromise.catch(() => {});
85
102
  stopPromise = null; unlock = null; helper = null; game = null; source = null; window = null; frame = null; pendingFrame = null;
86
103
  gameEnded = null; exited = null; launched = false; pointerAt = null; recorder = null; time = null; lastView = undefined;
87
- output = null; ending = null; access = null; step = 0; shots = 0;
104
+ output = null; ending = null; access = null; step = 0; shots = 0; runHome = null; timeSummaries = []; slowAsked = null; driver.sessions = 0;
88
105
  heldErrors.length = 0; world = createWorldWatch(); Object.assign(metrics, freshMetrics());
89
106
  }
90
107
  const label = () => describeGame(metadata);
@@ -129,13 +146,13 @@ export function createDesktopAppDriver({
129
146
  if (stopPromise) return stopPromise;
130
147
  stopPromise = (async () => {
131
148
  let result = { videoPath: null };
132
- const timeControl = time ? time.summary() : null;
149
+ const timeControl = sessionTimeSummary(timeSummaries, time ? time.summary() : null);
133
150
  try {
134
151
  if (recorder) result = await recorder.stop(exited && !['stopped', 'preflight', 'completed'].includes(reason) ? 'game_exited' : reason);
135
152
  // Resume the game before it is stopped, so nothing is left frozen.
136
153
  if (time) await time.close().catch(() => {});
137
154
  } finally {
138
- try { await stopGame(); await helper?.stop(); }
155
+ try { await stopGame(); await helper?.stop(); await runHome?.remove(); }
139
156
  finally { await unlock?.(); }
140
157
  }
141
158
  return timeControl ? { ...result, timeControl } : result;
@@ -166,15 +183,45 @@ export function createDesktopAppDriver({
166
183
  const raised = await helper.send({ kind: 'raise', pid: game.pid, ...point });
167
184
  if (!raised.onTop) throw new Error('Another window covers the game and the game could not be brought to the front; the input was not sent.');
168
185
  }
186
+ /**
187
+ * Start the game once with `env` (cleaned of credentials, the pause hook's variables added), the run's home and,
188
+ * on the first launch only, the start spec; then wait for its window. A later session plays on from what it saved.
189
+ */
190
+ async function openGame(env, { first }) {
191
+ const token = {};
192
+ launchToken = token;
193
+ const onExit = ended => { if (launchToken === token) exited = ended; };
194
+ const full = { ...env, ...(runHome ? runHome.env : {}), ...(first && start && start.spec ? { [START_ENV]: start.spec } : {}) };
195
+ // An app (and the LÖVE runtime, an app too) starts through LaunchServices, so macOS lets it come to
196
+ // the front for clicks; a bare executable is started directly.
197
+ const bundle = launchServices ? bundleOf(metadata) : null;
198
+ metrics.launch = bundle ? 'launch-services' : 'direct';
199
+ const { child } = bundle
200
+ ? await launchApp(bundle, metadata.executablePath, metadata.args || [], { env: full, now, find: request => helper.send({ kind: 'find', ...request }), onExit })
201
+ : launchGame(metadata.executablePath, metadata.args || [], { stdio: ['ignore', 'pipe', 'pipe'], env: full, cwd: metadata.cwd || undefined, spawnGame, now, onExit });
202
+ game = child;
203
+ output = createOutputTail([child.stdout, child.stderr]);
204
+ const deadline = now() + windowTimeoutMs;
205
+ while (!exited && !await refreshWindow()) {
206
+ if (now() > deadline) throw new Error('The game did not open a window in time.');
207
+ await sleep(250, signal);
208
+ }
209
+ if (exited) {
210
+ await endedBy();
211
+ throw new Error(`The game exited during launch (${exited.signal || `code ${exited.code}`}).${output.last ? ` It printed: ${output.last}` : ''}`);
212
+ }
213
+ }
169
214
  const driver = {
170
215
  name: DRIVER_NAME, touch: false, exactScreenshots: true, supportsHold: true,
171
216
  supportedActions: ['click', 'key', 'type', 'wait'],
172
217
  /** Frozen between actions while the SDK pause hook holds the game. */
173
218
  get frozenBetweenActions() { return Boolean(time && time.engaged); },
219
+ /** Slow the game while the playtester decides, once its kind is settled as an action game (../../slowMotion.js). */
220
+ async slowDown(options) { slowAsked = { ...(options || {}) }; return time ? time.slowDown(options) : { status: 'not_supported', reason: 'style', scale: null }; },
174
221
  /** Drag, hover and mouse look, and the wheel; no gamepad (there is no virtual pad without an engine module). */
175
222
  pointerTools: ['drag', 'look', 'hover', 'scroll'],
176
223
  get playNote() {
177
- const timing = time && time.engaged ? 'The game is paused while you decide; it runs during each input and for half a second after it.' : 'The game runs continuously while you think: timers and enemies do not pause.';
224
+ const timing = time && time.engaged ? 'The game is paused while you decide; it runs during each input and for half a second after it.' : (time && time.timingLine()) || 'The game runs continuously while you think: timers and enemies do not pause.';
178
225
  return `This is a desktop game (${label()}) running in a window on this computer. Read each current screenshot and use its x,y coordinates for the mouse. click is a mouse click (button, double and hold_ms work); drag presses, moves and releases the mouse; hover with x and y moves the pointer there. key presses physical keyboard keys: hold_ms holds a key while the game runs, to walk or steer, and with_keys holds more keys at once. hover with dx and dy moves the mouse by that much, as mouse look reads it (turns a first person view or orbits a camera), and with_keys walks while it turns. scroll turns the mouse wheel. ${timing} There is no touch and no gamepad in this runner. If repeated inputs do not produce the expected change, reassess the target and try another input the game asks for instead of repeating the same one.`;
179
226
  },
180
227
  async launch({ target, runDir, recordVideo = false, signal: abort }) {
@@ -188,6 +235,8 @@ export function createDesktopAppDriver({
188
235
  metadata = plan.metadata || await inspect(file, { args: plan.args });
189
236
  metrics.engine = metadata.engine;
190
237
  unlock = await lock(DESKTOP_LOCK);
238
+ // Saves and sessions play in a home of the run's own, never the developer's (./runHome.js).
239
+ if (needsRunHome(plan)) runHome = await makeRunHome({ plan, metadata, bundle: bundleOf(metadata) });
191
240
  helper = await startHelper({ signal });
192
241
  access = await helper.send({ kind: 'access' });
193
242
  if (!access.accessibility) throw new Error('macOS has not allowed this terminal to send mouse and keyboard input (System Settings, Privacy and Security, Accessibility).');
@@ -196,29 +245,13 @@ export function createDesktopAppDriver({
196
245
  let env = gameEnvironment();
197
246
  if (pauseHook !== false) {
198
247
  const identity = playtest && playtest.token && playtest.runId ? playtest : { token: 'local-check', runId: `check_${randomBytes(6).toString('hex')}` };
199
- time = makeTimeControl({ playtest: identity, realtime: pauseHook === 'realtime' });
248
+ time = makeTimeControl({ playtest: identity, realtime: pauseHook === 'realtime', ...(slowMotion ? { slowMotion } : {}) });
200
249
  const extra = await time.start();
201
250
  if (Object.keys(extra).length) env = { ...env, ...extra };
202
251
  else time = null;
203
252
  }
204
- // An app (and LÖVE's runtime, an app too) starts through LaunchServices, so macOS lets it come to
205
- // the front for clicks; a bare executable is started directly.
206
- const bundle = launchServices ? bundleOf(metadata) : null;
207
- metrics.launch = bundle ? 'launch-services' : 'direct';
208
- const { child } = bundle
209
- ? await launchApp(bundle, metadata.executablePath, metadata.args || [], { env, now, find: request => helper.send({ kind: 'find', ...request }), onExit: ended => { exited = ended; } })
210
- : launchGame(metadata.executablePath, metadata.args || [], { stdio: ['ignore', 'pipe', 'pipe'], env, cwd: metadata.cwd || undefined, spawnGame, now, onExit: ended => { exited = ended; } });
211
- game = child;
212
- output = createOutputTail([child.stdout, child.stderr]);
213
- const deadline = now() + windowTimeoutMs;
214
- while (!exited && !await refreshWindow()) {
215
- if (now() > deadline) throw new Error('The game did not open a window in time.');
216
- await sleep(250, signal);
217
- }
218
- if (exited) {
219
- await endedBy();
220
- throw new Error(`The game exited during launch (${exited.signal || `code ${exited.code}`}).${output.last ? ` It printed: ${output.last}` : ''}`);
221
- }
253
+ await openGame(env, { first: true });
254
+ driver.sessions = 1;
222
255
  // The SDK connects a moment after the game starts; give it that before the first look.
223
256
  if (time) await time.waitForHello(helloTimeoutMs);
224
257
  if (time && time.offersFrame) source = 'game';
@@ -233,11 +266,50 @@ export function createDesktopAppDriver({
233
266
  throw new DriverError(error.message, { fatal: true });
234
267
  }
235
268
  },
269
+ /** What the game was told about where to start: it reads the spec itself, so the run only knows it was sent. */
270
+ get startAnswer() { return startAnswerOf(start, runHome); },
271
+ /** Launches of the game so far in this run. */
272
+ sessions: 0,
273
+ /**
274
+ * A new session of the same run (../../sessions.js): the game is quit the way a player quits it and started
275
+ * again on the run's own home, with what it saved there and no start spec. The video goes on through it.
276
+ */
277
+ async relaunch() {
278
+ if (!launched || !game) throw new Error('The game has not launched.');
279
+ if (exited) throw new Error('The game has exited.');
280
+ // The hook's close lets the game run, so it can save as it quits.
281
+ if (time) { timeSummaries.push(time.summary()); await time.close().catch(() => {}); time = null; }
282
+ // Command-Q goes through macOS, so it needs the input permission; without it the game gets the stop signal.
283
+ const commandQ = access && access.accessibility ? async () => { await forward(); await helper.send({ kind: 'keys', pid: game.pid, codes: actionKeyCodes({ key: 'Meta+q' }), holdMs: 0 }); } : null;
284
+ const closed = await quitLikeAPlayer(game, { exited: () => exited, commandQ, quitWaitMs, termWaitMs });
285
+ if (output) heldErrors.push(...await output.read());
286
+ exited = null; ending = null; gameEnded = null; window = null; pendingFrame = null; lastView = undefined; pointerAt = null;
287
+ let env = gameEnvironment();
288
+ if (timeOptions) {
289
+ time = makeTimeControl(timeOptions);
290
+ const extra = await time.start();
291
+ if (Object.keys(extra).length) env = { ...env, ...extra };
292
+ else time = null;
293
+ }
294
+ const cameBack = async () => {
295
+ await openGame(env, { first: false });
296
+ if (time) await time.waitForHello(helloTimeoutMs);
297
+ if (time && time.offersFrame) source = 'game';
298
+ else if (access.screenCapture) source = 'window';
299
+ else throw new Error('The game came back without sending its own frames, and macOS has not allowed this terminal to record the screen.');
300
+ frame = await capture();
301
+ };
302
+ // A game that dies as it starts again is said as that, whichever step saw it go.
303
+ await cameBack().catch(error => { throw exited && !/exited during launch/.test(error.message) ? new Error(`The game exited as it started again (${exited.signal || `code ${exited.code}`}).`) : error; });
304
+ if (time && slowAsked) await time.slowDown(slowAsked).catch(() => null);
305
+ driver.sessions += 1;
306
+ return { session: driver.sessions, scene: null, files: runHome ? await runHome.savedFiles().catch(() => null) : null, closed };
307
+ },
236
308
  async observe() {
237
309
  if (time && !pendingFrame) await time.park();
238
310
  frame = pendingFrame || await capture(); pendingFrame = null;
239
311
  if (time && time.offersView3d && lastView === undefined) lastView = await time.view3d();
240
- const timing = time && time.engaged ? 'The game is paused until your next input.' : 'The game is running in real time.';
312
+ const timing = time && time.engaged ? 'The game is paused until your next input.' : (time && time.timingLine()) || 'The game is running in real time.';
241
313
  const view = viewText(lastView || null);
242
314
  return { step: ++step, text: `Desktop game window on macOS (${label()}), ${frame.width} by ${frame.height} pixels. Use x,y screenshot coordinates. ${timing}${view ? `\n${view}` : ''}`, screenshotBase64: frame.png.toString('base64'), screenshotMediaType: 'image/png', elapsedMs: now() - startedAt };
243
315
  },
@@ -0,0 +1,158 @@
1
+ // A folder of the run's own for a desktop game on this Mac (desktop_driver,
2
+ // unity_driver, unreal_driver), for a run that starts from a save or plays
3
+ // several sessions (../../startFrom.js, ../../sessions.js). The saves are
4
+ // placed there before the first launch, every session of the run starts on
5
+ // the same folder, and it is removed when the run ends. The developer's own
6
+ // saves are never read or written.
7
+ //
8
+ // Two kinds, by engine:
9
+ //
10
+ // - **home** (desktop_driver, unity_driver): the game is started with HOME
11
+ // and CFFIXED_USER_HOME set to a fresh folder. macOS answers the user's
12
+ // Library from CFFIXED_USER_HOME, and a program that reads HOME itself
13
+ // follows HOME, so a game's Application Support, Preferences and Logs land
14
+ // inside the run's folder. A Unity player started so treats the folder as
15
+ // a sandbox home and answers persistentDataPath as
16
+ // Library/Application Support/<bundle id> (seen with Unity 6000.6), and
17
+ // writes its Player.log under Library/Logs/<company>/<product>. An app in
18
+ // the App Sandbox keeps its data in its container whatever HOME says, so
19
+ // one is refused here.
20
+ // - **userdir** (unreal_driver): Unreal reads its user folder from
21
+ // `-userdir=<folder>`, and keeps Saved (SaveGames, Config, Logs, Crashes)
22
+ // under it. A Mac build from Unreal 5 is in the App Sandbox by default and
23
+ // may write only inside its container, so the folder is made in the
24
+ // container's own tmp (~/Library/Containers/<bundle id>/Data/tmp), which
25
+ // macOS made when the game first ran; for a build outside the sandbox it is
26
+ // made in this machine's temporary folder.
27
+ import fs from 'node:fs/promises';
28
+ import os from 'node:os';
29
+ import path from 'node:path';
30
+ import { command } from '../mobile/process.js';
31
+ import { placeSavesInFolder, SAVE_ROOTS, START_ENV, startRecord } from '../../startFrom.js';
32
+
33
+ /** The variables that point a game at the run's home. */
34
+ export const HOME_VARIABLES = Object.freeze(['HOME', 'CFFIXED_USER_HOME']);
35
+ /** Folders that hold what the engine writes for itself, not what the game saved. */
36
+ const NOT_SAVES = new Set(['Library/Logs', 'Library/Caches', 'Library/Saved Application State', 'Library/HTTPStorages', 'Library/WebKit', 'Saved/Logs', 'Saved/Crashes', 'Saved/Config/CrashReportClient', 'Saved/Ravensight']);
37
+ /** The most entries a count of saved files looks at. */
38
+ const MAX_COUNTED = 10000;
39
+ const PLAIN = value => typeof value === 'string' && /^[^\0/\\:]{1,128}$/.test(value) && value !== '.' && value !== '..';
40
+
41
+ /** A run whose desktop game needs a folder of its own: it starts from a save, or it plays several sessions. */
42
+ export function needsRunHome(plan = {}) {
43
+ const saves = plan && plan.start && Array.isArray(plan.start.saves) ? plan.start.saves.length : 0;
44
+ return saves > 0 || (Number.isSafeInteger(plan && plan.sessions) && plan.sessions > 1);
45
+ }
46
+
47
+ /**
48
+ * The folder a save root names under the run's folder, for this game.
49
+ *
50
+ * @param {string} root a key of SAVE_ROOTS
51
+ * @param {string} folder the run's home, or an Unreal game's user folder
52
+ * @param {{bundleId?: string}} metadata the build as the driver read it
53
+ * @returns {string}
54
+ */
55
+ export function saveFolder(root, folder, metadata = {}) {
56
+ if (root === 'desktop_home') return folder;
57
+ if (root === 'desktop_appdata') return path.join(folder, 'Library', 'Application Support');
58
+ if (root === 'unity_persistent') {
59
+ if (!PLAIN(metadata.bundleId)) throw new Error('unity:persistent:// needs the player\'s bundle identifier, which this build does not give.');
60
+ return path.join(folder, 'Library', 'Application Support', metadata.bundleId);
61
+ }
62
+ if (root === 'unreal_saved') return path.join(folder, 'Saved');
63
+ throw new Error(`${SAVE_ROOTS[root] ? SAVE_ROOTS[root].prefix : root} is not a folder a desktop game on this Mac reads.`);
64
+ }
65
+
66
+ /** Whether a Mac app runs in the App Sandbox, from its signed entitlements. */
67
+ export async function sandboxedApp(bundle, { run = command } = {}) {
68
+ if (!bundle) return false;
69
+ const xml = await run('codesign', ['-d', '--entitlements', '-', '--xml', bundle], { timeout: 15000 }).catch(() => '');
70
+ return /<key>com\.apple\.security\.app-sandbox<\/key>\s*<true\s*\/>/.test(String(xml));
71
+ }
72
+
73
+ /** How many files the game has saved under the folder, not counting the engine's own logs and caches. */
74
+ export async function countSavedFiles(folder, { fsImpl = fs } = {}) {
75
+ let count = 0, seen = 0;
76
+ async function visit(at, relative) {
77
+ if (seen > MAX_COUNTED || NOT_SAVES.has(relative)) return;
78
+ const entries = await fsImpl.readdir(at, { withFileTypes: true }).catch(() => []);
79
+ for (const entry of entries) {
80
+ if (++seen > MAX_COUNTED) return;
81
+ const rel = relative ? `${relative}/${entry.name}` : entry.name;
82
+ if (entry.isDirectory()) await visit(path.join(at, entry.name), rel);
83
+ else if (entry.isFile() && !entry.name.startsWith('.')) count++;
84
+ }
85
+ }
86
+ await visit(folder, '');
87
+ return count;
88
+ }
89
+
90
+ /**
91
+ * Make the run's folder and place the saves in it.
92
+ *
93
+ * @param {Object} options
94
+ * @param {Object} options.plan the native plan: `start` (../../startFrom.js resolveStart) and `sessions`
95
+ * @param {Object} options.metadata the build as the driver read it (bundleId, project)
96
+ * @param {string|null} [options.bundle] the .app, read for the App Sandbox
97
+ * @param {'home'|'userdir'} [options.kind]
98
+ * @returns {Promise<{kind: string, home: string, env: Object, args: string[], logs: string[], crashes: string[], placed: string[], savedFiles: () => Promise<number>, remove: () => Promise<void>}>}
99
+ */
100
+ export async function createRunHome({ plan = {}, metadata = {}, bundle = null, kind = 'home', tmp = os.tmpdir(), userHome = os.homedir(), fsImpl = fs, run = command } = {}) {
101
+ const sandboxed = await sandboxedApp(bundle, { run });
102
+ let base = tmp;
103
+ if (kind === 'home' && sandboxed) {
104
+ throw new Error(`${path.basename(bundle)} runs in the App Sandbox, so it keeps its data in its container in your own Library whatever home it is given, and a playtest never writes there. Build it without the App Sandbox for playtests, or run without --save and --sessions.`);
105
+ }
106
+ if (kind === 'userdir' && sandboxed) {
107
+ if (!PLAIN(metadata.bundleId)) throw new Error('The game is in the App Sandbox and names no bundle identifier, so its container cannot be found.');
108
+ base = path.join(userHome, 'Library', 'Containers', metadata.bundleId, 'Data', 'tmp');
109
+ const info = await fsImpl.stat(base).catch(() => null);
110
+ if (!info || !info.isDirectory()) throw new Error(`${path.basename(bundle)} is in the App Sandbox and macOS has not made its container yet. Open the game once on this Mac, quit it, and run again.`);
111
+ }
112
+ const made = await fsImpl.mkdtemp(path.join(base, kind === 'userdir' ? 'ravensight-run-' : 'ravensight-home-'));
113
+ // The folder as the game will see it (/var is /private/var on a Mac).
114
+ const home = await fsImpl.realpath(made);
115
+ const remove = () => fsImpl.rm(home, { recursive: true, force: true }).catch(() => {});
116
+ const placed = [];
117
+ try {
118
+ const saves = plan.start && Array.isArray(plan.start.saves) ? plan.start.saves : [];
119
+ const byRoot = new Map();
120
+ for (const save of saves) byRoot.set(save.root, [...(byRoot.get(save.root) || []), save]);
121
+ for (const [root, list] of byRoot) {
122
+ const result = await placeSavesInFolder(saveFolder(root, home, metadata), list, { fs: fsImpl });
123
+ placed.push(...result.placed);
124
+ }
125
+ } catch (error) {
126
+ await remove();
127
+ throw error;
128
+ }
129
+ const project = PLAIN(metadata.project) ? metadata.project : null;
130
+ return {
131
+ kind,
132
+ home,
133
+ sandboxed,
134
+ env: kind === 'home' ? Object.fromEntries(HOME_VARIABLES.map(name => [name, home])) : {},
135
+ args: kind === 'userdir' ? [`-userdir=${home}`] : [],
136
+ // An Unreal game with a user folder logs and crashes under its Saved.
137
+ logs: kind === 'userdir' && project ? [path.join(home, 'Saved', 'Logs', `${project}.log`)] : [],
138
+ crashes: kind === 'userdir' ? [path.join(home, 'Saved', 'Crashes')] : [],
139
+ placed,
140
+ savedFiles: () => countSavedFiles(home, { fsImpl }),
141
+ remove
142
+ };
143
+ }
144
+
145
+ /**
146
+ * What a desktop game was told about where to start, for the report: a game reads the spec itself, so the
147
+ * run only knows it was sent.
148
+ */
149
+ export function startAnswerOf(start, runHome) {
150
+ if (!start) return null;
151
+ return {
152
+ handled: null,
153
+ sent: [...(start.spec ? [`the environment variable ${START_ENV}`] : []), ...(start.saves && start.saves.length && runHome ? [`${start.saves.length} save file(s) in a folder of the run's own`] : [])],
154
+ record: startRecord(start)
155
+ };
156
+ }
157
+
158
+ export default { startAnswerOf, createRunHome, needsRunHome, saveFolder, sandboxedApp, countSavedFiles, HOME_VARIABLES };
@@ -368,6 +368,8 @@ export class GodotDriver {
368
368
  importProject = importProjectCopy,
369
369
  env = process.env,
370
370
  extraEnv = {},
371
+ // The studio's own arguments for the game (--launch-arg, ../launchArgs.js), after Godot's `--`.
372
+ launchArgs = [],
371
373
  spawnFn = spawn,
372
374
  detect = detectGodotBinary,
373
375
  prepare = prepareProjectCopy,
@@ -437,6 +439,7 @@ export class GodotDriver {
437
439
  this._paused = false;
438
440
  this.env = env;
439
441
  this.extraEnv = extraEnv;
442
+ this.launchArgs = Array.isArray(launchArgs) ? launchArgs.map(String) : [];
440
443
  this._spawn = spawnFn;
441
444
  this._detect = detect;
442
445
  this._prepare = prepare;
@@ -639,7 +642,7 @@ export class GodotDriver {
639
642
  const token = randomBytes(24).toString('hex');
640
643
  const lines = [];
641
644
  const env = { ...allowlistedEnv(this.env), ...(this.extraEnv ?? {}), RAVENSIGHT_DRIVER: '1', RAVENSIGHT_DRIVER_PORT: String(port), RAVENSIGHT_DRIVER_TOKEN: token };
642
- const child = this._spawn(this.godot.path, ['--path', this.projectCopy, '--headless', '--', '--ravensight-driver', `--ravensight-driver-port=${port}`], { cwd: this.projectCopy, env, stdio: ['ignore', 'pipe', 'pipe'] });
645
+ const child = this._spawn(this.godot.path, ['--path', this.projectCopy, '--headless', '--', '--ravensight-driver', `--ravensight-driver-port=${port}`, ...this.launchArgs], { cwd: this.projectCopy, env, stdio: ['ignore', 'pipe', 'pipe'] });
643
646
  let exit = null;
644
647
  child.on('exit', (code, signal) => { exit = { code, signal }; });
645
648
  child.on('error', () => { exit = { code: -1, signal: null }; });
@@ -755,6 +758,8 @@ export class GodotDriver {
755
758
  if (this.headless) args.push('--headless');
756
759
  else args.push('--resolution', `${this.viewport.w}x${this.viewport.h}`);
757
760
  args.push('--', '--ravensight-driver', `--ravensight-driver-port=${this.port}`);
761
+ // The studio's own arguments come last, as user arguments the game reads with OS.get_cmdline_user_args().
762
+ args.push(...this.launchArgs);
758
763
  return args;
759
764
  }
760
765
 
@@ -1011,6 +1016,8 @@ export class GodotDriver {
1011
1016
  viewport: this.viewport,
1012
1017
  ...(await this._cursorHeader()),
1013
1018
  ...(this.start ? { start: startRecord(this.start), ...(this.startAnswer ? { start_answer: this.startAnswer } : {}) } : {}),
1019
+ // The studio's launch arguments, so a replay of this trace starts the game the same way.
1020
+ ...(this.launchArgs.length ? { launch_args: this.launchArgs } : {}),
1014
1021
  ...(this.traceHeader ?? {}),
1015
1022
  }, digest);
1016
1023
  }
@@ -27,7 +27,7 @@ const ANDROID_KEYS = { Back: '4', Escape: '4', Enter: '66', Backspace: '67', Tab
27
27
  const ANDROID_INPUT_SETTLE_MS = 700;
28
28
  /** How long after launch the runner waits for the game's SDK to say hello on the pause hook (contract section 12). */
29
29
  export const HELLO_WAIT_MS = 10000;
30
- export function createMobileDriver({ name, native: plan = {}, adb = createAdb(), simctl = createSimctl(), startHelper = startIosHelper, startRecording = startMobileRecording, lock = lockDevice, now = Date.now, orientationSettleMs = 5000, createCrashTracker = async options => (await import('./crash.js')).createIosCrashTracker(options), playtest = null, pauseHook = false, timeControl: makeTimeControl = createTimeControl, helloWaitMs = HELLO_WAIT_MS } = {}) {
30
+ export function createMobileDriver({ name, native: plan = {}, adb = createAdb(), simctl = createSimctl(), startHelper = startIosHelper, startRecording = startMobileRecording, lock = lockDevice, now = Date.now, orientationSettleMs = 5000, createCrashTracker = async options => (await import('./crash.js')).createIosCrashTracker(options), playtest = null, pauseHook = false, slowMotion = null, timeControl: makeTimeControl = createTimeControl, helloWaitMs = HELLO_WAIT_MS } = {}) {
31
31
  const android = name === 'android_driver';
32
32
  // The SDK pause hook on a test device (contract section 12): the variables, the port mapped into an emulator, and
33
33
  // the game's 3D view for the world watch. A game that never says hello is played exactly as without it.
@@ -127,6 +127,8 @@ export function createMobileDriver({ name, native: plan = {}, adb = createAdb(),
127
127
  const driver = {
128
128
  name, touch: true, inputProfile: 'native-mobile', exactScreenshots: true,
129
129
  get frozenBetweenActions() { return Boolean(time && time.engaged); },
130
+ /** Slow the game while the playtester decides, once its kind is settled as an action game (../../slowMotion.js). */
131
+ async slowDown(options) { return time ? time.slowDown(options) : { status: 'not_supported', reason: 'style', scale: null }; },
130
132
  supportedActions: ['click', 'key', 'type', 'wait', 'swipe'], pointerTools: ['drag', 'pinch', 'touches', 'stick', ...(android ? ['tilt'] : [])],
131
133
  playNote: `This is a native mobile game on an emulator or simulator. Read each current screenshot and tap using its x,y coordinates. click is a tap; hold_ms is a long press; drag moves one finger; pinch puts two fingers down and moves them apart or together; touches puts down one or two fingers each on its own path and clock, such as a thumb held on a stick while the other taps a button; stick holds an on-screen joystick pushed, with an optional second finger swiping to look${android ? '; tilt tips the device to steer a game that reads the motion sensor' : ''}. Coordinates are in the displayed screenshot, including system bars. Unless the game's Ravensight SDK pauses it between your inputs (each observation then says so), the game runs continuously while you think: timers do not pause. Tap only visible in-app controls. There is no hover, mouse wheel or desktop navigation. ${android ? 'On Android, key Back is a system action available even when no Back control is drawn. It may dismiss the current layer, navigate back or leave the app; observe the result.' : 'On iOS, use visible in-app navigation; this runner has no system Back action.'} If repeated taps do not produce the expected change, reassess the target and consider another supported action appropriate to your intent instead of repeating ineffective taps. System permission dialogs and first-launch full-screen tips may cover the app and consume taps: identify the visible overlay before interpreting an action as a game response. Dismiss a tip only through its visible control. Do not infer a game fault from a system overlay or an input this runner could not send.`,
132
134
  async launch({ target, runDir, recordVideo = false, signal: abort }) {
@@ -143,7 +145,7 @@ export function createMobileDriver({ name, native: plan = {}, adb = createAdb(),
143
145
  if (pauseHook && (!android || typeof adb.shellScript === 'function')) {
144
146
  // A free check has no job, so it uses a one off local identity; the SDK needs only that the three are set.
145
147
  const identity = playtest && playtest.token && playtest.runId ? playtest : { token: 'local-check', runId: `check_${randomBytes(6).toString('hex')}` };
146
- time = makeTimeControl({ playtest: identity, realtime: pauseHook === 'realtime' });
148
+ time = makeTimeControl({ playtest: identity, realtime: pauseHook === 'realtime', ...(slowMotion ? { slowMotion } : {}) });
147
149
  hookEnv = await time.start();
148
150
  if (!Object.keys(hookEnv).length) { time = null; hookEnv = null; }
149
151
  }
@@ -240,7 +242,7 @@ export function createMobileDriver({ name, native: plan = {}, adb = createAdb(),
240
242
  if (time && !pendingFrame) await time.park();
241
243
  frame = pendingFrame || await capture(); pendingFrame = null;
242
244
  if (time && time.offersView3d && lastView === undefined) lastView = await time.view3d();
243
- const timing = time && time.engaged ? 'The game is paused until your next input.' : 'The game is running in real time.';
245
+ const timing = time && time.engaged ? 'The game is paused until your next input.' : (time && time.timingLine()) || 'The game is running in real time.';
244
246
  return { step: ++step, text: `Native ${android ? 'Android emulator' : 'iOS simulator'} screen, ${frame.width} by ${frame.height} pixels. Use x,y screenshot coordinates. ${timing}`, screenshotBase64: frame.png.toString('base64'), screenshotMediaType: 'image/png', elapsedMs: now() - startedAt };
245
247
  },
246
248
  async act(requested) {
@@ -62,9 +62,10 @@ function desktopTarget(options, config, driverName, repoRoot, explicitNative, na
62
62
  }
63
63
  if (nativeFlags) throw new Error(`${driverName} plays a packaged game in a window on this computer; --device, --package, --bundle-id, --portrait and --landscape do not apply.`);
64
64
  const build = options.nativeBuild || configRef;
65
- // desktop_driver: the game's own arguments from the project settings (native.args), never from the model.
65
+ // The game's own arguments: the project settings' native.args, then each --launch-arg, never from the model.
66
66
  const native = config?.native && typeof config.native === 'object' ? config.native : {};
67
- const args = driverName === 'desktop_driver' && native.args !== undefined ? { args: gameArgs(native.args) } : {};
67
+ const given = [...(native.args !== undefined ? gameArgs(native.args) : []), ...(options.launchArg !== undefined ? [].concat(options.launchArg).map(String) : [])];
68
+ const args = native.args !== undefined || options.launchArg !== undefined ? { args: gameArgs(given) } : {};
68
69
  return { mode: 'native', driver: driverName, build: options.nativeBuild ? path.resolve(repoRoot, build) : configBuild(repoRoot, build), device: 'mac', resolvedDevice: 'mac', ...args };
69
70
  }
70
71
  export async function buildDigest(file) {