ravensight-playtest 0.18.0 → 0.19.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.
Files changed (85) hide show
  1. package/README.md +160 -16
  2. package/addons/desktop/RavensightDesktop.swift +367 -0
  3. package/addons/mobile/UITests/MobileInputTests.swift +67 -1
  4. package/addons/ravensight_driver/driver.gd +557 -4
  5. package/docs/ADAPTERS.md +37 -7
  6. package/docs/DESKTOP.md +117 -0
  7. package/docs/MOBILE.md +30 -3
  8. package/docs/UNITY.md +149 -0
  9. package/docs/UNREAL.md +123 -0
  10. package/docs/godot-driver.md +98 -1
  11. package/package.json +15 -5
  12. package/src/cli.js +26 -10
  13. package/src/commands/build.js +40 -0
  14. package/src/commands/feature.js +1 -1
  15. package/src/commands/hosted.js +78 -9
  16. package/src/commands/run.js +47 -13
  17. package/src/commands/validate.js +1 -1
  18. package/src/hosted/archivePreflight.js +31 -4
  19. package/src/hosted/buildStatus.js +26 -0
  20. package/src/hosted/buildUpload.js +24 -9
  21. package/src/hosted/nativeBuild.js +87 -0
  22. package/src/hosted/recordedRun.js +15 -3
  23. package/src/run/anygame/genre.js +98 -24
  24. package/src/run/anygame/genre2d.js +108 -0
  25. package/src/run/anygame/index.js +7 -4
  26. package/src/run/anygame/scene3d.js +562 -0
  27. package/src/run/anygame/shared-hashes.json +4 -2
  28. package/src/run/anygame/shared.js +3 -3
  29. package/src/run/args.js +15 -4
  30. package/src/run/drivers/desktop/app.js +104 -0
  31. package/src/run/drivers/desktop/common.js +336 -0
  32. package/src/run/drivers/desktop/driver.js +383 -0
  33. package/src/run/drivers/desktop/helper.js +98 -0
  34. package/src/run/drivers/desktop/keys.js +124 -0
  35. package/src/run/drivers/desktop/output.js +107 -0
  36. package/src/run/drivers/desktop/preflight.js +134 -0
  37. package/src/run/drivers/desktop3d.js +106 -0
  38. package/src/run/drivers/desktopSequence.js +72 -0
  39. package/src/run/drivers/godot-3d.js +298 -0
  40. package/src/run/drivers/godot.js +465 -30
  41. package/src/run/drivers/index.js +6 -0
  42. package/src/run/drivers/mobile/adb.js +25 -1
  43. package/src/run/drivers/mobile/frame.js +3 -2
  44. package/src/run/drivers/mobile/gestures.js +76 -0
  45. package/src/run/drivers/mobile/lock.js +51 -11
  46. package/src/run/drivers/mobile/multitouch.js +150 -0
  47. package/src/run/drivers/mobile/native.js +229 -31
  48. package/src/run/drivers/mobile/preflight.js +14 -1
  49. package/src/run/drivers/mobile/target.js +21 -1
  50. package/src/run/drivers/stdio.js +150 -12
  51. package/src/run/drivers/unity/app.js +72 -0
  52. package/src/run/drivers/unity/engine.js +58 -0
  53. package/src/run/drivers/unity/link.js +108 -0
  54. package/src/run/drivers/unity/logs.js +76 -0
  55. package/src/run/drivers/unreal/app.js +40 -0
  56. package/src/run/drivers/unreal/driver.js +686 -0
  57. package/src/run/drivers/unreal/frames.js +243 -0
  58. package/src/run/drivers/unreal/logs.js +276 -0
  59. package/src/run/drivers/unreal/preflight.js +61 -0
  60. package/src/run/drivers/web.js +211 -13
  61. package/src/run/drivers/webdriver.js +79 -12
  62. package/src/run/endScreen.js +88 -0
  63. package/src/run/engineErrors.js +16 -0
  64. package/src/run/featureLoop.js +1 -1
  65. package/src/run/fingers.js +99 -0
  66. package/src/run/focusForKeys.js +54 -0
  67. package/src/run/godotTesterProbes.js +21 -2
  68. package/src/run/honesty.js +11 -1
  69. package/src/run/inputs.js +3 -3
  70. package/src/run/intent.js +12 -0
  71. package/src/run/pauseHook.js +494 -0
  72. package/src/run/personaLoop.js +139 -10
  73. package/src/run/pixels.js +22 -10
  74. package/src/run/planGuard.js +103 -0
  75. package/src/run/replay.js +5 -1
  76. package/src/run/reportChecks.js +17 -4
  77. package/src/run/resume.js +6 -2
  78. package/src/run/sessions.js +170 -0
  79. package/src/run/startFrom.js +415 -0
  80. package/src/run/testerProbes.js +36 -5
  81. package/src/run/tools.js +191 -10
  82. package/src/run/view3dState.js +125 -0
  83. package/src/run/web3d.js +375 -0
  84. package/src/run/world3d.js +164 -0
  85. package/templates/godot-3d/README.md +3 -2
