Skip to content

Commit 4086f9b

Browse files
committed
refactor: model recording backends
1 parent 8c2b1ad commit 4086f9b

4 files changed

Lines changed: 476 additions & 298 deletions

File tree

‎CONTEXT.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
- Target: selected automation destination, such as mobile, tv, or desktop.
1515
- Modality: broad supported device family, such as mobile, tv, or desktop.
1616
- Session: daemon-owned state for a selected target and opened app or surface.
17+
- Recording backend: daemon-internal module interface selected per recording target that owns platform recording validation, output path policy, start/stop execution, and record-only cleanup below the daemon recording lifecycle.
1718
- Command surface: catalog of public command identity, interface exposure, adapter policy, and shared command metadata across CLI, Node.js, MCP, and batch entrypoints.
1819
- Daemon command registry: daemon-side source of truth for command route ownership and request-policy traits, including admission exemptions, session locking, selector validation, replay-scoped actions, recording invalidation, Android dialog guards, and request provider device resolution.
1920
- Runner command traits: per-command-type classification for iOS/macOS runner lifecycle behavior, distinct from the public command surface and daemon command registry. The Swift runner traits classify interaction, read-only, and runner-lifecycle axes for XCTest execution; Swift resolves the alert command as read-only only for its `get` action. The TypeScript runner command traits classify daemon-side runner send/recovery policy such as read-only retry routing, readiness probes, and recent-healthy-mutation preflight skips; the TypeScript table is command-type keyed and currently classifies alert as read-only for daemon retry policy. Each side keeps one source of truth keyed by runner command type.
Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
import fs from 'node:fs';
2+
import { withDiagnosticTimer } from '../../utils/diagnostics.ts';
3+
import { sleep } from '../../utils/timeouts.ts';
4+
import type { DaemonRequest, DaemonResponse, SessionState } from '../types.ts';
5+
import {
6+
buildRecordStopFailure,
7+
formatRecordTraceError,
8+
formatRecordTraceExecFailure,
9+
} from '../record-trace-errors.ts';
10+
import { finalizeRecordingOverlay } from './record-trace-finalize.ts';
11+
import {
12+
getIosRunnerOptions,
13+
normalizeAppBundleId,
14+
warmIosSimulatorRunner,
15+
} from './record-trace-ios.ts';
16+
import {
17+
IOS_SIMULATOR_RECORDING_STOP_TIMEOUT_MS,
18+
stopIosSimulatorRecordingProcess,
19+
} from './record-trace-ios-simulator.ts';
20+
import type { RecordTraceDeps, RecordingBase } from './record-trace-types.ts';
21+
import { errorResponse } from './response.ts';
22+
23+
const LOCAL_RECORDING_READY_POLL_MS = 250;
24+
const LOCAL_RECORDING_READY_SETTLE_POLLS = 2;
25+
const IOS_SIMULATOR_VIDEO_READY_POLL_MS = 150;
26+
const IOS_SIMULATOR_VIDEO_READY_ATTEMPTS = 12;
27+
28+
type ActiveRecording = NonNullable<SessionState['recording']>;
29+
type IosSimulatorRecording = Extract<ActiveRecording, { platform: 'ios' }>;
30+
31+
export async function startIosSimulatorRecording(params: {
32+
req: DaemonRequest;
33+
activeSession: SessionState;
34+
device: SessionState['device'];
35+
logPath?: string;
36+
deps: RecordTraceDeps;
37+
recordingBase: RecordingBase;
38+
resolvedOut: string;
39+
}): Promise<DaemonResponse | ActiveRecording> {
40+
const { req, activeSession, device, logPath, deps, recordingBase, resolvedOut } = params;
41+
42+
// The warm-up carries the gesture-clock anchor on its snapshot response when the runner
43+
// stamps it, letting us skip a standalone uptime command. The anchor is a pure clock pair
44+
// (origin uptime + daemon receipt time), so capturing it before the recorder spawn/settle
45+
// window is equivalent to capturing it after: recordingStartedAt stays readyAt below.
46+
const warmAnchor = recordingBase.showTouches
47+
? await warmIosSimulatorRunner({ req, activeSession, device, logPath, deps })
48+
: undefined;
49+
const { child, wait } = deps.startIosSimulatorRecording({ device, outPath: resolvedOut });
50+
const readyAt = await waitForLocalRecordingSettleWindow(resolvedOut);
51+
let gestureClockOriginAtMs: number | undefined;
52+
let gestureClockOriginUptimeMs: number | undefined;
53+
if (warmAnchor) {
54+
gestureClockOriginAtMs = warmAnchor.gestureClockOriginAtMs;
55+
gestureClockOriginUptimeMs = warmAnchor.gestureClockOriginUptimeMs;
56+
} else if (recordingBase.showTouches) {
57+
// Fallback for older runner builds (or a failed/unavailable warm anchor): issue a
58+
// standalone uptime command and pair it at the request midpoint.
59+
try {
60+
const uptimeRequestStartedAtMs = Date.now();
61+
const uptimeResult = await deps.runIosRunnerCommand(
62+
device,
63+
{
64+
command: 'uptime',
65+
appBundleId: normalizeAppBundleId(activeSession),
66+
},
67+
getIosRunnerOptions(req, logPath, activeSession),
68+
);
69+
const uptimeRequestFinishedAtMs = Date.now();
70+
gestureClockOriginAtMs = Math.round(
71+
(uptimeRequestStartedAtMs + uptimeRequestFinishedAtMs) / 2,
72+
);
73+
gestureClockOriginUptimeMs =
74+
typeof uptimeResult.currentUptimeMs === 'number' ? uptimeResult.currentUptimeMs : undefined;
75+
} catch {
76+
// Best effort only; wall-clock fallback remains available.
77+
}
78+
}
79+
return {
80+
platform: 'ios',
81+
child,
82+
wait,
83+
...recordingBase,
84+
recorderPid: child.pid,
85+
startedAt: readyAt,
86+
gestureClockOriginAtMs:
87+
gestureClockOriginUptimeMs === undefined ? undefined : gestureClockOriginAtMs,
88+
gestureClockOriginUptimeMs,
89+
};
90+
}
91+
92+
export async function stopIosSimulatorRecording(params: {
93+
deps: RecordTraceDeps;
94+
recording: IosSimulatorRecording;
95+
stopRequestedAt: number;
96+
}): Promise<DaemonResponse | null> {
97+
const { deps, recording, stopRequestedAt } = params;
98+
99+
await withDiagnosticTimer('record_stop_tail_settle', () => deps.waitForRecordingTail(recording), {
100+
platform: recording.platform,
101+
gestureEventCount: recording.gestureEvents.length,
102+
});
103+
const stopResult = await withDiagnosticTimer(
104+
'record_stop_ios_simulator_process',
105+
() => stopIosSimulatorRecordingProcess({ deps, recording }),
106+
{
107+
outPath: recording.outPath,
108+
},
109+
);
110+
if (!stopResult) {
111+
return buildIosSimulatorRecordingStopFailure(
112+
`failed to stop recording: simctl recordVideo did not exit after ${IOS_SIMULATOR_RECORDING_STOP_TIMEOUT_MS}ms and forced cleanup`,
113+
recording,
114+
stopRequestedAt,
115+
);
116+
}
117+
if (stopResult.exitCode !== 0) {
118+
return buildIosSimulatorRecordingStopFailure(
119+
`failed to stop recording: ${formatRecordTraceExecFailure(stopResult, 'simctl recordVideo')}`,
120+
recording,
121+
stopRequestedAt,
122+
);
123+
}
124+
125+
await withDiagnosticTimer(
126+
'record_stop_video_stable',
127+
() =>
128+
deps.waitForStableFile(recording.outPath, {
129+
pollMs: IOS_SIMULATOR_VIDEO_READY_POLL_MS,
130+
attempts: IOS_SIMULATOR_VIDEO_READY_ATTEMPTS,
131+
}),
132+
{
133+
outPath: recording.outPath,
134+
},
135+
);
136+
const playable = await withDiagnosticTimer(
137+
'record_stop_video_playable_check',
138+
() => deps.isPlayableVideo(recording.outPath),
139+
{
140+
outPath: recording.outPath,
141+
},
142+
);
143+
if (!playable) {
144+
return buildIosSimulatorRecordingStopFailure(
145+
`failed to stop recording: ${recording.outPath} was not finalized into a playable video`,
146+
recording,
147+
stopRequestedAt,
148+
);
149+
}
150+
151+
if (recording.maxSize !== undefined) {
152+
try {
153+
await withDiagnosticTimer(
154+
'record_stop_resize',
155+
() =>
156+
deps.resizeRecording({
157+
videoPath: recording.outPath,
158+
maxSize: recording.maxSize!,
159+
exportQuality: recording.exportQuality,
160+
targetLabel: 'iOS recording',
161+
}),
162+
{
163+
outPath: recording.outPath,
164+
maxSize: recording.maxSize,
165+
},
166+
);
167+
} catch (error) {
168+
recording.overlayWarning = `failed to resize recording: ${formatRecordTraceError(error)}`;
169+
}
170+
}
171+
172+
await withDiagnosticTimer(
173+
'record_stop_finalize_overlay',
174+
() =>
175+
finalizeRecordingOverlay({
176+
recording,
177+
deps,
178+
targetLabel: 'iOS recording',
179+
}),
180+
{
181+
outPath: recording.outPath,
182+
showTouches: recording.showTouches,
183+
gestureEventCount: recording.gestureEvents.length,
184+
},
185+
);
186+
187+
return null;
188+
}
189+
190+
async function waitForLocalRecordingSettleWindow(outPath: string): Promise<number> {
191+
// simctl recordVideo can take a beat to open its output even though recording has already
192+
// started. This is a short settle window, not a strict readiness guarantee. We prefer a
193+
// close recorder anchor over blocking start indefinitely waiting for non-zero bytes.
194+
for (let attempt = 0; attempt < LOCAL_RECORDING_READY_SETTLE_POLLS; attempt += 1) {
195+
try {
196+
const stat = fs.statSync(outPath);
197+
if (stat.size > 0) {
198+
return Date.now();
199+
}
200+
} catch {
201+
// Wait for the recorder to create the output file.
202+
}
203+
204+
if (attempt + 1 >= LOCAL_RECORDING_READY_SETTLE_POLLS) {
205+
return Date.now();
206+
}
207+
208+
await sleep(LOCAL_RECORDING_READY_POLL_MS);
209+
}
210+
211+
return Date.now();
212+
}
213+
214+
function buildIosSimulatorRecordingStopFailure(
215+
message: string,
216+
recording: IosSimulatorRecording,
217+
stopRequestedAt: number,
218+
): DaemonResponse {
219+
const failure = buildRecordStopFailure(message, recording, stopRequestedAt);
220+
removeInvalidRecordingOutput(recording.outPath);
221+
return errorResponse('COMMAND_FAILED', failure.message);
222+
}
223+
224+
function removeInvalidRecordingOutput(outPath: string): void {
225+
try {
226+
fs.rmSync(outPath, { force: true });
227+
} catch {
228+
// Best effort: the error response still reports the failed finalization.
229+
}
230+
}

0 commit comments

Comments
 (0)