Repository navigation
Expand file tree
/
Copy pathsnapshot-command-runtime.ts
More file actions
303 lines (291 loc) · 10.5 KB
/
Copy pathsnapshot-command-runtime.ts
File metadata and controls
303 lines (291 loc) · 10.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
import {
copySnapshotClickabilityEvidence,
snapshotCaptureAnnotationsFrom,
summarizeSnapshotDiagnostics,
type SnapshotDiffSummary,
} from '@agent-device/contracts/capture';
import type { SnapshotResult } from '@agent-device/contracts/snapshot-runtime';
import { publicPlatformString } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import type { AgentDeviceBackend, BackendSnapshotResult } from '../backend.ts';
import type { CommandSessionRecord } from '../runtime-contract.ts';
import { createCommandSurfaceAgentDevice } from '../runtime-command-surface.ts';
import { getRequestSignal } from '@agent-device/host-kit/request';
import { maybeBuildAndroidSnapshotTimeoutFailure } from './android-snapshot-timeout-evidence.ts';
import { captureSnapshot } from './snapshot-capture.ts';
import { createSnapshotSession, withSessionlessRunnerCleanup } from './snapshot-session.ts';
import { resolveSessionScope } from './session-routing.ts';
import { activateCompleteRefFrame } from './ref-frame.ts';
import {
applyRecoveredWarningLatch,
type CapturedSnapshotQuality,
} from './snapshot-quality-latch.ts';
import { createDaemonRuntimePolicy } from './runtime-policy.ts';
import { createDaemonRuntimeSessionStore } from './runtime-session.ts';
import { isInteractiveObservation } from './session-action-recorder.ts';
import { setCommandSnapshot } from './session-snapshot.ts';
import { SessionStore } from './session-store.ts';
import {
resolveBoundSnapshotCaptureRuntime,
type SnapshotRuntimeRouteParams,
} from './snapshot-runtime-binding.ts';
import type { DaemonRequest, DaemonResponse, DaemonResponseData } from './daemon-request.ts';
import type { SessionRef, SessionState } from './session-state.ts';
export type SnapshotRuntimeRecord =
| { kind: 'snapshot'; nodes: number; truncated: boolean | undefined }
| {
kind: 'diff';
mode: 'snapshot';
baselineInitialized: boolean;
summary: SnapshotDiffSummary;
};
type SnapshotRuntimeCommandParams = SnapshotRuntimeRouteParams & {
command: 'snapshot' | 'diff';
execute(params: {
runtime: ReturnType<typeof createSnapshotRuntime>['runtime'];
sessionName: string;
req: DaemonRequest;
snapshotScope: string | undefined;
getSession(): SessionState | undefined;
}): Promise<{ data: DaemonResponseData; record: SnapshotRuntimeRecord }>;
};
/** Shared snapshot/diff command construction after one request-bound capture has been admitted. */
export async function dispatchSnapshotRuntimeCommand(
params: SnapshotRuntimeCommandParams,
): Promise<DaemonResponse> {
const capture = await resolveBoundSnapshotCaptureRuntime(params, params.command);
if (!capture.ok) return capture.response;
const { ref, session, device, snapshotScope } = capture;
return await withSessionlessRunnerCleanup(
session,
device,
async () => {
const { req, sessionName, logPath, sessionStore } = params;
const capturedQuality: CapturedSnapshotQuality = {};
const { runtime, sessions } = createSnapshotRuntime({
req,
sessionName,
logPath,
sessionStore,
ref,
session,
device,
snapshotScope,
capturedQuality,
captureSnapshotData: capture.captureSnapshot,
});
const getSession = () => {
const currentRef = sessions.getRef();
return currentRef ? sessionStore.requireCurrent(currentRef) : undefined;
};
let result: Awaited<ReturnType<SnapshotRuntimeCommandParams['execute']>>;
try {
result = await params.execute({ runtime, sessionName, req, snapshotScope, getSession });
} catch (error) {
const timeoutResponse = await maybeBuildAndroidSnapshotTimeoutFailure({
error,
command: params.command,
logPath,
session,
device,
inspectFacts: params.inspectFacts,
bindDevice: params.bindDevice,
});
if (!timeoutResponse) throw error;
return timeoutResponse;
}
const current = getSession();
recordSnapshotRuntimeAction({
req,
sessionName,
sessionStore,
session: current,
result: result.record,
});
const data = applyRecoveredWarningLatch({
session: current,
data: result.data,
verdict: capturedQuality.value,
internalObservation: req.internal?.observationOnly === true,
});
return {
ok: true,
data: copySnapshotClickabilityEvidence(result.data, data),
};
},
params.platformResourceCleanup,
);
}
function createSnapshotRuntime(params: {
req: DaemonRequest;
sessionName: string;
logPath: string;
sessionStore: SessionStore;
ref: SessionRef | undefined;
session: SessionState | undefined;
device: SessionState['device'];
snapshotScope: string | undefined;
capturedQuality: CapturedSnapshotQuality;
captureSnapshotData: () => Promise<SnapshotResult>;
}) {
const { req, sessionName, logPath, sessionStore, session, device, snapshotScope } = params;
const sessions = createDaemonRuntimeSessionStore({
sessionName,
sessionStore,
ref: params.ref,
recordOptions: { includeSnapshot: true },
setRecord: (record, current, ref) => {
const snapshotRecord = assertSnapshotSessionRecord(record);
const keepCurrentSnapshot = shouldKeepCurrentSnapshot(
current,
snapshotRecord,
isRefScopedSnapshot(req),
);
const snapshot = keepCurrentSnapshot ? current.snapshot : snapshotRecord.snapshot;
const nextSession: SessionState =
current ??
createSnapshotSession({
sessionName,
sessionScope: resolveSessionScope(req),
device,
snapshot,
appBundleId: record.appBundleId,
});
nextSession.appName = record.appName ?? current?.appName;
setCommandSnapshot(nextSession, {
snapshot,
scopeSource: resolveNextSnapshotScopeSource({
current,
keepCurrentSnapshot,
refScopedSnapshot: isRefScopedSnapshot(req),
}),
keptCurrentSnapshot: keepCurrentSnapshot,
previousGeneration: current?.snapshotGeneration,
});
reactivateCompleteFrameIfIssuing(
nextSession,
keepCurrentSnapshot,
req.command === 'snapshot' && req.internal?.observationOnly !== true,
);
return ref ?? sessionStore.publish(sessionName, nextSession);
},
});
const runtime = createCommandSurfaceAgentDevice({
backend: createDaemonSnapshotBackend({
req,
logPath,
session,
device,
snapshotScope,
capturedQuality: params.capturedQuality,
captureSnapshotData: params.captureSnapshotData,
}),
...createDaemonRuntimePolicy('snapshot'),
signal: getRequestSignal(req.meta?.requestId),
sessions,
});
return { runtime, sessions };
}
function isRefScopedSnapshot(req: DaemonRequest): boolean {
return req.flags?.snapshotScope?.trim().startsWith('@') === true;
}
function shouldKeepCurrentSnapshot(
current: SessionState | undefined,
record: CommandSessionRecord,
refScopedSnapshot: boolean,
): current is SessionState & { snapshot: NonNullable<SessionState['snapshot']> } {
return (
refScopedSnapshot && record.snapshot?.nodes.length === 0 && current?.snapshot !== undefined
);
}
// ADR 0014: only a snapshot command hands the client the complete ref namespace.
function reactivateCompleteFrameIfIssuing(
session: SessionState,
keepCurrentSnapshot: boolean,
issuesRefsToClient: boolean,
): void {
if (!keepCurrentSnapshot && issuesRefsToClient) activateCompleteRefFrame(session);
}
function resolveNextSnapshotScopeSource(params: {
current: SessionState | undefined;
keepCurrentSnapshot: boolean;
refScopedSnapshot: boolean;
}): SessionState['snapshotScopeSource'] {
const { current, keepCurrentSnapshot, refScopedSnapshot } = params;
if (!refScopedSnapshot) return undefined;
if (keepCurrentSnapshot) return current?.snapshotScopeSource;
return current?.snapshotScopeSource ?? current?.snapshot;
}
function createDaemonSnapshotBackend(params: {
req: DaemonRequest;
logPath: string;
session: SessionState | undefined;
device: SessionState['device'];
snapshotScope: string | undefined;
capturedQuality: CapturedSnapshotQuality;
captureSnapshotData: () => Promise<SnapshotResult>;
}): AgentDeviceBackend {
const { req, logPath, session, device, snapshotScope } = params;
return {
platform: publicPlatformString(device),
captureSnapshot: async (context, options): Promise<BackendSnapshotResult> => {
const capture = await captureSnapshot({
device,
session,
flags: req.flags,
outPath: options?.outPath ?? req.flags?.out,
logPath,
snapshotScope,
signal: context.signal,
captureData: params.captureSnapshotData,
});
const annotations = snapshotCaptureAnnotationsFrom(capture);
params.capturedQuality.value = annotations.quality;
const snapshotDiagnostics = summarizeSnapshotDiagnostics(session);
return {
snapshot: capture.snapshot,
...annotations,
...(snapshotDiagnostics ? { snapshotDiagnostics } : {}),
appName: session?.appBundleId ? (session.appName ?? session.appBundleId) : undefined,
appBundleId: session?.appBundleId,
};
},
};
}
function recordSnapshotRuntimeAction(params: {
req: DaemonRequest;
sessionName: string;
sessionStore: SessionStore;
session: SessionState | undefined;
result: SnapshotRuntimeRecord;
}): void {
const session = params.session;
if (!session) return;
params.sessionStore.recordAction(session, {
command: params.req.command,
positionals: params.req.positionals ?? [],
flags: params.req.flags ?? {},
result: toRecordedSnapshotRuntimeResult(params.result),
interactiveObservation: isInteractiveObservation(params.req),
});
}
function assertSnapshotSessionRecord(
record: CommandSessionRecord,
): CommandSessionRecord & { snapshot: NonNullable<CommandSessionRecord['snapshot']> } {
if (!record.snapshot) {
throw new AppError('UNKNOWN', 'snapshot runtime did not produce session state');
}
return record as CommandSessionRecord & {
snapshot: NonNullable<CommandSessionRecord['snapshot']>;
};
}
function toRecordedSnapshotRuntimeResult(record: SnapshotRuntimeRecord): Record<string, unknown> {
if (record.kind === 'snapshot') {
return { nodes: record.nodes, truncated: record.truncated };
}
return {
mode: record.mode,
baselineInitialized: record.baselineInitialized,
summary: record.summary,
};
}