package/src/run/args.js CHANGED
@@ -10,6 +10,9 @@
10
10
  * spends the developer's money on 25 actions.
11
11
  */
12
12
 
13
+ import { startProblems } from './startFrom.js';
14
+ import { sessionProblems } from './sessions.js';
15
+
13
16
  /** Options that take a value. */
14
17
  const VALUED = new Map([
15
18
  ['--personas', 'personas'],
@@ -46,13 +49,20 @@ const VALUED = new Map([
46
49
  // A cloud tier's allowance for a local run, its play length, and where a web build opens.
47
50
  ['--tier', 'tier'],
48
51
  ['--minutes', 'minutes'],
49
- ['--start', 'start']
52
+ ['--start', 'start'],
53
+ // A native local run's start (./startFrom.js): where the saves go, and a spec the game reads.
54
+ ['--save-target', 'saveTarget'],
55
+ ['--start-spec', 'startSpec'],
56
+ // A native local run played as several launches of the game (./sessions.js).
57
+ ['--sessions', 'sessions']
50
58
  ]);
51
59
 
52
60
  /** Options that may be given several times; each value is kept, in order. */
53
61
  const REPEATED = new Map([
54
62
  ['--focus', 'focus'],
55
- ['--avoid', 'avoid']
63
+ ['--avoid', 'avoid'],
64
+ // A save file a native local run starts from, up to eight (./startFrom.js).
65
+ ['--save', 'save']
56
66
  ]);
57
67
 
58
68
  /** Options that are just present or absent. */
@@ -113,7 +123,7 @@ const BOOLEAN = new Map([
113
123
  ]);
114
124
 
115
125
  /** Options whose value is a number. */
116
- const NUMERIC = new Set(['maxActions', 'concurrency', 'minutes']);
126
+ const NUMERIC = new Set(['maxActions', 'concurrency', 'minutes', 'sessions']);
117
127
 
118
128
  /**
119
129
  * @param {string[]} argv the leftovers commander handed over
@@ -263,8 +273,9 @@ export function scopeProblems(options = {}, driverName = '') {
263
273
  }
264
274
  if (options.start !== undefined) {
265
275
  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.');
266
- else if (driverName && driverName !== 'playwright_web') problems.push(`--start opens a web build at a query or hash, and this run uses ${driverName}.`);
276
+ 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.`);
267
277
  }
278
+ problems.push(...startProblems(options, driverName), ...sessionProblems(options, driverName));
268
279
  return problems;
269
280
  }
270
281
 
@@ -0,0 +1,104 @@
1
+ // Reading any desktop game for a local run on this Mac: a macOS app (.app),
2
+ // a plain executable, or a LÖVE game (a folder with main.lua, or a .love
3
+ // file) played with the LÖVE runtime on this machine. What engine made it is
4
+ // read only to name it in the run; any engine plays the same way.
5
+ import fs from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { command } from '../mobile/process.js';
8
+
9
+ const inside = (root, file) => file === root || file.startsWith(root + path.sep);
10
+ const exists = file => fs.access(file).then(() => true, () => false);
11
+ const LOVE_PATHS = ['/Applications/love.app/Contents/MacOS/love'];
12
+ /** The most arguments a project may pass to its game, and the longest each may be. */
13
+ export const MAX_GAME_ARGS = 32;
14
+ export const MAX_GAME_ARG_CHARS = 1024;
15
+
16
+ /**
17
+ * The game's own arguments from the project settings (`native.args`), as
18
+ * plain strings handed to the game without a shell.
19
+ *
20
+ * @param {unknown} args
21
+ * @returns {string[]}
22
+ */
23
+ export function gameArgs(args) {
24
+ if (args === undefined || args === null) return [];
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.`);
27
+ }
28
+ return [...args];
29
+ }
30
+
31
+ /** The LÖVE runtime on this machine: RAVENSIGHT_LOVE, the app in /Applications, or love on the PATH. */
32
+ export async function findLove(env = process.env, { candidates = LOVE_PATHS } = {}) {
33
+ if (env.RAVENSIGHT_LOVE) {
34
+ if (await exists(env.RAVENSIGHT_LOVE)) return env.RAVENSIGHT_LOVE;
35
+ throw new Error(`RAVENSIGHT_LOVE names ${env.RAVENSIGHT_LOVE}, which does not exist.`);
36
+ }
37
+ for (const candidate of candidates) if (await exists(candidate)) return candidate;
38
+ for (const folder of String(env.PATH || '').split(path.delimiter).filter(Boolean)) {
39
+ const candidate = path.join(folder, 'love');
40
+ if (await fs.access(candidate, fs.constants.X_OK).then(() => true, () => false)) return candidate;
41
+ }
42
+ throw new Error('This is a LÖVE game, and LÖVE is not installed on this Mac. Install LÖVE 11 into /Applications, or set RAVENSIGHT_LOVE to its love executable.');
43
+ }
44
+
45
+ /** What made a macOS app, from what its bundle holds, or null when it does not say. */
46
+ async function appEngine(root) {
47
+ const has = relative => exists(path.join(root, 'Contents', ...relative.split('/')));
48
+ if (await has('UE')) return 'unreal';
49
+ if (await has('Frameworks/UnityPlayer.dylib') || await has('Resources/Data/globalgamemanagers') || await has('Resources/Data/data.unity3d')) return 'unity';
50
+ if (await has('Frameworks/FlutterMacOS.framework')) return 'flutter';
51
+ if (await has('Resources/game.projectc') || await has('Resources/game.arcd')) return 'defold';
52
+ if (await has('Resources/game.ios') || await has('Resources/game.droid')) return 'gamemaker';
53
+ const resources = await fs.readdir(path.join(root, 'Contents', 'Resources')).catch(() => []);
54
+ if (resources.some(name => name.endsWith('.love'))) return 'love';
55
+ if (resources.some(name => name.endsWith('.pck'))) return 'godot';
56
+ return null;
57
+ }
58
+
59
+ /**
60
+ * @param {string} file a .app folder, an executable, a LÖVE folder or a .love file
61
+ * @param {{run?: Function, env?: Object, args?: string[], loveCandidates?: string[]}} [options]
62
+ * @returns {Promise<{kind: 'app'|'executable'|'love', engine: string|null, bundleId: string|null, executable: string, executablePath: string, args: string[], cwd: string|null, platform: 'mac', abi: string[]}>}
63
+ */
64
+ export async function inspectDesktopApp(file, { run = command, env = process.env, args = [], loveCandidates } = {}) {
65
+ if (!file) throw new Error('Pass --native-build with the game: a macOS app (.app), an executable, or a LÖVE game folder or .love file.');
66
+ const root = await fs.realpath(file).catch(() => { throw new Error(`No game at ${file}.`); });
67
+ const info = await fs.stat(root);
68
+ const extra = gameArgs(args);
69
+ const archs = async executable => run('lipo', ['-archs', executable], { timeout: 10000 }).then(out => out.split(/\s+/).filter(Boolean), () => []);
70
+ // A LÖVE game: its folder (main.lua) or its .love archive, played by the LÖVE runtime.
71
+ if ((info.isDirectory() && !/\.app\/?$/i.test(file) && await exists(path.join(root, 'main.lua'))) || (info.isFile() && /\.love$/i.test(root))) {
72
+ const love = await findLove(env, loveCandidates ? { candidates: loveCandidates } : {});
73
+ const executablePath = await fs.realpath(love);
74
+ return { kind: 'love', engine: 'love', bundleId: null, executable: path.basename(executablePath), executablePath, args: [root, ...extra], cwd: info.isDirectory() ? root : path.dirname(root), platform: 'mac', abi: await archs(executablePath) };
75
+ }
76
+ if (info.isDirectory()) {
77
+ if (!/\.app\/?$/i.test(file) && !/\.app$/i.test(root)) throw new Error('Pass a macOS app (a folder ending in .app), an executable file, or a LÖVE game folder with main.lua.');
78
+ const plist = path.join(root, 'Contents', 'Info.plist');
79
+ let plistInfo;
80
+ try { plistInfo = JSON.parse(await run('plutil', ['-convert', 'json', '-o', '-', plist], { timeout: 10000 })); }
81
+ catch { throw new Error('The app has no readable Contents/Info.plist.'); }
82
+ const executable = String(plistInfo.CFBundleExecutable || '');
83
+ if (!/^[A-Za-z0-9][A-Za-z0-9 ._+-]{0,127}$/.test(executable)) throw new Error('The app names no valid executable (CFBundleExecutable).');
84
+ const executablePath = path.join(root, 'Contents', 'MacOS', executable);
85
+ const realExecutable = await fs.realpath(executablePath).catch(() => null);
86
+ if (!realExecutable || !inside(root, realExecutable) || !(await fs.stat(realExecutable)).isFile()) throw new Error('The app executable is missing.');
87
+ const bundleId = typeof plistInfo.CFBundleIdentifier === 'string' && /^[A-Za-z0-9.-]{1,155}$/.test(plistInfo.CFBundleIdentifier) ? plistInfo.CFBundleIdentifier : null;
88
+ return { kind: 'app', engine: await appEngine(root), bundleId, executable, executablePath: realExecutable, args: extra, cwd: null, platform: 'mac', abi: await archs(realExecutable) };
89
+ }
90
+ if (!info.isFile()) throw new Error('The game must be a macOS app, an executable file, or a LÖVE game.');
91
+ if (!(await fs.access(root, fs.constants.X_OK).then(() => true, () => false))) throw new Error(`${path.basename(root)} is not executable (chmod +x it, or pass the .app).`);
92
+ // Games load their files from where they start, so an executable runs from its own folder.
93
+ return { kind: 'executable', engine: null, bundleId: null, executable: path.basename(root), executablePath: root, args: extra, cwd: path.dirname(root), platform: 'mac', abi: await archs(root) };
94
+ }
95
+
96
+ /** The game in the run's words: its engine, or what kind of build it is. */
97
+ export function describeGame(metadata) {
98
+ const names = { love: 'LÖVE', unity: 'Unity', unreal: 'Unreal', flutter: 'Flutter', defold: 'Defold', gamemaker: 'GameMaker', godot: 'Godot' };
99
+ const engine = metadata && names[metadata.engine];
100
+ const kind = metadata && metadata.kind === 'app' ? 'macOS app' : metadata && metadata.kind === 'love' ? 'LÖVE game' : 'executable';
101
+ return engine && kind !== 'LÖVE game' ? `${engine} ${kind}` : kind;
102
+ }
103
+
104
+ export default { inspectDesktopApp, findLove, gameArgs, describeGame };
@@ -0,0 +1,336 @@
1
+ // What every local desktop driver on this Mac shares (../unreal/driver.js for
2
+ // a packaged Unreal game, ./driver.js for any other desktop game): the game's
3
+ // environment without credentials, the mapping from the frame the persona saw
4
+ // to a point on screen, a capture of one window, the game process and its
5
+ // exit, and the recorder that turns the frames the run saw into its video.
6
+ import { spawn } from 'node:child_process';
7
+ import { EventEmitter } from 'node:events';
8
+ import { PassThrough } from 'node:stream';
9
+ import { createHash, randomBytes } from 'node:crypto';
10
+ import fs from 'node:fs/promises';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { completePng } from '../mobile/frame.js';
14
+ import { command, sleep } from '../mobile/process.js';
15
+ import { recordingDirectory, recordingMetadata, saveRecording, encodeFrames, RECORDING_LIMITS } from '../recording.js';
16
+
17
+ /** One local desktop run plays at a time on this Mac, whatever the engine. */
18
+ export const DESKTOP_LOCK = 'desktop:mac';
19
+ export const DEFAULT_RESOLUTION = Object.freeze({ width: 1280, height: 720 });
20
+ export const RECORD_INTERVAL_MS = 500;
21
+ export const MODEL_LONG_EDGE = 1280;
22
+ /** Signals that mean the game crashed, rather than was told to stop. */
23
+ export const CRASH_SIGNALS = new Set(['SIGSEGV', 'SIGBUS', 'SIGILL', 'SIGABRT', 'SIGFPE', 'SIGTRAP', 'SIGSYS']);
24
+ /** How long each step of a look takes when the persona gives no time. */
25
+ export const LOOK_STEP_MS = 16;
26
+ const SECRET_ENV = /(TOKEN|SECRET|PASSWORD|PASSWD|API_?KEY|ACCESS_?KEY|CREDENTIAL|SESSION|COOKIE|AUTH)/i;
27
+
28
+ /** The game inherits this process's environment without credentials or Ravensight settings. */
29
+ export function gameEnvironment(env = process.env) {
30
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !name.startsWith('RAVENSIGHT_') && !SECRET_ENV.test(name)));
31
+ }
32
+
33
+ /**
34
+ * A point on the frame the persona saw, as a point on screen for an input.
35
+ * Game frames are the viewport only, so the window's title bar is added;
36
+ * a window capture already includes it.
37
+ *
38
+ * @param {{x: number, y: number}} point in the model's frame
39
+ * @param {{width: number, height: number, nativeWidth: number, nativeHeight: number}} frame
40
+ * @param {{x: number, y: number, width: number, height: number}} window in screen points
41
+ * @param {'game'|'window'} source
42
+ */
43
+ export function screenPoint(point, frame, window, source) {
44
+ if (!frame || !point || !Number.isFinite(point.x) || !Number.isFinite(point.y) || point.x < 0 || point.y < 0 || point.x >= frame.width || point.y >= frame.height) {
45
+ throw new Error('Use coordinates inside the most recent screenshot.');
46
+ }
47
+ if (!window || !(window.width > 0) || !(window.height > 0)) throw new Error('The game window is not on screen.');
48
+ const nativeX = point.x * frame.nativeWidth / frame.width, nativeY = point.y * frame.nativeHeight / frame.height;
49
+ const scale = frame.nativeWidth / window.width;
50
+ const top = source === 'game' ? Math.max(0, window.height - frame.nativeHeight / scale) : 0;
51
+ return { x: Math.round((window.x + nativeX / scale) * 10) / 10, y: Math.round((window.y + top + nativeY / scale) * 10) / 10 };
52
+ }
53
+
54
+ /** A point on the frame the persona saw, as a pixel of the game's own frame. */
55
+ export function gamePixel(point, frame) {
56
+ if (!frame || !point || !Number.isFinite(point.x) || !Number.isFinite(point.y) || point.x < 0 || point.y < 0 || point.x >= frame.width || point.y >= frame.height) {
57
+ throw new Error('Use coordinates inside the most recent screenshot.');
58
+ }
59
+ return { x: Math.min(frame.nativeWidth - 1, Math.floor(point.x * frame.nativeWidth / frame.width)), y: Math.min(frame.nativeHeight - 1, Math.floor(point.y * frame.nativeHeight / frame.height)) };
60
+ }
61
+
62
+ /**
63
+ * A look of dx, dy as whole-pixel moves that add up to it exactly, one for
64
+ * each frame or so of `ms`, as a mouse reports a turn.
65
+ */
66
+ export function lookSteps(dx, dy, ms) {
67
+ const parts = Math.min(32, Math.max(1, Math.round(ms / LOOK_STEP_MS)));
68
+ const out = [];
69
+ let x = 0, y = 0;
70
+ for (let i = 1; i <= parts; i++) {
71
+ const nx = Math.round(dx * i / parts), ny = Math.round(dy * i / parts);
72
+ if (nx !== x || ny !== y) out.push({ dx: nx - x, dy: ny - y });
73
+ x = nx; y = ny;
74
+ }
75
+ return out;
76
+ }
77
+
78
+ /** A capture of one window by its id (needs Screen Recording for this terminal). */
79
+ export async function captureWindow(windowId, { run = command } = {}) {
80
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ravensight-desktop-frame-'));
81
+ try {
82
+ const file = path.join(directory, 'frame.png');
83
+ await run('screencapture', ['-x', '-o', '-t', 'png', `-l${windowId}`, file], { timeout: 10000 });
84
+ const png = await fs.readFile(file);
85
+ if (!completePng(png)) throw new Error('The window capture is not a complete PNG.');
86
+ return png;
87
+ } finally { await fs.rm(directory, { recursive: true, force: true }); }
88
+ }
89
+
90
+ /**
91
+ * Start the game with a pipe set for each of `stdio`, and keep its exit: the
92
+ * child gets `exitPromise`, and `exited()` says how it ended (null while it
93
+ * runs). A CLI that dies mid run never leaves the game running.
94
+ *
95
+ * @returns {{child: import('node:child_process').ChildProcess, exited: () => ({code: number|null, signal: string|null, error?: string, at: number}|null)}}
96
+ */
97
+ export function launchGame(file, args, { env, stdio, cwd, spawnGame = spawn, now = Date.now, onExit = () => {} }) {
98
+ const child = spawnGame(file, args, { stdio, env, detached: false, ...(cwd ? { cwd } : {}) });
99
+ let exited = null;
100
+ const orphan = () => { if (!exited) child.kill('SIGKILL'); };
101
+ process.once('exit', orphan);
102
+ child.exitPromise = new Promise(resolve => {
103
+ child.once('exit', (code, signalName) => { exited = { code, signal: signalName, at: now() }; process.removeListener('exit', orphan); onExit(exited); resolve(exited); });
104
+ child.once('error', error => { exited = { code: null, signal: null, error: error.message, at: now() }; process.removeListener('exit', orphan); onExit(exited); resolve(exited); });
105
+ });
106
+ return { child, exited: () => exited };
107
+ }
108
+
109
+ /**
110
+ * The app bundle a game runs from, for a launch through LaunchServices, or
111
+ * null for a bare executable: an .app's own folder, or the .app that holds
112
+ * the runtime (LÖVE's love.app).
113
+ */
114
+ export function bundleOf(metadata) {
115
+ const match = String(metadata && metadata.executablePath || '').match(/^(.*?\.app)\/Contents\/MacOS\/[^/]+$/);
116
+ return match ? match[1] : null;
117
+ }
118
+
119
+ /** A file the game writes to, read as a stream as it grows, until `finish()` reads the rest and ends it. */
120
+ function followFile(file, { intervalMs = 150 } = {}) {
121
+ const stream = new PassThrough();
122
+ let offset = 0, stopped = false, timer = null;
123
+ const read = async () => {
124
+ const handle = await fs.open(file, 'r').catch(() => null);
125
+ if (!handle) return;
126
+ try {
127
+ for (;;) {
128
+ const buffer = Buffer.alloc(65536);
129
+ const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
130
+ if (!bytesRead) break;
131
+ offset += bytesRead;
132
+ stream.write(buffer.subarray(0, bytesRead));
133
+ }
134
+ } finally { await handle.close(); }
135
+ };
136
+ const loop = async () => { if (stopped) return; await read().catch(() => {}); if (!stopped) { timer = setTimeout(loop, intervalMs); timer.unref?.(); } };
137
+ void loop();
138
+ stream.finish = async () => { stopped = true; clearTimeout(timer); await read().catch(() => {}); stream.end(); };
139
+ return stream;
140
+ }
141
+
142
+ /**
143
+ * Start a game app through LaunchServices (`open -n`), as Finder does, so
144
+ * macOS lets it come to the front: a game started directly by a terminal in
145
+ * the background may never be given focus, and then a click never reaches
146
+ * it. The app inherits `open`'s own environment, which is `env` exactly, so
147
+ * no variable (the pause hook's nonce and token among them) is ever on a
148
+ * command line another process could read; the arguments carry only the
149
+ * game's own. Its standard output and error go to files in a private folder,
150
+ * followed as streams. The new process is the one `find` names (the input
151
+ * helper: exactly this executable, started by launchd, with this launch's
152
+ * own random marker in its environment); none or more than one is refused.
153
+ * The handle looks like a child process: pid, kill, exitPromise, stdout,
154
+ * stderr. Its exit status is not known (it is not this process's child), so
155
+ * an exit reads as code null unless a crash report says more.
156
+ *
157
+ * @param {(request: {executable: string, marker: string}) => Promise<{pids: number[]}>} find
158
+ */
159
+ export async function launchThroughLaunchServices(bundle, executable, args, { env, find, now = Date.now, onExit = () => {}, run = command, startTimeoutMs = 30000, pollMs = 250 }) {
160
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ravensight-desktop-output-'));
161
+ const out = path.join(directory, 'stdout.log'), err = path.join(directory, 'stderr.log');
162
+ await Promise.all([fs.writeFile(out, '', { mode: 0o600 }), fs.writeFile(err, '', { mode: 0o600 })]);
163
+ const marker = randomBytes(32).toString('hex');
164
+ try {
165
+ await run('open', ['-n', '-a', bundle, '--stdout', out, '--stderr', err, '--args', ...args], { timeout: startTimeoutMs, env: { ...env, RAVENSIGHT_DESKTOP_LAUNCH: marker } });
166
+ } catch (error) { await fs.rm(directory, { recursive: true, force: true }); throw error; }
167
+ let pid = null;
168
+ for (const deadline = now() + startTimeoutMs; !pid && now() < deadline;) {
169
+ let pids = [];
170
+ try { ({ pids = [] } = await find({ executable, marker })); }
171
+ catch (error) { await fs.rm(directory, { recursive: true, force: true }); throw new Error(`The game app started but could not be identified (${error.message}); quit ${path.basename(bundle)} if it is still open.`); }
172
+ if (pids.length > 1) { await fs.rm(directory, { recursive: true, force: true }); throw new Error(`More than one process claims to be the game this run started; nothing was sent to either. Quit ${path.basename(bundle)} if it is still open.`); }
173
+ if (pids.length === 1 && Number.isSafeInteger(pids[0]) && pids[0] > 1) pid = pids[0]; else await sleep(pollMs);
174
+ }
175
+ if (!pid) { await fs.rm(directory, { recursive: true, force: true }); throw new Error(`The game app did not start, or could not be identified; quit ${path.basename(bundle)} if it opened.`); }
176
+ const stdout = followFile(out), stderr = followFile(err);
177
+ let exited = null, poll = null;
178
+ const handle = new EventEmitter();
179
+ const finish = state => {
180
+ if (exited) return;
181
+ exited = state;
182
+ clearInterval(poll);
183
+ process.removeListener('exit', orphan);
184
+ void Promise.all([stdout.finish(), stderr.finish()]).finally(() => fs.rm(directory, { recursive: true, force: true }).catch(() => {}));
185
+ onExit(exited);
186
+ handle.emit('exit', null, null);
187
+ };
188
+ const alive = () => { try { process.kill(pid, 0); return true; } catch (error) { return error.code === 'EPERM'; } };
189
+ const orphan = () => { if (!exited) try { process.kill(pid, 'SIGKILL'); } catch { /* gone */ } };
190
+ process.once('exit', orphan);
191
+ poll = setInterval(() => { if (!alive()) finish({ code: null, signal: null, at: now() }); }, pollMs);
192
+ poll.unref?.();
193
+ handle.pid = pid;
194
+ handle.stdout = stdout;
195
+ handle.stderr = stderr;
196
+ handle.exitPromise = new Promise(resolve => handle.once('exit', () => resolve(exited)));
197
+ handle.kill = (signalName = 'SIGTERM') => { try { process.kill(pid, signalName); return true; } catch { return false; } };
198
+ return { child: handle, exited: () => exited };
199
+ }
200
+
201
+ /** Ask the game to stop, then make it. */
202
+ export async function stopGame(child, exited) {
203
+ if (!child || exited()) return;
204
+ // A timer that does not hold the CLI open once the game has gone.
205
+ const grace = ms => new Promise(resolve => setTimeout(resolve, ms).unref?.());
206
+ child.kill('SIGTERM');
207
+ const gone = await Promise.race([child.exitPromise.then(() => true), grace(5000).then(() => false)]);
208
+ if (!gone) { child.kill('SIGKILL'); await Promise.race([child.exitPromise, grace(2000)]); }
209
+ }
210
+
211
+ /**
212
+ * The run's video from the frames it saw: every capture is offered, a timer
213
+ * adds one about twice a second, and the frames are encoded to session.mp4
214
+ * when the run stops.
215
+ *
216
+ * @param {Object} options
217
+ * @param {string} options.runDir
218
+ * @param {string} options.driver the driver's name, for recording.json
219
+ * @param {() => Promise<unknown>} options.capture takes a frame (and offers it back)
220
+ * @param {() => boolean} options.ended true once the game has gone
221
+ * @param {() => string} options.captureKind 'game-frames' or 'window-capture'
222
+ */
223
+ export async function startFrameRecorder({ runDir, driver, capture, ended, captureKind, intervalMs = RECORD_INTERVAL_MS, now = Date.now, encode = encodeFrames }) {
224
+ const state = { frames: [], bytes: 0, directory: null, timer: null, last: null, ended: null, reason: 'stopped', startedAt: now(), busy: false, writing: Promise.resolve() };
225
+ const write = async (png, at) => {
226
+ const hash = createHash('sha1').update(png).digest('hex');
227
+ // Two captures can finish out of order; the video keeps time order.
228
+ if (hash === state.last || state.ended || (state.frames.length && at < state.frames.at(-1).at)) return;
229
+ if (state.bytes + png.length > RECORDING_LIMITS.frameBytes) { state.ended = at; state.reason = 'size_limit'; return; }
230
+ state.last = hash;
231
+ const name = `${String(state.frames.length + 1).padStart(6, '0')}.png`;
232
+ await fs.writeFile(path.join(state.directory, name), png, { flag: 'wx', mode: 0o600 });
233
+ state.frames.push({ name, at }); state.bytes += png.length;
234
+ };
235
+ state.directory = await recordingDirectory(runDir);
236
+ const tick = async () => {
237
+ if (state.busy || state.ended || ended()) return;
238
+ state.busy = true;
239
+ try { await capture(); } catch { /* the next action reports a capture failure */ } finally { state.busy = false; }
240
+ };
241
+ state.timer = setInterval(() => { void tick(); }, intervalMs);
242
+ state.timer.unref?.();
243
+ return {
244
+ startedAt: state.startedAt,
245
+ // Frames are written in capture order, one at a time.
246
+ offer(png, at) { if (!state.ended) state.writing = state.writing.then(() => write(png, at)).catch(() => {}); },
247
+ async stop(reason) {
248
+ clearInterval(state.timer);
249
+ while (state.busy) await sleep(20);
250
+ await state.writing;
251
+ const endedAt = state.ended ?? now();
252
+ let meta = recordingMetadata({ driver, startedAt: state.startedAt, endedAt, reason: state.reason === 'size_limit' ? 'size_limit' : reason, frameCount: state.frames.length, captureFpsLimit: Math.round(1000 / intervalMs), timeOrigin: 'first-frame', capture: captureKind() });
253
+ let videoPath = null;
254
+ if (state.directory) {
255
+ try {
256
+ const encoded = await encode({ directory: state.directory, frames: state.frames, endedAt });
257
+ videoPath = path.join(runDir, 'session.mp4');
258
+ await fs.rename(encoded.file, videoPath);
259
+ meta = { ...meta, status: state.reason === 'size_limit' || encoded.truncated ? 'partial' : 'complete', relativePath: 'session.mp4', mimeType: encoded.mimeType, bytes: encoded.bytes, durationMs: encoded.durationMs, durationSource: encoded.durationSource ?? 'frame-timestamps', firstFrameOffsetMs: state.frames[0].at - state.startedAt };
260
+ } catch (error) {
261
+ meta.reason = ['no_frames', 'encoder_unavailable', 'encoding_timeout', 'encoding_failed'].includes(error.message) ? error.message : 'encoding_failed';
262
+ }
263
+ await fs.rm(state.directory, { recursive: true, force: true });
264
+ }
265
+ await saveRecording(runDir, meta);
266
+ return { videoPath, recording: meta };
267
+ }
268
+ };
269
+ }
270
+
271
+ /** A screenshot of the run kept for the model, read back only from inside the run's screenshots folder. */
272
+ export async function runScreenshot(runDirectory, screenshot) {
273
+ const file = path.resolve(screenshot.path || '');
274
+ const root = path.resolve(runDirectory, 'screenshots');
275
+ if (!file.startsWith(`${root}${path.sep}`)) throw new Error('The requested screenshot is outside this run.');
276
+ const [realFile, realRoot] = await Promise.all([fs.realpath(file), fs.realpath(root)]);
277
+ if (!realFile.startsWith(`${realRoot}${path.sep}`)) throw new Error('The requested screenshot resolves outside this run.');
278
+ return { data: (await fs.readFile(realFile)).toString('base64'), mediaType: 'image/png' };
279
+ }
280
+
281
+ export const round1 = n => (Number.isFinite(Number(n)) ? String(Math.round(Number(n) * 10) / 10) : '?');
282
+ const vec = v => (Array.isArray(v) ? `(${v.map(round1).join(', ')})` : '(?)');
283
+
284
+ /** The game's own 3D view as lines of the observation, and the tagged things the persona can aim at. */
285
+ export function viewText(view, names = []) {
286
+ const lines = [];
287
+ if (view && view.has_3d && view.camera) {
288
+ const cam = view.camera;
289
+ lines.push('3D view, from the game\'s own state (metres, y up):');
290
+ lines.push(` camera at ${vec(cam.position)} facing ${round1(cam.yaw)} degrees round, ${round1(cam.pitch)} degrees up${cam.up && cam.up[1] < 0 ? ', UPSIDE DOWN' : ''}${cam.inside ? `, inside ${cam.inside.name}` : ''}${view.paused ? '; the game itself is paused' : ''}`);
291
+ const player = (view.bodies || []).find(body => body.player);
292
+ if (player) lines.push(` player ${player.name} at ${vec(player.position)}, speed ${round1(player.speed)} m/s, ${player.on_floor ? 'on the ground' : 'in the air'}${player.on_wall ? ', against a wall' : ''}`);
293
+ if (view.world) lines.push(` the level's solid ground spans y ${round1(view.world.min[1])} to ${round1(view.world.max[1])}`);
294
+ }
295
+ if (names.length) lines.push(`Named things in the level (hover aim_at turns the view onto one): ${names.join(', ')}.`);
296
+ return lines.join('\n');
297
+ }
298
+
299
+ /** Whether an exit looks like a crash or a failure, so the crash report is worth waiting for. */
300
+ export function abnormalExit(exited) {
301
+ return Boolean(exited && ((exited.signal && CRASH_SIGNALS.has(exited.signal)) || (exited.code !== 0 && exited.code !== null)));
302
+ }
303
+
304
+ /**
305
+ * How long to wait for the crash report macOS writes after the game ended: the
306
+ * full wait after a crashing signal or a failing status; longer still when the
307
+ * status is unknown (a game started through LaunchServices is not this
308
+ * process's child), since a big report (a Unity player's) can take about ten
309
+ * seconds to appear and is then the only sign of a crash; a short wait after a
310
+ * clean quit.
311
+ */
312
+ export function crashWait(exited, crashWaitMs) {
313
+ if (exited && exited.code === null && !exited.signal) return Math.round(crashWaitMs * 2.5);
314
+ return abnormalExit(exited) ? crashWaitMs : Math.min(1500, crashWaitMs);
315
+ }
316
+
317
+ /**
318
+ * How the game ended, in the run's words: a crash with the report it left, a
319
+ * crash with none, or a quit. `recent` is the game's last output, quoted.
320
+ *
321
+ * @param {{exited: {code: number|null, signal: string|null}, crash: {source: string, summary: string}|null, lastError?: string|null, recent?: string[]}} facts
322
+ * @returns {{kind: 'crashed'|'exited', message: string, log?: string}}
323
+ */
324
+ export function describeEnd({ exited, crash, lastError = null, recent = [] }) {
325
+ // A game started through LaunchServices is not this process's child: its exit status is not known.
326
+ const status = exited.signal || (exited.code === null ? 'exit status unknown' : `exit code ${exited.code}`);
327
+ // The loop's crash finding ends each message with its own full stop, and quotes the game's last output.
328
+ const tail = recent.length ? { log: recent.join('\n') } : {};
329
+ const bare = text => String(text).replace(/[.\s]+$/, '');
330
+ const how = exited.signal || exited.code !== null ? ` (${status})` : '';
331
+ if (crash) return { kind: 'crashed', message: bare(`The game crashed during play${how}. ${crash.source === 'engine' ? 'Its crash report says' : 'The macOS crash report says'}: ${crash.summary}`.slice(0, 600)), ...tail };
332
+ if (exited.signal && CRASH_SIGNALS.has(exited.signal)) return { kind: 'crashed', message: bare(`The game crashed during play (${status}); it left no crash report this runner could read${lastError ? `. The last error it logged: ${lastError}` : ''}`.slice(0, 600)), ...tail };
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
+ }
335
+
336
+ export default { gameEnvironment, screenPoint, gamePixel, lookSteps, captureWindow, launchGame, stopGame, startFrameRecorder, runScreenshot, viewText, describeEnd, abnormalExit, DESKTOP_LOCK };