ravensight-playtest 0.11.0 → 0.12.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/README.md +89 -21
- package/addons/mobile/Host/AppDelegate.swift +11 -0
- package/addons/mobile/RavensightMobile.xcodeproj/project.pbxproj +398 -0
- package/addons/mobile/RavensightMobile.xcodeproj/project.xcworkspace/contents.xcworkspacedata +7 -0
- package/addons/mobile/RavensightMobile.xcodeproj/xcshareddata/xcschemes/RavensightMobile.xcscheme +116 -0
- package/addons/mobile/UITests/MobileInputTests.swift +152 -0
- package/addons/mobile/project.yml +45 -0
- package/docs/ADAPTERS.md +5 -4
- package/docs/MOBILE.md +107 -0
- package/docs/NATIVE_RUNNER.md +7 -3
- package/docs/godot-driver.md +1 -1
- package/package.json +7 -5
- package/src/api/README.md +3 -3
- package/src/cli.js +36 -6
- package/src/commands/check.js +17 -3
- package/src/commands/device.js +64 -0
- package/src/commands/fakeCore.js +1 -1
- package/src/commands/hosted.js +16 -13
- package/src/commands/login.js +1 -1
- package/src/commands/run.js +39 -11
- package/src/dashboard.js +2 -3
- package/src/detect.js +17 -0
- package/src/fsutil.js +1 -1
- package/src/hosted/archivePreflight.js +3 -3
- package/src/hosted/buildUpload.js +8 -7
- package/src/hosted/recordedRun.js +19 -3
- package/src/run/anygame/index.js +9 -3
- package/src/run/args.js +6 -0
- package/src/run/budgetReserve.js +29 -9
- package/src/run/claimProtocol.js +27 -0
- package/src/run/completion.js +86 -0
- package/src/run/context.js +2 -2
- package/src/run/drivers/android.js +3 -0
- package/src/run/drivers/godot.js +1 -1
- package/src/run/drivers/index.js +4 -0
- package/src/run/drivers/ios.js +3 -0
- package/src/run/drivers/mobile/adb.js +91 -0
- package/src/run/drivers/mobile/attempt.js +18 -0
- package/src/run/drivers/mobile/crash.js +115 -0
- package/src/run/drivers/mobile/frame.js +64 -0
- package/src/run/drivers/mobile/ios-helper.js +102 -0
- package/src/run/drivers/mobile/lock.js +32 -0
- package/src/run/drivers/mobile/native.js +227 -0
- package/src/run/drivers/mobile/preflight.js +80 -0
- package/src/run/drivers/mobile/process.js +57 -0
- package/src/run/drivers/mobile/recording.js +88 -0
- package/src/run/drivers/mobile/screenshot.js +34 -0
- package/src/run/drivers/mobile/simctl.js +60 -0
- package/src/run/drivers/mobile/target.js +53 -0
- package/src/run/honesty.js +66 -26
- package/src/run/inputMeasurement.js +49 -0
- package/src/run/model.js +24 -31
- package/src/run/paths.js +1 -1
- package/src/run/personaLoop.js +282 -74
- package/src/run/proxyClient.js +173 -0
- package/src/run/repoTools.js +1 -1
- package/src/run/report.js +19 -0
- package/src/run/resume.js +33 -4
- package/src/run/screenshots.js +3 -1
- package/src/run/tools.js +31 -5
- package/src/run/usage.js +2 -2
- package/src/upload/allowlist.js +2 -2
- package/src/upload/index.js +9 -9
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { paths } from '../../../paths.js';
|
|
7
|
+
import { command, startProcess, stopProcess } from './process.js';
|
|
8
|
+
|
|
9
|
+
export const HELPER_PROJECT = fileURLToPath(new URL('../../../../addons/mobile/RavensightMobile.xcodeproj', import.meta.url));
|
|
10
|
+
export function helperDirectory() { return process.env.RAVENSIGHT_IOS_HELPER_DIR || path.join(paths.userDir(), 'mobile', 'xctest'); }
|
|
11
|
+
export async function helperBuilt(directory = helperDirectory()) {
|
|
12
|
+
const products = path.join(directory, 'Build', 'Products');
|
|
13
|
+
return (await fs.readdir(products).catch(() => [])).some(name => name.endsWith('.xctestrun'));
|
|
14
|
+
}
|
|
15
|
+
export async function buildIosHelper({ run = command, directory = helperDirectory() } = {}) {
|
|
16
|
+
if (process.platform !== 'darwin') throw new Error('The iOS input helper requires macOS and Xcode.');
|
|
17
|
+
await fs.mkdir(directory, { recursive: true });
|
|
18
|
+
await run('xcodebuild', ['build-for-testing', '-project', HELPER_PROJECT, '-scheme', 'RavensightMobile', '-sdk', 'iphonesimulator', '-destination', 'generic/platform=iOS Simulator', '-derivedDataPath', directory, 'CODE_SIGNING_ALLOWED=NO'], { timeout: 300000, maxBuffer: 8 * 1024 * 1024 });
|
|
19
|
+
if (!await helperBuilt(directory)) throw new Error('Xcode did not produce the simulator input test runner.');
|
|
20
|
+
return directory;
|
|
21
|
+
}
|
|
22
|
+
export async function startIosHelper({ device, signal, directory = helperDirectory(), launch = true, timeout = 180000 } = {}) {
|
|
23
|
+
if (signal?.aborted) throw new Error('iOS input startup cancelled.');
|
|
24
|
+
if (launch && !await helperBuilt(directory)) throw new Error('The iOS input helper is not built. Run ravensight-playtest device setup ios.');
|
|
25
|
+
const token = randomBytes(24).toString('hex');
|
|
26
|
+
let pendingPoll = null, pollTimer = null, nextId = 0, child = null, stopped = false, failed = false, dimensions = null;
|
|
27
|
+
const queue = [], requests = new Map();
|
|
28
|
+
let onReady, readyReject;
|
|
29
|
+
const ready = new Promise((resolve, reject) => { onReady = resolve; readyReject = reject; });
|
|
30
|
+
// The caller always observes ready below; attach a rejection handler for a fast startup failure.
|
|
31
|
+
ready.catch(() => {});
|
|
32
|
+
const reply = (res, data, status = 200) => { if (!res.writableEnded) { res.writeHead(status, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(data)); } };
|
|
33
|
+
const flush = () => { if (pendingPoll && queue.length) { clearTimeout(pollTimer); reply(pendingPoll, queue.shift()); pendingPoll = null; } };
|
|
34
|
+
const invalidate = error => {
|
|
35
|
+
failed = true; queue.length = 0;
|
|
36
|
+
for (const pending of requests.values()) { clearTimeout(pending.timer); pending.reject(error); }
|
|
37
|
+
requests.clear();
|
|
38
|
+
if (pendingPoll) { clearTimeout(pollTimer); reply(pendingPoll, { kind: 'shutdown' }); pendingPoll = null; }
|
|
39
|
+
};
|
|
40
|
+
const server = http.createServer(async (req, res) => {
|
|
41
|
+
if (!req.url?.startsWith(`/${token}/`)) { reply(res, { error: 'not_found' }, 404); return; }
|
|
42
|
+
const route = req.url.slice(token.length + 1);
|
|
43
|
+
if (req.method === 'GET' && route === '/next') {
|
|
44
|
+
if (failed) { reply(res, { kind: 'shutdown' }); return; }
|
|
45
|
+
if (pendingPoll) reply(pendingPoll, {});
|
|
46
|
+
clearTimeout(pollTimer); pendingPoll = res; res.on('close', () => { if (pendingPoll === res) { clearTimeout(pollTimer); pendingPoll = null; } });
|
|
47
|
+
pollTimer = setTimeout(() => { if (pendingPoll === res) { reply(res, {}); pendingPoll = null; } }, 5000); flush(); return;
|
|
48
|
+
}
|
|
49
|
+
if (req.method !== 'POST' || !['/ready', '/result'].includes(route)) { reply(res, {}, 404); return; }
|
|
50
|
+
let size = 0, body = '';
|
|
51
|
+
try {
|
|
52
|
+
for await (const part of req) { size += part.length; if (size > 65536) throw new Error('too_large'); body += part; }
|
|
53
|
+
const value = JSON.parse(body);
|
|
54
|
+
if (route === '/ready') {
|
|
55
|
+
if (!Number.isFinite(value.width) || !Number.isFinite(value.height) || value.width < 1 || value.height < 1) throw new Error('invalid_dimensions');
|
|
56
|
+
dimensions = { width: value.width, height: value.height }; onReady(dimensions);
|
|
57
|
+
} else {
|
|
58
|
+
const pending = requests.get(value.id);
|
|
59
|
+
if (pending) {
|
|
60
|
+
if (Number.isFinite(value.width) && Number.isFinite(value.height) && value.width > 0 && value.height > 0) dimensions = { width: value.width, height: value.height };
|
|
61
|
+
clearTimeout(pending.timer); requests.delete(value.id); value.ok ? pending.resolve(value) : pending.reject(new Error(String(value.error || 'iOS input failed').slice(0, 500)));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
reply(res, { ok: true });
|
|
65
|
+
} catch { reply(res, { error: 'invalid_request' }, 400); }
|
|
66
|
+
});
|
|
67
|
+
server.requestTimeout = 15000; server.headersTimeout = 10000;
|
|
68
|
+
await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve); });
|
|
69
|
+
const url = `http://127.0.0.1:${server.address().port}/${token}`;
|
|
70
|
+
function send(action, timeoutMs = 15000) {
|
|
71
|
+
if (stopped || (failed && action.kind !== 'shutdown')) return Promise.reject(new Error('The iOS input helper has stopped.'));
|
|
72
|
+
return new Promise((resolve, reject) => {
|
|
73
|
+
const id = ++nextId;
|
|
74
|
+
const timer = setTimeout(() => { invalidate(new Error(`iOS ${action.kind} timed out; the input session has been stopped.`)); if (child) child.child.kill('SIGTERM'); }, timeoutMs);
|
|
75
|
+
requests.set(id, { resolve, reject, timer }); queue.push({ ...action, id }); flush();
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
async function stop() {
|
|
79
|
+
if (stopped) return;
|
|
80
|
+
if (!failed) await send({ kind: 'shutdown' }, 2000).catch(() => {});
|
|
81
|
+
stopped = true; clearTimeout(pollTimer);
|
|
82
|
+
for (const pending of requests.values()) { clearTimeout(pending.timer); pending.reject(new Error('The iOS input helper stopped.')); }
|
|
83
|
+
requests.clear(); if (pendingPoll) reply(pendingPoll, { kind: 'shutdown' });
|
|
84
|
+
server.closeAllConnections(); await new Promise(resolve => server.close(resolve));
|
|
85
|
+
await stopProcess(child, 'SIGINT', 10000);
|
|
86
|
+
signal?.removeEventListener('abort', abort);
|
|
87
|
+
}
|
|
88
|
+
const abort = () => { readyReject(new Error('iOS input startup cancelled.')); void stop(); };
|
|
89
|
+
signal?.addEventListener('abort', abort, { once: true });
|
|
90
|
+
if (launch) {
|
|
91
|
+
const resultPath = path.join(directory, 'results', `run-${Date.now()}-${randomBytes(4).toString('hex')}.xcresult`);
|
|
92
|
+
await fs.mkdir(path.dirname(resultPath), { recursive: true });
|
|
93
|
+
child = startProcess('xcodebuild', ['test-without-building', '-project', HELPER_PROJECT, '-scheme', 'RavensightMobile', '-derivedDataPath', directory, '-destination', `id=${device}`, '-parallel-testing-enabled', 'NO', '-resultBundlePath', resultPath, '-only-testing:RavensightMobileUITests/MobileInputTests/testServe', 'CODE_SIGNING_ALLOWED=NO'], { env: { ...process.env, TEST_RUNNER_RAVENSIGHT_MOBILE_URL: url, RAVENSIGHT_MOBILE_URL: url } });
|
|
94
|
+
child.done.then(result => { if (!stopped) { const error = new Error(`The iOS input runner exited: ${result.diagnostic.slice(-500)}`); readyReject(error); invalidate(error); } });
|
|
95
|
+
}
|
|
96
|
+
let readyTimer;
|
|
97
|
+
const waitReady = Promise.race([ready, new Promise((_, reject) => { readyTimer = setTimeout(() => reject(new Error('The iOS input helper did not become ready. Check Xcode and Simulator permissions.')), timeout); })]);
|
|
98
|
+
// Tests get the loopback protocol without starting Xcode.
|
|
99
|
+
if (!launch) return { url, send, stop, ready: waitReady.finally(() => clearTimeout(readyTimer)), get dimensions() { return dimensions; } };
|
|
100
|
+
try { await waitReady; clearTimeout(readyTimer); return { send, stop, get dimensions() { return dimensions; } }; }
|
|
101
|
+
catch (error) { clearTimeout(readyTimer); await stop(); throw error; }
|
|
102
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { mkdir, readFile, writeFile, rm } from 'node:fs/promises';
|
|
2
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
|
|
6
|
+
// Machine-wide, including commands with different RAVENSIGHT_HOME values.
|
|
7
|
+
export async function lockDevice(device, { root = path.join(os.tmpdir(), 'ravensight-mobile-locks'), pid = process.pid } = {}) {
|
|
8
|
+
await mkdir(root, { recursive: true, mode: 0o700 });
|
|
9
|
+
const directory = path.join(root, createHash('sha256').update(device).digest('hex'));
|
|
10
|
+
const token = randomUUID();
|
|
11
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
12
|
+
try {
|
|
13
|
+
await mkdir(directory, { mode: 0o700 });
|
|
14
|
+
await writeFile(path.join(directory, 'owner.json'), JSON.stringify({ pid, token, device }), { mode: 0o600 });
|
|
15
|
+
return async () => {
|
|
16
|
+
const owner = await readFile(path.join(directory, 'owner.json'), 'utf8').then(JSON.parse).catch(() => null);
|
|
17
|
+
if (owner?.token === token) await rm(directory, { recursive: true, force: true });
|
|
18
|
+
};
|
|
19
|
+
} catch (error) {
|
|
20
|
+
if (error.code !== 'EEXIST') throw error;
|
|
21
|
+
const owner = await readFile(path.join(directory, 'owner.json'), 'utf8').then(JSON.parse).catch(() => null);
|
|
22
|
+
// An incompletely written lock might belong to a live creator. Never guess.
|
|
23
|
+
if (!owner || !Number.isInteger(owner.pid)) throw new Error(`Device ${device} has a lock with unknown ownership; inspect ${directory}.`);
|
|
24
|
+
let alive = true;
|
|
25
|
+
try { process.kill(owner.pid, 0); } catch (error) { alive = error.code !== 'ESRCH'; }
|
|
26
|
+
if (alive) throw new Error(`Device ${device} is already in use by process ${owner.pid}.`);
|
|
27
|
+
// Rename is not used: another contender could create a fresh lock before deletion.
|
|
28
|
+
// Leave stale locks for explicit recovery rather than risk deleting a new owner.
|
|
29
|
+
throw new Error(`Device ${device} has a stale lock from process ${owner.pid}; remove ${directory} after checking that process has stopped.`);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
}
|
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createAdb, quoteAndroidText } from './adb.js';
|
|
4
|
+
import { createSimctl } from './simctl.js';
|
|
5
|
+
import { startIosHelper } from './ios-helper.js';
|
|
6
|
+
import { lockDevice } from './lock.js';
|
|
7
|
+
import { mobileFrame, devicePoint } from './frame.js';
|
|
8
|
+
import { startMobileRecording } from './recording.js';
|
|
9
|
+
import { buildDigest } from './target.js';
|
|
10
|
+
import { sameScreen } from '../../pixels.js';
|
|
11
|
+
import { screenshotName, DriverError } from '../driver.js';
|
|
12
|
+
import { sleep } from './process.js';
|
|
13
|
+
|
|
14
|
+
const ANDROID_KEYS = { Back: '4', Escape: '4', Enter: '66', Backspace: '67', Tab: '61', Space: '62', ArrowUp: '19', ArrowDown: '20', ArrowLeft: '21', ArrowRight: '22' };
|
|
15
|
+
const ANDROID_INPUT_SETTLE_MS = 700;
|
|
16
|
+
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) } = {}) {
|
|
17
|
+
const android = name === 'android_driver';
|
|
18
|
+
let device, metadata, runDirectory, signal, unlock, helper, recording, crashTracker, frame, pendingFrame, startedAt, stopPromise, launched = false, launchAttempted = false, rotation = null, windowRotation = null, step = 0, shots = 0, gameEnded = null;
|
|
19
|
+
const metrics = { captures: 0, captureRetries: 0, captureReclaims: 0, captureMs: 0, orientationSettleMs: 0, actionSettleMs: 0, actions: 0, actionMs: 0 };
|
|
20
|
+
async function capture() {
|
|
21
|
+
const began = now();
|
|
22
|
+
let png;
|
|
23
|
+
try {
|
|
24
|
+
if (android) png = await adb.call(device.id, ['exec-out', 'screencap', '-p'], { binary: true, signal, timeout: 10000 });
|
|
25
|
+
else if (simctl.screenshot) {
|
|
26
|
+
const result = await simctl.screenshot(device.id, { signal, timeout: 10000 });
|
|
27
|
+
png = result.png;
|
|
28
|
+
if (result.processReapedEarly) metrics.captureReclaims++;
|
|
29
|
+
} else {
|
|
30
|
+
const file = path.join(runDirectory, '.native-frame.png');
|
|
31
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
32
|
+
await fs.rm(file, { force: true });
|
|
33
|
+
try { await simctl.call(['io', device.id, 'screenshot', '--type=png', file], { signal, timeout: 10000 }); break; }
|
|
34
|
+
catch (error) {
|
|
35
|
+
if (attempt || signal?.aborted || !/timed out/i.test(error.message)) throw error;
|
|
36
|
+
metrics.captureRetries++; await sleep(250, signal);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
png = await fs.readFile(file); await fs.rm(file, { force: true });
|
|
40
|
+
}
|
|
41
|
+
metrics.captures++; metrics.captureMs += now() - began;
|
|
42
|
+
return mobileFrame(png);
|
|
43
|
+
} catch (error) { throw new DriverError(`Native screenshot failed: ${error.message}`, { fatal: true }); }
|
|
44
|
+
}
|
|
45
|
+
async function stop({ reason = 'stopped' } = {}) {
|
|
46
|
+
if (stopPromise) return stopPromise;
|
|
47
|
+
stopPromise = (async () => {
|
|
48
|
+
let result = { videoPath: null };
|
|
49
|
+
try {
|
|
50
|
+
if (recording) result = await recording.stop(reason);
|
|
51
|
+
} finally {
|
|
52
|
+
try {
|
|
53
|
+
if (launchAttempted && device) {
|
|
54
|
+
if (android) await adb.call(device.id, ['shell', 'am', 'force-stop', metadata.packageId], { timeout: 10000 }).catch(() => {});
|
|
55
|
+
else await simctl.call(['terminate', device.id, metadata.bundleId], { timeout: 10000 }).catch(() => {});
|
|
56
|
+
}
|
|
57
|
+
if (android && rotation && device) {
|
|
58
|
+
for (const [key, value] of Object.entries(rotation)) if (/^[0-9]+$/.test(value)) await adb.call(device.id, ['shell', 'settings', 'put', 'system', key, value]).catch(() => {});
|
|
59
|
+
}
|
|
60
|
+
if (android && windowRotation && device) await adb.call(device.id, ['shell', 'wm', 'user-rotation', ...windowRotation.split(/\s+/)], { timeout: 10000 }).catch(() => {});
|
|
61
|
+
await helper?.stop();
|
|
62
|
+
} finally { await unlock?.(); }
|
|
63
|
+
}
|
|
64
|
+
return result;
|
|
65
|
+
})();
|
|
66
|
+
return stopPromise;
|
|
67
|
+
}
|
|
68
|
+
const driver = {
|
|
69
|
+
name, touch: true, frozenBetweenActions: false, inputProfile: 'native-mobile', exactScreenshots: true,
|
|
70
|
+
supportedActions: ['click', 'key', 'type', 'wait', 'swipe'], pointerTools: ['drag'],
|
|
71
|
+
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. Coordinates are in the displayed screenshot, including system bars. The game runs continuously while you think: timers do not pause. Tap only visible in-app controls. There is no hover, mouse wheel, pinch 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.`,
|
|
72
|
+
async launch({ target, runDir, recordVideo = false, signal: abort }) {
|
|
73
|
+
runDirectory = runDir; signal = abort; startedAt = now();
|
|
74
|
+
await fs.mkdir(path.join(runDir, 'screenshots'), { recursive: true });
|
|
75
|
+
const file = plan.build || target;
|
|
76
|
+
try {
|
|
77
|
+
if (plan.buildHash && await buildDigest(file) !== plan.buildHash) throw new Error('The native build changed since preflight or the saved job. Start a new job for the changed build.');
|
|
78
|
+
metadata = plan.metadata || await (android ? adb : simctl).inspect(file);
|
|
79
|
+
device = await (android ? adb : simctl).select(plan.resolvedDevice || plan.device, { boot: false, signal });
|
|
80
|
+
if (plan.resolvedDevice && device.id !== plan.resolvedDevice) throw new Error('The saved native device is unavailable. A resumed run cannot switch devices.');
|
|
81
|
+
unlock = await lock(`${android ? 'android' : 'ios'}:${device.id}`);
|
|
82
|
+
if (android) {
|
|
83
|
+
rotation = {};
|
|
84
|
+
for (const key of ['accelerometer_rotation', 'user_rotation']) rotation[key] = await adb.call(device.id, ['shell', 'settings', 'get', 'system', key]);
|
|
85
|
+
const prior = await adb.call(device.id, ['shell', 'wm', 'user-rotation']);
|
|
86
|
+
if (!/^(free|lock [0-3])$/.test(prior)) throw new Error('Android window rotation state is unavailable; orientation cannot be safely changed and restored.');
|
|
87
|
+
windowRotation = prior;
|
|
88
|
+
await adb.call(device.id, ['shell', 'settings', 'put', 'system', 'accelerometer_rotation', '0']);
|
|
89
|
+
await adb.call(device.id, ['shell', 'settings', 'put', 'system', 'user_rotation', plan.orientation === 'landscape' ? '1' : '0']);
|
|
90
|
+
await adb.call(device.id, ['install', '-r', file], { signal, timeout: 120000 });
|
|
91
|
+
launchAttempted = true;
|
|
92
|
+
const output = await adb.call(device.id, ['shell', 'am', 'start', '-W', '-S', '-n', `${metadata.packageId}/${metadata.activity}`], { signal, timeout: 30000 });
|
|
93
|
+
if (/Error:|Exception|Status:\s*(?!ok)\w+/i.test(output)) throw new Error(`Android could not launch the app: ${output.slice(0, 400)}`);
|
|
94
|
+
// Android may restore a per-app display rotation during am start.
|
|
95
|
+
await adb.call(device.id, ['shell', 'wm', 'user-rotation', 'lock', plan.orientation === 'landscape' ? '1' : '0'], { signal, timeout: 10000 });
|
|
96
|
+
launched = true;
|
|
97
|
+
} else {
|
|
98
|
+
await simctl.call(['install', device.id, file], { signal, timeout: 120000 });
|
|
99
|
+
helper = await startHelper({ device: device.id, signal });
|
|
100
|
+
await helper.send({ kind: 'orientation', orientation: plan.orientation || 'portrait' });
|
|
101
|
+
launchAttempted = true;
|
|
102
|
+
const launchStartedAt = Date.now();
|
|
103
|
+
const output = await simctl.call(['launch', '--terminate-running-process', device.id, metadata.bundleId], { signal, timeout: 30000 });
|
|
104
|
+
const prefix = `${metadata.bundleId}:`;
|
|
105
|
+
const pid = Number(String(output).split('\n').find(line => line.startsWith(prefix))?.slice(prefix.length).trim());
|
|
106
|
+
if (!Number.isSafeInteger(pid) || pid < 1) throw new Error('Simulator launch did not report the selected app PID; scoped crash diagnostics cannot be established.');
|
|
107
|
+
crashTracker = await createCrashTracker({ device: device.id, bundleId: metadata.bundleId, executable: path.basename(metadata.executable || ''), pid, launchStartedAt, launchCompletedAt: Date.now(), runDir });
|
|
108
|
+
await helper.send({ kind: 'launch', bundleId: metadata.bundleId, activate: true }, 30000);
|
|
109
|
+
launched = true;
|
|
110
|
+
}
|
|
111
|
+
frame = await capture();
|
|
112
|
+
const landscape = plan.orientation === 'landscape';
|
|
113
|
+
const rotationBegan = Date.now();
|
|
114
|
+
const rotationDeadline = rotationBegan + Math.max(0, Math.min(5000, orientationSettleMs));
|
|
115
|
+
while ((frame.width > frame.height) !== landscape && Date.now() < rotationDeadline) { await sleep(100, signal); frame = await capture(); }
|
|
116
|
+
metrics.orientationSettleMs += Date.now() - rotationBegan;
|
|
117
|
+
if ((frame.width > frame.height) !== landscape) throw new Error(`The app stayed in ${frame.width > frame.height ? 'landscape' : 'portrait'} after ${landscape ? 'landscape' : 'portrait'} was requested. This build may lock its orientation; use its supported orientation.`);
|
|
118
|
+
if (recordVideo) recording = await startRecording({ platform: android ? 'android' : 'ios', device: device.id, adb, simctl, runDir, width: frame.nativeWidth, height: frame.nativeHeight });
|
|
119
|
+
} catch (error) {
|
|
120
|
+
const crashed = crashTracker && !signal?.aborted ? await crashTracker.check({ exitObservedAt: Date.now() }).catch(() => null) : null;
|
|
121
|
+
if (crashed) gameEnded = crashed;
|
|
122
|
+
await stop({ reason: 'launch_failed' }).catch(() => {});
|
|
123
|
+
throw new DriverError(`${error.message}${crashed ? ` ${crashed.message}` : ''}`, { fatal: true });
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
async observe() {
|
|
127
|
+
frame = pendingFrame || await capture(); pendingFrame = null;
|
|
128
|
+
return { step: ++step, text: `Native ${android ? 'Android emulator' : 'iOS simulator'} screen, ${frame.width} by ${frame.height} pixels. Use x,y screenshot coordinates. The game is running in real time.`, screenshotBase64: frame.png.toString('base64'), screenshotMediaType: 'image/png', elapsedMs: now() - startedAt };
|
|
129
|
+
},
|
|
130
|
+
async act(action) {
|
|
131
|
+
const began = now(), before = frame;
|
|
132
|
+
let helperFailed = false;
|
|
133
|
+
const send = async request => { try { return await helper.send(request); } catch (error) { helperFailed = true; throw error; } };
|
|
134
|
+
try {
|
|
135
|
+
if (!frame || !device || !launched) throw new Error('The native game has not launched.');
|
|
136
|
+
if (action.button && action.button !== 'left') throw new Error('Touch has no right or middle mouse button.');
|
|
137
|
+
if (action.ref || action.replace || action.target && action.kind === 'type') throw new Error('This native driver cannot resolve element refs or replace a text field. Tap the field first.');
|
|
138
|
+
const point = value => devicePoint(value, frame, android ? undefined : helper.dimensions);
|
|
139
|
+
const ms = (value, fallback = 0) => { if (value === undefined) return fallback; if (!Number.isFinite(value) || value < 0 || value > 5000) throw new Error('Native input duration must be between 0 and 5000 milliseconds.'); return Math.round(value); };
|
|
140
|
+
if (action.kind === 'wait') await sleep(Math.min(5000, ms(action.ms)), signal);
|
|
141
|
+
else if (action.kind === 'click') {
|
|
142
|
+
const p = point(action.target);
|
|
143
|
+
if (android) {
|
|
144
|
+
const tap = () => action.holdMs ? adb.call(device.id, ['shell', 'input', 'swipe', p.x, p.y, p.x, p.y, ms(action.holdMs)], { signal }) : adb.call(device.id, ['shell', 'input', 'tap', p.x, p.y], { signal });
|
|
145
|
+
await tap(); if (action.double) { await sleep(80, signal); await tap(); }
|
|
146
|
+
} else await send({ kind: 'click', bundleId: metadata.bundleId, ...p, holdMs: ms(action.holdMs), double: Boolean(action.double) });
|
|
147
|
+
} else if (['drag', 'swipe'].includes(action.kind)) {
|
|
148
|
+
if (action.via?.length || action.holdMs || action.steps) throw new Error('This native driver supports straight drags without explicit steps, waypoints or a held pickup.');
|
|
149
|
+
const from = point(action.from), to = point(action.to);
|
|
150
|
+
if (android) await adb.call(device.id, ['shell', 'input', 'swipe', from.x, from.y, to.x, to.y, ms(action.durationMs, 500)], { signal });
|
|
151
|
+
else await send({ kind: 'drag', bundleId: metadata.bundleId, ...from, toX: to.x, toY: to.y, durationMs: ms(action.durationMs, 500) });
|
|
152
|
+
} else if (action.kind === 'key') {
|
|
153
|
+
if (action.holdMs || action.keys?.length) throw new Error('Native held keys and chords are unavailable.');
|
|
154
|
+
if (android) { if (!ANDROID_KEYS[action.key]) throw new Error('Android supports Back, Escape, Enter, Backspace, Tab, Space and arrow keys.'); await adb.call(device.id, ['shell', 'input', 'keyevent', ANDROID_KEYS[action.key]], { signal }); }
|
|
155
|
+
else { if (!['Enter', 'Backspace'].includes(action.key)) throw new Error('iOS keyboard input supports Enter and Backspace; use visible in-app navigation.'); await send({ kind: 'key', bundleId: metadata.bundleId, key: action.key }); }
|
|
156
|
+
} else if (action.kind === 'type') {
|
|
157
|
+
if (android) { await adb.call(device.id, ['shell', 'input', 'text', quoteAndroidText(action.text)], { signal }); if (action.submit) await adb.call(device.id, ['shell', 'input', 'keyevent', '66'], { signal }); }
|
|
158
|
+
else { const text = String(action.text || ''); if (!text || text.length > 2000) throw new Error('iOS text entry accepts 1 to 2000 characters.'); await send({ kind: 'type', bundleId: metadata.bundleId, text }); if (action.submit) await send({ kind: 'key', bundleId: metadata.bundleId, key: 'Enter' }); }
|
|
159
|
+
} else throw new Error(`This native driver cannot send ${action.kind}.`);
|
|
160
|
+
if (action.kind !== 'wait') {
|
|
161
|
+
const running = android ? Boolean(await adb.call(device.id, ['shell', 'pidof', metadata.packageId], { timeout: 5000 }).catch(error => { if (error.cause?.code === 1 && !error.cause?.killed) return ''; throw error; })) : (await send({ kind: 'status', bundleId: metadata.bundleId })).running;
|
|
162
|
+
// A missing process proves exit, not its cause. Without a scoped crash
|
|
163
|
+
// diagnostic, do not manufacture the loop's automatic crash finding.
|
|
164
|
+
if (running === false) { gameEnded = (crashTracker ? await crashTracker.check({ exitObservedAt: Date.now() }).catch(() => null) : null) || { kind: 'exited', message: 'The app process stopped during native play; its exit cause is unavailable.' }; throw new DriverError(gameEnded.message); }
|
|
165
|
+
if (android) {
|
|
166
|
+
// adb input returns before the app presents its response. A capture
|
|
167
|
+
// taken immediately can show the old screen or a blended transition
|
|
168
|
+
// even when PNG encoding finishes much later. Keep this bounded;
|
|
169
|
+
// live games and their timers continue throughout the interval.
|
|
170
|
+
const settlingAt = now();
|
|
171
|
+
try { await sleep(ANDROID_INPUT_SETTLE_MS, signal); }
|
|
172
|
+
finally { metrics.actionSettleMs += now() - settlingAt; }
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
// One capture, consumed by executeTool's immediate observe. Additional looks are fresh.
|
|
176
|
+
pendingFrame = await capture(); frame = pendingFrame;
|
|
177
|
+
metrics.actions++; metrics.actionMs += now() - began;
|
|
178
|
+
return { ok: true, changed: !sameScreen(before.png, frame.png) };
|
|
179
|
+
} catch (error) {
|
|
180
|
+
if (gameEnded) throw error;
|
|
181
|
+
if (helperFailed && crashTracker && !signal?.aborted) {
|
|
182
|
+
const crashed = await crashTracker.check({ exitObservedAt: Date.now() }).catch(() => null);
|
|
183
|
+
if (crashed) { gameEnded = crashed; throw new DriverError(crashed.message); }
|
|
184
|
+
}
|
|
185
|
+
return { ok: false, changed: false, driverError: true, error: error.message };
|
|
186
|
+
}
|
|
187
|
+
},
|
|
188
|
+
async screenshot(reason) {
|
|
189
|
+
const current = await capture();
|
|
190
|
+
const relativePath = path.posix.join('screenshots', screenshotName(++shots, reason)), file = path.join(runDirectory, relativePath);
|
|
191
|
+
await fs.writeFile(file, current.png, { mode: 0o600 }); return { path: file, relativePath, reason };
|
|
192
|
+
},
|
|
193
|
+
async screenProbe() {
|
|
194
|
+
// Scene and blank-screen checks follow observe. Inspect that same frame,
|
|
195
|
+
// rather than advancing a real-time game through redundant captures.
|
|
196
|
+
// observe, screenshot and an unqualified modelFrame are fresh looks.
|
|
197
|
+
if (!frame) throw new DriverError('The native game has not produced a screen.');
|
|
198
|
+
return frame.png;
|
|
199
|
+
},
|
|
200
|
+
async modelFrame({ screenshot } = {}) {
|
|
201
|
+
if (screenshot) {
|
|
202
|
+
const file = path.resolve(screenshot.path || '');
|
|
203
|
+
const root = path.resolve(runDirectory, 'screenshots');
|
|
204
|
+
if (!file.startsWith(`${root}${path.sep}`)) throw new Error('The requested native screenshot is outside this run.');
|
|
205
|
+
const [realFile, realRoot] = await Promise.all([fs.realpath(file), fs.realpath(root)]);
|
|
206
|
+
if (!realFile.startsWith(`${realRoot}${path.sep}`)) throw new Error('The requested native screenshot resolves outside this run.');
|
|
207
|
+
// Show the exact saved pixels. Capturing again can show another point
|
|
208
|
+
// in a transition and incorrectly mark the saved picture as seen.
|
|
209
|
+
return { data: (await fs.readFile(realFile)).toString('base64'), mediaType: 'image/png' };
|
|
210
|
+
}
|
|
211
|
+
return { data: (await capture()).png.toString('base64'), mediaType: 'image/png' };
|
|
212
|
+
},
|
|
213
|
+
recordingStartedAt() { return recording?.startedAt || null; },
|
|
214
|
+
playMetrics() { return { native: { ...metrics, device: device?.id, realtime: true } }; },
|
|
215
|
+
async consoleErrors() { return []; },
|
|
216
|
+
gameEnded() { return gameEnded; },
|
|
217
|
+
capabilityNotes() { return [
|
|
218
|
+
{ input: 'native scope', reason: 'Only this emulator or simulator and this build were played. Physical hardware, performance, sensors, push notifications, purchases and audio were not tested.' },
|
|
219
|
+
{ input: 'native input', reason: 'Tap, long press, straight drag and basic text entry are available. Pinch, waypoint drags, held keys and process freezing are not available.' },
|
|
220
|
+
{ input: 'native telemetry', reason: 'This driver does not inject the Ravensight synthetic identity into the app. Use a test build with analytics disabled or an explicitly configured synthetic session.' },
|
|
221
|
+
{ input: 'native diagnostics', reason: 'An iOS crash is attributed only when a fatal report matches this simulator, app, PID and launch interval. Only a sanitized summary is retained. Missing or mismatched reports, including Android exits without scoped diagnostics, have an unknown exit cause.' },
|
|
222
|
+
{ input: 'replay', reason: 'Native input replay is not available; findings are checked against their recorded screenshots.' }
|
|
223
|
+
]; },
|
|
224
|
+
stop
|
|
225
|
+
};
|
|
226
|
+
return driver;
|
|
227
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { createAdb } from './adb.js';
|
|
5
|
+
import { createSimctl } from './simctl.js';
|
|
6
|
+
import { createMobileDriver } from './native.js';
|
|
7
|
+
import { buildDigest } from './target.js';
|
|
8
|
+
import { helperBuilt } from './ios-helper.js';
|
|
9
|
+
import { lockDevice } from './lock.js';
|
|
10
|
+
import { probe, sdkTool, sdkRoot } from './process.js';
|
|
11
|
+
|
|
12
|
+
export async function nativeChecks(plan, { adb = createAdb(), simctl = createSimctl(), checkProbe = probe, smoke = false, boot = false, signal, driverFactory = createMobileDriver, helperReady = helperBuilt, reserve = false, lock = lockDevice, recordVideo = true, sdkFolderExists = async () => fs.access(sdkRoot()).then(() => true, () => false) } = {}) {
|
|
13
|
+
const rows = [], android = plan.driver === 'android_driver', tool = android ? adb : simctl;
|
|
14
|
+
const add = (name, status, detail, fix = null) => rows.push({ name, status, detail, fix });
|
|
15
|
+
const prepared = { ...plan };
|
|
16
|
+
let lease = null;
|
|
17
|
+
try {
|
|
18
|
+
if (!plan.build) throw new Error(`Pass --native-build with ${android ? 'an Android APK' : 'an iOS simulator APP'}.`);
|
|
19
|
+
if (!['portrait', 'landscape'].includes(plan.orientation)) throw new Error('Native orientation must be portrait or landscape.');
|
|
20
|
+
prepared.metadata = await tool.inspect(plan.build);
|
|
21
|
+
const override = android ? plan.package : plan.bundleId;
|
|
22
|
+
if (override && override !== (prepared.metadata.packageId || prepared.metadata.bundleId)) throw new Error('The package or bundle override does not match the selected build.');
|
|
23
|
+
prepared.buildHash = await buildDigest(plan.build);
|
|
24
|
+
add('native build', 'pass', `${prepared.metadata.packageId || prepared.metadata.bundleId}; ${prepared.metadata.abi.join(', ') || 'no native libraries'}`);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
add('native build', 'fail', error.message, android
|
|
27
|
+
? 'Pass --native-build with an APK built for the emulator. Reading it needs the Android SDK build-tools (or RAVENSIGHT_AAPT).'
|
|
28
|
+
: 'Pass --native-build with an iOS Simulator .app (not an .ipa). Reading it needs Xcode and its command line tools.');
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
if (!plan.resolvedDevice && !plan.device) throw new Error('Pass --device explicitly or set native.device in the project configuration.');
|
|
32
|
+
const device = await tool.select(plan.resolvedDevice || plan.device, { boot, signal });
|
|
33
|
+
prepared.resolvedDevice = device.id;
|
|
34
|
+
const abi = await tool.abi(device.id);
|
|
35
|
+
if (prepared.metadata?.abi?.length && !prepared.metadata.abi.some(a => abi.includes(a))) throw new Error(`Build ABI ${prepared.metadata.abi.join(', ')} does not match device ABI ${abi.join(', ')}.`);
|
|
36
|
+
add('native device', 'pass', `${device.id}: ${device.name}; ${abi.join(', ')}`);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
add('native device', 'fail', error.message, `Run ravensight-playtest device list, start one with device boot <name> --platform ${android ? 'android' : 'ios'}, then pass its exact id with --device.`);
|
|
39
|
+
}
|
|
40
|
+
if (android) {
|
|
41
|
+
const sdkFound = await sdkFolderExists();
|
|
42
|
+
add('Android SDK', sdkFound ? 'pass' : 'warn', sdkFound ? sdkRoot() : `${sdkRoot()} does not exist`,
|
|
43
|
+
sdkFound ? null : 'Install the Android SDK command line tools and set ANDROID_HOME to its folder, then run ravensight-playtest device setup android.');
|
|
44
|
+
const emulator = await checkProbe(await sdkTool('emulator'), ['-accel-check']);
|
|
45
|
+
add('emulator acceleration', emulator.ok ? 'pass' : 'warn', emulator.detail, emulator.ok ? null : 'Install the emulator with ravensight-playtest device setup android, and turn on hardware acceleration for it.');
|
|
46
|
+
} else {
|
|
47
|
+
const built = await helperReady();
|
|
48
|
+
add('iOS input helper', built ? 'pass' : 'fail', built ? 'The XCTest simulator helper is built.' : 'The XCTest simulator helper has not been built.', built ? null : 'ravensight-playtest device setup ios');
|
|
49
|
+
}
|
|
50
|
+
for (const name of recordVideo ? ['ffmpeg', 'ffprobe'] : []) {
|
|
51
|
+
const found = await checkProbe(process.env[`RAVENSIGHT_${name.toUpperCase()}`] || name, ['-version']);
|
|
52
|
+
add(name, found.ok ? 'pass' : 'fail', found.detail, found.ok ? null : `Install ${name} for native video, or use --no-record-video. Screenshots do not need it.`);
|
|
53
|
+
}
|
|
54
|
+
if (reserve && !rows.some(row => row.status === 'fail')) {
|
|
55
|
+
try {
|
|
56
|
+
const key = `${android ? 'android' : 'ios'}:${prepared.resolvedDevice}`;
|
|
57
|
+
const release = await lock(key);
|
|
58
|
+
lease = { release, lock: async requested => { if (requested !== key) throw new Error('The native device does not match the reserved device.'); return async () => {}; } };
|
|
59
|
+
add('native device lease', 'pass', 'Reserved the selected device until this job finishes.');
|
|
60
|
+
} catch (error) { add('native device lease', 'fail', error.message); }
|
|
61
|
+
}
|
|
62
|
+
if (smoke && !rows.some(row => row.status === 'fail')) {
|
|
63
|
+
let directory, driver;
|
|
64
|
+
try {
|
|
65
|
+
directory = await fs.mkdtemp(path.join(os.tmpdir(), 'ravensight-native-preflight-'));
|
|
66
|
+
driver = driverFactory({ name: plan.driver, native: prepared, adb, simctl, ...(lease ? { lock: lease.lock } : {}) });
|
|
67
|
+
await driver.launch({ target: plan.build, runDir: directory, recordVideo: false, signal });
|
|
68
|
+
const observation = await driver.observe();
|
|
69
|
+
if (!observation.screenshotBase64) throw new Error('The native app returned no screenshot.');
|
|
70
|
+
add('native launch', 'pass', 'Installed and launched the app, received its screen and checked the local input connection. No job or model call was made.');
|
|
71
|
+
} catch (error) { add('native launch', 'fail', error.message); }
|
|
72
|
+
finally {
|
|
73
|
+
if (driver) await driver.stop({ reason: 'preflight' }).catch(error => add('native cleanup', 'fail', error.message));
|
|
74
|
+
if (directory) await fs.rm(directory, { recursive: true, force: true }).catch(error => add('native cleanup', 'fail', error.message));
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
const ok = !rows.some(row => row.status === 'fail');
|
|
78
|
+
if (!ok && lease) { await lease.release(); lease = null; }
|
|
79
|
+
return { rows, plan: prepared, ok, ...(lease ? { lease } : {}) };
|
|
80
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { promisify } from 'node:util';
|
|
3
|
+
import { access } from 'node:fs/promises';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
|
|
7
|
+
const execute = promisify(execFile);
|
|
8
|
+
export async function command(file, args, { timeout = 30000, signal, binary = false, maxBuffer = 16 * 1024 * 1024, ...options } = {}) {
|
|
9
|
+
try {
|
|
10
|
+
const answer = await execute(file, args.map(String), { timeout, signal, maxBuffer, windowsHide: true, encoding: binary ? 'buffer' : 'utf8', ...options });
|
|
11
|
+
return binary ? answer.stdout : String(answer.stdout || '').trim();
|
|
12
|
+
} catch (error) {
|
|
13
|
+
const detail = String(error.stderr || error.message || '').trim().split('\n').slice(0, 3).join(' ').slice(0, 500);
|
|
14
|
+
throw new Error(`${path.basename(file)} ${error.code === 'ENOENT' ? 'was not found' : error.killed ? 'timed out' : signal?.aborted ? 'was cancelled' : 'failed'}${detail ? `: ${detail}` : ''}`, { cause: error });
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
export async function probe(file, args = ['--version']) {
|
|
18
|
+
try { return { ok: true, detail: (await command(file, args, { timeout: 10000 })).split('\n')[0] }; }
|
|
19
|
+
catch (error) { return { ok: false, detail: error.message }; }
|
|
20
|
+
}
|
|
21
|
+
export function sdkRoot(env = process.env) {
|
|
22
|
+
return env.ANDROID_HOME || env.ANDROID_SDK_ROOT || (process.platform === 'darwin' ? path.join(os.homedir(), 'Library/Android/sdk') : path.join(os.homedir(), 'Android/Sdk'));
|
|
23
|
+
}
|
|
24
|
+
export async function sdkTool(name, env = process.env) {
|
|
25
|
+
const explicit = env[`RAVENSIGHT_${name.toUpperCase()}`];
|
|
26
|
+
if (explicit) return explicit;
|
|
27
|
+
const bin = process.platform === 'win32' ? `${name}${['sdkmanager', 'avdmanager'].includes(name) ? '.bat' : '.exe'}` : name;
|
|
28
|
+
const sub = name === 'adb' ? 'platform-tools' : name === 'emulator' ? 'emulator' : 'cmdline-tools/latest/bin';
|
|
29
|
+
const full = path.join(sdkRoot(env), sub, bin);
|
|
30
|
+
try { await access(full); return full; } catch { return bin; }
|
|
31
|
+
}
|
|
32
|
+
export function startProcess(file, args, options = {}) {
|
|
33
|
+
const child = spawn(file, args, { stdio: ['ignore', 'ignore', 'pipe'], windowsHide: true, ...options });
|
|
34
|
+
let diagnostic = '';
|
|
35
|
+
child.stderr?.on('data', data => { diagnostic = (diagnostic + data.toString()).slice(-4000); });
|
|
36
|
+
child.on('error', error => { diagnostic = error.message; });
|
|
37
|
+
const done = new Promise(resolve => { child.once('close', (code, signal) => resolve({ code, signal, diagnostic })); });
|
|
38
|
+
return { child, done, diagnostic: () => diagnostic };
|
|
39
|
+
}
|
|
40
|
+
export async function stopProcess(process, signal = 'SIGINT', timeout = 10000) {
|
|
41
|
+
if (!process) return null;
|
|
42
|
+
if (process.child.exitCode === null && !process.child.killed) process.child.kill(signal);
|
|
43
|
+
let timer;
|
|
44
|
+
const result = await Promise.race([process.done, new Promise(resolve => { timer = setTimeout(() => resolve(null), timeout); })]);
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
if (result) return result;
|
|
47
|
+
process.child.kill('SIGKILL');
|
|
48
|
+
let finalTimer;
|
|
49
|
+
try { return await Promise.race([process.done, new Promise((_, reject) => { finalTimer = setTimeout(() => reject(new Error('The native subprocess did not close after SIGKILL.')), 1000); })]); }
|
|
50
|
+
finally { clearTimeout(finalTimer); }
|
|
51
|
+
}
|
|
52
|
+
export const sleep = (ms, signal) => new Promise((resolve, reject) => {
|
|
53
|
+
if (signal?.aborted) { reject(new Error('Device operation cancelled.')); return; }
|
|
54
|
+
const onAbort = () => { clearTimeout(timer); reject(new Error('Device operation cancelled.')); };
|
|
55
|
+
const timer = setTimeout(() => { signal?.removeEventListener('abort', onAbort); resolve(); }, ms);
|
|
56
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
57
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { command, startProcess, stopProcess } from './process.js';
|
|
5
|
+
import { recordingDirectory, recordingMetadata, saveRecording, probeVideo, RECORDING_LIMITS } from '../recording.js';
|
|
6
|
+
|
|
7
|
+
// Native recordings are continuous. Android uses the emulator console recorder,
|
|
8
|
+
// which was proved past adb screenrecord's historical 180 second boundary.
|
|
9
|
+
// Original captures stay local, separate from the bounded, audio-free upload file.
|
|
10
|
+
export async function startMobileRecording({ platform, device, adb, simctl, runDir, width, height, run = command, inspect = probeVideo, start = startProcess, finish = stopProcess, now = Date.now }) {
|
|
11
|
+
const directory = await recordingDirectory(runDir);
|
|
12
|
+
const captureDirectory = await fs.mkdtemp(path.join(os.tmpdir(), 'ravensight-mobile-video-'));
|
|
13
|
+
const capture = path.join(captureDirectory, platform === 'android' ? 'original.webm' : 'original.mp4');
|
|
14
|
+
const began = now();
|
|
15
|
+
let captureProcess = null, stopped = null, captureStop = null, limited = false;
|
|
16
|
+
const scale = Math.min(1, 1280 / Math.max(width, height), 720 / Math.min(width, height));
|
|
17
|
+
const w = Math.max(2, Math.floor(width * scale / 2) * 2), h = Math.max(2, Math.floor(height * scale / 2) * 2);
|
|
18
|
+
try {
|
|
19
|
+
if (platform === 'android') {
|
|
20
|
+
const answer = await adb.call(device, ['emu', 'screenrecord', 'start', '--size', `${w}x${h}`, '--time-limit', '900', '--fps', '10', capture], { timeout: 10000 });
|
|
21
|
+
if (/\bKO\b|error/i.test(answer)) throw new Error(`Emulator video capture is unavailable: ${answer}`);
|
|
22
|
+
} else captureProcess = start(simctl.binary, ['simctl', 'io', device, 'recordVideo', '--codec=h264', '--force', capture]);
|
|
23
|
+
} catch (error) {
|
|
24
|
+
await fs.rm(captureDirectory, { recursive: true, force: true }); await fs.rm(directory, { recursive: true, force: true }); throw error;
|
|
25
|
+
}
|
|
26
|
+
function stopCapture() {
|
|
27
|
+
if (!captureStop) captureStop = (async () => {
|
|
28
|
+
if (platform === 'android') {
|
|
29
|
+
const result = await adb.call(device, ['emu', 'screenrecord', 'stop'], { timeout: 15000 });
|
|
30
|
+
if (/\bKO\b|error/i.test(result)) throw new Error(`Emulator capture did not stop: ${result}`);
|
|
31
|
+
} else {
|
|
32
|
+
const result = await finish(captureProcess, 'SIGINT', 15000);
|
|
33
|
+
if (result?.code !== 0 && result?.signal !== 'SIGINT') throw new Error(`Simulator recording failed: ${result?.diagnostic || result?.signal || result?.code}`);
|
|
34
|
+
}
|
|
35
|
+
})();
|
|
36
|
+
return captureStop;
|
|
37
|
+
}
|
|
38
|
+
const ceiling = setTimeout(() => { limited = true; void stopCapture().catch(() => {}); }, RECORDING_LIMITS.durationMs);
|
|
39
|
+
ceiling.unref?.();
|
|
40
|
+
return {
|
|
41
|
+
startedAt: began,
|
|
42
|
+
stop(reason = 'stopped') {
|
|
43
|
+
if (stopped) return stopped;
|
|
44
|
+
stopped = (async () => {
|
|
45
|
+
const requestedEnd = now();
|
|
46
|
+
clearTimeout(ceiling);
|
|
47
|
+
const captureError = await stopCapture().then(() => null, error => error);
|
|
48
|
+
const ended = now();
|
|
49
|
+
let metadata = recordingMetadata({ driver: `${platform === 'android' ? 'android' : 'ios'}_driver`, startedAt: began, endedAt: ended, reason, capture: platform === 'android' ? 'emulator-console' : 'simctl', requestedDurationMs: Math.max(0, requestedEnd - began), gaps: [], originals: [] });
|
|
50
|
+
let videoPath = null;
|
|
51
|
+
try {
|
|
52
|
+
const original = path.join(directory, path.basename(capture));
|
|
53
|
+
await fs.copyFile(capture, original);
|
|
54
|
+
metadata.originals = [{ relativePath: path.relative(runDir, original).split(path.sep).join('/'), startedAt: new Date(began).toISOString(), endedAt: null, durationMs: null, audio: null, bytes: (await fs.stat(original)).size }];
|
|
55
|
+
const raw = JSON.parse(await run(process.env.RAVENSIGHT_FFPROBE || 'ffprobe', ['-v', 'error', '-show_entries', 'stream=codec_type:format=duration', '-of', 'json', original], { timeout: 10000 }));
|
|
56
|
+
const durationMs = Math.round(Number(raw.format?.duration) * 1000);
|
|
57
|
+
if (!Number.isFinite(durationMs) || durationMs <= 0 || !raw.streams?.some(s => s.codec_type === 'video')) throw new Error('Native capture has no playable video timeline.');
|
|
58
|
+
metadata.originals = [{ relativePath: path.relative(runDir, original).split(path.sep).join('/'), startedAt: new Date(began).toISOString(), endedAt: new Date(began + durationMs).toISOString(), durationMs, audio: raw.streams.some(s => s.codec_type === 'audio'), bytes: (await fs.stat(original)).size }];
|
|
59
|
+
if (captureError) throw captureError;
|
|
60
|
+
videoPath = path.join(runDir, 'session.mp4');
|
|
61
|
+
// Simulator H264 can repeat a presentation timestamp. FFmpeg's default
|
|
62
|
+
// best-effort selection then falls back to earlier decode timestamps.
|
|
63
|
+
// Prefer the original presentation timestamps; never add a time offset.
|
|
64
|
+
const inputTiming = platform === 'ios' ? ['-fflags', '+igndts'] : [];
|
|
65
|
+
// Normalize VFR to 10 fps within the measured original timeline.
|
|
66
|
+
const frames = Math.max(1, Math.round(Math.min(durationMs, RECORDING_LIMITS.durationMs) / 100));
|
|
67
|
+
await run(process.env.RAVENSIGHT_FFMPEG || 'ffmpeg', ['-v', 'error', '-nostdin', ...inputTiming, '-i', original, '-an', '-vf', `scale=${w}:${h}:force_original_aspect_ratio=decrease:force_divisible_by=2,fps=10`, '-c:v', 'libx264', '-preset', 'fast', '-crf', '25', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', '-t', '900', '-frames:v', String(frames), '-fs', String(RECORDING_LIMITS.videoBytes), '-n', videoPath], { timeout: 60000 });
|
|
68
|
+
const inspected = await inspect(videoPath);
|
|
69
|
+
if (!inspected.durationMs) throw new Error('ffprobe is required to verify native recording duration.');
|
|
70
|
+
const missingMs = Math.max(0, requestedEnd - began - durationMs);
|
|
71
|
+
const truncated = limited || inspected.durationMs + 1500 < durationMs || missingMs > 3000;
|
|
72
|
+
metadata = { ...metadata, ...inspected, status: truncated ? 'partial' : 'complete', relativePath: 'session.mp4', audio: false,
|
|
73
|
+
...(missingMs > 3000 ? { gaps: [{ position: 'unknown', durationMs: missingMs, detail: 'The recorded timeline is shorter than the requested capture interval; the missing interval cannot be placed precisely.' }] } : {}),
|
|
74
|
+
...(truncated ? { detail: 'The video does not cover the full requested capture interval; the original capture is retained locally.' } : {}) };
|
|
75
|
+
} catch (error) {
|
|
76
|
+
metadata = { ...metadata, status: 'failed', detail: error.message };
|
|
77
|
+
if (videoPath) await fs.rm(videoPath, { force: true }); videoPath = null;
|
|
78
|
+
// Even an invalid capture stays local for diagnosis.
|
|
79
|
+
await fs.copyFile(capture, path.join(directory, path.basename(capture))).catch(() => {});
|
|
80
|
+
}
|
|
81
|
+
await saveRecording(runDir, metadata);
|
|
82
|
+
await fs.rm(captureDirectory, { recursive: true, force: true });
|
|
83
|
+
return { videoPath, recording: metadata };
|
|
84
|
+
})();
|
|
85
|
+
return stopped;
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
}
|