Repository navigation
Expand file tree
/
Copy pathrecord-runtime.ts
More file actions
329 lines (315 loc) · 11.5 KB
/
Copy pathrecord-runtime.ts
File metadata and controls
329 lines (315 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
import path from 'node:path';
import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host';
import type {
ScreenRecordingCompletion,
ScreenRecordingStartInput,
} from '@agent-device/contracts/screen-recording-runtime';
import { bindSessionScreenRecording } from '../session-capture-binding.ts';
import {
resolveScreenRecordingRuntimePlan,
screenRecordingAdmissionUse,
screenRecordingRecoveryUse,
screenRecordingStartUse,
} from '@agent-device/contracts/screen-recording-runtime-plan';
import { isWholeScreenRecordingScope } from '@agent-device/contracts/recording';
import { AppError, normalizeError } from '@agent-device/kernel/errors';
import { resolveTargetDevice } from '@agent-device/device-selection/dispatch-resolve';
import { ensureBoundDeviceReady } from '../request-runtime-binding.ts';
import { type ScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger';
import { createScreenRecordingRecoveryControl } from '@agent-device/capture-kit/screen-recording-recovery';
import {
adoptStartedScreenRecording,
finishLiveScreenRecording,
finishRecoveredScreenRecording,
screenRecordingDurableResource,
} from '@agent-device/capture-kit/screen-recording-session-resource';
import {
resolveScreenRecordingStopRecovery,
screenRecordingManifestIsTerminal,
} from '@agent-device/capture-kit/screen-recording-stop-recovery';
import { resolveSessionScope } from '../session-routing.ts';
import type { SessionStore } from '../session-store.ts';
import type { BindDeviceRuntime, BindExactDeviceRuntime } from '../request-runtime-binding.ts';
import type { DaemonRequest, DaemonResponse } from '../daemon-request.ts';
import type { SessionRef, SessionState } from '../session-state.ts';
import { bindRecordOnlyScreenRecording } from '../screen-recording-session-binding.ts';
import { recordSessionAction } from '../session-action-recorder.ts';
import {
missingAppSessionResponse,
prepareRecordingRequest,
readRecordingScope,
} from './record-runtime-request.ts';
import { resolveRecordingOutputPaths } from '@agent-device/capture-kit/recording-output-path';
import {
buildRecordingStartResponse,
buildRecordingStartedAction,
buildRecordingStopResponse,
buildRecordingUnsupportedResponse,
} from './record-runtime-response.ts';
/**
* A stop either finishes the live export or reports one the daemon already finished. Only the
* first owes a session action: the request that terminalized the recording already recorded it.
*/
type ScreenRecordingStop = Readonly<{
completion: ScreenRecordingCompletion;
recordsSessionAction: boolean;
}>;
export type RecordRuntimeHandlerParams = Readonly<{
req: DaemonRequest;
sessionName: string;
sessionStore: SessionStore;
bindDevice: BindDeviceRuntime;
bindExactDevice: BindExactDeviceRuntime;
admissionLedger: ScreenRecordingAdmissionLedger;
requestScope: PlatformRequestScope;
retainDeviceExecutionLock(deviceId: string): Promise<void>;
throwIfCanceled(): void;
}>;
export async function handleRecordCommand(
params: RecordRuntimeHandlerParams,
): Promise<DaemonResponse> {
try {
return await handleRecordCommandUnsafe(params);
} catch (error) {
return { ok: false, error: normalizeError(error) };
}
}
async function handleRecordCommandUnsafe(
params: RecordRuntimeHandlerParams,
): Promise<DaemonResponse> {
const { req, sessionName, sessionStore } = params;
const existingRef = sessionStore.lookup(sessionName);
const existingSession = existingRef?.session;
const { plan, scope } = resolveRecordPlan(req, existingSession);
if (plan.kind === 'start' && !isWholeScreenRecordingScope(scope) && !existingSession) {
return missingAppSessionResponse(req);
}
const resolvedSession = await resolveRecordingSession(params, existingRef);
const { session } = resolvedSession;
if (plan.kind === 'start') {
return await startRecording(
params,
session,
resolvedSession.ref,
prepareRecordingRequest(req),
plan.use,
resolvedSession.needsReadiness,
);
}
return await stopRecording(
params,
session,
resolvedSession.ref,
plan.kind,
resolvedSession.needsReadiness,
);
}
function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined) {
const scope = readRecordingScope(req.flags?.recordingScope);
return {
scope,
plan: resolveScreenRecordingRuntimePlan({
action: req.positionals?.[0],
scope,
hasLiveHandle: session?.screenRecording !== undefined,
}),
};
}
async function resolveRecordingSession(
params: RecordRuntimeHandlerParams,
ref: SessionRef | undefined,
): Promise<Readonly<{ session: SessionState; ref?: SessionRef; needsReadiness: boolean }>> {
const device = ref?.session.device ?? (await resolveTargetDevice(params.req.flags ?? {}));
await params.retainDeviceExecutionLock(device.id);
if (ref) return { session: params.sessionStore.requireCurrent(ref), ref, needsReadiness: false };
return { session: createRecordOnlySession(params, device), needsReadiness: true };
}
async function startRecording(
params: RecordRuntimeHandlerParams,
session: SessionState,
ref: SessionRef | undefined,
prepared: ReturnType<typeof prepareRecordingRequest>,
use: typeof screenRecordingStartUse,
needsReadiness: boolean,
): Promise<DaemonResponse> {
if (session.screenRecording) {
return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } };
}
const draft = ref
? undefined
: bindRecordOnlyScreenRecording(params.sessionStore, params.sessionName, session);
const binding = ref ? bindSessionScreenRecording(params.sessionStore, ref) : draft!.binding;
binding.assertAdoptable();
const admission = await params.bindDevice(session.device, screenRecordingAdmissionUse);
if (needsReadiness) await ensureBoundDeviceReady(admission);
const startFact = admission.facts.screenRecordingStart;
if (!startFact.available) return buildRecordingUnsupportedResponse(startFact);
const runtime = await params.bindDevice(session.device, use);
const { fence, outputPaths } = prepareRecordingStart(params, session);
binding.assertAdoptable();
const started = await runtime.operations.screenRecordingStart(
screenRecordingStartInput(params, session, prepared, fence, outputPaths.outputPath),
);
await adoptStartedScreenRecording({
admissionLedger: params.admissionLedger,
binding,
device: session.device,
owner: runtime.owner,
fence,
...started,
throwIfCanceled: params.throwIfCanceled,
});
const adoptedRef = ref ?? draft!.requireRef();
const adopted = binding.read();
if (!adopted) throw new TypeError('Screen recording adoption did not publish a live handle');
const snapshot = adopted.handle.inspect();
recordSessionAction(
params.sessionStore,
params.sessionStore.requireCurrent(adoptedRef),
params.req,
params.req.command,
buildRecordingStartedAction(snapshot),
);
return buildRecordingStartResponse(
snapshot,
params.sessionStore.ensureSessionDir(params.sessionName),
outputPaths.requestedPath,
);
}
function prepareRecordingStart(params: RecordRuntimeHandlerParams, session: SessionState) {
const resourcePath = screenRecordingDurableResource.resourcePath(
params.sessionStore,
params.sessionName,
);
return {
fence: screenRecordingDurableResource.createNextFence({
admissionLedger: params.admissionLedger,
resourcePath,
device: session.device,
}),
outputPaths: resolveRecordingOutputPaths({
requestedPath: params.req.positionals?.[1],
platform: session.device.platform,
cwd: params.req.meta?.cwd,
}),
};
}
function screenRecordingStartInput(
params: RecordRuntimeHandlerParams,
session: SessionState,
prepared: ReturnType<typeof prepareRecordingRequest>,
fence: ScreenRecordingStartInput['fence'],
outputPath: string,
): ScreenRecordingStartInput {
return {
sessionId: params.sessionName,
outputPath,
clientOutputPath: params.req.meta?.clientArtifactPaths?.outPath,
scope: prepared.scope,
showTouches: prepared.showTouches,
hideTouchesRequested: prepared.hideTouchesRequested,
recordOnlySession: session.recordOnlySession === true,
activeSessionApp: recordingAppIdentity(session),
exportQuality: prepared.exportQuality,
fps: prepared.fps,
fence,
};
}
function recordingAppIdentity(
session: SessionState,
): ScreenRecordingStartInput['activeSessionApp'] {
if (!session.appBundleId) return undefined;
return { bundleId: session.appBundleId, ...(session.appName ? { name: session.appName } : {}) };
}
async function stopRecording(
params: RecordRuntimeHandlerParams,
session: SessionState,
ref: SessionRef | undefined,
kind: 'stop-live' | 'stop-recovery',
needsReadiness: boolean,
): Promise<DaemonResponse> {
let stopped: ScreenRecordingStop;
try {
stopped =
kind === 'stop-live'
? {
completion: await finishLiveScreenRecording({
intent: 'capture',
binding: bindSessionScreenRecording(params.sessionStore, ref!),
}),
recordsSessionAction: true,
}
: await finishRecovered(params, session, needsReadiness);
} catch (error) {
deleteTerminalRecordOnlySession(params, session, ref);
throw error;
}
const completion = stopped.completion;
const response = buildRecordingStopResponse(completion);
if (stopped.recordsSessionAction) {
recordSessionAction(params.sessionStore, session, params.req, params.req.command, {
action: 'stop',
outPath: completion.outPath,
...(completion.clientOutPath
? { requestedFileName: path.basename(completion.clientOutPath) }
: {}),
showTouches: completion.showTouches,
});
}
if (session.recordOnlySession && ref) params.sessionStore.retire(ref);
return response;
}
function deleteTerminalRecordOnlySession(
params: Pick<RecordRuntimeHandlerParams, 'sessionName' | 'sessionStore'>,
session: SessionState,
ref: SessionRef | undefined,
): void {
if (!session.recordOnlySession || !ref) return;
if (screenRecordingManifestIsTerminal(params)) params.sessionStore.retire(ref);
}
async function finishRecovered(
params: RecordRuntimeHandlerParams,
session: SessionState,
needsReadiness: boolean,
): Promise<ScreenRecordingStop> {
const recovery = resolveScreenRecordingStopRecovery({
sessionName: params.sessionName,
sessionStore: params.sessionStore,
device: session.device,
});
if (recovery.kind === 'completed') {
return { completion: recovery.completion, recordsSessionAction: false };
}
if (recovery.kind === 'none') {
throw new AppError('INVALID_ARGS', 'no active recording');
}
const completion = await finishRecoveredScreenRecording({
resourcePath: recovery.resourcePath,
scope: params.requestScope,
acquireControl: async (envelope, recoveryScope) => {
const runtime = await params.bindExactDevice(
session.device,
envelope.owner,
envelope.fence,
screenRecordingRecoveryUse,
recoveryScope,
);
if (needsReadiness) await ensureBoundDeviceReady(runtime);
return createScreenRecordingRecoveryControl({ runtime, dispose: async () => {} });
},
});
return { completion, recordsSessionAction: true };
}
function createRecordOnlySession(
params: Pick<RecordRuntimeHandlerParams, 'req' | 'sessionName'>,
device: SessionState['device'],
): SessionState {
return {
name: params.sessionName,
sessionScope: resolveSessionScope(params.req),
device,
createdAt: Date.now(),
recordOnlySession: true,
actions: [],
};
}