ravensight-playtest 0.19.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) {
@@ -62,7 +62,7 @@ export async function readBridgeConfig(file) {
62
62
  return config;
63
63
  }
64
64
 
65
- export function createStdioDriver({ spawn: spawnImpl = spawn, timeoutMs = 30000, playtest = null, pauseHook = true, timeControl: makeTimeControl = createTimeControl } = {}) {
65
+ export function createStdioDriver({ spawn: spawnImpl = spawn, timeoutMs = 30000, playtest = null, pauseHook = true, slowMotion = null, timeControl: makeTimeControl = createTimeControl } = {}) {
66
66
  let child, childState, buffer = '', nextId = 0, runDirectory, step = 0, shots = 0, lastHash, time = null;
67
67
  const pending = new Map();
68
68
  // The game's own 3D view through the pause hook (../view3dState.js, contract section 9), read the same
@@ -93,7 +93,8 @@ export function createStdioDriver({ spawn: spawnImpl = spawn, timeoutMs = 30000,
93
93
  if (time) await time.park();
94
94
  const value = await request('observe');
95
95
  if (!value || typeof value.text !== 'string') throw new DriverError('Bridge observation needs text.');
96
- const observation = { step: ++step, text: truncateObservation(value.text), elapsedMs: 0 };
96
+ const slowed = time ? time.timingLine() : null;
97
+ const observation = { step: ++step, text: truncateObservation(slowed ? `${value.text}\n${slowed}` : value.text), elapsedMs: 0 };
97
98
  if (typeof value.screenshotBase64 === 'string' && value.screenshotBase64.startsWith('iVBORw0KGgo')) {
98
99
  observation.screenshotBase64 = value.screenshotBase64;
99
100
  observation.screenshotMediaType = 'image/png';
@@ -159,7 +160,7 @@ export function createStdioDriver({ spawn: spawnImpl = spawn, timeoutMs = 30000,
159
160
  // whose SDK never connects is played exactly as without this.
160
161
  let env;
161
162
  if (config.pauseHook === true && pauseHook !== false) {
162
- time = makeTimeControl({ playtest, realtime: pauseHook === 'realtime' });
163
+ time = makeTimeControl({ playtest, realtime: pauseHook === 'realtime', ...(slowMotion ? { slowMotion } : {}) });
163
164
  const extra = await time.start();
164
165
  if (Object.keys(extra).length) env = { ...process.env, ...extra };
165
166
  else time = null;
@@ -196,6 +197,8 @@ export function createStdioDriver({ spawn: spawnImpl = spawn, timeoutMs = 30000,
196
197
  },
197
198
  /** The inputs this bridge named at launch, for the run log. */
198
199
  get bridgeInputs() { return [...inputs]; },
200
+ /** Slow the game while the playtester decides, once its kind is settled as an action game (../slowMotion.js). */
201
+ async slowDown(options) { return time ? time.slowDown(options) : { status: 'not_supported', reason: 'style', scale: null }; },
199
202
  observe,
200
203
  async act(action) {
201
204
  if (action.kind === 'type' && (action.replace || action.target)) return { ok: false, changed: false, error: 'replace (empty a field, then type) and a typing target are only available on playwright_web; this driver can only type more text into what has focus' };
@@ -15,6 +15,15 @@
15
15
  // world, a player stuck on geometry, a camera in a wall or upside down, and
16
16
  // moves that get nowhere. The game's log and crash reports (./logs.js) are
17
17
  // read for its errors and for why it died.
18
+ //
19
+ // A run that starts from a save or plays several sessions gives the game a
20
+ // folder of the run's own (../desktop/runHome.js) with the saves in it: a
21
+ // home for a Unity player (unity:persistent://, desktop:appdata://,
22
+ // desktop:home://), a user folder for an Unreal game (-userdir,
23
+ // unreal:saved://). The start spec is in its environment
24
+ // (RAVENSIGHT_PLAYTEST_START, first launch only). Between sessions the game
25
+ // is quit the way a player quits it (relaunch) and started again on the same
26
+ // folder.
18
27
  import { spawn } from 'node:child_process';
19
28
  import fs from 'node:fs/promises';
20
29
  import os from 'node:os';
@@ -31,7 +40,9 @@ import { inspectUnrealApp } from './app.js';
31
40
  import { startDesktopHelper } from '../desktop/helper.js';
32
41
  import { createFrameChannel } from './frames.js';
33
42
  import { actionKeyCodes, actionKeyCodeNames } from '../desktop/keys.js';
34
- import { bundleOf, crashWait, captureWindow, launchThroughLaunchServices, DEFAULT_RESOLUTION, DESKTOP_LOCK, describeEnd, gameEnvironment, gamePixel, launchGame, lookSteps, MODEL_LONG_EDGE, RECORD_INTERVAL_MS, round1, runScreenshot, screenPoint, startFrameRecorder, stopGame as stopProcess, viewText } from '../desktop/common.js';
43
+ import { createRunHome, needsRunHome, startAnswerOf } from '../desktop/runHome.js';
44
+ import { START_ENV } from '../../startFrom.js';
45
+ import { bundleOf, crashWait, quitLikeAPlayer, QUIT_WAIT_MS, TERM_WAIT_MS, sessionTimeSummary, captureWindow, launchThroughLaunchServices, DEFAULT_RESOLUTION, DESKTOP_LOCK, describeEnd, gameEnvironment, gamePixel, launchGame, lookSteps, MODEL_LONG_EDGE, RECORD_INTERVAL_MS, round1, runScreenshot, screenPoint, startFrameRecorder, stopGame as stopProcess, viewText } from '../desktop/common.js';
35
46
  import { PIPE_MAX_LOOK, PIPE_NAME } from './frames.js';
36
47
  import { createLogTail, findCrash, unrealPaths } from './logs.js';
37
48
  import { touchesTimeline, parseFingers } from '../../fingers.js';
@@ -60,6 +71,7 @@ const EARLY_CRASH_MS = 15000;
60
71
  const MIN_KEY_MS = 60;
61
72
  /** How long a closed frames link waits for the game's exit to be seen, so a crash is told from a dropped link. */
62
73
  const GAME_EXIT_GRACE_MS = 3000;
74
+ const NO_ACCESS = 'macOS has not allowed this terminal to send mouse and keyboard input (System Settings, Privacy and Security, Accessibility).';
63
75
 
64
76
  /**
65
77
  * What differs between engines: how the game is recognised, started and
@@ -77,6 +89,8 @@ export const UNREAL_ENGINE = Object.freeze({
77
89
  moduleAdvice: 'Add the Unreal SDK (it includes the RavensightPlaytest module) and package again',
78
90
  rebuild: 'update the Unreal SDK and package again',
79
91
  osKeysOnly: true,
92
+ // A run's own folder is the game's user folder (-userdir), inside its container when it is sandboxed (../desktop/runHome.js).
93
+ runHome: 'userdir',
80
94
  inspect: inspectUnrealApp,
81
95
  paths: unrealPaths,
82
96
  logTail: (paths, options) => createLogTail(paths, { ...options, readyLine: UNREAL_READY_LINE }),
@@ -142,11 +156,31 @@ export function createUnrealDriver({
142
156
  native: plan = {}, startHelper = startDesktopHelper, spawnGame = spawn, lock = lockDevice,
143
157
  digest = buildDigest, windowCapture = captureWindow, encode = encodeFrames, now = Date.now, platform = process.platform,
144
158
  settleMs = 200, windowTimeoutMs = 90000, helloTimeoutMs = 15000, raiseTimeoutMs = 20000, recordIntervalMs = RECORD_INTERVAL_MS,
145
- playtest = null, pauseHook = true, timeControl: makeTimeControl = createTimeControl, home = os.homedir(), crashWaitMs = 6000,
159
+ playtest = null, pauseHook = true, slowMotion = null, timeControl: givenTimeControl = createTimeControl, home = os.homedir(), crashWaitMs = 6000,
146
160
  findCrashImpl = findCrash, engine = UNREAL_ENGINE, inspect: inspectGiven = null,
147
161
  helloCapMs = HELLO_STARTING_CAP_MS, helloAfterReadyMs = HELLO_AFTER_READY_MS,
148
- launchServices = true, launchApp = launchThroughLaunchServices
162
+ launchServices = true, launchApp = launchThroughLaunchServices,
163
+ makeRunHome = createRunHome, quitWaitMs = QUIT_WAIT_MS, termWaitMs = TERM_WAIT_MS
149
164
  } = {}) {
165
+ // The time control is made again for each session's launch, with the options of the first (relaunch).
166
+ let timeOptions = null;
167
+ // Slow motion asked for after a hello (an action game, ../../slowMotion.js) is asked of each relaunch's hook again.
168
+ let slowAsked = null;
169
+ const makeTimeControl = options => { timeOptions = options; return givenTimeControl(options); };
170
+ // Where the run starts (../../startFrom.js): a home of the run's own, with the saves in it, and the start spec.
171
+ const start = plan.start && ((plan.start.saves && plan.start.saves.length) || plan.start.spec) ? plan.start : null;
172
+ let runHome = null, timeSummaries = [];
173
+ /** The game's environment beyond the cleaned one: the run's home and, on the first launch only, the start spec. */
174
+ const ownEnv = first => ({ ...(runHome ? runHome.env : {}), ...(first && start && start.spec ? { [START_ENV]: start.spec } : {}) });
175
+ /** The game's arguments: the engine's window switches, the run's own user folder, then the project's and --launch-arg's. */
176
+ const gameArgs = () => [...engine.args(plan.resolution || DEFAULT_RESOLUTION), ...(runHome ? runHome.args : []), ...(plan.args || [])];
177
+ /** Where the game logs and crashes: in the run's own folder first when it has one, then where it always does. */
178
+ function gamePaths() {
179
+ const mine = engine.paths(metadata, { home });
180
+ if (!runHome) return mine;
181
+ const own = runHome.kind === 'home' ? engine.paths(metadata, { home: runHome.home }) : { logs: runHome.logs, crashes: runHome.crashes, engines: [] };
182
+ return { ...mine, logs: [...own.logs, ...mine.logs], crashes: [...own.crashes, ...mine.crashes], engines: [...own.engines, ...mine.engines] };
183
+ }
150
184
  const inspectApp = inspectGiven || engine.inspect;
151
185
  let metadata, runDirectory, signal, unlock, helper, game, frames, source, pointer, window, frame, pendingFrame, startedAt, stopPromise;
152
186
  let step = 0, shots = 0, gameEnded = null, exited = null, launched = false;
@@ -172,6 +206,7 @@ export function createUnrealDriver({
172
206
  stopPromise = null; unlock = null; helper = null; game = null; frames = null; source = null; pointer = null; window = null;
173
207
  frame = null; pendingFrame = null; gameEnded = null; exited = null; launched = false; recorder = null; time = null; lastView = undefined;
174
208
  names = []; paths = null; logTail = null; ending = null; link = null; access = null; step = 0; shots = 0;
209
+ runHome = null; timeSummaries = []; slowAsked = null; driver.sessions = 0;
175
210
  heldErrors.length = 0; world = createWorldWatch(); Object.assign(metrics, freshMetrics());
176
211
  }
177
212
  /** The game's module takes this request (./frames.js can). */
@@ -245,13 +280,13 @@ export function createUnrealDriver({
245
280
  if (stopPromise) return stopPromise;
246
281
  stopPromise = (async () => {
247
282
  let result = { videoPath: null };
248
- const timeControl = time ? time.summary() : null;
283
+ const timeControl = sessionTimeSummary(timeSummaries, time ? time.summary() : null);
249
284
  try {
250
285
  // Resume the game before it is stopped, so nothing is left frozen.
251
286
  if (time) await time.close().catch(() => {});
252
287
  if (recorder) result = await recorder.stop(exited && !['stopped', 'preflight', 'completed'].includes(reason) ? 'game_exited' : reason);
253
288
  } finally {
254
- try { frames?.close(); await stopGame(); await helper?.stop(); await link?.close(); }
289
+ try { frames?.close(); await stopGame(); await helper?.stop(); await link?.close(); await runHome?.remove(); }
255
290
  finally { await unlock?.(); }
256
291
  }
257
292
  return timeControl ? { ...result, timeControl } : result;
@@ -326,11 +361,59 @@ export function createUnrealDriver({
326
361
  if (missing.length) text += ` ${list(missing).replace(/^./, c => c.toUpperCase())} ${missing.length === 1 ? 'is' : 'are'} not available: ${source !== 'game' ? `${missing.length === 1 ? 'it needs' : 'they need'} ${engine.module}` : osOnlyInput() && !frames.capabilities.includes('input_new') ? 'the game reads Unity\'s old Input Manager, which takes only what the operating system delivers' : `${missing.length === 1 ? 'it needs' : 'they need'} ${engine.module}${engine.osKeysOnly ? ' at protocol 3' : ' with the Input System'}`}.`;
327
362
  return text;
328
363
  }
364
+ /**
365
+ * Start the game once with `env` and wait for its window. `exited` is this launch's own: an earlier launch's
366
+ * exit is never read as this one's.
367
+ */
368
+ async function openGame(env) {
369
+ exited = null;
370
+ let child = null;
371
+ const onExit = ended => { if (game === child) exited = ended; };
372
+ // An engine whose window takes the mouse only in front (Unity) starts through LaunchServices, as Finder
373
+ // starts an app, which is the start macOS lets come to the front; one started straight from this process
374
+ // in the background is refused the front, and a press at the pointer then never reaches it.
375
+ const bundle = engine.launchServices && launchServices ? bundleOf(metadata) : null;
376
+ metrics.launch = bundle ? 'launch-services' : 'direct';
377
+ ({ child } = bundle
378
+ ? await launchApp(bundle, metadata.executablePath, gameArgs(), { env, now, find: request => helper.send({ kind: 'find', ...request }), onExit })
379
+ : launchGame(metadata.executablePath, gameArgs(), { stdio: link.stdio, env, spawnGame, now, onExit }));
380
+ game = child;
381
+ frames = link.channel(child, helloTimeoutMs + windowTimeoutMs);
382
+ const deadline = now() + windowTimeoutMs;
383
+ while (!exited && !await refreshWindow()) {
384
+ if (now() > deadline) throw new Error('The game did not open a window in time.');
385
+ await sleep(250, signal);
386
+ }
387
+ }
388
+ /** How the runner sees the started game and sends it input: its module's frames and input, or macOS's. */
389
+ async function settleGame() {
390
+ if (await waitForModule()) source = 'game';
391
+ else if (stillStarting) throw new Error(`The game had not finished starting ${Math.round(helloCapMs / 1000)} s after its window opened (its log never reached the end of the engine's start up), so the runner stopped waiting for its playtest module. This is a limit of this runner on a busy computer, not a problem found in the game; run again when the computer is less busy.`);
392
+ else if (access.screenCapture) source = 'window';
393
+ else throw new Error(`This build does not include the Ravensight playtest frames module, and macOS has not allowed this terminal to record the screen. ${engine.moduleAdvice}, or allow Screen Recording for this terminal in System Settings, Privacy and Security.`);
394
+ // A game whose module takes the mouse needs no cursor moves and no window on top. A game that reads only the
395
+ // operating system's input (Unity's old Input Manager) gets its mouse and keys from macOS, which every system reads.
396
+ pointer = gameCan('pointer') && !osOnlyInput() ? 'game' : 'system';
397
+ metrics.pointerInput = pointer;
398
+ metrics.keyInput = keysInGame() ? 'game' : 'system';
399
+ metrics.frameSource = source;
400
+ metrics.protocol = source === 'game' ? frames.version : 0;
401
+ metrics.inputSystems = source === 'game' && frames.capabilities ? frames.capabilities.filter(word => word.startsWith('input_')).map(word => word.slice(6)) : null;
402
+ if (!access.accessibility && (pointer === 'system' || !keysInGame())) {
403
+ throw new Error(`${NO_ACCESS}${source === 'game' && frames.capabilities ? ' This game takes its mouse or keys from the operating system, so the runner sends them through macOS.' : ''}`);
404
+ }
405
+ // A just started game cannot be brought forward until it has finished
406
+ // starting; wait for that here, so the persona's first click is not lost.
407
+ const raiseBy = now() + raiseTimeoutMs;
408
+ while (pointer === 'system' && !(await helper.send({ kind: 'raise', pid: game.pid }, 10000).catch(() => ({}))).onTop && now() < raiseBy && !exited) await sleep(500, signal);
409
+ }
329
410
  const driver = {
330
411
  name: engine.driver, touch: false, exactScreenshots: true, supportsHold: true,
331
412
  supportedActions: ['click', 'key', 'type', 'wait'],
332
413
  /** Frozen between actions while the SDK pause hook holds the game. */
333
414
  get frozenBetweenActions() { return Boolean(time && time.engaged); },
415
+ /** Slow the game while the playtester decides, once its kind is settled as an action game (../../slowMotion.js). */
416
+ async slowDown(options) { slowAsked = { ...(options || {}) }; return time ? time.slowDown(options) : { status: 'not_supported', reason: 'style', scale: null }; },
334
417
  /** Drag always; with the module at protocol 3, mouse look and hover, the wheel and the gamepad too. */
335
418
  get pointerTools() {
336
419
  return ['drag', ...(full() ? ['look'] : []), ...(gameCan('wheel') ? ['scroll'] : []), ...(gameCan('pad') ? ['gamepad'] : []), ...(gameCan('touch') ? ['touches'] : [])];
@@ -359,22 +442,21 @@ export function createUnrealDriver({
359
442
  if (platform !== 'darwin') throw new Error(`Local ${engine.label} playtests run on macOS. Cloud playtests play web builds only.`);
360
443
  if (plan.buildHash && await digest(file) !== plan.buildHash) throw new Error('The native build changed since preflight or the saved job. Start a new job for the changed build.');
361
444
  metadata = plan.metadata || await inspectApp(file);
362
- paths = engine.paths(metadata, { home });
363
- logTail = engine.logTail(paths, { since: startedAt });
364
445
  unlock = await lock(DESKTOP_LOCK);
446
+ // Saves and sessions play in a home of the run's own, never the developer's (../desktop/runHome.js).
447
+ if (needsRunHome(plan)) runHome = await makeRunHome({ plan, metadata, bundle: bundleOf(metadata), kind: engine.runHome || 'home', userHome: home });
448
+ paths = gamePaths();
449
+ logTail = engine.logTail(paths, { since: startedAt });
365
450
  helper = await startHelper({ signal });
366
451
  access = await helper.send({ kind: 'access' });
367
- const noAccess = 'macOS has not allowed this terminal to send mouse and keyboard input (System Settings, Privacy and Security, Accessibility).';
368
452
  // An engine whose keys always go through macOS needs the permission before anything starts.
369
- if (!access.accessibility && engine.osKeysOnly) throw new Error(noAccess);
370
- const resolution = plan.resolution || DEFAULT_RESOLUTION;
371
- // The game's own arguments only: the pause hook's and the frames link's secrets go in the environment, never argv.
372
- const args = [...engine.args(resolution), ...(plan.args || [])];
453
+ if (!access.accessibility && engine.osKeysOnly) throw new Error(NO_ACCESS);
454
+ // The game's own arguments only (gameArgs): the pause hook's and the frames link's secrets go in the environment, never argv.
373
455
  for (let attempt = 1; ; attempt++) {
374
456
  // The SDK pause hook: the variables go to this game only. A game whose SDK never connects plays as without it.
375
457
  let env = gameEnvironment();
376
458
  if (pauseHook !== false) {
377
- time = makeTimeControl({ playtest, realtime: pauseHook === 'realtime' });
459
+ time = makeTimeControl({ playtest, realtime: pauseHook === 'realtime', ...(slowMotion ? { slowMotion } : {}) });
378
460
  const extra = await time.start();
379
461
  if (Object.keys(extra).length) env = { ...env, ...extra };
380
462
  else time = null;
@@ -382,26 +464,9 @@ export function createUnrealDriver({
382
464
  // Unreal: -NoLogThread -FORCELOGFLUSH write and flush each log line where it is logged, not later on the engine's log
383
465
  // thread, so what the game logged just before a crash is in the file (./logs.js).
384
466
  link = await engine.frames();
385
- env = { ...env, ...link.env };
467
+ env = { ...env, ...link.env, ...ownEnv(true) };
386
468
  const spawnedAt = now();
387
- exited = null;
388
- let child = null;
389
- const onExit = ended => { if (game === child) exited = ended; };
390
- // An engine whose window takes the mouse only in front (Unity) starts through LaunchServices, as Finder
391
- // starts an app, which is the start macOS lets come to the front; one started straight from this process
392
- // in the background is refused the front, and a press at the pointer then never reaches it.
393
- const bundle = engine.launchServices && launchServices ? bundleOf(metadata) : null;
394
- metrics.launch = bundle ? 'launch-services' : 'direct';
395
- ({ child } = bundle
396
- ? await launchApp(bundle, metadata.executablePath, args, { env, now, find: request => helper.send({ kind: 'find', ...request }), onExit })
397
- : launchGame(metadata.executablePath, args, { stdio: link.stdio, env, spawnGame, now, onExit }));
398
- game = child;
399
- frames = link.channel(child, helloTimeoutMs + windowTimeoutMs);
400
- const deadline = now() + windowTimeoutMs;
401
- while (!exited && !await refreshWindow()) {
402
- if (now() > deadline) throw new Error('The game did not open a window in time.');
403
- await sleep(250, signal);
404
- }
469
+ await openGame(env);
405
470
  if (!exited) break;
406
471
  const how = exited.signal || `code ${exited.code}`;
407
472
  // A crash in the game's first seconds, before it has a window, is started once more. A Development or Test
@@ -418,25 +483,8 @@ export function createUnrealDriver({
418
483
  }
419
484
  throw new Error(`The game exited during launch (${how}).`);
420
485
  }
421
- if (await waitForModule()) source = 'game';
422
- else if (stillStarting) throw new Error(`The game had not finished starting ${Math.round(helloCapMs / 1000)} s after its window opened (its log never reached the end of the engine's start up), so the runner stopped waiting for its playtest module. This is a limit of this runner on a busy computer, not a problem found in the game; run again when the computer is less busy.`);
423
- else if (access.screenCapture) source = 'window';
424
- else throw new Error(`This build does not include the Ravensight playtest frames module, and macOS has not allowed this terminal to record the screen. ${engine.moduleAdvice}, or allow Screen Recording for this terminal in System Settings, Privacy and Security.`);
425
- // A game whose module takes the mouse needs no cursor moves and no window on top. A game that reads only the
426
- // operating system's input (Unity's old Input Manager) gets its mouse and keys from macOS, which every system reads.
427
- pointer = gameCan('pointer') && !osOnlyInput() ? 'game' : 'system';
428
- metrics.pointerInput = pointer;
429
- metrics.keyInput = keysInGame() ? 'game' : 'system';
430
- metrics.frameSource = source;
431
- metrics.protocol = source === 'game' ? frames.version : 0;
432
- metrics.inputSystems = source === 'game' && frames.capabilities ? frames.capabilities.filter(word => word.startsWith('input_')).map(word => word.slice(6)) : null;
433
- if (!access.accessibility && (pointer === 'system' || !keysInGame())) {
434
- throw new Error(`${noAccess}${source === 'game' && frames.capabilities ? ' This game takes its mouse or keys from the operating system, so the runner sends them through macOS.' : ''}`);
435
- }
436
- // A just started game cannot be brought forward until it has finished
437
- // starting; wait for that here, so the persona's first click is not lost.
438
- const raiseBy = now() + raiseTimeoutMs;
439
- while (pointer === 'system' && !(await helper.send({ kind: 'raise', pid: game.pid }, 10000).catch(() => ({}))).onTop && now() < raiseBy && !exited) await sleep(500, signal);
486
+ await settleGame();
487
+ driver.sessions = 1;
440
488
  // The SDK connects a moment after the game starts; give it that before the first look.
441
489
  if (time) await time.waitForHello(5000);
442
490
  launched = true;
@@ -447,12 +495,54 @@ export function createUnrealDriver({
447
495
  throw new DriverError(error.message, { fatal: true });
448
496
  }
449
497
  },
498
+ /** What the game was told about where to start: it reads the spec itself, so the run only knows it was sent. */
499
+ get startAnswer() { return startAnswerOf(start, runHome); },
500
+ /** Launches of the game so far in this run. */
501
+ sessions: 0,
502
+ /**
503
+ * A new session of the same run (../../sessions.js): the game is quit the way a player quits it and started
504
+ * again on the run's own home, with what it saved there and no start spec. The video goes on through it.
505
+ */
506
+ async relaunch() {
507
+ if (!launched || !game) throw new Error('The game has not launched.');
508
+ if (exited) throw new Error('The game has exited.');
509
+ // The hook's close lets the game run, so it can save as it quits.
510
+ if (time) { timeSummaries.push(time.summary()); await time.close().catch(() => {}); time = null; }
511
+ // Command-Q goes through macOS, so it needs the input permission; without it the game gets the stop signal.
512
+ const commandQ = access && access.accessibility ? async () => { await helper.send({ kind: 'raise', pid: game.pid }, 10000).catch(() => null); await helper.send({ kind: 'keys', pid: game.pid, codes: actionKeyCodes({ key: 'Meta+q' }), holdMs: 0 }); } : null;
513
+ const closed = await quitLikeAPlayer(game, { exited: () => exited, commandQ, quitWaitMs, termWaitMs });
514
+ if (logTail) heldErrors.push(...await logTail.read().catch(() => []));
515
+ frames?.close();
516
+ await link?.close().catch(() => {});
517
+ ending = null; gameEnded = null; window = null; pendingFrame = null; lastView = undefined; names = []; stillStarting = false;
518
+ logTail = engine.logTail(paths, { since: now() });
519
+ let env = gameEnvironment();
520
+ if (timeOptions) {
521
+ time = makeTimeControl(timeOptions);
522
+ const extra = await time.start();
523
+ if (Object.keys(extra).length) env = { ...env, ...extra };
524
+ else time = null;
525
+ }
526
+ link = await engine.frames();
527
+ const cameBack = async () => {
528
+ await openGame({ ...env, ...link.env, ...ownEnv(false) });
529
+ if (exited) throw new Error('it exited');
530
+ await settleGame();
531
+ if (time) await time.waitForHello(5000);
532
+ frame = await capture();
533
+ };
534
+ // A game that dies as it starts again is said as that, whichever step saw it go.
535
+ await cameBack().catch(error => { throw exited ? new Error(`The game exited as it started again (${exited.signal || `code ${exited.code}`}).`) : error; });
536
+ if (time && slowAsked) await time.slowDown(slowAsked).catch(() => null);
537
+ driver.sessions += 1;
538
+ return { session: driver.sessions, scene: null, files: runHome ? await runHome.savedFiles().catch(() => null) : null, closed };
539
+ },
450
540
  async observe() {
451
541
  if (time && !pendingFrame) await time.park();
452
542
  frame = pendingFrame || await capture(); pendingFrame = null;
453
543
  if (gameCan('names')) names = await frames.names().catch(() => names);
454
544
  if (time && time.offersView3d && lastView === undefined) lastView = await time.view3d();
455
- const timing = time && time.engaged ? 'The game is paused until your next input.' : 'The game is running in real time.';
545
+ const timing = time && time.engaged ? 'The game is paused until your next input.' : (time && time.timingLine()) || 'The game is running in real time.';
456
546
  const view = viewText(lastView || null, names);
457
547
  return { step: ++step, text: `${engine.label} game window on macOS, ${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 };
458
548
  },
@@ -82,7 +82,7 @@ export const PHONE_USER_AGENT = 'Mozilla/5.0 (Linux; Android 14; Pixel 8) AppleW
82
82
  export const TAP_MS = 60;
83
83
 
84
84
  /** What the persona is told about a run played with touch. */
85
- export const TOUCH_PLAY_NOTE = 'This run plays on a phone sized screen with touch, as a player holding a phone would: there is no mouse and no hover. click is a tap with one finger (hold_ms makes it a long press, double a double tap). drag is a finger put down, moved and lifted: a swipe, a flick, a pull on a joystick, a card carried to a slot (duration_ms sets how fast). The pinch tool, when this run has it, puts two fingers down and moves them apart or together; the touches tool 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. A finding about hover, right click or the mouse wheel is not one this run can make.';
85
+ export const TOUCH_PLAY_NOTE = 'This run plays on a phone sized screen with touch, as a player holding a phone would: there is no mouse and no hover. click is a tap with one finger (hold_ms makes it a long press, double a double tap). drag is a finger put down, moved and lifted: a swipe, a flick, a pull on a joystick, a card carried to a slot (duration_ms sets how fast). The pinch tool, when this run has it, puts two fingers down and moves them apart or together; the touches tool 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. Keys reach the game only if it listens for a keyboard, and a game made for a phone usually does not: when keys change nothing, play with your thumbs (touches to hold a stick and fire together, stick for an on-screen stick), not more keys. A finding about hover, right click or the mouse wheel is not one this run can make.';
86
86
 
87
87
  /**
88
88
  * The frame a canvas observation sends the model: JPEG at this quality, at the