diff --git a/docs/adr/0024-screen-recording-provable-signal.md b/docs/adr/0024-screen-recording-provable-signal.md index 7211d84905..274f18caf6 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -287,12 +287,27 @@ Artifact cleanup is a separate, explicit decision (rule 6). Session teardown and failed-start rollback dispose through the backend under the fence. They do this only after the manifest records that no recoverable export is lost. -A leased session's teardown that commits an export at a remote temp path registers it, and its telemetry, as downloadable artifacts of that lease (rule 1, #2281). -Only a request that sends the id of the ended lease lists or downloads them (ADR 0007). +A remote recording reserves a daemon-chosen destination at start. +The manifest records the producing lifetime, a tenant or explicit global marker, and a lease verifier or unleased marker. +The completed manifest records the verified file identities of the video, later chunks, and telemetry. +If verification cannot read a finished export, keep its completion and reservation for an exact-owner retry. +Explicit stop and teardown commit the verified files under that producer's authority. +The producer can discover committed recordings after a canceled or failed response. The inventory names the session, and the usual delete-after-download and 15-minute expiry apply. -A later `record stop` replay of that manifest serves the same artifact ids. -If registration fails, teardown deletes the files. -A failed teardown finish still runs forced cleanup (disposal intent) and registers nothing. +If registry delivery fails during teardown, expire the verified standalone export at the same deadline. +Only remove files that still match the original proof. +A retry for consumed or expired bytes returns `RESOURCE_EXPIRED`. +A retry uses the artifact IDs derived from the persisted reservation and the original deadline. +The download records consumption before releasing its file. +Only the original lease credential can list or download leased exports (ADR 0007). +A manifest must carry explicit producer scope, completion time, and file identities before it can serve a remote export. +After a daemon upgrade, remote `record stop` returns `LEASE_OUTPUT_MISMATCH` for an older manifest that lacks producer evidence, including for client-destination recordings. +The daemon keeps any finished files on the host for local recovery. +The old destination and lease verifier alone cannot prove the identity of the finished files. +A failed teardown finish still runs forced cleanup (disposal intent) and publishes no recording. +A suite includes recordings committed by cleanup in its result and archive. +Each remote suite gets a fresh daemon directory. +The recording stays in its reservation. The suite copies verified bytes into the archive so each download has its own lifetime. ### 2.6 Native markers diff --git a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-session-resource.test.ts b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-session-resource.test.ts index 86bec99fe1..4e3bf85129 100644 --- a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-session-resource.test.ts +++ b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-session-resource.test.ts @@ -5,6 +5,10 @@ import { expect, test, vi } from 'vitest'; import { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; import type { ScreenRecordingLiveHandle } from '@agent-device/contracts/screen-recording-runtime'; +import { + createStopProgress, + withDurableCaptureResourceFence, +} from '../../durable-capture/fence.ts'; import { createDurableResourceEnvelope } from '../../durable-resource-envelope.ts'; import { createScreenRecordingLiveHandle } from '../../screen-recording-live-handle.ts'; import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts'; @@ -13,6 +17,8 @@ import { createScreenRecordingAdmissionLedger } from '../screen-recording-admiss import { adoptStartedScreenRecording, finishLiveScreenRecording, + finishRecoveredScreenRecording, + screenRecordingDurableResource, } from '../screen-recording-session-resource.ts'; import { screenRecordingResourceStore } from '../screen-recording-resource-store.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -276,6 +282,115 @@ test('a record stop that fails after collecting resumes through the fence withou expect(sessionStore.get(sessionName)?.screenRecording).toBeUndefined(); }); +test.each([ + { route: 'startup recovery', proof: 'present' }, + { route: 'recovered stop', proof: 'present' }, + { route: 'recovered stop', proof: 'replaced' }, + { route: 'startup recovery', proof: 'absent' }, + { route: 'recovered stop', proof: 'absent' }, +])( + '$route checks the manifest and export after native completion with $proof producer proof', + async ({ route, proof }) => { + const sessionsDir = mkdtempForTestSync('screen-recording-completed-recovery-'); + const sessionDir = path.join(sessionsDir, 'recording'); + const resourcePath = screenRecordingResourceStore.resolvePath(sessionDir); + const outPath = path.join(sessionDir, 'recording.mp4'); + const fence = { token: 'recording-fence', generation: 1 }; + const envelope = createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: 'recording', + device: { id: device.id, family: 'android', kind: 'emulator' }, + owner: localRuntimeOwner('android'), + fence, + lifecycle: 'open', + descriptor: { version: 1, body: { recordingId: 'recording-id' } }, + metadata: { remoteCapturePath: outPath, remoteCaptureReservation: fence.token }, + }); + screenRecordingResourceStore.write(resourcePath, envelope); + // Android publishes native completion only after this sequence returns. Leave the host + // manifest open to model a daemon that exits before its durable finish transition. + const nativeCompletion = await withDurableCaptureResourceFence({ + store: screenRecordingResourceStore, + resourcePath, + expected: fence, + onCompleted: () => { + throw new Error('Expected an open manifest'); + }, + run: (lease) => + stopAndExportScreenRecording({ + snapshot: { + backend: 'android', + outPath, + startedAt: 1, + scope: 'app', + showTouches: false, + recordOnlySession: false, + gestureEvents: [], + }, + progress: proof === 'absent' ? undefined : createStopProgress(lease), + steps: { + stop: async () => ({ observation: { recorder: 'confirmed' } }), + collect: async () => {}, + finalize: async () => { + fs.writeFileSync(outPath, 'producer export'); + return { nativePathDisposition: 'retirable' }; + }, + discard: async () => {}, + }, + }), + }); + const scope = { + signal: new AbortController().signal, + diagnostics: { emit: () => {} }, + progress: { report: () => {} }, + }; + const acquireControl = async () => ({ + reattach: async () => nativeCompletion, + cleanup: async () => ({ status: 'cleaned' as const }), + [Symbol.asyncDispose]: async () => {}, + }); + const stop = () => finishRecoveredScreenRecording({ resourcePath, scope, acquireControl }); + + if (proof === 'replaced') { + fs.writeFileSync(outPath, 'different bytes at the reserved path'); + await expect(stop()).rejects.toThrow('Recording export does not match its stored proof.'); + expect(screenRecordingResourceStore.read(resourcePath)).toMatchObject({ + envelope: { lifecycle: 'open' }, + }); + return; + } + if (route === 'startup recovery') { + await expect( + screenRecordingDurableResource.recoverOne( + { sessionsDir, scope, acquireControl }, + resourcePath, + ), + ).resolves.toBe('recovered'); + } else { + await expect(stop()).resolves.toEqual(nativeCompletion.result); + } + const settled = screenRecordingResourceStore.read(resourcePath); + expect(settled).toMatchObject({ + envelope: { + lifecycle: 'completed', + metadata: { + completion: { outPath }, + }, + }, + }); + if (settled.status !== 'decoded') throw new Error('Expected the settled recording manifest'); + if (proof === 'absent') { + expect(settled.envelope.metadata).not.toHaveProperty('remoteCaptureExport'); + expect(fs.readFileSync(outPath, 'utf8')).toBe('producer export'); + } else { + expect(settled.envelope.metadata?.remoteCaptureExport).toEqual({ + completedAt: expect.any(Number), + identities: [expect.any(String)], + }); + } + }, +); + /** * What session teardown does with a recording `record stop` already committed: the queued disposal had * read the session's recording before that stop, so it still holds the handle and the fence the record diff --git a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts index b6fb6cf0d8..a918c44227 100644 --- a/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts +++ b/packages/capture-kit/src/capture-admission/__tests__/screen-recording-stop-recovery.test.ts @@ -44,9 +44,9 @@ test('a completed manifest hands back the whole stop response it stored', async fs.writeFileSync(harness.videoPath, 'mp4'); writeManifest(harness, encodeScreenRecordingCompletionMetadata(completion)); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'completed', completion }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), + ).toMatchObject({ kind: 'completed', completion }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(true); }); @@ -111,9 +111,9 @@ test('an open manifest stays available for exact-owner recovery', async () => { const harness = makeHarness(); writeManifest(harness, { phase: 'active' }, { lifecycle: 'open' }); - expect(resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE })).toEqual( - { kind: 'open', resourcePath: manifestPath(harness.sessionStore) }, - ); + expect( + resolveScreenRecordingStopRecovery({ ...harness.params, device: SESSION_DEVICE }), + ).toMatchObject({ kind: 'open', resourcePath: manifestPath(harness.sessionStore) }); expect(screenRecordingManifestIsTerminal(harness.params)).toBe(false); }); diff --git a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts index 6aad9e9472..2bd12cf12b 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts @@ -70,6 +70,11 @@ export function listDurableCaptureStartConflicts( ); } if (existing.status !== 'decoded' || existing.envelope.lifecycle === 'completed') continue; + if ( + existingPath !== resourcePath && + definition.nativeCleanupSettled?.(existing.envelope.metadata) + ) + continue; const onStartDevice = sameDeviceIdentity(existing.envelope.device, startDevice); if (onStartDevice || existingPath === resourcePath) { records.push({ resourcePath: existingPath, envelope: existing.envelope, onStartDevice }); diff --git a/packages/capture-kit/src/capture-admission/screen-recording-resource-store.ts b/packages/capture-kit/src/capture-admission/screen-recording-resource-store.ts index a98ac339d3..4552df11ad 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-resource-store.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-resource-store.ts @@ -1,10 +1,33 @@ +import type fs from 'node:fs'; import { SCREEN_RECORDING_RESOURCE_KIND } from '@agent-device/contracts/screen-recording-runtime'; +import type { JsonObject } from '@agent-device/contracts/client'; +import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { createDurableCaptureResourceStore } from '../durable-capture/index.ts'; +export class RecordingProofIoError extends AppError { + readonly evidence?: JsonObject; + + constructor(evidence?: JsonObject) { + super('COMMAND_FAILED', 'Recording ownership proof could not be read.', { retriable: true }); + this.evidence = evidence; + } +} + +export function recordingCheckpointError(error: unknown): RecordingProofIoError { + emitDiagnostic({ + level: 'warn', + phase: 'screen_recording_proof_io_failed', + data: { error: errorMessage(error) }, + }); + return new RecordingProofIoError(); +} + export const screenRecordingResourceStore = createDurableCaptureResourceStore({ resourceKind: SCREEN_RECORDING_RESOURCE_KIND, fileName: 'screen-recording.resource.json', displayName: 'screen recording', + checkpointError: recordingCheckpointError, }); /** @@ -13,3 +36,9 @@ export const screenRecordingResourceStore = createDurableCaptureResourceStore({ * `screen-recording-stop-recovery.ts`; both name this key so a replay cannot miss what was written. */ export const SCREEN_RECORDING_COMPLETION_METADATA_KEY = 'completion'; + +export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null { + return stat?.isFile() + ? `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` + : null; +} diff --git a/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts index b94f1b9a6a..9f9331f278 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts @@ -18,14 +18,18 @@ import type { DurableCaptureRecoveryControl, DurableCaptureSessionBinding, } from '../durable-capture/index.ts'; +import { withDurableCaptureResourceFence } from '../durable-capture/fence.ts'; import { createDurableCaptureResource } from './durable-capture-resource.ts'; import type { DurableCaptureFinishIntent } from './durable-capture-resource.ts'; import type { ScreenRecordingAdmissionLedger } from './screen-recording-admission-ledger.ts'; import { SCREEN_RECORDING_COMPLETION_METADATA_KEY, + RecordingProofIoError, screenRecordingResourceStore, } from './screen-recording-resource-store.ts'; +export { recordingExportFileIdentity } from './screen-recording-resource-store.ts'; + export const screenRecordingDurableResource = createDurableCaptureResource< 'screen-recording', ScreenRecordingLiveHandle, @@ -34,7 +38,26 @@ export const screenRecordingDurableResource = createDurableCaptureResource< resourceKind: 'screen-recording', displayName: 'screen recording', store: screenRecordingResourceStore, - completionMetadata: encodeScreenRecordingCompletionMetadata, + completionMetadata: async (result, metadata, progress) => ({ + ...encodeScreenRecordingCompletionMetadata(result), + ...(typeof metadata?.remoteCapturePath === 'string' && + typeof metadata.remoteCaptureReservation === 'string' && + (progress !== undefined || metadata.remoteCaptureExport !== undefined) + ? { + remoteCaptureExport: (await import('../recording/export-proof.ts')).verifyRecordingExport( + metadata.remoteCapturePath, + result, + metadata, + progress, + ), + } + : {}), + }), + pendingCompletionMetadata: (result, error, completion) => + error instanceof RecordingProofIoError + ? (completion ?? { ...encodeScreenRecordingCompletionMetadata(result), ...error.evidence }) + : undefined, + nativeCleanupSettled: screenRecordingNativeCleanupSettled, // The manifest holds the whole stop response this kind wrote, so a caller that reaches the committed // record is served the same export the first stop was answered with. That answer is a cold path: the // record has to be read before anyone can be refused or served, so the reader is reached on demand @@ -51,6 +74,13 @@ export const screenRecordingDurableResource = createDurableCaptureResource< }, }); +export function screenRecordingNativeCleanupSettled(metadata: JsonObject | undefined): boolean { + return ( + metadata?.phase === 'export-proof-pending' && + (metadata.cleanupStatus === 'cleaned' || metadata.cleanupStatus === 'already-missing') + ); +} + export function adoptStartedScreenRecording(params: { admissionLedger: ScreenRecordingAdmissionLedger; binding: DurableCaptureSessionBinding<'screen-recording', ScreenRecordingLiveHandle>; @@ -72,6 +102,41 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } +export async function finishPendingScreenRecordingProof( + resourcePath: string, + expected: DurableResourceEnvelope<'screen-recording'>, +): Promise> { + const { readStoredCompletion, unreadableRecordingProof } = + await import('./screen-recording-stop-recovery.ts'); + return withDurableCaptureResourceFence({ + store: screenRecordingResourceStore, + resourcePath, + expected: expected.fence, + onCompleted: ({ envelope }) => envelope, + run: async (lease) => { + const { metadata } = lease.envelope; + const completion = readStoredCompletion(metadata); + if ( + !metadata || + !screenRecordingNativeCleanupSettled(metadata) || + !completion || + typeof metadata.remoteCapturePath !== 'string' || + metadata.remoteCaptureReservation !== expected.fence.token + ) + throw unreadableRecordingProof(); + const { verifyRecordingExport } = await import('../recording/export-proof.ts'); + const proof = verifyRecordingExport(metadata.remoteCapturePath, completion, metadata); + return lease.transition('completed', { + metadata: { + ...lease.envelope.metadata, + phase: 'completed', + remoteCaptureExport: proof, + }, + }); + }, + }); +} + export function encodeScreenRecordingCompletionMetadata( completion: ScreenRecordingCompletion, ): JsonObject { diff --git a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts index 4e0383fa74..a71b5203a5 100644 --- a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts +++ b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts @@ -8,17 +8,13 @@ import type { ScreenRecordingCompletion, } from '@agent-device/contracts/screen-recording-runtime'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; -import { - deviceIdentity, - sameDeviceIdentity, - type DeviceIdentity, - type DeviceInfo, -} from '@agent-device/kernel/device'; +import { deviceIdentity, sameDeviceIdentity, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError, RUNTIME_CONTRACT_REASONS } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import type { DurableCaptureResourceRecord } from '../durable-capture/index.ts'; import { + RecordingProofIoError, SCREEN_RECORDING_COMPLETION_METADATA_KEY, screenRecordingResourceStore, } from './screen-recording-resource-store.ts'; @@ -33,8 +29,16 @@ import { * handed a path it cannot download. */ export type ScreenRecordingStopRecovery = - | Readonly<{ kind: 'completed'; completion: ScreenRecordingCompletion }> - | Readonly<{ kind: 'open'; resourcePath: string }> + | Readonly<{ + kind: 'completed'; + completion: ScreenRecordingCompletion; + envelope: DurableResourceEnvelope<'screen-recording'>; + }> + | Readonly<{ + kind: 'open'; + resourcePath: string; + envelope: DurableResourceEnvelope<'screen-recording'>; + }> | Readonly<{ kind: 'none' }>; const OPTIONAL_RESPONSE_FIELDS = [ @@ -50,13 +54,28 @@ type ScreenRecordingManifestParams = Readonly<{ }>; export function resolveScreenRecordingStopRecovery( - params: ScreenRecordingManifestParams & Readonly<{ device: DeviceInfo }>, + params: ScreenRecordingManifestParams & + Readonly<{ + device: DeviceInfo; + admittedEnvelope?: DurableResourceEnvelope<'screen-recording'>; + }>, ): ScreenRecordingStopRecovery { - const { resourcePath, record } = readSessionManifest(params); + const resourcePath = screenRecordingResourceStore.resolvePath( + params.sessionStore.resolveSessionDir(params.sessionName), + ); + const record = params.admittedEnvelope + ? { status: 'decoded' as const, envelope: params.admittedEnvelope } + : screenRecordingResourceStore.read(resourcePath); + if (record.status === 'unreattachable') throw unreadableRecordingProof(); if (record.status !== 'decoded') return { kind: 'none' }; assertManifestBelongsToRequest(params, record.envelope); - if (record.envelope.lifecycle !== 'completed') return { kind: 'open', resourcePath }; - const completion = readReplayableStoredCompletion(record.envelope.metadata); + if (record.envelope.lifecycle !== 'completed') + return { kind: 'open', resourcePath, envelope: record.envelope }; + const { metadata } = record.envelope; + const completion = + metadata?.remoteCaptureOutput === true + ? readStoredCompletion(metadata) + : readReplayableStoredCompletion(metadata); if (completion === undefined) { emitDiagnostic({ level: 'warn', @@ -65,7 +84,7 @@ export function resolveScreenRecordingStopRecovery( }); return { kind: 'none' }; } - return { kind: 'completed', completion }; + return { kind: 'completed', completion, envelope: record.envelope }; } /** Whether the session's manifest recorded a terminal recording, even one with no serveable file. */ @@ -74,21 +93,6 @@ export function screenRecordingManifestIsTerminal(params: ScreenRecordingManifes return record.status === 'decoded' && record.envelope.lifecycle === 'completed'; } -/** - * The device a stop without a held session must be answered on: the one the session's durable - * manifest names, when a decodable manifest exists. `undefined` means there is nothing to recover - * from, and a caller that addressed a session answers on the session instead of choosing a device. - * The caller still resolves this identity against the host to recover the live device fields, and - * `assertManifestBelongsToRequest` still fails the request closed when the resolved device or the - * session address does not match what the manifest recorded. - */ -export function screenRecordingManifestDevice( - params: ScreenRecordingManifestParams, -): DeviceIdentity | undefined { - const { record } = readSessionManifest(params); - return record.status === 'decoded' ? record.envelope.device : undefined; -} - function readSessionManifest(params: ScreenRecordingManifestParams): Readonly<{ resourcePath: string; record: DurableCaptureResourceRecord<'screen-recording'>; @@ -132,6 +136,17 @@ function assertManifestBelongsToRequest( */ export function readReplayableStoredCompletion( metadata: JsonObject | undefined, +): ScreenRecordingCompletion | undefined { + const completion = readStoredCompletion(metadata); + return completion && fs.existsSync(completion.outPath) ? completion : undefined; +} + +export function unreadableRecordingProof(): AppError { + return new RecordingProofIoError(); +} + +export function readStoredCompletion( + metadata: JsonObject | undefined, ): ScreenRecordingCompletion | undefined { const stored = metadata?.[SCREEN_RECORDING_COMPLETION_METADATA_KEY]; if ( @@ -142,8 +157,7 @@ export function readReplayableStoredCompletion( ) { return undefined; } - const completion = stored as unknown as ScreenRecordingCompletion; - return fs.existsSync(completion.outPath) ? completion : undefined; + return stored as unknown as ScreenRecordingCompletion; } /** The values a stop response computes on rather than repeats. */ diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index f9adebf12a..3cfa38a303 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -1,4 +1,5 @@ import type { JsonObject } from '@agent-device/contracts/client'; +import type { DurableCaptureProgress } from '@agent-device/contracts/durable-resource'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import type { @@ -56,7 +57,11 @@ export type DurableCaptureRecordDefinition = Readonly<{ resourceKind: K; displayName: string; store: DurableCaptureResourceStore; - completionMetadata(result: C): JsonObject; + completionMetadata( + result: C, + metadata: DurableResourceEnvelope['metadata'], + progress?: DurableCaptureProgress, + ): JsonObject | Promise; /** * The completion this kind stored in a record that is already committed, or nothing it can serve. * @@ -69,6 +74,12 @@ export type DurableCaptureRecordDefinition = Readonly<{ * Optional because a kind whose stored metadata cannot carry its whole outcome has nothing honest to * replay; its callers then get the terminal refusal. */ + pendingCompletionMetadata?( + result: C, + error: unknown, + completion: JsonObject | undefined, + ): JsonObject | undefined; + nativeCleanupSettled?(metadata: JsonObject | undefined): boolean; completionFromMetadata?(metadata: JsonObject | undefined): C | undefined | Promise; failedFinishPolicy: DurableCaptureFailedFinishPolicy; messages: Readonly<{ diff --git a/packages/capture-kit/src/durable-capture/fence.ts b/packages/capture-kit/src/durable-capture/fence.ts index dfbaf53be3..9ac6ee1d3a 100644 --- a/packages/capture-kit/src/durable-capture/fence.ts +++ b/packages/capture-kit/src/durable-capture/fence.ts @@ -1,4 +1,6 @@ import { AppError, type ReasonTable, DURABLE_RESOURCE_REASONS } from '@agent-device/kernel/errors'; +import type { JsonObject } from '@agent-device/contracts/client'; +import type { DurableCaptureProgress } from '@agent-device/contracts/durable-resource'; import type { DurableResourceEnvelope, DurableResourceLifecycleState, @@ -63,7 +65,8 @@ export async function withDurableCaptureResourceFence( }>, ): Promise { return await serializeResource(params.resourcePath, async () => { - const admitted = requireAdmissibleRecord(params.store, params.resourcePath, params.expected); + const read = () => requireAdmissibleRecord(params.store, params.resourcePath, params.expected); + const admitted = read(); if (admitted.envelope.lifecycle === 'completed') { return await params.onCompleted({ envelope: admitted.envelope }); } @@ -77,22 +80,23 @@ export async function withDurableCaptureResourceFence( }, transition(lifecycle, update = {}) { // The persisted record decides, so a lease cannot publish from a view its own run cached. - const persisted = requireAdmissibleRecord( - params.store, - params.resourcePath, - params.expected, - ); + const persisted = read(); if (persisted.envelope.lifecycle === 'completed') { throw completedDurableCaptureError(params.store); } if (!issued) throw releasedLeaseError(params.store); - current = Object.freeze({ + const next = Object.freeze({ ...persisted.envelope, lifecycle, ...(update.descriptor === undefined ? {} : { descriptor: update.descriptor }), ...(update.metadata === undefined ? {} : { metadata: update.metadata }), }); - params.store.write(params.resourcePath, current); + try { + params.store.write(params.resourcePath, next); + } catch (error) { + throw params.store.checkpointError?.(error) ?? error; + } + current = next; return current; }, }); @@ -108,8 +112,16 @@ function requireAdmissibleRecord( resourcePath: string, expected: ResourceOwnershipFence, ): Extract, { status: 'decoded' }> { - const record = store.read(resourcePath); + let record; + try { + record = store.read(resourcePath); + } catch (error) { + throw store.checkpointError?.(error) ?? error; + } if (record.status !== 'decoded') { + if (record.status === 'unreattachable' && store.checkpointError) { + throw store.checkpointError(record.message); + } throw fenceError( store, record.status === 'missing' @@ -123,6 +135,18 @@ function requireAdmissibleRecord( return record; } +/** Stores stop progress under the current fence so a retry can use the facts already recorded. */ +export function createStopProgress( + lease: DurableCaptureOpenResourceFenceLease, +): DurableCaptureProgress { + return Object.freeze({ + learned: lease.envelope.metadata, + record: (fact: JsonObject) => { + lease.transition('open', { metadata: { ...lease.envelope.metadata, ...fact } }); + }, + }); +} + function sameFence(left: ResourceOwnershipFence, right: ResourceOwnershipFence): boolean { return left.token === right.token && left.generation === right.generation; } diff --git a/packages/capture-kit/src/durable-capture/finish-recovered.ts b/packages/capture-kit/src/durable-capture/finish-recovered.ts index 98db3919f9..6c85608367 100644 --- a/packages/capture-kit/src/durable-capture/finish-recovered.ts +++ b/packages/capture-kit/src/durable-capture/finish-recovered.ts @@ -82,10 +82,9 @@ export async function finishRecoveredDurableCapture< // caller is being served, so this attempt writes nothing of its own. onCompleted: () => undefined, run: async (lease) => { - transitionFinishOutcome(definition, lease, { + await transitionFinishOutcome(definition, lease, { status: 'completed', result, - alreadyCompleted: true, }); }, }); diff --git a/packages/capture-kit/src/durable-capture/recovery.ts b/packages/capture-kit/src/durable-capture/recovery.ts index 805f32ff84..f4046786dd 100644 --- a/packages/capture-kit/src/durable-capture/recovery.ts +++ b/packages/capture-kit/src/durable-capture/recovery.ts @@ -21,6 +21,7 @@ import { cleanupDurableCaptureDescriptor, markCompletingDurableCapture, transitionCleanupOutcome, + transitionFinishOutcome, } from './transitions.ts'; const DEFAULT_ACQUISITION_DEADLINE_MS = 5_000; @@ -127,7 +128,11 @@ function readRecoveryCandidate }); return { status: 'retained' }; } - if (record.status === 'missing' || record.envelope.lifecycle === 'completed') { + if ( + record.status === 'missing' || + record.envelope.lifecycle === 'completed' || + params.definition.nativeCleanupSettled?.(record.envelope.metadata) + ) { return { status: 'ignored' }; } const canonicalPath = params.definition.store.resolvePath( @@ -192,14 +197,8 @@ async function settleRecoveryAuthority, resourcePath: string, envelope: DurableResourceEnvelope, - metadata: Record, + outcome: { status: 'completed'; result: C } | { status: 'missing' }, ): Promise { await withDurableCaptureResourceFence({ store: params.definition.store, @@ -236,9 +235,18 @@ async function transitionTerminal undefined, run: async (lease) => { - lease.transition('completed', { - metadata: { ...(lease.envelope.metadata ?? {}), phase: 'completed', ...metadata }, - }); + if (params.definition.nativeCleanupSettled?.(lease.envelope.metadata)) return; + if (outcome.status === 'completed') { + await transitionFinishOutcome(params.definition, lease, outcome); + } else { + lease.transition('completed', { + metadata: { + ...lease.envelope.metadata, + phase: 'completed', + recoveryStatus: 'already-missing', + }, + }); + } }, }); } diff --git a/packages/capture-kit/src/durable-capture/store.ts b/packages/capture-kit/src/durable-capture/store.ts index 5cf510d5a7..d55e4eb387 100644 --- a/packages/capture-kit/src/durable-capture/store.ts +++ b/packages/capture-kit/src/durable-capture/store.ts @@ -22,6 +22,7 @@ export type DurableCaptureResourceRecord = export type DurableCaptureResourceStore = Readonly<{ resourceKind: K; displayName: string; + checkpointError?(error: unknown): Error; resolvePath(sessionDir: string): string; read(resourcePath: string): DurableCaptureResourceRecord; write(resourcePath: string, envelope: DurableResourceEnvelope): void; @@ -33,6 +34,7 @@ export function createDurableCaptureResourceStore( resourceKind: K; fileName: string; displayName: string; + checkpointError?(error: unknown): Error; }>, ): DurableCaptureResourceStore { assertFileName(options.fileName); @@ -40,6 +42,7 @@ export function createDurableCaptureResourceStore( return Object.freeze({ resourceKind: options.resourceKind, displayName: options.displayName, + checkpointError: options.checkpointError, resolvePath, read(resourcePath: string): DurableCaptureResourceRecord { let descriptor: number | undefined; diff --git a/packages/capture-kit/src/durable-capture/transitions.test.ts b/packages/capture-kit/src/durable-capture/transitions.test.ts index 719181ccae..3c0709da45 100644 --- a/packages/capture-kit/src/durable-capture/transitions.test.ts +++ b/packages/capture-kit/src/durable-capture/transitions.test.ts @@ -91,6 +91,34 @@ test('finish failure remains primary when cleanup and cleanup-pending persistenc expect(context.sessions.get(context.sessionName)?.capture?.handle).toBe(start.handle); }); +test('a failed terminal write does not dispose a capture without a pending proof policy', async () => { + const context = makeDurableCaptureContext(); + const writeError = new Error('completion write failed'); + const definition = createTestCaptureDefinition({ + ...testCaptureStore, + write(resourcePath, envelope) { + if (envelope.lifecycle === 'completed') throw writeError; + testCaptureStore.write(resourcePath, envelope); + }, + }); + const start = makeDurableCaptureStartResult(context); + await adoptStartedDurableCapture( + definition, + { ...context, ...start, throwIfCanceled: () => {} }, + context.resourcePath, + ); + + await expect( + finishLiveDurableCapture( + definition, + { binding: context.binding, intent: 'disposal' }, + context.resourcePath, + ), + ).rejects.toBe(writeError); + expect(start.forceCleanup).not.toHaveBeenCalled(); + expect(context.binding.read()?.handle).toBe(start.handle); +}); + test('an uncertain finish preserves its error after confirmed compensating cleanup', async () => { const context = makeDurableCaptureContext(); const start = makeDurableCaptureStartResult(context, { diff --git a/packages/capture-kit/src/durable-capture/transitions.ts b/packages/capture-kit/src/durable-capture/transitions.ts index ee296f5fa6..4f4db909ab 100644 --- a/packages/capture-kit/src/durable-capture/transitions.ts +++ b/packages/capture-kit/src/durable-capture/transitions.ts @@ -1,6 +1,5 @@ import { type CleanupOutcome, - type DurableCaptureProgress, type FinishOutcome, type LiveResourceHandle, isConfirmedCleanup, @@ -12,6 +11,7 @@ import { AppError, errorMessage, DURABLE_RESOURCE_REASONS } from '@agent-device/ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { completedDurableCaptureError, + createStopProgress, withDurableCaptureResourceFence, type DurableCaptureOpenResourceFenceLease, } from './fence.ts'; @@ -56,7 +56,9 @@ export async function finishLiveDurableCapture< if ( !cleanupPending && record.status === 'decoded' && - record.envelope.lifecycle === 'completed' + (record.envelope.lifecycle === 'completed' || + (record.envelope.fence.token === active.envelope.fence.token && + definition.nativeCleanupSettled?.(record.envelope.metadata))) ) { params.binding.clear(active); } @@ -132,10 +134,33 @@ export async function finishDurableCaptureHandle< throw finishError; } if (finishOutcome.status === 'completed') { - transitionFinishOutcome(definition, lease, finishOutcome); + await commitFinishedCapture( + definition, + lease, + finishOutcome, + async (proofError, pending) => { + const settled = await respondToFailedFinish( + definition, + lease, + params, + proofError, + params.intent, + pending, + ); + if (params.intent === 'disposal' && settled) { + emitDiagnostic({ + level: 'warn', + phase: `${durableCaptureDiagnosticPrefix(definition.resourceKind)}_unverified_export_disposed`, + data: { resourcePath: params.resourcePath, error: errorMessage(proofError) }, + }); + throw completedDurableCaptureError(definition.store); + } + throw proofError; + }, + ); return finishOutcome.result; } - transitionFinishOutcome(definition, lease, finishOutcome); + transitionCleanupOutcome(lease, finishOutcome); const finishError = cleanupPendingError(definition, finishOutcome); settleIfMissing(lease); await respondToFailedFinish(definition, lease, params, finishError, params.intent); @@ -150,10 +175,12 @@ async function respondToFailedFinish { + pendingCompletion?: JsonObject, +): Promise { if (intent === 'capture' && definition.failedFinishPolicy === 'preserve-retry-material') { + if (pendingCompletion) preserveCompletionCheckpoint(lease, pendingCompletion); emitFailedFinishPreservedDiagnostic(definition, params, finishError); - return; + return false; } let cleanup: CleanupOutcome; try { @@ -167,10 +194,21 @@ async function respondToFailedFinish( @@ -346,39 +385,54 @@ function cleanupPendingError( ); } -export function transitionFinishOutcome( +export async function transitionFinishOutcome( definition: DurableCaptureRecordDefinition, lease: DurableCaptureOpenResourceFenceLease, outcome: FinishOutcome, -): void { +): Promise { if (outcome.status === 'completed') { - lease.transition('completed', { - metadata: { - ...(lease.envelope.metadata ?? {}), - ...definition.completionMetadata(outcome.result), - phase: 'completed', - }, - }); + await commitFinishedCapture(definition, lease, { ...outcome, alreadyCompleted: true }); return; } transitionCleanupOutcome(lease, outcome); } -/** - * The manifest the stop is allowed to write into while it holds this fence (ADR 0024 2.3). What a - * kind records is its own vocabulary; the mechanics only merge each fact into the metadata and hand - * back what is already there, so a stop that dies mid-way leaves its own facts beside the open - * record and the next attempt reads them instead of redoing durable work. - */ -function createStopProgress( +async function commitFinishedCapture( + definition: DurableCaptureRecordDefinition, lease: DurableCaptureOpenResourceFenceLease, -): DurableCaptureProgress { - return Object.freeze({ - learned: lease.envelope.metadata, - record: (fact: JsonObject) => { - lease.transition('open', { metadata: { ...(lease.envelope.metadata ?? {}), ...fact } }); - }, - }); + outcome: Extract, { status: 'completed' }>, + onProofFailure?: (error: unknown, pending: JsonObject | undefined) => Promise, +): Promise { + let completion; + const { result, alreadyCompleted } = outcome; + try { + completion = await definition.completionMetadata( + result, + lease.envelope.metadata, + alreadyCompleted ? undefined : createStopProgress(lease), + ); + lease.transition('completed', { + metadata: { ...lease.envelope.metadata, ...completion, phase: 'completed' }, + }); + } catch (error) { + const pending = definition.pendingCompletionMetadata?.(result, error, completion); + if (onProofFailure && (completion === undefined || pending !== undefined)) { + await onProofFailure(error, pending); + } + if (pending) preserveCompletionCheckpoint(lease, pending); + throw error; + } +} + +function preserveCompletionCheckpoint( + lease: DurableCaptureOpenResourceFenceLease, + completion: JsonObject, +): void { + try { + lease.transition('open', { metadata: { ...lease.envelope.metadata, ...completion } }); + } catch { + // Report the original checkpoint error. The fence diagnoses further I/O failures. + } } /** diff --git a/packages/capture-kit/src/recording/export-proof.ts b/packages/capture-kit/src/recording/export-proof.ts new file mode 100644 index 0000000000..bae77aca4e --- /dev/null +++ b/packages/capture-kit/src/recording/export-proof.ts @@ -0,0 +1,121 @@ +import fs from 'node:fs'; +import { AppError } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import type { JsonObject } from '@agent-device/contracts/client'; +import type { DurableCaptureProgress } from '@agent-device/contracts/durable-resource'; +import type { ScreenRecordingCompletion } from '@agent-device/contracts/screen-recording-runtime'; +import { + RecordingProofIoError, + SCREEN_RECORDING_COMPLETION_METADATA_KEY, + recordingCheckpointError, + recordingExportFileIdentity, +} from '../capture-admission/screen-recording-resource-store.ts'; +import { chunkPathAt } from './output-path.ts'; +import { readStopCheckpoints } from './stop-checkpoints.ts'; +import { deriveRecordingTelemetryPath } from './telemetry.ts'; + +export function verifyRecordingExport( + reservedPath: string, + completion: ScreenRecordingCompletion, + metadata: JsonObject, + progress?: DurableCaptureProgress, +) { + const files = recordingExportFiles(reservedPath, completion); + const stored = metadata.remoteCaptureExport; + if (stored !== undefined) { + const { completedAt, identities } = readRecordingExportProgress(stored, files.length); + if ( + identities.some( + (identity, index) => + identity !== null && readRecordingExportIdentity(files[index]!) !== identity, + ) + ) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its stored proof.'); + } + if (identities.includes(null)) { + if (progress && metadata[SCREEN_RECORDING_COMPLETION_METADATA_KEY] === undefined) + throw new RecordingProofIoError({ remoteCaptureExport: { completedAt, identities } }); + throw missingProducerProof(); + } + return { completedAt, identities }; + } + if (!progress || readStopCheckpoints(metadata).finalization) throw missingProducerProof(); + const evidence = captureRecordingExportEvidence(reservedPath, completion); + if (evidence.remoteCaptureExport.identities.includes(null)) + throw new RecordingProofIoError(evidence); + try { + progress.record(evidence); + } catch (error) { + if (error instanceof RecordingProofIoError) throw new RecordingProofIoError(evidence); + throw error; + } + return evidence.remoteCaptureExport; +} + +/** Capture the identities while the producer still controls the finalized files. */ +export function captureRecordingExportEvidence( + reservedPath: string, + completion: ScreenRecordingCompletion, +) { + const files = recordingExportFiles(reservedPath, completion); + const completedAt = Date.now(); + const identities: (string | null)[] = files.map(() => null); + try { + for (const [index, file] of files.entries()) + identities[index] = readRecordingExportIdentity(file); + } catch (error) { + if (!(error instanceof RecordingProofIoError)) throw error; + } + return { remoteCaptureExport: { completedAt, identities } }; +} + +function recordingExportFiles(reservedPath: string, completion: ScreenRecordingCompletion) { + const files = [ + completion.outPath, + ...(completion.chunks?.slice(1).map((chunk) => chunk.path) ?? []), + ...(completion.telemetryPath ? [completion.telemetryPath] : []), + ]; + const matchesReservation = + completion.outPath === reservedPath && + (completion.chunks?.every( + (chunk, offset) => + chunk.index === offset + 1 && chunk.path === chunkPathAt(reservedPath, chunk.index), + ) ?? + true) && + (completion.telemetryPath === undefined || + completion.telemetryPath === deriveRecordingTelemetryPath(reservedPath)); + if (!matchesReservation) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); + } + return files; +} + +function readRecordingExportProgress(previous: unknown, fileCount: number) { + const { completedAt, identities } = isRecord(previous) ? previous : {}; + if ( + typeof completedAt !== 'number' || + !Number.isFinite(completedAt) || + !Array.isArray(identities) || + identities.length !== fileCount || + !identities.every( + (identity): identity is string | null => identity === null || typeof identity === 'string', + ) + ) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its stored proof.'); + } + return { completedAt, identities }; +} + +function readRecordingExportIdentity(file: string): string { + try { + const identity = recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); + if (identity !== null) return identity; + } catch (error) { + throw recordingCheckpointError(error); + } + throw new RecordingProofIoError(); +} + +function missingProducerProof(): AppError { + return new AppError('COMMAND_FAILED', 'Recording export is missing producer proof.'); +} diff --git a/packages/capture-kit/src/recording/output-path.ts b/packages/capture-kit/src/recording/output-path.ts index c83047f2d5..81863d49c7 100644 --- a/packages/capture-kit/src/recording/output-path.ts +++ b/packages/capture-kit/src/recording/output-path.ts @@ -40,3 +40,18 @@ export function resolveRecordingOutputPaths(params: { outputPath: resolveUserPath(requestedPath, { cwd: params.cwd }), }); } + +/** + * The host path of a recording's `index`th file (1-based). The first file keeps the base path and each + * later one takes a `.part-NNN` suffix. Pulled, served and journaled chunk sets all follow this one + * rule from their own base, which is what lets an attempt that never ran the pull name the files a + * previous attempt left behind. + */ +export function chunkPathAt(basePath: string, index: number): string { + if (index === 1) return basePath; + const parsed = path.parse(basePath); + return path.join( + parsed.dir, + `${parsed.name}.part-${String(index).padStart(3, '0')}${parsed.ext || '.mp4'}`, + ); +} diff --git a/packages/capture-kit/src/recording/stop-sequence.ts b/packages/capture-kit/src/recording/stop-sequence.ts index a7a5787222..4dcd5decbd 100644 --- a/packages/capture-kit/src/recording/stop-sequence.ts +++ b/packages/capture-kit/src/recording/stop-sequence.ts @@ -99,17 +99,13 @@ export async function stopAndExportScreenRecording( exportPath: snapshot.outPath, stoppedAtMs: stoppedAtMs ?? now(), })); - progress?.record(writeStopCheckpoint({ exportPath: snapshot.outPath, finalization })); - // The copy is what a retry re-finalizes from, so it goes only after the finalization it produced is - // journaled: from here a retry replays that finalization and never reads the copy again. - await steps.discard(collectedPath); const { nativePathDisposition, warning, ...exportFacts } = finalization; const warnings = [warning, recorderWarning].filter( (entry): entry is string => entry !== undefined && entry.length > 0, ); // The recorder's disclosure is folded into the warning the caller reads; every other field the // finalizer returned is served as it was journaled, so a replay serves what the first stop would have. - return createScreenRecordingCompletion( + const completion = createScreenRecordingCompletion( snapshot, { ...exportFacts, ...(warnings.length === 0 ? {} : { warning: warnings.join(' ') }) }, { @@ -117,4 +113,21 @@ export async function stopAndExportScreenRecording( ...(nativePathDisposition === undefined ? {} : { nativePathDisposition }), }, ); + const reservedPath = progress?.learned?.remoteCapturePath; + const proof = + learned.finalization === undefined && + typeof reservedPath === 'string' && + typeof progress?.learned?.remoteCaptureReservation === 'string' + ? (await import('./export-proof.ts')).captureRecordingExportEvidence( + reservedPath, + completion.result, + ) + : undefined; + progress?.record({ + ...writeStopCheckpoint({ exportPath: snapshot.outPath, finalization }), + ...proof, + }); + // Keep the collected copy until the finalization and its producer proof are durable together. + await steps.discard(collectedPath); + return completion; } diff --git a/packages/capture-kit/src/screen-recording-live-handle.test.ts b/packages/capture-kit/src/screen-recording-live-handle.test.ts index 59ba4083e5..bc42d60e55 100644 --- a/packages/capture-kit/src/screen-recording-live-handle.test.ts +++ b/packages/capture-kit/src/screen-recording-live-handle.test.ts @@ -126,6 +126,10 @@ test('retried finish re-drives a failed finish and replays a finished one', asyn await assert.rejects(async () => await handle.finish(), /could not confirm the recorder/); assert.deepEqual(await handle.finish(), completed()); assert.deepEqual(await handle.finish(), completed()); + assert.deepEqual(await handle.finish({ learned: undefined, record() {} }), { + ...completed(), + alreadyCompleted: true, + }); assert.equal(finish.mock.calls.length, 2); }); diff --git a/packages/capture-kit/src/screen-recording-live-handle.ts b/packages/capture-kit/src/screen-recording-live-handle.ts index c136e11145..184975353f 100644 --- a/packages/capture-kit/src/screen-recording-live-handle.ts +++ b/packages/capture-kit/src/screen-recording-live-handle.ts @@ -42,7 +42,13 @@ export function createScreenRecordingLiveHandle( // Only a finished recording stays memoized. A finish the host refused has to be re-driven // by the next `record stop`, which is how a recording recovers without a daemon restart. terminalRequested = true; - finish ??= implementation.finish(snapshot, progress).catch((error: unknown) => { + if (finish) { + if (!progress) return finish; + return finish.then((outcome) => + outcome.status === 'completed' ? { ...outcome, alreadyCompleted: true } : outcome, + ); + } + finish = implementation.finish(snapshot, progress).catch((error: unknown) => { finish = undefined; throw error; }); diff --git a/packages/command-surface/src/recording/output-schemas.ts b/packages/command-surface/src/recording/output-schemas.ts index bd8ad1f247..3fe51ab4e5 100644 --- a/packages/command-surface/src/recording/output-schemas.ts +++ b/packages/command-surface/src/recording/output-schemas.ts @@ -46,7 +46,7 @@ export const RECORDING_COMMAND_OUTPUT_SCHEMAS = { activeSessionApp: looseObjectSchema(), showTouches: booleanSchema(), }, - ['recording', 'outPath', 'sessionStateDir', 'showTouches'], + ['recording', 'outPath', 'showTouches'], ), objectSchema( { diff --git a/packages/command-surface/src/replay/index.ts b/packages/command-surface/src/replay/index.ts index 3639075eba..8ab2c22893 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -150,6 +150,18 @@ export const REPLAY_COMMAND_OUTPUT_SCHEMAS = { durationMs: numberSchema(), failures: { type: 'array', items: looseObjectSchema() }, tests: { type: 'array', items: looseObjectSchema() }, + recordingArtifacts: { + type: 'array', + items: objectSchema( + { + session: stringSchema(), + path: stringSchema(), + fileName: stringSchema(), + artifactId: stringSchema(), + }, + ['session'], + ), + }, snapshotDiagnostics: looseObjectSchema(), }, [ diff --git a/packages/contracts/src/facades/replay.ts b/packages/contracts/src/facades/replay.ts index 76f85624a3..7050e4c6d2 100644 --- a/packages/contracts/src/facades/replay.ts +++ b/packages/contracts/src/facades/replay.ts @@ -11,6 +11,7 @@ export type { ReplayScriptSourceBundle, ReplaySuiteAttemptFailure, ReplaySuiteResult, + ReplaySuiteRecordingArtifact, ReplaySuiteTestFailed, ReplaySuiteTestPassed, ReplaySuiteTestResult, diff --git a/packages/contracts/src/recording.ts b/packages/contracts/src/recording.ts index 2b54f9851d..d07998d9b2 100644 --- a/packages/contracts/src/recording.ts +++ b/packages/contracts/src/recording.ts @@ -11,7 +11,7 @@ export type RecordingAppIdentity = { export type RecordingStartCommandResult = { recording: 'started'; outPath: string; - sessionStateDir: string; + sessionStateDir?: string; recordingBackend?: string; recordingScope?: RecordingScope; recordOnlySession?: boolean; diff --git a/packages/contracts/src/replay-test-execution.ts b/packages/contracts/src/replay-test-execution.ts index 1e7022c926..8efe98fc55 100644 --- a/packages/contracts/src/replay-test-execution.ts +++ b/packages/contracts/src/replay-test-execution.ts @@ -187,7 +187,10 @@ export type ReplayTestRunReplay = ( params: ReplayTestRunReplayParams, ) => Promise; -export type ReplayTestCleanupSession = (sessionName: string) => Promise; +export type ReplayTestCleanupSession = ( + sessionName: string, + artifactPaths?: Set, +) => Promise; /** * Runs after the attempt settles and before cleanup. Returns a failure outcome when diff --git a/packages/contracts/src/replay.ts b/packages/contracts/src/replay.ts index 835755bab8..4789fb88a1 100644 --- a/packages/contracts/src/replay.ts +++ b/packages/contracts/src/replay.ts @@ -145,7 +145,18 @@ export type ReplaySuiteTestResult = | ReplaySuiteTestFailed | ReplaySuiteTestSkipped; -export type ReplaySuiteResult = { +export type ReplaySuiteRecordingArtifact = Readonly<{ + session: string; + path?: string; + fileName?: string; + artifactId?: string; +}>; + +type ReplaySuiteRecordingArtifacts = { + recordingArtifacts?: readonly ReplaySuiteRecordingArtifact[]; +}; + +export type ReplaySuiteResult = ReplaySuiteRecordingArtifacts & { total: number; executed: number; passed: number; diff --git a/packages/daemon-contracts/src/device-claim-reconciliation.test.ts b/packages/daemon-contracts/src/device-claim-reconciliation.test.ts index 7c57b61e4b..1552c419b4 100644 --- a/packages/daemon-contracts/src/device-claim-reconciliation.test.ts +++ b/packages/daemon-contracts/src/device-claim-reconciliation.test.ts @@ -241,6 +241,33 @@ const unavailable = Object.freeze({ reason: 'owner-capability-missing' as const, }); +test('a recording awaiting export proof only blocks a claim if native cleanup is unconfirmed', async () => { + const claim = makeClaim(mkdtempForTestSync('device-claim-recording-proof-')); + const store = screenRecordingDurableResource.store; + const resourcePath = store.resolvePath(path.join(claim.stateDir, 'sessions', claim.session)); + const envelope = createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: claim.session, + device: claim.device, + owner: localRuntimeOwner('android'), + fence: { token: 'fence', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: {} }, + }); + const pending = (cleanupStatus: string) => ({ + ...envelope, + metadata: { phase: 'export-proof-pending', cleanupStatus }, + }); + store.write(resourcePath, pending('cleanup-pending')); + expect(inspectDeviceClaimRecovery(claim)).toMatchObject({ recoveryKinds: ['screen-recording'] }); + store.write(resourcePath, pending('cleaned')); + expect(inspectDeviceClaimRecovery(claim)).toEqual({ + status: 'inspectable', + recoveryKinds: [], + ownedResources: [{ resourceKind: 'screen-recording', resourcePath }], + }); +}); + test.each([ { caseName: 'appearing', initiallyOwned: false, mode: 'direct' }, { caseName: 'changing owner', initiallyOwned: true, mode: 'direct' }, diff --git a/packages/daemon-contracts/src/device-claim-reconciliation.ts b/packages/daemon-contracts/src/device-claim-reconciliation.ts index 7e78f19aed..ed62812778 100644 --- a/packages/daemon-contracts/src/device-claim-reconciliation.ts +++ b/packages/daemon-contracts/src/device-claim-reconciliation.ts @@ -1,4 +1,5 @@ import { appLogDurableResource } from '@agent-device/capture-kit/app-log-durable-resource'; +import type { JsonObject } from '@agent-device/contracts/client'; import { recoverAppLogResourceAfterDaemonLock } from '@agent-device/capture-kit/app-log-resource-recovery'; import type { DeviceRuntimeGateway } from '@agent-device/contracts/platform-runtime'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; @@ -14,7 +15,10 @@ import { type DurableSessionResourceKind } from '@agent-device/capture-kit/durab import { recoverPerfCaptureResourceAfterDaemonLock } from '@agent-device/capture-kit/perf-capture-recovery'; import { perfCaptureDurableResource } from '@agent-device/capture-kit/perf-capture-session-resource'; import { recoverScreenRecordingResourceAfterDaemonLock } from '@agent-device/capture-kit/screen-recording-recovery'; -import { screenRecordingDurableResource } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { + screenRecordingDurableResource, + screenRecordingNativeCleanupSettled, +} from '@agent-device/capture-kit/screen-recording-session-resource'; import { resolveSessionDir } from './session-artifact-paths.ts'; export function createDeviceClaimReconciler(params: { @@ -34,7 +38,7 @@ export function createDeviceClaimReconciler(params: { const resource = DEVICE_CLAIM_DURABLE_RESOURCES[resourceKind]; const currentOwnership = inspectResourceOwnership(resource, claim, sessionDir); if (currentOwnership.status === 'retained') return currentOwnership; - if (currentOwnership.status === 'missing') continue; + if (currentOwnership.status === 'missing' || !currentOwnership.requiresRecovery) continue; // Recovery is intentionally sequential: resources can bind the same exact // device/runtime owner, so one must release its binding before the next starts. const outcome = await resource.recover(params, sessionsDir, resourcePath); @@ -134,6 +138,7 @@ export function inspectDeviceClaimRecovery(claim: DeviceClaim): ClaimRecoveryIns type ClaimDurableResource = Readonly<{ resourceKind: DurableSessionResourceKind; + nativeCleanupSettled?(metadata: JsonObject | undefined): boolean; store: | typeof appLogDurableResource.store | typeof screenRecordingDurableResource.store @@ -160,6 +165,7 @@ const DEVICE_CLAIM_DURABLE_RESOURCES = { }, 'screen-recording': { resourceKind: 'screen-recording', + nativeCleanupSettled: screenRecordingNativeCleanupSettled, store: screenRecordingDurableResource.store, recover: async (params, sessionsDir, resourcePath) => await recoverScreenRecordingResourceAfterDaemonLock({ @@ -216,7 +222,13 @@ function inspectResourceOwnership( ) { return { status: 'retained', reason: `${resource.resourceKind}-owner-mismatch` }; } - return { status: 'owned', resourcePath, requiresRecovery: record.envelope.lifecycle === 'open' }; + return { + status: 'owned', + resourcePath, + requiresRecovery: + record.envelope.lifecycle === 'open' && + !resource.nativeCleanupSettled?.(record.envelope.metadata), + }; } /** A failure's code or class, without its message: the message can name a session path. */ diff --git a/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts b/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts index 6b64c2c288..71722363b1 100644 --- a/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts +++ b/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts @@ -104,3 +104,34 @@ const unavailable = Object.freeze({ available: false as const, reason: 'owner-capability-missing' as const, }); + +test('recovery preserves a pending recording proof after native cleanup', async () => { + const sessionsDir = mkdtempForTestSync('screen-recording-proof-recovery-'); + const session = { name: 'session', device }; + const resource = makeTestScreenRecordingResource(session); + const resourcePath = screenRecordingResourceStore.resolvePath( + path.join(sessionsDir, session.name), + ); + const envelope = { + ...resource.envelope, + metadata: { phase: 'export-proof-pending', cleanupStatus: 'already-missing' }, + }; + screenRecordingResourceStore.write(resourcePath, envelope); + const bind = vi.fn(); + const gateway: DeviceRuntimeGateway = { + bind, + inspectFacts: vi.fn(), + shutdown: vi.fn(), + }; + + await expect( + recoverScreenRecordingResourceAfterDaemonLock({ + sessionsDir, + resourcePath, + gateway, + scope, + }), + ).resolves.toBe('ignored'); + expect(bind).not.toHaveBeenCalled(); + expect(screenRecordingResourceStore.read(resourcePath)).toEqual({ status: 'decoded', envelope }); +}); diff --git a/packages/daemon/src/core/session-store.ts b/packages/daemon/src/core/session-store.ts index 5f059b49e1..75e67a1717 100644 --- a/packages/daemon/src/core/session-store.ts +++ b/packages/daemon/src/core/session-store.ts @@ -153,9 +153,9 @@ export class SessionStore { } } - publish(address: string, session: SessionState): SessionRef { + publish(address: string, session: SessionState, journalId = randomUUID()): SessionRef { this.assertPublishable(address); - const entry = { current: session, journalId: randomUUID() }; + const entry = { current: session, journalId }; this.sessions.set(address, entry); for (const retained of this.retainedExecutionHosts.values()) { if (devicesOverlap(retained.device.id, session.device.id)) { @@ -682,6 +682,7 @@ export type AuthorizedSession = Readonly<{ export type AuthorizedOpenSlot = Readonly<{ [openAuthority]: true; + lifetimeId: string; assertPublishable(): void; canPersist(): boolean; publish(draft: Omit): AuthorizedSession; @@ -802,6 +803,7 @@ export class SessionCoordinator { reserve(req: DaemonRequest, address: string): AuthorizedOpenSlot { const admitted = req.internal?.admittedLease; const lease = admitted && sessionLeaseOf(admitted); + const lifetimeId = randomUUID(); let published = false; const active = () => req.internal?.sessionAuthorityActive?.() !== false; const assertPublishable = () => { @@ -812,12 +814,13 @@ export class SessionCoordinator { assertPublishable(); return { [openAuthority]: true, + lifetimeId, assertPublishable, canPersist: () => !published && !this.#store.get(address), publish: (draft) => { assertPublishable(); throwIfRequestCanceled(req.meta?.requestId); - const ref = this.#store.publish(address, { ...draft, lease }); + const ref = this.#store.publish(address, { ...draft, lease }, lifetimeId); published = true; req.internal?.onLifetimePublished?.(address, ref.lifetime); const authority = this.bind(ref, () => active() && !isRequestCanceled(req.meta?.requestId)); diff --git a/packages/daemon/src/resources/artifact-file-storage.ts b/packages/daemon/src/resources/artifact-file-storage.ts new file mode 100644 index 0000000000..620f8205ee --- /dev/null +++ b/packages/daemon/src/resources/artifact-file-storage.ts @@ -0,0 +1,94 @@ +import fs from 'node:fs'; +import { publishDurableFileSync } from '@agent-device/host-kit/file'; +import type { DaemonArtifact } from '@agent-device/kernel/contracts'; +import { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { AppError } from '@agent-device/kernel/errors'; +import { TENANT_RESOURCE_REASONS } from '../core/tenant-owned-entry.ts'; + +export type RecordingFile = DaemonArtifact & { + path: string; + sourceIdentity: string; + artifactId: string; +}; + +function expiredRecording(): AppError { + return new AppError('COMMAND_FAILED', 'Recording output was consumed or expired.', { + reason: TENANT_RESOURCE_REASONS.expired.reason, + }); +} + +export function verifyRecordingFiles(files: readonly RecordingFile[], expiresAt: number): void { + if (Date.now() >= expiresAt) throw expiredRecording(); + for (const file of files) { + if (inspectRecordingPath(consumptionPath(file.path))) { + throw expiredRecording(); + } + const stat = inspectRecordingPath(file.path); + if (!stat) throw expiredRecording(); + if (recordingExportFileIdentity(stat) !== file.sourceIdentity) { + throw new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); + } + } +} + +function inspectRecordingPath(file: string): fs.Stats | undefined { + try { + return fs.lstatSync(file, { throwIfNoEntry: false }); + } catch (error) { + throw new AppError( + 'COMMAND_FAILED', + 'Recording output could not be inspected.', + { retriable: true }, + error, + ); + } +} + +export function retainUnregisteredRecording( + pending: Map>, + reservationId: string, + files: readonly RecordingFile[], + expiresAt: number, +): void { + if (files.length === 0 || pending.has(reservationId)) return; + const expire = () => { + pending.delete(reservationId); + expireUnregisteredSources(files); + }; + if (expiresAt <= Date.now()) expire(); + else pending.set(reservationId, setTimeout(expire, expiresAt - Date.now()).unref()); +} + +export function recordConsumption(file: string, expiresAt: number): void { + const receipt = consumptionPath(file); + publishDurableFileSync({ destination: receipt, contents: 'consumed\n' }); + setTimeout( + () => { + try { + fs.unlinkSync(receipt); + } catch { + // A receipt survives if the directory is inaccessible. + } + }, + Math.max(0, expiresAt - Date.now()), + ).unref(); +} + +function consumptionPath(file: string): string { + return file + '.consumed'; +} + +function expireUnregisteredSources(files: readonly RecordingFile[]): void { + for (const { path, sourceIdentity } of files) { + try { + if ( + recordingExportFileIdentity(fs.lstatSync(path, { throwIfNoEntry: false })) === + sourceIdentity + ) { + fs.unlinkSync(path); + } + } catch { + // Keep files whose identity cannot be established. + } + } +} diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index f547049eef..1279e3a36d 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -1,3 +1,4 @@ +import type { RecordingFile } from './artifact-file-storage.ts'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -30,9 +31,6 @@ import type { SessionRef } from '../core/session-state.ts'; import type { SessionStore } from '../core/session-store.ts'; import { resolveLeaseScope } from '../core/lease-context.ts'; -// --- Leased output ownership --- - -/** The `error.details.reason` values a leased-output refusal publishes. */ const LEASED_OUTPUT_REASONS = { // The request does not send the id of the lease that produced the artifact or diagnostics record. leaseMismatch: { reason: 'LEASE_OUTPUT_MISMATCH' }, @@ -137,9 +135,7 @@ export function diagnosticsRecordOwner(recordId: string): string | undefined | n return owner === UNLEASED_RECORD ? undefined : owner; } -// --- Downloadable artifact tracking --- - -const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; +export const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; const DOWNLOADABLE_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { @@ -177,7 +173,13 @@ type ArtifactEntry = { artifactPath: string; tenantId?: string; leaseVerifier?: string; - reservation?: Readonly<{ directory: string; lifetimeId: string }>; + reservation?: Readonly<{ + directory?: string; + lifetimeId: string; + recording?: true; + awaitingArchive?: boolean; + consume?: () => void; + }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; artifactType: DaemonArtifactType | undefined; @@ -197,6 +199,8 @@ type ArtifactEntry = { type ArtifactTrackingState = { artifacts: Map; reservations: Set<() => void>; + recordingScope: AbortController; + unregisteredRecordings: Map>; uploads: Map; retainedPerformanceSources: Map< string, @@ -211,13 +215,19 @@ const artifactTracking = (): ArtifactTrackingState => (): ArtifactTrackingState => ({ artifacts: new Map(), reservations: new Set(), + recordingScope: new AbortController(), + unregisteredRecordings: new Map(), uploads: new Map(), retainedPerformanceSources: new Map(), }), (state) => { + state.recordingScope.abort( + expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, 'recording'), + ); for (const discard of state.reservations) discard(); for (const [id, entry] of state.artifacts) { - requestArtifactCleanup(state.artifacts, id, entry); + if (!entry.reservation?.recording || entry.cleanupRequested) + requestArtifactCleanup(state.artifacts, id, entry); for (const download of entry.activeDownloads) cancelArtifactDownload(id, entry, download); } for (const entry of state.uploads.values()) { @@ -242,7 +252,6 @@ export function settleCommittedFileOutputs( } } -/** What a finished request registers for each artifact it hands back to the client. */ export type DownloadableArtifactRegistration = { artifactPath: string; tenantId?: string; @@ -311,19 +320,81 @@ export function reserveFileOutput( { directory, lifetimeId }, ); reservations.delete(discard); - const artifact = { ...delivery, artifactType, artifactId: id }; - committedFileOutputDeliveries.set(artifact, (delivered) => { - const entry = artifacts.get(id); - if (!entry) return; - if (delivered) entry.awaitingDelivery = false; - else requestArtifactCleanup(artifacts, id, entry); - }); - return artifact; + return bindFileOutputDelivery(artifacts, { ...delivery, artifactType, artifactId: id }); }, }; } -/** What a request presents to list or download artifacts. */ +function bindFileOutputDelivery( + artifacts: Map, + artifact: DaemonArtifact & { artifactId: string }, +) { + committedFileOutputDeliveries.set(artifact, (delivered) => { + const entry = artifacts.get(artifact.artifactId); + if (!entry) return; + if (delivered) entry.awaitingDelivery = false; + else requestArtifactCleanup(artifacts, artifact.artifactId, entry); + }); + return artifact; +} + +export const recordingRegistrySignal = () => artifactTracking().recordingScope.signal; + +export async function commitRecordingFileOutputs( + files: readonly RecordingFile[], + producer: FileOutputProducer, + sessionName: string, + completedAt: number, + reservationId: string, + publication: 'publish' | 'retain' | 'await-archive' = 'publish', +): Promise { + const { verifyRecordingFiles, recordConsumption, retainUnregisteredRecording } = + await import('./artifact-file-storage.ts'); + const { artifacts, unregisteredRecordings } = artifactTracking(); + const expiresAt = completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS; + const unregistered = files.filter(({ artifactId }) => !artifacts.has(artifactId)); + retainUnregisteredRecording(unregisteredRecordings, reservationId, unregistered, expiresAt); + if (publication === 'retain') return []; + verifyRecordingFiles(files, expiresAt); + const results = files.map(({ path: artifactPath, sourceIdentity, artifactId, ...delivery }) => { + if (!artifacts.has(artifactId)) { + addArtifactEntry( + artifacts, + artifactId, + { + artifactPath, + artifactType: delivery.artifactType, + fileName: delivery.fileName, + tenantId: producer.tenantId, + leaseVerifier: producer.leaseVerifier ?? undefined, + sessionName, + }, + sourceIdentity, + { remainingEntries: 1, deleteAfterDownload: true }, + { + lifetimeId: producer.lifetimeId, + recording: true, + awaitingArchive: publication === 'await-archive', + consume: () => recordConsumption(artifactPath, expiresAt), + }, + completedAt, + ); + } + return { ...delivery, artifactId }; + }); + clearTimeout(unregisteredRecordings.get(reservationId)); + unregisteredRecordings.delete(reservationId); + return results; +} + +export function settleRecordingArchiveCopy(files: readonly RecordingFile[]): void { + const artifacts = pendingArtifacts(); + for (const { artifactId } of files) { + const entry = artifacts.get(artifactId); + if (entry?.reservation?.awaitingArchive) entry.awaitingDelivery = false; + } +} + export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; type PreparedDownloadableArtifact = { @@ -340,12 +411,7 @@ export type OpenedDownloadableArtifact = PreparedDownloadableArtifact & { release: () => void; }; -/** - * Registers one output for download and returns its id. The same output registered again for the - * same tenant and lease returns its existing entry unchanged: two ids for one file would each - * delete it after their own download. An id serves only the output that it registered: another - * output written to the same path gets its own id, and the earlier id expires. - */ +/** Reuses the ID for the same output, tenant, and lease. A replacement file gets its own ID. */ export function trackDownloadableArtifact(params: DownloadableArtifactRegistration): string { const output = readOutputIdentity(params.artifactPath); const existingId = findTrackedArtifactId(params, output); @@ -368,12 +434,15 @@ function addArtifactEntry( output: string | undefined, sourceCleanup: ArtifactSourceCleanup, reservation?: ArtifactEntry['reservation'], + createdAt = Date.now(), ): void { - const createdAt = Date.now(); - const timer = setTimeout(() => { - const entry = artifacts.get(artifactId); - if (entry) requestArtifactCleanup(artifacts, artifactId, entry); - }, ARTIFACT_CLEANUP_TIMEOUT_MS); + const timer = setTimeout( + () => { + const entry = artifacts.get(artifactId); + if (entry) requestArtifactCleanup(artifacts, artifactId, entry); + }, + Math.max(0, createdAt + ARTIFACT_CLEANUP_TIMEOUT_MS - Date.now()), + ); timer.unref(); artifacts.set(artifactId, { artifactPath: params.artifactPath, @@ -388,7 +457,8 @@ function addArtifactEntry( sourceCleanup, activeDownloads: new Set(), cleanupRequested: false, - awaitingDelivery: reservation !== undefined, + awaitingDelivery: + reservation !== undefined && (!reservation.recording || reservation.awaitingArchive === true), createdAt, timer, }); @@ -425,14 +495,22 @@ function findArtifactSourceCleanup( } /** What tells one output at a path from the next one written there. A directory keeps its identity while its entries change. */ -function outputIdentity(stat: fs.Stats): string { +function outputIdentity(stat: fs.Stats, recording = false): string { const inode = `${stat.dev}:${stat.ino}`; - return stat.isDirectory() ? inode : `${inode}:${stat.size}:${stat.mtimeMs}`; + if (stat.isDirectory()) return inode; + const file = `${inode}:${stat.size}:${stat.mtimeMs}`; + return recording ? `${file}:${stat.ctimeMs}` : file; } -function readOutputIdentity(artifactPath: string, noFollow = false): string | undefined { +function readOutputIdentity( + artifactPath: string, + reservation?: { recording?: true }, +): string | undefined { try { - return outputIdentity(noFollow ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath)); + return outputIdentity( + reservation ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath), + reservation?.recording !== undefined, + ); } catch { return undefined; } @@ -542,7 +620,10 @@ function openRegisteredFile(artifactId: string, entry: ArtifactEntry): fs.ReadSt ); try { const stat = fs.fstatSync(fd); - if (!stat.isFile() || outputIdentity(stat) !== entry.output) { + if ( + !stat.isFile() || + outputIdentity(stat, entry.reservation?.recording !== undefined) !== entry.output + ) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -574,9 +655,7 @@ export async function listDownloadableArtifacts( const artifacts: DaemonArtifactInventoryEntry[] = []; for (const [id, entry] of pendingArtifacts()) { if (!canReadArtifact(entry, reader)) continue; - const stat = statRegisteredOutput(id, entry); - if (!stat) continue; - const payload = await prepareArtifactPayloadForInventory(id, entry, stat, hostEnv); + const payload = await prepareArtifactPayloadForInventory(id, entry, hostEnv); if (!payload || entry.cleanupRequested) continue; artifacts.push({ id, @@ -594,12 +673,22 @@ export async function listDownloadableArtifacts( } /** The output that `entry` registered. Cleans the entry up when the output is gone or replaced. */ -function statRegisteredOutput(artifactId: string, entry: ArtifactEntry): fs.Stats | undefined { +function statRegisteredOutput( + artifactId: string, + entry: ArtifactEntry, + downloading = false, +): fs.Stats | undefined { try { const stat = statArtifactPath(entry); - if (outputIdentity(stat) === entry.output) return stat; - } catch { - // A missing output is cleaned up like a replaced one. + if (outputIdentity(stat, entry.reservation?.recording !== undefined) === entry.output) + return stat; + } catch (error) { + const code = (error as NodeJS.ErrnoException).code; + if (entry.reservation?.recording && code !== 'ENOENT' && code !== 'ENOTDIR') throw error; + if (downloading && !entry.reservation?.recording) { + cleanupDownloadableArtifact(artifactId); + throw new AppError('COMMAND_FAILED', `Artifact file is missing: ${entry.artifactPath}`); + } } cleanupDownloadableArtifact(artifactId); return undefined; @@ -608,11 +697,11 @@ function statRegisteredOutput(artifactId: string, entry: ArtifactEntry): fs.Stat async function prepareArtifactPayloadForInventory( artifactId: string, entry: ArtifactEntry, - stat: fs.Stats, hostEnv: NodeJS.ProcessEnv, ): Promise { try { - return await prepareArtifactPayload(artifactId, entry, stat, hostEnv); + const stat = statRegisteredOutput(artifactId, entry); + return stat ? await prepareArtifactPayload(artifactId, entry, stat, hostEnv) : null; } catch { // Inventory is best-effort; direct downloads still surface artifact-specific errors. return null; @@ -639,17 +728,8 @@ function readDownloadableArtifactEntry( if (entry.cleanupRequested) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } - let stat: fs.Stats; - try { - stat = statArtifactPath(entry); - } catch { - cleanupDownloadableArtifact(artifactId); - throw new AppError('COMMAND_FAILED', `Artifact file is missing: ${entry.artifactPath}`); - } - if (outputIdentity(stat) !== entry.output) { - cleanupDownloadableArtifact(artifactId); - throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); - } + const stat = statRegisteredOutput(artifactId, entry, true); + if (!stat) throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); return { entry, stat }; } @@ -806,10 +886,11 @@ function hasUnsafeFilenameCharacter(fileName: string): boolean { ); } -export function cleanupDownloadableArtifact(artifactId: string): void { +export function cleanupDownloadableArtifact(artifactId: string, consumed = false): void { const artifacts = pendingArtifacts(); const entry = artifacts.get(artifactId); if (!entry) return; + if (consumed && !entry.cleanupRequested) entry.reservation?.consume?.(); requestArtifactCleanup(artifacts, artifactId, entry); } @@ -834,11 +915,11 @@ function requestArtifactCleanup( entry.sourceCleanup.remainingEntries === 0 && entry.sourceCleanup.deleteAfterDownload && entry.output !== undefined && - readOutputIdentity(entry.artifactPath, entry.reservation !== undefined) === entry.output + readOutputIdentity(entry.artifactPath, entry.reservation) === entry.output ) { removeBestEffort(entry.artifactPath); } - if (entry.reservation) { + if (entry.reservation?.directory) { try { fs.rmdirSync(entry.reservation.directory); } catch { @@ -861,8 +942,6 @@ function cleanupDirectoryArchive(entry: ArtifactEntry): void { entry.directoryArchive = undefined; } -// --- Upload artifact tracking --- - const UPLOAD_CLEANUP_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes const UPLOADED_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { diff --git a/packages/daemon/src/server/__tests__/request-finalization.test.ts b/packages/daemon/src/server/__tests__/request-finalization.test.ts index 39cb28cda6..59b88fc7b7 100644 --- a/packages/daemon/src/server/__tests__/request-finalization.test.ts +++ b/packages/daemon/src/server/__tests__/request-finalization.test.ts @@ -6,10 +6,7 @@ import type { DaemonArtifactType, DaemonResponse } from '@agent-device/kernel/co import type { DownloadableArtifactRegistration } from '../../resources/artifact-tracking.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { leaseVerifier } from '../../resources/artifact-tracking.ts'; -import { - asDaemonDeliveredArtifact, - withCaptureOutputOwnership, -} from '../../core/capture-output-ownership.ts'; +import { asDaemonDeliveredArtifact } from '../../core/capture-output-ownership.ts'; test('finalizeDaemonResponse preserves handler error hints from details', () => { const req: DaemonRequest = { @@ -75,8 +72,8 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { const req: DaemonRequest = { token: 'token', session: 'default', - command: 'record', - positionals: ['stop'], + command: 'snapshot', + positionals: [], meta: { tenantId: 'tenant-a' }, }; const response: DaemonResponse = { @@ -84,11 +81,11 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { data: { artifacts: [ { - field: 'telemetryPath', - artifactType: 'screen-recording-telemetry', - path: '/tmp/telemetry.json', - localPath: '/client/telemetry.json', - fileName: 'telemetry.json', + field: 'fallbackScreenshotPath', + artifactType: 'screenshot', + path: '/tmp/fallback.png', + localPath: '/client/fallback.png', + fileName: 'fallback.png', }, { field: 'rawPath', @@ -117,11 +114,11 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { data: { artifacts: [ { - field: 'telemetryPath', - artifactType: 'screen-recording-telemetry', + field: 'fallbackScreenshotPath', + artifactType: 'screenshot', artifactId: 'artifact-id-1', - fileName: 'telemetry.json', - localPath: '/client/telemetry.json', + fileName: 'fallback.png', + localPath: '/client/fallback.png', }, { field: 'rawPath', @@ -141,10 +138,10 @@ test('finalizeDaemonResponse registers downloadable artifact type', () => { expect(finalizedArtifacts?.[1]).not.toHaveProperty('artifactType'); expect(tracked).toEqual([ { - artifactPath: '/tmp/telemetry.json', + artifactPath: '/tmp/fallback.png', tenantId: 'tenant-a', - artifactType: 'screen-recording-telemetry', - fileName: 'telemetry.json', + artifactType: 'screenshot', + fileName: 'fallback.png', }, { artifactPath: '/tmp/raw.bin', @@ -365,10 +362,15 @@ test.each([ }, ); -test('a delivered script keeps the admitted lease alongside an unleased recording', () => { +test('a delivered script keeps its admitted lease alongside a committed recording', () => { const lease = new LeaseRegistry().allocateLease({ tenantId: 'tenant', runId: 'record' }); const tracked: DownloadableArtifactRegistration[] = []; - finalizeDaemonResponse( + const recording = { + field: 'outPath', + artifactType: 'screen-recording', + artifactId: 'recording-output', + }; + const response = finalizeDaemonResponse( { token: 'token', session: 'default', @@ -379,32 +381,34 @@ test('a delivered script keeps the admitted lease alongside an unleased recordin }, { ok: true, - data: withCaptureOutputOwnership( - { - artifacts: [ - { field: 'outPath', artifactType: 'screen-recording', path: '/daemon/video.mp4' }, - asDaemonDeliveredArtifact( - { - field: 'savedScript', - artifactType: 'session-script', - path: '/daemon/session.ad', - }, - 'tenant', - ), - ], - }, - 'daemon', - undefined, - null, - ), + data: { + artifacts: [ + recording, + asDaemonDeliveredArtifact( + { + field: 'savedScript', + artifactType: 'session-script', + path: '/daemon/session.ad', + }, + 'tenant', + ), + ], + }, }, (entry) => { tracked.push(entry); - return 'artifact'; + return 'script-output'; }, ); - expect(tracked.map((artifact) => [artifact.tenantId, artifact.leaseVerifier])).toEqual([ - ['tenant', undefined], - ['tenant', leaseVerifier(lease.leaseId)], + expect(tracked).toEqual([ + expect.objectContaining({ + tenantId: 'tenant', + leaseVerifier: leaseVerifier(lease.leaseId), + artifactType: 'session-script', + }), ]); + expect(response).toMatchObject({ + ok: true, + data: { artifacts: [recording, { field: 'savedScript', artifactId: 'script-output' }] }, + }); }); diff --git a/packages/daemon/src/server/downloadable-artifact-http.ts b/packages/daemon/src/server/downloadable-artifact-http.ts index 35443e9ad4..8de8938c11 100644 --- a/packages/daemon/src/server/downloadable-artifact-http.ts +++ b/packages/daemon/src/server/downloadable-artifact-http.ts @@ -130,7 +130,12 @@ async function handleArtifactDownload( transform(chunk: Buffer, _encoding, callback) { bytesRead += chunk.length; if (bytesRead >= artifact.sizeBytes && options.retainArtifacts !== true) { - cleanupDownloadableArtifact(artifactId); + try { + cleanupDownloadableArtifact(artifactId, true); + } catch (error) { + callback(error as Error); + return; + } } callback(null, chunk); }, @@ -145,8 +150,12 @@ async function handleArtifactDownload( ); return; } - if (options.retainArtifacts !== true) cleanupDownloadableArtifact(artifactId); - callback(); + try { + if (options.retainArtifacts !== true) cleanupDownloadableArtifact(artifactId, true); + callback(); + } catch (error) { + callback(error as Error); + } }, }); await pipeline(stream, checked, res, { signal: artifact.signal }); diff --git a/packages/daemon/src/server/http/http-server-capture-publication.test.ts b/packages/daemon/src/server/http/http-server-capture-publication.test.ts index 022233f64c..2fd6285f86 100644 --- a/packages/daemon/src/server/http/http-server-capture-publication.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-publication.test.ts @@ -18,8 +18,10 @@ import { screenshotRuntimeFixture } from '../../__tests__/support/screenshot-run import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts'; import { sessionLeaseOf } from '../../core/lease-context.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { trackDownloadableArtifact } from '../../resources/artifact-tracking.ts'; -import { finalizeDaemonResponse } from '../request-finalization.ts'; +import { + settleCommittedFileOutputs, + trackDownloadableArtifact, +} from '../../resources/artifact-tracking.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; import { successfulData, withHttp } from './http-output.fixtures.ts'; @@ -276,17 +278,29 @@ test('direct HTTP recording replay requires known remote output provenance', asy const { remoteCaptureLease: _owner, ...metadata } = record.envelope.metadata ?? {}; screenRecordingResourceStore.write(resourcePath, { ...record.envelope, metadata }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + async (request) => { + const response = await harness.run( + request.positionals, + request.meta, + request.flags, + request.internal, + ); + if (response.ok) settleCommittedFileOutputs(response.data?.artifacts, true); + return response; + }, async (post, base) => { const replay = async () => await post({ command: 'record', positionals: ['stop'] }, false); expect((await replay()).error?.data?.details).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH', }); + const { remoteCaptureReservation: _reservation, ...unreserved } = metadata; + screenRecordingResourceStore.write(resourcePath, { + ...record.envelope, + metadata: { ...unreserved, remoteCaptureLease: 'unleased' }, + }); + expect((await replay()).error?.data?.details).toMatchObject({ + reason: 'LEASE_OUTPUT_MISMATCH', + }); const savedCompletion = metadata.completion; if ( !savedCompletion || @@ -318,6 +332,7 @@ test('direct HTTP recording replay requires known remote output provenance', asy const data = successfulData(await replay()); expect(data.artifacts?.[0]?.localPath).toBe(clientPath); const id = data.artifacts?.[0]?.artifactId; + expect(id).toBe(`${record.envelope.fence.token}-1`); const download = await fetch(`${base}/artifacts/${id}`, { headers: { authorization: 'Bearer test-token' }, }); diff --git a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index 89642bd698..fffb4bc835 100644 --- a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts @@ -10,6 +10,8 @@ import { } from '@agent-device/test-kit'; import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { markRequestCanceled } from '@agent-device/host-kit/request'; import { defineUse } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createDaemonHttpServer } from './http-server.ts'; @@ -20,12 +22,16 @@ import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { listDownloadableArtifacts, - trackDownloadableArtifact, + cleanupDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; -test.each([false, true])( - 'local stop keeps the producing tenant for a remote recording (client destination: %s)', - async (clientDestination) => { +test.each([ + { clientDestination: false, cancelStop: false }, + { clientDestination: true, cancelStop: false }, + { clientDestination: true, cancelStop: true }, +])( + 'local stop keeps the producing tenant for a remote recording ($clientDestination, stop canceled: $cancelStop)', + async ({ clientDestination, cancelStop }) => { const root = mkdtempForTestSync('capture-producing-tenant-'); const tenantId = 'tenant-a'; const sessionName = tenantScopedSessionName(tenantId, 'capture'); @@ -42,6 +48,32 @@ test.each([false, true])( fs.writeFileSync(input.outputPath, 'private-recording'); return await start(input); }); + const finish = harness.runtime.finish.getMockImplementation()!; + const canceledStopId = 'recording-response-canceled'; + let cancelNextFinish = cancelStop; + harness.runtime.finish.mockImplementation(async () => { + const stopped = await finish(); + if (cancelNextFinish) { + cancelNextFinish = false; + markRequestCanceled(canceledStopId); + } + const { result } = stopped; + const chunk = result.outPath.replace(/\.mp4$/, '.part-002.mp4'); + const telemetryPath = deriveRecordingTelemetryPath(result.outPath); + fs.writeFileSync(chunk, 'second-chunk'); + fs.writeFileSync(telemetryPath, '{"events":[]}'); + return { + ...stopped, + result: { + ...result, + telemetryPath, + chunks: [ + { index: 1, path: result.outPath }, + { index: 2, path: chunk }, + ], + }, + }; + }); const recordingUse = defineUse({ required: ['screenRecordingStart', 'screenRecordingReattach', 'screenRecordingCleanup'], }); @@ -69,7 +101,9 @@ test.each([false, true])( bind: async ({ device }) => await recordingBinding(device), shutdown: async () => {}, }, - trackDownloadableArtifact, + trackDownloadableArtifact: () => { + throw new Error('Recording must be committed before request finalization'); + }, }); const hookPath = path.join(root, 'auth-hook.mjs'); fs.writeFileSync( @@ -108,19 +142,42 @@ test.each([false, true])( const startBody = await started.json(); expect(startBody.result?.ok, JSON.stringify(startBody)).toBe(true); - const stop = async () => + const stop = async (requestId?: string) => await handleRequest({ token: 'capture-token', session: sessionName, command: 'record', positionals: ['stop'], - meta: { leaseId: lease.leaseId }, + meta: { leaseId: lease.leaseId, requestId }, + }); + if (cancelStop) { + expect(await stop(canceledStopId)).toMatchObject({ + ok: false, + error: { details: { reason: 'request_canceled' } }, }); + const owner = { tenantId, leaseId: lease.leaseId }; + const retained = await listDownloadableArtifacts(owner, {}); + expect(retained.map((entry) => entry.artifactType)).toEqual([ + 'screen-recording', + 'screen-recording-chunk', + 'screen-recording-telemetry', + ]); + expect(await listDownloadableArtifacts({ tenantId }, {})).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId, leaseId: 'f'.repeat(32) }, {})).toEqual( + [], + ); + expect(await listDownloadableArtifacts({ ...owner, tenantId: 'tenant-b' }, {})).toEqual([]); + } const stopped = await stop(); expect(stopped.ok, JSON.stringify(stopped)).toBe(true); if (!stopped.ok) return; const artifactId = stopped.data?.artifacts?.[0]?.artifactId; expect(artifactId).toBeTypeOf('string'); + expect(stopped.data?.artifacts?.map(({ field, path }) => [field, path])).toEqual([ + ['outPath', undefined], + ['chunkPath', undefined], + ['telemetryPath', undefined], + ]); expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, {})).toEqual([]); expect( (await listDownloadableArtifacts({ tenantId, leaseId: lease.leaseId }, {})).some( @@ -137,6 +194,16 @@ test.each([false, true])( headers: { authorization: 'Bearer capture-token', 'x-tenant': 'tenant-b' }, }); expect(otherTenant.status).toBe(401); + for (const leaseId of [undefined, 'f'.repeat(32)]) { + const denied = await fetch(`${base}/artifacts/${artifactId}`, { + headers: { + authorization: 'Bearer capture-token', + ...(leaseId ? { [DAEMON_HTTP_LEASE_HEADER]: leaseId } : {}), + }, + }); + expect(denied.status).toBe(401); + expect(await denied.json()).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH' }); + } const ownTenant = await fetch(`${base}/artifacts/${artifactId}`, { headers: { authorization: 'Bearer capture-token', @@ -146,6 +213,38 @@ test.each([false, true])( }); expect(ownTenant.status).toBe(200); expect(await ownTenant.text()).toBe('private-recording'); + const sourcePath = harness.runtime.start.mock.calls[0]![0].outputPath; + // A consumed export cannot be re-minted from a replacement written at that path. + await expect.poll(() => fs.existsSync(sourcePath)).toBe(false); + expect(await stop()).toMatchObject({ + ok: false, + error: { code: 'COMMAND_FAILED', details: { reason: 'RESOURCE_EXPIRED' } }, + }); + fs.writeFileSync(sourcePath, 'unrelated-replacement'); + expect(await stop()).toMatchObject({ ok: false }); + expect(fs.readFileSync(sourcePath, 'utf8')).toBe('unrelated-replacement'); + for (const [index, bytes] of [ + [1, 'second-chunk'], + [2, '{"events":[]}'], + ] as const) { + const sidecar = await fetch( + `${base}/artifacts/${stopped.data?.artifacts?.[index]?.artifactId}`, + { + headers: { + authorization: 'Bearer capture-token', + [DAEMON_HTTP_LEASE_HEADER]: lease.leaseId, + }, + }, + ); + expect(sidecar.status).toBe(200); + expect(await sidecar.text()).toBe(bytes); + } + for (const { id } of await listDownloadableArtifacts( + { tenantId, leaseId: lease.leaseId }, + {}, + )) { + cleanupDownloadableArtifact(id); + } } finally { await closeLoopbackServer(server); } diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index f4d219b406..93eaa2d650 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -32,10 +32,10 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, + settleCommittedFileOutputs, trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { localEnv, successfulData, withHttp } from './http-output.fixtures.ts'; -import { finalizeDaemonResponse } from '../request-finalization.ts'; import { runBatchCommands } from '../../sessions/handlers/session-batch.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; @@ -258,6 +258,20 @@ test('local HTTP still honors capture destinations and cwd', async () => { ); }); +async function handleRecordingRequest( + harness: ReturnType, + request: DaemonRequest, +) { + const response = await harness.run( + request.positionals, + request.meta, + request.flags, + request.internal, + ); + if (response.ok) settleCommittedFileOutputs(response.data?.artifacts, true); + return response; +} + test('remote recording without client metadata stays in its session and downloads by ID', async () => { const harness = makeRecordRuntimeHarness('remote-record-output-'); const root = mkdtempForTestSync('remote-record-victim-'); @@ -269,12 +283,7 @@ test('remote recording without client metadata stays in its session and download return await start(input); }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + (request) => handleRecordingRequest(harness, request), async (post, base) => { const started = await post({ command: 'record', @@ -282,14 +291,16 @@ test('remote recording without client metadata stays in its session and download meta: { cwd: root }, }); expect(started.result?.ok).toBe(true); - const output = started.result?.data?.outPath as string; - expect(path.dirname(output)).toBe( + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(path.dirname(source)).toBe( harness.sessionStore.resolveSessionDir(harness.sessionName), ); - expect(output).toMatch(/recording-[0-9a-f-]+\.mp4$/); + expect(started.result?.data?.outPath).toBe(path.basename(source)); + expect(started.result?.data?.sessionStateDir).toBeUndefined(); expect(fs.readFileSync(victim, 'utf8')).toBe('protected-content'); const stopped = await post({ command: 'record', positionals: ['stop'] }); expect(stopped.result?.ok).toBe(true); + expect(stopped.result?.data?.outPath).toBe(path.basename(source)); const artifact = stopped.result?.data?.artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { @@ -313,12 +324,7 @@ test.each(['local', 'local-client-destination', 'remote'] as const)( return await start(input); }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + (request) => handleRecordingRequest(harness, request), async (post) => { const started = await post( { @@ -331,10 +337,11 @@ test.each(['local', 'local-client-destination', 'remote'] as const)( origin === 'remote', ); expect(started.result?.ok, JSON.stringify(started)).toBe(true); - const stopped = await post( - { command: 'record', positionals: ['stop'] }, - origin !== 'remote', - ); + if (origin !== 'remote') { + const refused = await post({ command: 'record', positionals: ['stop'] }, true); + expect(refused.error?.data?.details).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH' }); + } + const stopped = await post({ command: 'record', positionals: ['stop'] }, false); expect(stopped.result?.ok, JSON.stringify(stopped)).toBe(true); const artifactId = stopped.result?.data?.artifacts?.[0]?.artifactId; if (origin === 'remote') { @@ -687,12 +694,11 @@ test('batch recording keeps remote origin and generates a session-owned destinat async (request) => await harness.run(request.positionals, request.meta, request.flags, request.internal), ); - expect(response.ok).toBe(true); - if (!response.ok) return; + if (!response.ok) throw new Error(response.error.message); const results = response.data?.results as Array<{ data: { outPath: string } }>; - expect(path.dirname(results[0]!.data.outPath)).toBe( - harness.sessionStore.resolveSessionDir(harness.sessionName), - ); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(path.dirname(source)).toBe(harness.sessionStore.resolveSessionDir(harness.sessionName)); + expect(results[0]!.data.outPath).toBe(path.basename(source)); await harness.run(['stop']); }); diff --git a/packages/daemon/src/server/http/http-server-remote-suite.test.ts b/packages/daemon/src/server/http/http-server-remote-suite.test.ts new file mode 100644 index 0000000000..d958f977a1 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-remote-suite.test.ts @@ -0,0 +1,74 @@ +import path from 'node:path'; +import { gunzipSync } from 'node:zlib'; +import { expect, test } from 'vitest'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; +import { createRequestHandler } from '../../__tests__/support/test-device-runtime-gateway.ts'; +import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { LeaseRegistry } from '../../resources/lease-registry.ts'; +import { + cleanupDownloadableArtifact, + trackDownloadableArtifact, +} from '../../resources/artifact-tracking.ts'; +import { successfulData, withHttp } from './http-output.fixtures.ts'; + +test('trusted remote suites with a repeated request ID download distinct archives', async () => { + const root = mkdtempForTestSync('trusted-remote-suite-'); + const scriptPath = path.join(root, 'flow.ad'); + const sessionStore = makeSessionStore('trusted-remote-suite-session-'); + const handler = createRequestHandler({ + host: createTestHostEnvironment({ cwd: root, env: {} }), + createCommandSurface: screenshotCommandSurface, + logPath: path.join(root, 'daemon.log'), + token: 'test-token', + sessionStore, + leaseRegistry: new LeaseRegistry(), + deviceInventoryGateways: createTestDeviceInventoryGateways(), + trackDownloadableArtifact, + }); + await withHttp(handler, async (post, base) => { + const run = async (marker: string) => { + const source = `# ${marker}\ncontext platform=android\nwait 0\n`; + const data = successfulData( + await post( + { + command: 'test', + session: 'capture', + positionals: [scriptPath], + flags: { + replayScriptSources: [{ entry: scriptPath, files: { [scriptPath]: source } }], + }, + meta: { + requestId: 'repeat-request', + clientArtifactPaths: { artifactsDir: '/client/downloads' }, + }, + }, + false, + ), + ); + expect(data.executed).toBe(1); + return data.artifacts![0]!.artifactId!; + }; + const first = await run('first-archive-only'); + const second = await run('second-archive-only'); + try { + expect(first).not.toBe(second); + for (const [id, wanted, unwanted] of [ + [first, 'first-archive-only', 'second-archive-only'], + [second, 'second-archive-only', 'first-archive-only'], + ] as const) { + const response = await fetch(`${base}/artifacts/${id}`, { + headers: { authorization: 'Bearer test-token' }, + }); + expect(response.status).toBe(200); + const archive = gunzipSync(Buffer.from(await response.arrayBuffer())); + expect(archive.includes(Buffer.from(wanted))).toBe(true); + expect(archive.includes(Buffer.from(unwanted))).toBe(false); + } + } finally { + cleanupDownloadableArtifact(first); + cleanupDownloadableArtifact(second); + } + }); +}); diff --git a/packages/daemon/src/server/request-finalization.ts b/packages/daemon/src/server/request-finalization.ts index 0d54e6fddc..22493d84e4 100644 --- a/packages/daemon/src/server/request-finalization.ts +++ b/packages/daemon/src/server/request-finalization.ts @@ -184,7 +184,9 @@ function registerDownloadableArtifacts( scriptRevision: artifact.scriptRevision, }; }; - if (captureOutputOwnership(data) === 'caller') { + const isRecordingStop = + req.command === 'record' && req.positionals?.[0]?.toLowerCase() === 'stop'; + if (captureOutputOwnership(data) === 'caller' || isRecordingStop) { // Caller-owned capture output stays at the caller path; a daemon-delivered artifact still registers. if (!data.artifacts?.some(daemonDeliveredArtifact)) return data; return { diff --git a/packages/daemon/src/server/request-router.ts b/packages/daemon/src/server/request-router.ts index 86f2fc0347..8dfc6e7f75 100644 --- a/packages/daemon/src/server/request-router.ts +++ b/packages/daemon/src/server/request-router.ts @@ -792,7 +792,15 @@ async function finalizeRequestBindingCleanup( let finalResponse = response; try { await scope[Symbol.asyncDispose](); - if (response.ok && scope.command === 'screenshot') scope.throwIfCanceled(); + if ( + response.ok && + (scope.command === 'screenshot' || + (scope.command === 'record' && + response.data?.recording === 'stopped' && + response.data.artifacts?.some((artifact) => artifact.artifactId))) + ) { + scope.throwIfCanceled(); + } } catch (cleanupError) { if (response.ok) { finalResponse = finalizeThrownRequestError(cleanupError); diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts deleted file mode 100644 index f7487e568d..0000000000 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ /dev/null @@ -1,436 +0,0 @@ -import fs from 'node:fs'; -import http from 'node:http'; -import path from 'node:path'; -import { afterEach, expect, test, vi } from 'vitest'; -import { - IOS_SIMULATOR, - closeLoopbackServer, - listenOnLoopback, - mkdtempForTestSync, - skipWhenLoopbackUnavailable, -} from '@agent-device/test-kit'; -import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; -import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; -import { resolveScreenRecordingStopRecovery } from '@agent-device/capture-kit/screen-recording-stop-recovery'; -import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; -import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; -import type { - ScreenRecordingCompletion, - ScreenRecordingLiveHandle, -} from '@agent-device/contracts/screen-recording-runtime'; -import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; -import { makeIosSession } from '../../__tests__/support/session-factories.ts'; -import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; -import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; -import type { SessionStore } from '../../core/session-store.ts'; -import type { SessionState } from '../../core/session-state.ts'; -import { - cleanupDownloadableArtifact, - leaseVerifier, - listDownloadableArtifacts, - trackDownloadableArtifact, -} from '../../resources/artifact-tracking.ts'; -import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; -import { tryHandleDownloadableArtifactHttpRoute } from '../../server/downloadable-artifact-http.ts'; -import { finalizeDaemonResponse } from '../../server/request-finalization.ts'; -import { buildRecordingStopResponse } from '../handlers/record-runtime-response.ts'; -import { teardownSessionResources } from '../session-teardown.ts'; -import { makeRecordRuntimeHarness } from '../handlers/__tests__/record-runtime.fixtures.ts'; - -const tracking = vi.hoisted(() => ({ failOnCall: 0, calls: 0 })); -vi.mock('../../resources/artifact-tracking.ts', async (importOriginal) => { - const actual = await importOriginal(); - return { - ...actual, - trackDownloadableArtifact: ( - ...args: Parameters - ): string => { - tracking.calls += 1; - if (tracking.calls === tracking.failOnCall) throw new Error('registration failed'); - return actual.trackDownloadableArtifact(...args); - }, - }; -}); - -const TENANT = 'tenant-a'; -const LEASE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; -const OWNER = { tenantId: TENANT, leaseId: LEASE_ID }; -const ADDRESS = `${TENANT}:checkout-flow`; -const createdPaths: string[] = []; - -afterEach(async () => { - for (const { id } of await listDownloadableArtifacts(OWNER, process.env)) { - cleanupDownloadableArtifact(id); - } - for (const filePath of createdPaths.splice(0)) fs.rmSync(filePath, { force: true }); - tracking.failOnCall = 0; - tracking.calls = 0; - vi.useRealTimers(); -}); - -type RecordingExport = { - outPath: string; - clientOutPath?: string; - telemetryPath: string; - daemonOwned?: true; -}; - -function remoteRecordingExport(): RecordingExport { - const outPath = path.join(mkdtempForTestSync('daemon-recording-export-'), 'checkout.mp4'); - return { - outPath, - clientOutPath: '/Users/client/checkout.mp4', - daemonOwned: true, - telemetryPath: deriveRecordingTelemetryPath(outPath), - }; -} - -function localRecordingExport(): RecordingExport { - const outPath = path.join(mkdtempForTestSync('agent-device-local-recording-'), 'checkout.mp4'); - return { outPath, telemetryPath: deriveRecordingTelemetryPath(outPath) }; -} - -/** Publishes a session whose live recording finishes into `recordingExport`, or fails to stop. */ -function publishRecordingSession( - sessionStore: SessionStore, - recordingExport: RecordingExport, - options: { - leased?: boolean; - finishFails?: boolean; - unleasedProducer?: boolean; - producerTenant?: string; - } = {}, -) { - const session: SessionState = makeIosSession(ADDRESS, { - appBundleId: 'com.example.app', - ...(options.leased === false - ? {} - : { - lease: { leaseId: LEASE_ID, tenantId: TENANT, runId: 'run-1', backend: 'ios-simulator' }, - }), - }); - const completion: ScreenRecordingCompletion = { - backend: 'simctl recordVideo', - outPath: recordingExport.outPath, - ...(recordingExport.clientOutPath ? { clientOutPath: recordingExport.clientOutPath } : {}), - telemetryPath: recordingExport.telemetryPath, - startedAt: Date.now() - 5_000, - completedAt: Date.now(), - scope: 'app', - showTouches: true, - recordOnlySession: false, - }; - const finish = vi.fn(async () => { - if (options.finishFails) { - return { - status: 'cleanup-pending', - reason: 'transport-failed', - message: 'failed to stop recording', - } as const; - } - createdPaths.push(recordingExport.outPath, recordingExport.telemetryPath); - fs.writeFileSync(recordingExport.outPath, 'video'); - fs.writeFileSync(recordingExport.telemetryPath, '{"events":[]}'); - return { status: 'completed', result: completion } as const; - }); - const forceCleanup = vi.fn(async () => ({ status: 'cleaned' }) as const); - const handle: ScreenRecordingLiveHandle = { - inspect: () => ({ ...completion, gestureEvents: [] }), - appendGestureEvents: () => {}, - setTouchReferenceFrame: () => {}, - setRunnerSessionId: () => {}, - invalidate: () => {}, - finish, - forceCleanup, - [Symbol.asyncDispose]: async () => {}, - }; - const envelope = createDurableResourceEnvelope({ - resourceKind: 'screen-recording', - sessionId: ADDRESS, - device: { id: session.device.id, family: 'apple', appleOs: 'ios', kind: 'simulator' }, - owner: localRuntimeOwner('apple'), - fence: { token: 'recording-fence', generation: 1 }, - lifecycle: 'open', - descriptor: { version: 1, body: { recordingId: 'checkout-flow' } }, - metadata: { - phase: 'active', - ...(recordingExport.daemonOwned ? { remoteCaptureOutput: true } : {}), - ...(options.unleasedProducer && !options.producerTenant - ? {} - : { remoteCaptureTenantId: options.producerTenant ?? TENANT }), - remoteCaptureLease: - options.leased === false || options.unleasedProducer ? 'unleased' : leaseVerifier(LEASE_ID), - }, - }); - session.screenRecording = { handle, envelope }; - screenRecordingResourceStore.write( - screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), - envelope, - ); - return { ref: sessionStore.publish(ADDRESS, session), finish, forceCleanup }; -} - -async function teardown(sessionStore: SessionStore) { - await teardownSessionResources({ - appLog: 'already-settled', - ref: sessionStore.lookup(ADDRESS)!, - sessionStore, - platformCleanup: platformResourceCleanupFixture(), - }); -} - -test('a leased session teardown keeps the remote recording export downloadable by its lease', async () => { - const sessionStore = makeSessionStore('agent-device-leased-recording-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport); - - await teardown(sessionStore); - - const artifacts = await listDownloadableArtifacts(OWNER, process.env); - expect(artifacts).toEqual([ - expect.objectContaining({ - artifactType: 'screen-recording', - filename: 'checkout.mp4', - sessionName: 'checkout-flow', - }), - expect.objectContaining({ - artifactType: 'screen-recording-telemetry', - filename: path.basename(recordingExport.telemetryPath), - sessionName: 'checkout-flow', - }), - ]); - expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, process.env)).toEqual([]); - expect(await listDownloadableArtifacts({ tenantId: TENANT }, process.env)).toEqual([]); -}); - -test('a retained recording is deleted once its lease holder downloads it', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - const sessionStore = makeSessionStore('agent-device-leased-recording-download-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport); - await teardown(sessionStore); - const [video] = await listDownloadableArtifacts(OWNER, process.env); - const server = http.createServer((req, res) => { - tryHandleDownloadableArtifactHttpRoute({ - req, - res, - authorize: async () => ({ tenantId: TENANT }), - hostEnv: process.env, - }); - }); - const port = await listenOnLoopback(server); - try { - const url = `http://127.0.0.1:${port}/artifacts/${video!.id}`; - const refused = await fetch(url); - expect(refused.status).toBe(401); - expect(await refused.json()).toMatchObject({ - code: 'UNAUTHORIZED', - reason: 'LEASE_OUTPUT_MISMATCH', - field: 'leaseId', - }); - - const response = await fetch(url, { headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID } }); - - expect(await response.text()).toBe('video'); - await vi.waitFor(() => expect(fs.existsSync(recordingExport.outPath)).toBe(false)); - expect( - (await listDownloadableArtifacts(OWNER, process.env)).map((a) => a.artifactType), - ).toEqual(['screen-recording-telemetry']); - } finally { - await closeLoopbackServer(server); - } -}); - -test('a retained recording nobody downloads is deleted when it expires', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); - const sessionStore = makeSessionStore('agent-device-leased-recording-expiry-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport); - await teardown(sessionStore); - expect(await listDownloadableArtifacts(OWNER, process.env)).toHaveLength(2); - - await vi.advanceTimersByTimeAsync(15 * 60 * 1000); - - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); - expect(fs.existsSync(recordingExport.outPath)).toBe(false); - expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); -}); - -test('a failed teardown finish runs forced cleanup and keeps nothing for download', async () => { - const sessionStore = makeSessionStore('agent-device-leased-recording-failed-'); - const { forceCleanup } = publishRecordingSession(sessionStore, remoteRecordingExport(), { - finishFails: true, - }); - - await expect(teardown(sessionStore)).rejects.toThrow(/recording: .*failed to stop recording/); - - expect(forceCleanup).toHaveBeenCalledOnce(); - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); -}); - -test('a leased teardown that cannot register the export deletes it instead of leaking it', async () => { - tracking.failOnCall = 2; - const sessionStore = makeSessionStore('agent-device-leased-recording-unregistered-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport); - - await teardown(sessionStore); - - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); - expect(fs.existsSync(recordingExport.outPath)).toBe(false); - expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); -}); - -test('a record stop replay after a leased teardown serves the artifacts teardown kept', async () => { - const sessionStore = makeSessionStore('agent-device-leased-recording-replay-'); - publishRecordingSession(sessionStore, remoteRecordingExport()); - await teardown(sessionStore); - const retained = await listDownloadableArtifacts(OWNER, process.env); - - const recovery = resolveScreenRecordingStopRecovery({ - sessionName: ADDRESS, - sessionStore, - device: IOS_SIMULATOR, - }); - if (recovery.kind !== 'completed') throw new Error(`expected a replay, got ${recovery.kind}`); - const stopped = buildRecordingStopResponse(recovery.completion); - if (!stopped.ok || !stopped.data) throw new Error('expected a stop response'); - // The stop handler names the lease of the manifest as the owner of a replayed export. - const replayed = finalizeDaemonResponse( - { - token: 't', - session: ADDRESS, - command: 'record', - positionals: ['stop'], - flags: {}, - meta: { tenantId: TENANT }, - }, - { - ok: true, - data: withCaptureOutputOwnership(stopped.data, 'daemon', TENANT, leaseVerifier(LEASE_ID)), - }, - trackDownloadableArtifact, - ); - - expect(replayed.ok && replayed.data?.artifacts?.map((a) => a.artifactId)).toEqual( - retained.map((a) => a.id), - ); - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ - expect.objectContaining({ id: retained[0]!.id, sessionName: 'checkout-flow' }), - expect.objectContaining({ id: retained[1]!.id, sessionName: 'checkout-flow' }), - ]); - // The replay registers under the lease of the manifest, so it opens no second way to the files. - expect(await listDownloadableArtifacts({ tenantId: TENANT }, process.env)).toEqual([]); -}); - -test.each([undefined, '/client/local-copy.mp4'])( - 'a leased teardown leaves a local caller export at its path and registers nothing with client destination %s', - async (clientOutPath) => { - const sessionStore = makeSessionStore('agent-device-leased-recording-local-'); - const recordingExport = { ...localRecordingExport(), clientOutPath }; - publishRecordingSession(sessionStore, recordingExport); - - await teardown(sessionStore); - - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); - expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); - }, -); - -test('an unleased session teardown registers nothing for a remote export', async () => { - const sessionStore = makeSessionStore('agent-device-unleased-recording-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport, { leased: false }); - - await teardown(sessionStore); - - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); - expect(await listDownloadableArtifacts({}, process.env)).toEqual([]); - expect(fs.existsSync(recordingExport.outPath)).toBe(true); -}); - -test.each([undefined, '/client/downloads/checkout.mp4'])( - 'remote admission retains session-owned recordings after leased teardown with client destination %s', - async (clientOutPath) => { - const harness = makeRecordRuntimeHarness('leased-remote-session-recording-', { - sessionName: ADDRESS, - lease: { - backend: 'ios-simulator', - leaseId: LEASE_ID, - tenantId: TENANT, - runId: 'run-1', - }, - }); - const start = harness.runtime.start.getMockImplementation()!; - harness.runtime.start.mockImplementation(async (input) => { - fs.writeFileSync(input.outputPath, 'session-owned-video'); - return await start(input); - }); - const started = await harness.run( - ['start'], - clientOutPath ? { clientArtifactPaths: { outPath: clientOutPath } } : undefined, - undefined, - { - publicNetworkOnly: true, - admittedLease: { - leaseId: LEASE_ID, - tenantId: TENANT, - runId: 'run-1', - backend: 'android-instance', - createdAt: 0, - heartbeatAt: 0, - expiresAt: 0, - }, - }, - ); - expect(started.ok).toBe(true); - const output = harness.runtime.start.mock.calls[0]![0].outputPath; - expect(path.dirname(output)).toBe(harness.sessionStore.resolveSessionDir(ADDRESS)); - - await teardown(harness.sessionStore); - - const artifacts = await listDownloadableArtifacts(OWNER, process.env); - expect(artifacts).toEqual([ - expect.objectContaining({ - artifactType: 'screen-recording', - filename: path.basename(clientOutPath ?? output), - sessionName: 'checkout-flow', - }), - ]); - expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, process.env)).toEqual([]); - expect(fs.readFileSync(output, 'utf8')).toBe('session-owned-video'); - expect( - screenRecordingResourceStore.read( - screenRecordingResourceStore.resolvePath(harness.sessionStore.resolveSessionDir(ADDRESS)), - ), - ).toMatchObject({ - status: 'decoded', - envelope: { lifecycle: 'completed', metadata: { remoteCaptureOutput: true } }, - }); - cleanupDownloadableArtifact(artifacts[0]!.id); - expect(fs.existsSync(output)).toBe(false); - }, -); - -test.each([undefined, 'former-tenant'])( - 'teardown assigns an unleased recording with producer tenant %s to the session lease tenant', - async (producerTenant) => { - const sessionStore = makeSessionStore('agent-device-unleased-recording-'); - publishRecordingSession(sessionStore, remoteRecordingExport(), { - unleasedProducer: true, - producerTenant, - }); - - await teardown(sessionStore); - - expect( - await listDownloadableArtifacts({ tenantId: producerTenant ?? 'tenant-b' }, process.env), - ).toEqual([]); - const artifacts = await listDownloadableArtifacts({ tenantId: TENANT }, process.env); - expect(artifacts).toEqual( - expect.arrayContaining([ - expect.objectContaining({ artifactType: 'screen-recording', filename: 'checkout.mp4' }), - ]), - ); - }, -); diff --git a/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts b/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts new file mode 100644 index 0000000000..1b3822436d --- /dev/null +++ b/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts @@ -0,0 +1,988 @@ +import fs from 'node:fs'; +import { randomUUID } from 'node:crypto'; +import http from 'node:http'; +import { gunzipSync } from 'node:zlib'; +import path from 'node:path'; +import { afterEach, expect, test, vi } from 'vitest'; +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { + IOS_SIMULATOR, + closeLoopbackServer, + listenOnLoopback, + mkdtempForTestSync, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { finishPendingScreenRecordingProof } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { resolveScreenRecordingStopRecovery } from '@agent-device/capture-kit/screen-recording-stop-recovery'; +import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import type { + ScreenRecordingCompletion, + ScreenRecordingLiveHandle, +} from '@agent-device/contracts/screen-recording-runtime'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { makeIosSession } from '../../__tests__/support/session-factories.ts'; +import { makeSessionStore } from '../../__tests__/support/store-factory.ts'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import type { SessionStore } from '../../core/session-store.ts'; +import type { SessionState } from '../../core/session-state.ts'; +import { + cleanupDownloadableArtifact, + trackDownloadableArtifact, + leaseVerifier, + listDownloadableArtifacts, + openDownloadableArtifact, + settleCommittedFileOutputs, +} from '../../resources/artifact-tracking.ts'; +import { tryHandleDownloadableArtifactHttpRoute } from '../../server/downloadable-artifact-http.ts'; +import { collectSuiteRecordingOutputs, commitRecordingOutputs } from '../recording-outputs.ts'; +import { teardownSessionResources } from '../session-teardown.ts'; +import { makeRecordRuntimeHarness } from '../handlers/__tests__/record-runtime.fixtures.ts'; + +const TENANT = 'tenant-a'; +const LEASE_ID = 'a1b2c3d4e5f60718293a4b5c6d7e8f90'; +const OWNER = { tenantId: TENANT, leaseId: LEASE_ID }; +const ADDRESS = `${TENANT}:checkout-flow`; +const createdPaths: string[] = []; + +afterEach(async () => { + for (const { id } of await listDownloadableArtifacts(OWNER, process.env)) { + cleanupDownloadableArtifact(id); + } + for (const filePath of createdPaths.splice(0)) fs.rmSync(filePath, { force: true }); + vi.useRealTimers(); +}); + +type RecordingExport = { + outPath: string; + clientOutPath?: string; + telemetryPath: string; + daemonOwned?: true; +}; + +function remoteRecordingExport(): RecordingExport { + const outPath = path.join(mkdtempForTestSync('daemon-recording-export-'), 'checkout.mp4'); + return { + outPath, + clientOutPath: '/Users/client/checkout.mp4', + daemonOwned: true, + telemetryPath: deriveRecordingTelemetryPath(outPath), + }; +} + +function localRecordingExport(): RecordingExport { + const outPath = path.join(mkdtempForTestSync('agent-device-local-recording-'), 'checkout.mp4'); + return { outPath, telemetryPath: deriveRecordingTelemetryPath(outPath) }; +} + +/** Publishes a session whose live recording finishes into `recordingExport`, or fails to stop. */ +function publishRecordingSession( + sessionStore: SessionStore, + recordingExport: RecordingExport, + options: { + leased?: boolean; + finishFails?: boolean; + unleasedProducer?: boolean; + producerTenant?: string; + omitTelemetry?: boolean; + legacy?: boolean; + } = {}, +) { + const session: SessionState = makeIosSession(ADDRESS, { + appBundleId: 'com.example.app', + ...(options.leased === false + ? {} + : { + lease: { leaseId: LEASE_ID, tenantId: TENANT, runId: 'run-1', backend: 'ios-simulator' }, + }), + }); + const completion: ScreenRecordingCompletion = { + backend: 'simctl recordVideo', + outPath: recordingExport.outPath, + ...(recordingExport.clientOutPath ? { clientOutPath: recordingExport.clientOutPath } : {}), + telemetryPath: recordingExport.telemetryPath, + startedAt: Date.now() - 5_000, + completedAt: Date.now(), + scope: 'app', + showTouches: true, + recordOnlySession: false, + }; + const finish = vi.fn(async () => { + if (options.finishFails) { + return { + status: 'cleanup-pending', + reason: 'transport-failed', + message: 'failed to stop recording', + } as const; + } + createdPaths.push(recordingExport.outPath, recordingExport.telemetryPath); + fs.writeFileSync(recordingExport.outPath, 'video'); + if (!options.omitTelemetry) fs.writeFileSync(recordingExport.telemetryPath, '{"events":[]}'); + return { status: 'completed', result: completion } as const; + }); + const forceCleanup = vi.fn(async () => ({ status: 'cleaned' }) as const); + const handle: ScreenRecordingLiveHandle = { + inspect: () => ({ ...completion, gestureEvents: [] }), + appendGestureEvents: () => {}, + setTouchReferenceFrame: () => {}, + setRunnerSessionId: () => {}, + invalidate: () => {}, + finish, + forceCleanup, + [Symbol.asyncDispose]: async () => {}, + }; + const lifetimeId = randomUUID(); + const envelope = createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: ADDRESS, + device: { id: session.device.id, family: 'apple', appleOs: 'ios', kind: 'simulator' }, + owner: localRuntimeOwner('apple'), + fence: { token: path.basename(path.dirname(recordingExport.outPath)), generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: { recordingId: 'checkout-flow' } }, + metadata: { + phase: 'active', + ...(recordingExport.daemonOwned + ? { + remoteCaptureOutput: true, + ...(!options.legacy + ? { + remoteCapturePath: recordingExport.outPath, + remoteCaptureLifetime: lifetimeId, + remoteCaptureReservation: path.basename(path.dirname(recordingExport.outPath)), + } + : {}), + } + : {}), + ...(options.unleasedProducer && !options.producerTenant + ? {} + : { + remoteCaptureTenantId: + options.leased === false ? null : (options.producerTenant ?? TENANT), + }), + remoteCaptureLease: + options.leased === false || options.unleasedProducer ? 'unleased' : leaseVerifier(LEASE_ID), + }, + }); + session.screenRecording = { handle, envelope }; + screenRecordingResourceStore.write( + screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), + envelope, + ); + return { ref: sessionStore.publish(ADDRESS, session, lifetimeId), finish, forceCleanup }; +} + +async function teardown(sessionStore: SessionStore) { + await teardownSessionResources({ + appLog: 'already-settled', + ref: sessionStore.lookup(ADDRESS)!, + sessionStore, + platformCleanup: platformResourceCleanupFixture(), + }); +} + +test('a leased session teardown keeps the remote recording export downloadable by its lease', async () => { + const sessionStore = makeSessionStore('agent-device-leased-recording-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport); + + await teardown(sessionStore); + + const artifacts = await listDownloadableArtifacts(OWNER, process.env); + expect(artifacts).toEqual([ + expect.objectContaining({ + artifactType: 'screen-recording', + filename: 'checkout.mp4', + sessionName: 'checkout-flow', + }), + expect.objectContaining({ + artifactType: 'screen-recording-telemetry', + filename: path.basename(recordingExport.telemetryPath), + sessionName: 'checkout-flow', + }), + ]); + expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, process.env)).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, process.env)).toEqual([]); + expect( + await listDownloadableArtifacts({ tenantId: TENANT, leaseId: 'f'.repeat(32) }, process.env), + ).toEqual([]); +}); + +test('a retained recording is deleted once its lease holder downloads it', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const sessionStore = makeSessionStore('agent-device-leased-recording-download-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport); + await teardown(sessionStore); + const [video] = await listDownloadableArtifacts(OWNER, process.env); + const server = http.createServer((req, res) => { + tryHandleDownloadableArtifactHttpRoute({ + req, + res, + authorize: async () => ({ tenantId: TENANT }), + hostEnv: process.env, + }); + }); + const port = await listenOnLoopback(server); + try { + const url = `http://127.0.0.1:${port}/artifacts/${video!.id}`; + const refused = await fetch(url); + expect(refused.status).toBe(401); + expect(await refused.json()).toMatchObject({ + code: 'UNAUTHORIZED', + reason: 'LEASE_OUTPUT_MISMATCH', + field: 'leaseId', + }); + + const response = await fetch(url, { headers: { [DAEMON_HTTP_LEASE_HEADER]: LEASE_ID } }); + + expect(await response.text()).toBe('video'); + await vi.waitFor(() => expect(fs.existsSync(recordingExport.outPath)).toBe(false)); + expect( + (await listDownloadableArtifacts(OWNER, process.env)).map((a) => a.artifactType), + ).toEqual(['screen-recording-telemetry']); + } finally { + await closeLoopbackServer(server); + } +}); + +test('a retained recording nobody downloads is deleted when it expires', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const sessionStore = makeSessionStore('agent-device-leased-recording-expiry-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport); + await teardown(sessionStore); + expect(await listDownloadableArtifacts(OWNER, process.env)).toHaveLength(2); + + await vi.advanceTimersByTimeAsync(15 * 60 * 1000); + + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); + expect(fs.existsSync(recordingExport.outPath)).toBe(false); + expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); +}); + +test('a failed teardown finish runs forced cleanup and keeps nothing for download', async () => { + const sessionStore = makeSessionStore('agent-device-leased-recording-failed-'); + const { forceCleanup } = publishRecordingSession(sessionStore, remoteRecordingExport(), { + finishFails: true, + }); + + await expect(teardown(sessionStore)).rejects.toThrow(/recording: .*failed to stop recording/); + + expect(forceCleanup).toHaveBeenCalledOnce(); + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); +}); + +test('teardown with a missing sidecar keeps its source and publishes no partial recording', async () => { + const sessionStore = makeSessionStore('agent-device-leased-recording-unregistered-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport, { omitTelemetry: true }); + + await teardown(sessionStore); + + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); + expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); + expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); +}); + +test('a record stop replay after a leased teardown serves the artifacts teardown kept', async () => { + const sessionStore = makeSessionStore('agent-device-leased-recording-replay-'); + publishRecordingSession(sessionStore, remoteRecordingExport()); + await teardown(sessionStore); + const retained = await listDownloadableArtifacts(OWNER, process.env); + + const recovery = resolveScreenRecordingStopRecovery({ + sessionName: ADDRESS, + sessionStore, + device: IOS_SIMULATOR, + }); + if (recovery.kind !== 'completed') throw new Error(`expected a replay, got ${recovery.kind}`); + const record = screenRecordingResourceStore.read( + screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), + ); + if (record.status !== 'decoded') throw new Error('Expected completed recording manifest'); + const artifacts = await commitRecordingOutputs(record.envelope, 'replay'); + + expect(artifacts.map((artifact) => artifact.artifactId)).toEqual(retained.map((a) => a.id)); + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ + expect.objectContaining({ id: retained[0]!.id, sessionName: 'checkout-flow' }), + expect.objectContaining({ id: retained[1]!.id, sessionName: 'checkout-flow' }), + ]); + // The replay registers under the lease of the manifest, so it opens no second way to the files. + expect(await listDownloadableArtifacts({ tenantId: TENANT }, process.env)).toEqual([]); +}); + +test.each([undefined, '/client/local-copy.mp4'])( + 'a leased teardown leaves a local caller export at its path and registers nothing with client destination %s', + async (clientOutPath) => { + const sessionStore = makeSessionStore('agent-device-leased-recording-local-'); + const recordingExport = { ...localRecordingExport(), clientOutPath }; + publishRecordingSession(sessionStore, recordingExport); + + await teardown(sessionStore); + + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); + expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); + }, +); + +test('an unleased session teardown registers nothing for a remote export', async () => { + const sessionStore = makeSessionStore('agent-device-unleased-recording-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport, { leased: false }); + + await teardown(sessionStore); + + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); + expect(await listDownloadableArtifacts({}, process.env)).toEqual([]); + expect(fs.existsSync(recordingExport.outPath)).toBe(true); +}); + +test.each([undefined, '/client/downloads/checkout.mp4'])( + 'remote admission retains session-owned recordings after leased teardown with client destination %s', + async (clientOutPath) => { + const harness = makeRecordRuntimeHarness('leased-remote-session-recording-', { + sessionName: ADDRESS, + lease: { + backend: 'ios-simulator', + leaseId: LEASE_ID, + tenantId: TENANT, + runId: 'run-1', + }, + }); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'session-owned-video'); + return await start(input); + }); + const started = await harness.run( + ['start'], + clientOutPath ? { clientArtifactPaths: { outPath: clientOutPath } } : undefined, + undefined, + { + publicNetworkOnly: true, + admittedLease: { + leaseId: LEASE_ID, + tenantId: TENANT, + runId: 'run-1', + backend: 'android-instance', + createdAt: 0, + heartbeatAt: 0, + expiresAt: 0, + }, + }, + ); + expect(started.ok).toBe(true); + const output = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(path.dirname(output)).toBe(harness.sessionStore.resolveSessionDir(ADDRESS)); + + await teardown(harness.sessionStore); + + const artifacts = await listDownloadableArtifacts(OWNER, process.env); + expect(artifacts).toEqual([ + expect.objectContaining({ + artifactType: 'screen-recording', + filename: path.basename(clientOutPath ?? output), + sessionName: 'checkout-flow', + }), + ]); + expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, process.env)).toEqual([]); + expect(fs.readFileSync(output, 'utf8')).toBe('session-owned-video'); + expect( + screenRecordingResourceStore.read( + screenRecordingResourceStore.resolvePath(harness.sessionStore.resolveSessionDir(ADDRESS)), + ), + ).toMatchObject({ + status: 'decoded', + envelope: { lifecycle: 'completed', metadata: { remoteCaptureOutput: true } }, + }); + cleanupDownloadableArtifact(artifacts[0]!.id); + expect(fs.existsSync(output)).toBe(false); + }, +); + +test.each([ + [undefined, true], + ['former-tenant', true], + [TENANT, false], +] as const)( + 'teardown preserves proof-less files for legacy producer %s (unleased: %s)', + async (producerTenant, unleasedProducer) => { + const sessionStore = makeSessionStore('agent-device-unleased-recording-'); + const output = remoteRecordingExport(); + publishRecordingSession(sessionStore, output, { + legacy: true, + unleasedProducer, + producerTenant, + }); + + await teardown(sessionStore); + + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId: producerTenant }, {})).toEqual([]); + expect(await listDownloadableArtifacts(OWNER, {})).toEqual([]); + expect(fs.readFileSync(output.outPath, 'utf8')).toBe('video'); + }, +); + +test('fresh runtime slots can restore an intact recording from its producer manifest', async () => { + const harness = makeRecordRuntimeHarness('verified-recording-restart-'); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'surviving-original-export'); + return await start(input); + }); + const producer = createRuntimeStateHandle(); + const successor = createRuntimeStateHandle(); + const missingScope = createRuntimeStateHandle(); + const remote = { publicNetworkOnly: true } as const; + let originalId: string | undefined; + try { + await producer.run(async () => { + expect(await harness.run(['start'], { tenantId: TENANT }, undefined, remote)).toMatchObject({ + ok: true, + }); + const stopped = await harness.run(['stop'], { tenantId: TENANT }, undefined, remote); + if (!stopped.ok) throw new Error(stopped.error.message); + originalId = stopped.data?.artifacts?.[0]?.artifactId; + expect(originalId).toBeTypeOf('string'); + }); + producer.dispose(); + await successor.run(async () => { + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + expect(await harness.run(['stop'], { tenantId: 'other' }, undefined, remote)).toMatchObject({ + ok: false, + error: { code: 'UNAUTHORIZED' }, + }); + const stopped = await harness.run(['stop'], { tenantId: TENANT }, undefined, remote); + if (!stopped.ok) throw new Error(stopped.error.message); + expect(stopped.data?.artifacts?.[0]?.artifactId).toBe(originalId); + settleCommittedFileOutputs(stopped.data?.artifacts, true); + expect(await listDownloadableArtifacts({ tenantId: 'other' }, {})).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([ + expect.objectContaining({ artifactType: 'screen-recording' }), + ]); + }); + await missingScope.run(async () => { + const resourcePath = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(harness.sessionName), + ); + const record = screenRecordingResourceStore.read(resourcePath); + if (record.status !== 'decoded') throw new Error('Missing verified recording manifest'); + const { remoteCaptureTenantId: _tenant, ...metadata } = record.envelope.metadata!; + screenRecordingResourceStore.write(resourcePath, { ...record.envelope, metadata }); + expect(await harness.run(['stop'], { tenantId: 'other' }, undefined, remote)).toMatchObject({ + ok: false, + error: { code: 'UNAUTHORIZED' }, + }); + expect(await listDownloadableArtifacts({ tenantId: 'other' }, {})).toEqual([]); + }); + } finally { + missingScope.dispose(); + successor.dispose(); + producer.dispose(); + } +}); + +test('a failed completion manifest read never returns uncommitted remote paths', async () => { + const harness = makeRecordRuntimeHarness('recording-completion-proof-io-'); + const run = (action: string) => + harness.run([action], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }); + expect(await run('start')).toMatchObject({ ok: true }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(source, 'completed-video'); + const resourcePath = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(harness.sessionName), + ); + const lstat = fs.lstatSync; + let failed = false; + const inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if ( + file === resourcePath && + !failed && + fs.readFileSync(resourcePath, 'utf8').includes('"lifecycle":"completed"') + ) { + failed = true; + throw Object.assign(new Error('manifest unavailable'), { code: 'EIO' }); + } + return lstat(file, options); + }); + try { + expect(await run('stop')).toMatchObject({ ok: false, error: { code: 'COMMAND_FAILED' } }); + expect(failed).toBe(true); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } finally { + inspect.mockRestore(); + } + expect(await run('stop')).toMatchObject({ + ok: true, + data: { artifacts: [{ artifactId: expect.any(String) }] }, + }); +}); + +test('a transient inspection error preserves the recording and other inventory entries', async () => { + const harness = makeRecordRuntimeHarness('recording-inspection-retry-'); + const runtime = createRuntimeStateHandle(); + const run = (action: string) => + harness.run([action], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }); + try { + await runtime.run(async () => { + expect(await run('start')).toMatchObject({ ok: true }); + const video = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(video, 'published-video'); + const published = await run('stop'); + expect(published).toMatchObject({ + ok: true, + data: { artifacts: [{ artifactId: expect.any(String) }] }, + }); + if (!published.ok) throw new Error('Recording was not published'); + const recordingId = published.data?.artifacts?.[0]?.artifactId; + const healthy = path.join(mkdtempForTestSync('healthy-recording-inventory-'), 'frame.png'); + fs.writeFileSync(healthy, 'healthy artifact'); + const healthyId = trackDownloadableArtifact({ + artifactPath: healthy, + artifactType: 'screenshot', + tenantId: TENANT, + }); + const lstat = fs.lstatSync; + let failed = false; + const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === video && !failed) { + failed = true; + throw Object.assign(new Error('inspection I/O failed'), { code: 'EIO' }); + } + return lstat(file, options); + }); + try { + const result = await run('stop'); + expect(result).toMatchObject({ + ok: false, + error: { code: 'COMMAND_FAILED', message: 'Recording output could not be inspected.' }, + }); + expect(fs.readFileSync(video, 'utf8')).toBe('published-video'); + expect(await run('stop')).toEqual(published); + + const reader = { tenantId: TENANT }; + failed = false; + expect((await listDownloadableArtifacts(reader, {})).map(({ id }) => id)).toEqual([ + healthyId, + ]); + expect((await listDownloadableArtifacts(reader, {})).map(({ id }) => id)).toEqual( + expect.arrayContaining([recordingId, healthyId]), + ); + expect(fs.readFileSync(video, 'utf8')).toBe('published-video'); + } finally { + stat.mockRestore(); + } + }); + } finally { + runtime.dispose(); + } +}); + +async function startSuiteRecording(withSidecar = false) { + const suite = mkdtempForTestSync('archive-recording-retention-'); + const video = path.join(suite, 'recording.mp4'); + const harness = makeRecordRuntimeHarness('archive-recording-stop-', { + sessionName: ADDRESS, + suiteCapture: 'remote', + lease: { backend: 'android-instance', leaseId: LEASE_ID, tenantId: TENANT, runId: 'run-1' }, + }); + const meta = { + tenantId: TENANT, + leaseId: LEASE_ID, + clientArtifactPaths: { artifactsDir: '/client' }, + }; + const internal = { + publicNetworkOnly: true, + admittedLease: { + leaseId: LEASE_ID, + tenantId: TENANT, + runId: 'run-1', + backend: 'android-instance', + createdAt: 0, + heartbeatAt: 0, + expiresAt: 0, + }, + } as const; + const stop = () => harness.run(['stop'], meta, undefined, internal); + expect(await harness.run(['start', video], meta, undefined, internal)).toMatchObject({ + ok: true, + }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(source.startsWith(suite + path.sep)).toBe(false); + fs.writeFileSync(source, 'leased-suite-recording'); + if (withSidecar) { + const telemetryPath = deriveRecordingTelemetryPath(source); + fs.writeFileSync(telemetryPath, '{}'); + const finish = harness.runtime.finish.getMockImplementation()!; + harness.runtime.finish.mockImplementation(async () => { + const outcome = await finish(); + return { ...outcome, result: { ...outcome.result, telemetryPath } }; + }); + } + const collect = () => + collectSuiteRecordingOutputs(harness.sessionStore, harness.sessionStore.lookup(ADDRESS)!); + return { suite, video, source, stop, collect, harness }; +} + +test('transient manifest I/O cannot bypass a completed recording lease', async () => { + const { stop, harness, source } = await startSuiteRecording(); + expect(await stop()).toMatchObject({ ok: true }); + const resourcePath = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(ADDRESS), + ); + const lstat = fs.lstatSync; + let fail = true; + const inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === resourcePath && fail) { + fail = false; + throw Object.assign(new Error('manifest unavailable'), { code: 'EIO' }); + } + return lstat(file, options); + }); + const unleasedStop = () => + harness.run(['stop'], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }); + try { + expect(await unleasedStop()).toMatchObject({ ok: false, error: { code: 'COMMAND_FAILED' } }); + expect(fail).toBe(false); + expect(await unleasedStop()).toMatchObject({ ok: false, error: { code: 'UNAUTHORIZED' } }); + expect(fs.readFileSync(source, 'utf8')).toBe('leased-suite-recording'); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } finally { + inspect.mockRestore(); + } +}); + +test('close persists verified files before retrying an unreadable sidecar', async () => { + const { harness, source, stop } = await startSuiteRecording(true); + const sidecar = deriveRecordingTelemetryPath(source); + const resourcePath = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(ADDRESS), + ); + const stat = fs.lstatSync; + const unreadable = (target: string) => + vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === target) throw Object.assign(new Error(`cannot read ${target}`), { code: 'EIO' }); + return stat(file, options); + }); + const inspection = unreadable(sidecar); + try { + await teardown(harness.sessionStore); + } finally { + inspection.mockRestore(); + } + const pending = screenRecordingResourceStore.read(resourcePath); + expect(pending).toMatchObject({ + status: 'decoded', + envelope: { + lifecycle: 'open', + metadata: { + phase: 'export-proof-pending', + cleanupStatus: 'cleaned', + remoteCaptureExport: { + identities: [expect.any(String), null], + }, + }, + }, + }); + if (pending.status !== 'decoded') throw new Error('Expected a pending export'); + const manifest = unreadable(resourcePath); + try { + await expect( + finishPendingScreenRecordingProof(resourcePath, pending.envelope), + ).rejects.toMatchObject({ + message: 'Recording ownership proof could not be read.', + details: { retriable: true }, + }); + } finally { + manifest.mockRestore(); + } + + fs.writeFileSync(sidecar, 'unproved sidecar'); + await expect(stop()).resolves.toMatchObject({ + ok: false, + error: { message: 'Recording export is missing producer proof.' }, + }); + fs.writeFileSync(source, 'replacement before retry'); + await expect(stop()).resolves.toMatchObject({ + ok: false, + error: { message: 'Recording export does not match its stored proof.' }, + }); + expect(await listDownloadableArtifacts(OWNER, {})).toEqual([]); +}); + +test.each(['expiry', 'disposal'])( + 'stalled recording staging settles on %s before the writer', + async (end) => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const runtime = createRuntimeStateHandle(); + const { video, stop, collect } = await runtime.run(() => startSuiteRecording(true)); + const stopped = await runtime.run(stop); + if (!stopped.ok) throw new Error(stopped.error.message); + const artifactId = stopped.data!.artifacts![0]!.artifactId!; + let enter!: (target: string) => void; + const entered = new Promise((resolve) => { + enter = resolve; + }); + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const copy = fs.promises.copyFile; + const staging = vi.spyOn(fs.promises, 'copyFile').mockImplementationOnce(async (...args) => { + enter(String(args[1])); + await gate; + await copy(...args); + }); + let outcome: Awaited> | undefined; + const stopping = runtime.run(collect).then((result) => { + outcome = result; + }); + try { + const target = await entered; + await expect( + runtime.run(() => openDownloadableArtifact(artifactId, OWNER, {})), + ).rejects.toMatchObject({ + details: { reason: 'RESOURCE_EXPIRED' }, + }); + if (end === 'disposal') runtime.dispose(); + await vi.advanceTimersByTimeAsync(end === 'expiry' ? 15 * 60 * 1000 : 0); + expect(outcome).toMatchObject([ + { artifactId: expect.any(String) }, + { artifactId: expect.any(String) }, + ]); + expect(fs.existsSync(path.dirname(target))).toBe(true); + expect(staging).toHaveBeenCalledTimes(1); + release(); + await vi.waitFor(() => expect(fs.existsSync(path.dirname(target))).toBe(false)); + expect(staging).toHaveBeenCalledTimes(1); + expect(fs.existsSync(video)).toBe(false); + expect(await runtime.run(() => listDownloadableArtifacts(OWNER, {}))).toEqual([]); + } finally { + release(); + await stopping; + staging.mockRestore(); + runtime.dispose(); + } + }, +); + +for (const first of ['archive', 'recording']) { + test(`the producing lease retries after consuming the ${first} first`, async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { suite, video, source, stop, collect } = await startSuiteRecording(); + const stopped = await stop(); + if (!stopped.ok) throw new Error(stopped.error.message); + const recording = stopped.data!.artifacts![0]!; + expect(await listDownloadableArtifacts(OWNER, {})).toEqual([]); + expect(await collect()).toMatchObject([{ path: video, artifactId: recording.artifactId }]); + const archiveId = trackDownloadableArtifact({ + artifactPath: suite, + artifactType: 'test-artifacts', + tenantId: TENANT, + leaseVerifier: leaseVerifier(LEASE_ID), + }); + const server = http.createServer((req, res) => { + tryHandleDownloadableArtifactHttpRoute({ + req, + res, + authorize: async () => ({ tenantId: TENANT }), + hostEnv: process.env, + }); + }); + const port = await listenOnLoopback(server); + const get = (id: string, leaseId: string) => + fetch(`http://127.0.0.1:${port}/artifacts/${id}`, { + headers: { [DAEMON_HTTP_LEASE_HEADER]: leaseId }, + }); + try { + const consumeArchive = async () => { + const archive = await get(archiveId, LEASE_ID); + expect(archive.status).toBe(200); + expect( + gunzipSync(Buffer.from(await archive.arrayBuffer())).includes( + Buffer.from('leased-suite-recording'), + ), + ).toBe(true); + await vi.waitFor(() => expect(fs.existsSync(suite)).toBe(false)); + }; + const consumeRecording = async () => { + const refused = await get(recording.artifactId!, 'f'.repeat(32)); + expect(refused.status).toBe(401); + const download = await get(recording.artifactId!, LEASE_ID); + expect(download.status).toBe(200); + expect(await download.text()).toBe('leased-suite-recording'); + }; + if (first === 'archive') { + await consumeArchive(); + expect(await stop()).toMatchObject({ ok: true, data: { artifacts: [recording] } }); + await consumeRecording(); + } else { + const rm = fs.rmSync; + const retain = vi.spyOn(fs, 'rmSync').mockImplementation((target, options) => { + if (target !== source) return rm(target, options); + throw Object.assign(new Error('unlink interrupted'), { code: 'EIO' }); + }); + try { + await consumeRecording(); + await vi.waitFor(async () => + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ + expect.objectContaining({ id: archiveId }), + ]), + ); + } finally { + retain.mockRestore(); + } + expect(fs.readFileSync(source, 'utf8')).toBe('leased-suite-recording'); + await vi.waitFor(async () => + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ + expect.objectContaining({ id: archiveId }), + ]), + ); + expect(fs.readFileSync(video, 'utf8')).toBe('leased-suite-recording'); + const expired = { ok: false, error: { details: { reason: 'RESOURCE_EXPIRED' } } }; + expect(await stop()).toMatchObject(expired); + const restarted = createRuntimeStateHandle(); + try { + expect(await restarted.run(stop)).toMatchObject(expired); + } finally { + restarted.dispose(); + } + await consumeArchive(); + } + await vi.waitFor(async () => + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]), + ); + } finally { + cleanupDownloadableArtifact(archiveId); + cleanupDownloadableArtifact(recording.artifactId!); + await closeLoopbackServer(server); + } + }); +} + +test.each([1, 2])( + 'a transient stat failure on read %d permits retry only with producer proof', + async (failureRead) => { + const harness = makeRecordRuntimeHarness('recording-verification-retry-'); + const runtime = createRuntimeStateHandle(); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'original-export'); + return await start(input); + }); + const remote = { publicNetworkOnly: true } as const; + try { + await runtime.run(async () => { + const run = async (action: string) => + await harness.run([action], { tenantId: TENANT }, undefined, remote); + expect(await run('start')).toMatchObject({ ok: true }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + const lstat = fs.lstatSync; + let sourceReads = 0; + const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source && ++sourceReads === failureRead) { + throw Object.assign(new Error('transient stat failure'), { code: 'EIO' }); + } + return lstat(file, options); + }); + try { + expect(await run('stop')).toMatchObject({ ok: false }); + expect(sourceReads).toBe(failureRead); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } finally { + stat.mockRestore(); + } + const result = await run('stop'); + expect(result).toMatchObject( + failureRead === 1 + ? { ok: false, error: { message: 'Recording export is missing producer proof.' } } + : { + ok: true, + data: { recording: 'stopped', artifacts: [{ artifactId: expect.any(String) }] }, + }, + ); + expect(fs.readFileSync(source, 'utf8')).toBe('original-export'); + }); + } finally { + runtime.dispose(); + } + }, +); + +test.each([ + ['teardown', false, 'timer'], + ['teardown', true, 'timer'], + ['stop', false, 'timer'], + ['stop', true, 'timer'], + ['stop', false, 'replay'], + ['stop', true, 'replay'], +] as const)( + 'failed %s registration expires only the verified original (replaced: %s) on %s', + async (action, replace, expiry) => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const harness = makeRecordRuntimeHarness('recording-cleanup-expiry-', { sessionName: ADDRESS }); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'verified-export'); + return await start(input); + }); + expect( + await harness.run(['start'], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }), + ).toMatchObject({ ok: true }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + const lstat = fs.lstatSync; + let sourceReads = 0; + const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source && ++sourceReads === 2) + throw Object.assign(new Error('registry stat unavailable'), { code: 'EIO' }); + return lstat(file, options); + }); + const runtime = createRuntimeStateHandle(); + try { + await runtime.run(async () => { + if (action === 'stop') + expect( + await harness.run(['stop'], { tenantId: TENANT }, undefined, { + publicNetworkOnly: true, + }), + ).toMatchObject({ ok: false }); + await teardown(harness.sessionStore); + expect(sourceReads).toBe(2); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + }); + } finally { + stat.mockRestore(); + runtime.dispose(); + } + + await vi.advanceTimersByTimeAsync(14 * 60 * 1000); + expect(fs.readFileSync(source, 'utf8')).toBe('verified-export'); + if (replace) { + const unrelated = source + '.replacement'; + fs.writeFileSync(unrelated, 'unrelated-recording'); + fs.renameSync(unrelated, source); + } + if (expiry === 'timer') { + await vi.advanceTimersByTimeAsync(60 * 1000); + } else { + // Move the clock without dispatching the old runtime's timer. The manifest has the deadline. + vi.setSystemTime(Date.now() + 60 * 1000); + const successor = createRuntimeStateHandle(); + try { + expect( + await successor.run(() => + harness.run(['stop'], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }), + ), + ).toMatchObject({ ok: false, error: { details: { reason: 'RESOURCE_EXPIRED' } } }); + } finally { + successor.dispose(); + } + } + if (replace) expect(fs.readFileSync(source, 'utf8')).toBe('unrelated-recording'); + else expect(fs.existsSync(source)).toBe(false); + }, +); diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts index c16b0a93de..94ff05e67a 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-stop-recovery.test.ts @@ -1,3 +1,12 @@ +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +import { + flushDiagnosticsToSessionFile, + withDiagnosticsScope, +} from '@agent-device/host-kit/diagnostics'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { listDownloadableArtifacts } from '../../../resources/artifact-tracking.ts'; +import { platformResourceCleanupFixture } from '../../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { teardownSessionResources } from '../../session-teardown.ts'; import { daemonPlatformServicesFixture } from '../../../__tests__/support/platform-services-fixture.ts'; import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger'; import { handleRecordCommand } from '../record-runtime.ts'; @@ -16,8 +25,6 @@ import { } from '@agent-device/host-kit/request'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; import { LeaseRegistry } from '../../../resources/lease-registry.ts'; -import { leaseVerifier } from '../../../resources/artifact-tracking.ts'; -import { captureOutputLeaseVerifier } from '../../../core/capture-output-ownership.ts'; import { expectDecodedCompletedRecording, makeRecordRuntimeHarness, @@ -148,8 +155,6 @@ test('a completed leased export replays to the lease id that started it, with no // The lease ended with its session. The replay names it, and no request is admitted under it. const replayed = await replay(leaseId.toUpperCase()); expect(replayed).toMatchObject({ ok: true, data: { recording: 'stopped', outPath } }); - // The export stays with the lease of the manifest when the response is registered. - expect(replayed.ok && captureOutputLeaseVerifier(replayed.data!)).toBe(leaseVerifier(leaseId)); }); test('a completed remote export whose manifest names no owner is not replayed', async () => { @@ -767,3 +772,189 @@ test.each([false, true])( } }, ); + +const TENANT = 'tenant-a'; + +test.each(['first inspection', 'checkpoint write'])( + 'close preserves completion after %s fails', + async (fault) => { + const harness = makeRecordRuntimeHarness('recording-close-proof-io-', { + sessionName: 'tenant-a:checkout-flow', + }); + const remote = { publicNetworkOnly: true } as const; + const run = (action: string, tenantId = TENANT) => + harness.run([action], { tenantId }, undefined, remote); + expect(await run('start')).toMatchObject({ ok: true }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(source, 'verified-after-close'); + const lstat = fs.lstatSync; + const rename = fs.renameSync; + const manifest = recordingResourcePath(harness.sessionStore, harness.sessionName); + const ioError = Object.assign(new Error(`EIO accessing ${manifest}`), { code: 'EIO' }); + let failed = false; + const inspect = + fault === 'first inspection' + ? vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source) throw ioError; + return lstat(file, options); + }) + : vi.spyOn(fs, 'renameSync').mockImplementation((file, destination) => { + if (destination === manifest && harness.runtime.finish.mock.calls.length && !failed) { + failed = true; + throw ioError; + } + rename(file, destination); + }); + try { + await teardownSessionResources({ + appLog: 'already-settled', + ref: harness.sessionStore.lookup(harness.sessionName)!, + sessionStore: harness.sessionStore, + platformCleanup: platformResourceCleanupFixture(), + }); + } finally { + inspect.mockRestore(); + } + expect(harness.runtime.forceCleanup).toHaveBeenCalledOnce(); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + expect(await run('stop', 'other-tenant')).toMatchObject({ + ok: false, + error: { code: 'UNAUTHORIZED' }, + }); + expect(screenRecordingResourceStore.read(manifest)).toMatchObject({ + status: 'decoded', + envelope: { + metadata: { + phase: 'export-proof-pending', + completion: { outPath: source }, + remoteCaptureExport: { + identities: fault === 'first inspection' ? [null] : [expect.any(String)], + }, + }, + }, + }); + if (fault === 'first inspection') { + expect(await run('stop')).toMatchObject({ + ok: false, + error: { message: 'Recording export is missing producer proof.' }, + }); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } else { + expect(failed).toBe(true); + expect(await run('stop')).toMatchObject({ + ok: true, + data: { artifacts: [{ artifactId: expect.any(String) }] }, + }); + } + expect(harness.runtime.finish).toHaveBeenCalledOnce(); + expect(fs.readFileSync(source, 'utf8')).toBe('verified-after-close'); + }, +); + +test('explicit stop keeps its binding but never serves an unproved sidecar', async () => { + const harness = makeRecordRuntimeHarness('recording-sidecar-retry-'); + const finish = harness.runtime.finish.getMockImplementation()!; + harness.runtime.finish.mockImplementation(async () => { + const outcome = await finish(); + return { + ...outcome, + result: { + ...outcome.result, + telemetryPath: deriveRecordingTelemetryPath(outcome.result.outPath), + }, + }; + }); + const runtime = createRuntimeStateHandle(); + const run = (action: string) => + harness.run([action], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }); + try { + await runtime.run(async () => { + expect(await run('start')).toMatchObject({ ok: true }); + const video = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(video, 'completed-video'); + const active = harness.sessionStore.lookup(harness.sessionName)!.session.screenRecording; + expect(active).toBeDefined(); + expect(await run('stop')).toMatchObject({ + ok: false, + error: { code: 'COMMAND_FAILED' }, + }); + expect(harness.sessionStore.lookup(harness.sessionName)!.session.screenRecording).toBe( + active, + ); + expect(harness.runtime.forceCleanup).not.toHaveBeenCalled(); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + + fs.writeFileSync(deriveRecordingTelemetryPath(video), '{}'); + expect(await run('stop')).toMatchObject({ + ok: false, + error: { message: 'Recording export is missing producer proof.' }, + }); + harness.runtime.finish.mockImplementation(finish); + expect(await run('stop')).toMatchObject({ + ok: false, + error: { message: 'Recording export does not match its stored proof.' }, + }); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + }); + } finally { + runtime.dispose(); + } +}); + +test.each([ + ['live', 'read'], + ['recovered', 'read'], + ['live', 'write'], +] as const)('%s stop redacts a proof checkpoint %s failure', async (route, operation) => { + const harness = makeRecordRuntimeHarness('recording-checkpoint-read-', { + runtime: { reattachActive: true }, + }); + const run = (action: string) => + harness.run([action], { tenantId: TENANT, sessionExplicit: true }, undefined, { + publicNetworkOnly: true, + }); + expect(await run('start')).toMatchObject({ ok: true }); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(source, 'finished-export'); + if (route === 'recovered') + harness.sessionStore.retire(harness.sessionStore.lookup(harness.sessionName)!); + const manifest = recordingResourcePath(harness.sessionStore, harness.sessionName); + const lstat = fs.lstatSync; + const rename = fs.renameSync; + const logPath = manifest + '.diagnostics.ndjson'; + const ioError = `EIO at ${manifest}`; + let failed = false; + const failCheckpoint = (file: unknown) => { + if (file === manifest && harness.runtime.finish.mock.calls.length && !failed) { + failed = true; + throw Object.assign(new Error(ioError), { code: 'EIO' }); + } + }; + const inspect = + operation === 'read' + ? vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + failCheckpoint(file); + return lstat(file, options); + }) + : vi.spyOn(fs, 'renameSync').mockImplementation((file, destination) => { + failCheckpoint(destination); + rename(file, destination); + }); + try { + const result = await withDiagnosticsScope({ command: 'record', logPath }, async () => { + const response = await run('stop'); + flushDiagnosticsToSessionFile({ force: true }); + return response; + }); + expect(result).toMatchObject({ + ok: false, + error: { message: 'Recording ownership proof could not be read.', retriable: true }, + }); + expect(JSON.stringify(result)).not.toContain(manifest); + } finally { + inspect.mockRestore(); + } + expect(failed).toBe(true); + expect(fs.readFileSync(logPath, 'utf8')).toContain(ioError); + expect(await run('stop')).toMatchObject({ ok: true }); +}); diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts index afc68bc234..649e9f7c42 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts @@ -39,6 +39,7 @@ export function makeRecordRuntimeHarness( sessionName?: string; appBundleId?: string; recordOnlySession?: boolean; + suiteCapture?: 'local' | 'remote'; platform?: 'android' | 'apple' | 'linux' | 'vega'; device?: SessionState['device']; runtime?: RuntimeOptions; @@ -101,6 +102,7 @@ export function makeRecordRuntimeHarness( handleRecordCommand({ platformServices: daemonPlatformServicesFixture(), ...common, + suiteCapture: options.suiteCapture, sessionName: asSessionName, req: { token: 'token', @@ -135,7 +137,7 @@ function makeRuntime(session: SessionState, options: RuntimeOptions = {}) { const owner = localRuntimeOwner(session.device.platform); let currentOutPath = ''; let currentClientOutPath: string | undefined; - const handle: ScreenRecordingLiveHandle = { + const handle = { inspect: () => ({ backend: 'adb screenrecord', outPath: currentOutPath, @@ -168,7 +170,7 @@ function makeRuntime(session: SessionState, options: RuntimeOptions = {}) { }), forceCleanup: vi.fn(async () => options.cleanup ?? { status: 'cleaned' as const }), [Symbol.asyncDispose]: async () => {}, - }; + } satisfies ScreenRecordingLiveHandle; const start = vi.fn( async (input: Parameters[0]) => { currentOutPath = input.outputPath; diff --git a/packages/daemon/src/sessions/handlers/record-runtime-response.ts b/packages/daemon/src/sessions/handlers/record-runtime-response.ts index 7dd7caac40..fccc286d12 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime-response.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime-response.ts @@ -8,7 +8,6 @@ import type { } from '@agent-device/contracts/screen-recording-runtime'; import type { RuntimeOperationUnavailability } from '@agent-device/contracts/platform-runtime'; import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; -import { isRemoteTempArtifactPath } from '@agent-device/contracts/daemon-http'; export const UNLEASED_CAPTURE = 'unleased'; @@ -22,24 +21,19 @@ export function recordingOutputLeaseVerifier( return undefined; } -export function isLegacyRemoteRecordingOutput(completion: ScreenRecordingCompletion): boolean { - return ( - completion.clientOutPath !== undefined && - isRemoteTempArtifactPath(completion.outPath, 'recording', path.extname(completion.outPath)) - ); -} - export function buildRecordingStartResponse( snapshot: ScreenRecordingLiveSnapshot, sessionStateDir: string, requestedOutPath: string, + remote = false, ): DaemonResponse { return { ok: true, data: { recording: 'started', - outPath: snapshot.clientOutPath ?? requestedOutPath, - sessionStateDir, + outPath: + snapshot.clientOutPath ?? (remote ? path.basename(requestedOutPath) : requestedOutPath), + ...(!remote ? { sessionStateDir } : {}), recordingBackend: snapshot.backend, recordingScope: snapshot.scope, recordOnlySession: snapshot.recordOnlySession, @@ -73,14 +67,23 @@ export function buildRecordingUnsupportedResponse( }; } -export function buildRecordingStopResponse(completion: ScreenRecordingCompletion): DaemonResponse { +export function buildRecordingStopResponse( + completion: ScreenRecordingCompletion, + artifacts = recordingStopArtifacts(completion), + remote = false, +): DaemonResponse { return { ok: true, data: { recording: 'stopped', - outPath: completion.outPath, - telemetryPath: completion.telemetryPath, - artifacts: recordingStopArtifacts(completion), + outPath: remote + ? (artifacts[0]?.localPath ?? path.basename(completion.outPath)) + : completion.outPath, + telemetryPath: remote + ? (artifacts.find(({ field }) => field === 'telemetryPath')?.localPath ?? + (completion.telemetryPath ? path.basename(completion.telemetryPath) : undefined)) + : completion.telemetryPath, + artifacts, recordingBackend: completion.backend, recordingScope: completion.scope, recordOnlySession: completion.recordOnlySession, @@ -102,7 +105,7 @@ export function buildRecordingStopResponse(completion: ScreenRecordingCompletion overlayWarning: completion.overlayWarning, chunks: completion.chunks?.map((chunk) => ({ index: chunk.index, - path: chunk.clientOutPath ?? chunk.path, + path: chunk.clientOutPath ?? (remote ? path.basename(chunk.path) : chunk.path), })), } satisfies RecordingCommandResult, }; diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index a5a11a488c..03febb48b9 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -3,10 +3,7 @@ import type { DaemonPlatformServices } from '../../core/platform-services.ts'; import path from 'node:path'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; -import type { - ScreenRecordingCompletion, - ScreenRecordingStartInput, -} from '@agent-device/contracts/screen-recording-runtime'; +import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; import { bindSessionScreenRecording, bindRecordOnlyScreenRecording, @@ -34,12 +31,14 @@ import { createScreenRecordingRecoveryControl } from '@agent-device/capture-kit/ import { adoptStartedScreenRecording, finishLiveScreenRecording, + finishPendingScreenRecordingProof, finishRecoveredScreenRecording, screenRecordingDurableResource, } from '@agent-device/capture-kit/screen-recording-session-resource'; import { resolveScreenRecordingStopRecovery, - screenRecordingManifestDevice, + readStoredCompletion, + unreadableRecordingProof, screenRecordingManifestIsTerminal, } from '@agent-device/capture-kit/screen-recording-stop-recovery'; import { resolveSessionScope } from '../session-routing.ts'; @@ -52,7 +51,6 @@ import type { DaemonRequest } from '../../core/daemon-request.ts'; import { requestCwd } from '../../core/context.ts'; import type { SessionRef, SessionState } from '../../core/session-state.ts'; import { sessionHasOwnersBeyondRecording } from '../../core/session-state.ts'; -import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; import { resolveLeaseScope } from '../../core/lease-context.ts'; import { leasedOutputRefusal, @@ -71,17 +69,17 @@ import { recordingExtensionForPlatform, resolveRecordingOutputPaths, } from '@agent-device/capture-kit/recording-output-path'; -import { isRemoteTempArtifactPath } from '@agent-device/contracts/daemon-http'; +import { isRemoteTempArtifactPath, normalizeTenantId } from '@agent-device/contracts/daemon-http'; import { randomUUID } from 'node:crypto'; import { buildRecordingStartResponse, buildRecordingStartedAction, buildRecordingStopResponse, buildRecordingUnsupportedResponse, - isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, UNLEASED_CAPTURE, } from './record-runtime-response.ts'; +import { commitRecordingOutputs } from '../recording-outputs.ts'; import { resolveRequestTargetDevice } from '../../core/request-device-resolution.ts'; /** @@ -89,7 +87,7 @@ import { resolveRequestTargetDevice } from '../../core/request-device-resolution * first owes a session action: the request that terminalized the recording already recorded it. */ type ScreenRecordingStop = Readonly<{ - completion: ScreenRecordingCompletion; + envelope: DurableResourceEnvelope<'screen-recording'>; recordsSessionAction: boolean; }>; @@ -103,6 +101,7 @@ export type RecordRuntimeHandlerParams = Readonly<{ bindExactDevice: BindExactDeviceRuntime; admissionLedger: ScreenRecordingAdmissionLedger; requestScope: PlatformRequestScope; + suiteCapture?: 'local' | 'remote'; retainDeviceExecutionLock(deviceId: string): Promise; throwIfCanceled(): void; }>; @@ -136,7 +135,9 @@ async function handleRecordCommandUnsafe( ) { return missingAppSessionResponse(req); } - const resolvedSession = await resolveRecordingSession(params, existingRef, plan); + const authorized = plan.kind === 'start' ? undefined : readStopEnvelope(params); + if (authorized) assertRequestMayStopRecording(params, authorized); + const resolvedSession = await resolveRecordingSession(params, existingRef, authorized?.device); const { session } = resolvedSession; if (plan.kind === 'start') { return await startRecording( @@ -154,6 +155,7 @@ async function handleRecordCommandUnsafe( resolvedSession.ref, plan.kind, resolvedSession.needsReadiness, + authorized, ); } @@ -172,51 +174,27 @@ function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined async function resolveRecordingSession( params: RecordRuntimeHandlerParams, ref: SessionRef | undefined, - plan: ReturnType['plan'], + recorded: DeviceIdentity | undefined, ): Promise> { if (ref) return { session: params.sessionStore.requireCurrent(ref), ref, needsReadiness: false }; - const device = await resolveUnheldRecordingDevice(params, plan); + const device = await resolveUnheldRecordingDevice(params, recorded); await params.retainDeviceExecutionLock(device.id); return { session: createRecordOnlySession(params, device), needsReadiness: true }; } -/** - * The device an unheld record request is answered on, and the single place the record handler - * applies the named-session rule (#3674) at its only device selection. - * - * A request that names a session this daemon does not hold and states no device is answered from - * the durable manifest the session address finds, never from a sweep of every device on the host: - * a decodable manifest is re-resolved with the request's scope and lease keys under the manifest's - * family (admission proved the request states no device), and a start or a stop with no decodable - * manifest to recover from refuses with the named-session error. - * `assertManifestBelongsToRequest` owns the proof that the resolved device - * and session address match the manifest. - * - * The two shapes that keep their chosen target are unchanged: a request that never named a - * session resolves sessionlessly from its flags, and one that states a device selector resolves - * from it. - */ async function resolveUnheldRecordingDevice( params: RecordRuntimeHandlerParams, - plan: ReturnType['plan'], + recorded: DeviceIdentity | undefined, ): Promise { const { req, sessionName } = params; if (!namesSessionWithoutTarget(req)) return await resolveRequestTargetDevice(req, { env: params.sessionStore.host.env }); - if (plan.kind === 'stop-recovery') { - const recorded = screenRecordingManifestDevice({ - sessionName, - sessionStore: params.sessionStore, - }); - if (recorded) { - return await resolveManifestDevice(params, recorded); - } - } + // A named unheld session only selects the device from its authorized manifest (#3674). + if (recorded) return await resolveManifestDevice(params, recorded); const { namedSessionNotFoundError } = await import('../../core/explicit-session-resolution.ts'); throw namedSessionNotFoundError(sessionName); } -/** Whether this request is addressed to a session and leaves its device to the session. */ function namesSessionWithoutTarget(req: DaemonRequest): boolean { return namesSessionExplicitly(req) && !hasDeviceSelectionInput(req.flags); } @@ -257,14 +235,12 @@ async function startRecording( if (session.screenRecording) { return { ok: false, error: { code: 'INVALID_ARGS', message: 'recording already in progress' } }; } - const draft = ref + const slot = ref ? undefined - : bindRecordOnlyScreenRecording( - params.sessionStore, - params.sessionName, - session, - new SessionCoordinator(params.sessionStore).reserve(params.req, params.sessionName), - ); + : new SessionCoordinator(params.sessionStore).reserve(params.req, params.sessionName); + const draft = + slot && bindRecordOnlyScreenRecording(params.sessionStore, params.sessionName, session, slot); + const lifetimeId = ref?.lifetime.journalId ?? slot!.lifetimeId; const binding = ref ? bindSessionScreenRecording(params.sessionStore, ref) : draft!.binding; binding.assertAdoptable(); const admission = await params.bindDevice(session.device, screenRecordingAdmissionUse); @@ -298,7 +274,7 @@ async function startRecording( owner: runtime.owner, fence, ...started, - envelope: withCaptureOwner(started.envelope, params.req, outputPaths.daemonOwned === true), + envelope: withCaptureOwner(started.envelope, params, outputPaths, lifetimeId), throwIfCanceled: params.throwIfCanceled, }); const adoptedRef = ref ?? draft!.requireRef(); @@ -316,6 +292,7 @@ async function startRecording( snapshot, params.sessionStore.ensureSessionDir(params.sessionName), outputPaths.requestedPath, + !params.suiteCapture && outputPaths.daemonOwned === true, ); } @@ -325,18 +302,33 @@ async function startRecording( */ function withCaptureOwner( envelope: DurableResourceEnvelope<'screen-recording'>, - req: DaemonRequest, - daemonOwned: boolean, + { req, suiteCapture }: RecordRuntimeHandlerParams, + output: RecordingStartPaths, + lifetimeId: string, ): DurableResourceEnvelope<'screen-recording'> { const lease = req.internal?.admittedLease; - const tenantId = lease?.tenantId ?? req.meta?.tenantId; + const tenantId = normalizeTenantId(lease?.tenantId ?? req.meta?.tenantId); const leaseId = lease?.leaseId; return { ...envelope, metadata: { ...envelope.metadata, - ...(daemonOwned ? { remoteCaptureOutput: true } : {}), - ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(output.daemonOwned + ? { + remoteCaptureOutput: true, + remoteCapturePath: output.outputPath, + remoteCaptureReservation: envelope.fence.token, + remoteCaptureLifetime: lifetimeId, + remoteCaptureTenantId: tenantId ?? null, + ...(suiteCapture === 'remote' && + req.meta?.clientArtifactPaths?.artifactsDir && + req.positionals?.[1] + ? { suiteRecordingArchivePath: req.positionals[1] } + : {}), + } + : {}), + ...(!output.daemonOwned && tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(suiteCapture ? { suiteRecordingLifetime: lifetimeId } : {}), remoteCaptureLease: leaseId ? leaseVerifier(leaseId) : UNLEASED_CAPTURE, }, }; @@ -353,12 +345,23 @@ function prepareRecordingStart(params: RecordRuntimeHandlerParams, session: Sess resourcePath, device: session.device, }), - outputPaths: resolveRecordingStartPaths( - params.req, - session.device.platform, - params.sessionStore.host.cwd, - params.sessionStore.ensureSessionDir(params.sessionName), - ), + outputPaths: + params.suiteCapture === 'local' + ? { + ...resolveRecordingOutputPaths({ + requestedPath: params.req.positionals?.[1], + platform: session.device.platform, + cwd: params.sessionStore.host.cwd, + }), + } + : resolveRecordingStartPaths( + params.suiteCapture === 'remote' + ? { ...params.req, internal: { ...params.req.internal, publicNetworkOnly: true } } + : params.req, + session.device.platform, + params.sessionStore.host.cwd, + params.sessionStore.ensureSessionDir(params.sessionName), + ), }; } @@ -444,27 +447,21 @@ async function stopRecording( ref: SessionRef | undefined, kind: 'stop-live' | 'stop-recovery', needsReadiness: boolean, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, ): Promise { - const leaseOwner = assertRequestMayStopRecording(params); 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); + ? await finishAuthorizedLiveRecording(params, ref!, authorized) + : await finishRecovered(params, session, needsReadiness, authorized); } catch (error) { deleteTerminalRecordOnlySession(params, ref); throw error; } - const completion = stopped.completion; - const response = buildRecordingStopResponse(completion); - const { daemonOwned, tenantId } = readRecordingOutput(params, completion, leaseOwner, ref); + const { envelope } = stopped; + const completion = readStoredCompletion(envelope.metadata); + if (!completion) throw unreadableRecordingProof(); if (stopped.recordsSessionAction) { recordSessionAction(params.sessionStore, ref, params.req, params.req.command, { action: 'stop', @@ -479,69 +476,101 @@ async function stopRecording( // session has to be re-read here, because the record this stop started with may have gained an // app, a capture, a claim, or a lease while the recording was being finished. if (ref) retireRecordOnlySession(params.sessionStore, ref); - return response.ok && response.data - ? { - ...response, - data: withCaptureOutputOwnership( - response.data, - daemonOwned ? 'daemon' : 'caller', - tenantId, - leaseOwner, - ), - } - : response; + const remote = isRemoteRecordingRequest(params); + const artifacts = + envelope.metadata?.remoteCaptureOutput === true && + (remote || envelope.metadata.remoteCaptureExport !== undefined) + ? await commitRecordingOutputs(envelope, ref ? 'live' : 'replay') + : undefined; + if (remote && !artifacts) throw leasedOutputRefusal('Recording'); + return buildRecordingStopResponse(completion, artifacts, !params.suiteCapture && remote); } -function readRecordingOutput( +async function finishAuthorizedLiveRecording( params: RecordRuntimeHandlerParams, - completion: ScreenRecordingCompletion, - leaseOwner: string | null | undefined, - ref: SessionRef | undefined, -): { daemonOwned: boolean; tenantId?: string } { - const resourcePath = screenRecordingDurableResource.resourcePath( - params.sessionStore, - params.sessionName, + ref: SessionRef, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, +): Promise { + const binding = bindSessionScreenRecording(params.sessionStore, ref); + const active = binding.read(); + if (!authorized || !active || !sameRecordingFence(active.envelope, authorized)) + throw unreadableRecordingProof(); + await finishLiveScreenRecording({ intent: 'capture', binding }); + return { envelope: requireFinishedEnvelope(params, authorized), recordsSessionAction: true }; +} + +function isRemoteRecordingRequest(params: RecordRuntimeHandlerParams): boolean { + return ( + params.suiteCapture === 'remote' || + params.req.internal?.publicNetworkOnly === true || + params.req.meta?.clientArtifactPaths?.outPath !== undefined ); - const record = screenRecordingDurableResource.store.read(resourcePath); - const daemonOwned = - record.status === 'decoded' && record.envelope.metadata?.remoteCaptureOutput === true; - if (isLegacyRemoteRecordingOutput(completion) || (daemonOwned && leaseOwner === undefined)) { - throw leasedOutputRefusal('Recording'); - } - const storedTenant = - record.status === 'decoded' ? record.envelope.metadata?.remoteCaptureTenantId : undefined; - const tenantId = - typeof storedTenant === 'string' - ? storedTenant - : ((ref && params.sessionStore.resolveCurrent(ref)?.lease?.tenantId) ?? - params.req.meta?.tenantId); - return { daemonOwned, tenantId }; +} + +function readStopEnvelope(params: RecordRuntimeHandlerParams) { + const record = screenRecordingDurableResource.store.read( + screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), + ); + if (record.status === 'unreattachable') throw unreadableRecordingProof(); + return record.status === 'decoded' ? record.envelope : undefined; +} + +function sameRecordingFence( + left: DurableResourceEnvelope<'screen-recording'>, + right: DurableResourceEnvelope<'screen-recording'>, +): boolean { + return ( + left.sessionId === right.sessionId && + left.fence.token === right.fence.token && + left.fence.generation === right.fence.generation + ); +} + +function requireFinishedEnvelope( + params: RecordRuntimeHandlerParams, + expected: DurableResourceEnvelope<'screen-recording'>, +) { + const envelope = readStopEnvelope(params); + if ( + !envelope || + envelope.lifecycle !== 'completed' || + !sameRecordingFence(envelope, expected) || + envelope.metadata?.remoteCapturePath !== expected.metadata?.remoteCapturePath + ) + throw unreadableRecordingProof(); + assertRequestMayStopRecording(params, envelope); + return envelope; } /** - * Refuses a stop that the owner of the recording did not send, and returns the verifier of the - * lease that owns the export. A completed export needs only the lease id of its owner, also after + * A stopped export needs only the lease id of its owner, also after * that lease ended. A recording that still runs needs the admitted lease. */ function assertRequestMayStopRecording( params: RecordRuntimeHandlerParams, -): string | null | undefined { - const record = screenRecordingDurableResource.store.read( - screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), - ); - if (record.status !== 'decoded') return undefined; - const { metadata, lifecycle } = record.envelope; + envelope: DurableResourceEnvelope<'screen-recording'>, +): void { + const { metadata, lifecycle } = envelope; const owner = recordingOutputLeaseVerifier(metadata); - if (owner === undefined && metadata?.remoteCaptureOutput === true) { + if ( + isRemoteRecordingRequest(params) && + (owner === undefined || metadata?.remoteCaptureOutput !== true) + ) { throw leasedOutputRefusal('Recording'); } - if (typeof owner !== 'string') return owner; + if ( + metadata?.remoteCaptureOutput === true && + typeof metadata.remoteCaptureTenantId === 'string' && + metadata.remoteCaptureTenantId !== + normalizeTenantId(params.req.internal?.admittedLease?.tenantId ?? params.req.meta?.tenantId) + ) + throw leasedOutputRefusal('Recording'); + if (typeof owner !== 'string') return; const presented = - lifecycle === 'completed' - ? resolveLeaseScope(params.req).leaseId + lifecycle === 'completed' || metadata?.phase === 'export-proof-pending' + ? (resolveLeaseScope(params.req).leaseId ?? params.req.internal?.admittedLease?.leaseId) : params.req.internal?.admittedLease?.leaseId; if (!requestHoldsOutputLease(owner, presented)) throw leasedOutputRefusal('Recording'); - return owner; } function deleteTerminalRecordOnlySession( @@ -573,24 +602,37 @@ async function finishRecovered( params: RecordRuntimeHandlerParams, session: SessionState, needsReadiness: boolean, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, ): Promise { + if (!authorized) throw new AppError('INVALID_ARGS', 'no active recording'); const recovery = resolveScreenRecordingStopRecovery({ sessionName: params.sessionName, sessionStore: params.sessionStore, device: session.device, + admittedEnvelope: authorized, }); - if (recovery.kind === 'completed') { - return { completion: recovery.completion, recordsSessionAction: false }; - } - if (recovery.kind === 'none') { - throw new AppError('INVALID_ARGS', 'no active recording'); + if (recovery.kind === 'none') throw new AppError('INVALID_ARGS', 'no active recording'); + if (recovery.kind === 'completed') + return { envelope: recovery.envelope, recordsSessionAction: false }; + if (authorized.metadata?.phase === 'export-proof-pending') { + const envelope = await finishPendingScreenRecordingProof(recovery.resourcePath, authorized); + assertRequestMayStopRecording(params, envelope); + return { envelope, recordsSessionAction: false }; } - const completion = await finishRecoveredScreenRecording({ + const acquire = exactRecoveryControl(params, session.device, needsReadiness); + await finishRecoveredScreenRecording({ resourcePath: recovery.resourcePath, scope: params.requestScope, - acquireControl: exactRecoveryControl(params, session.device, needsReadiness), + acquireControl: (envelope, scope) => { + if (!sameRecordingFence(envelope, recovery.envelope)) throw unreadableRecordingProof(); + assertRequestMayStopRecording(params, envelope); + return acquire(envelope, scope); + }, }); - return { completion, recordsSessionAction: true }; + return { + envelope: requireFinishedEnvelope(params, authorized), + recordsSessionAction: true, + }; } /** diff --git a/packages/daemon/src/sessions/handlers/session-replay-command-recording-cleanup.test.ts b/packages/daemon/src/sessions/handlers/session-replay-command-recording-cleanup.test.ts new file mode 100644 index 0000000000..a2f4e5b832 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-replay-command-recording-cleanup.test.ts @@ -0,0 +1,169 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { createScreenRecordingAdmissionLedger } from '@agent-device/capture-kit/screen-recording-admission-ledger'; +import { getRequestSignal } from '@agent-device/host-kit/request'; +import { getReplayExecution } from '@agent-device/replay-port/replay-backend-registry'; +import { createTestHostEnvironment, mkdtempForTestSync } from '@agent-device/test-kit'; +import { + handleSessionCommands, + mockBindDeviceRuntime, +} from '../../__tests__/support/handlers/session-command-harness.ts'; +import { fakeCreateCommandSurface } from '../../__tests__/support/command-surface-fake.ts'; +import { platformResourceCleanupFixture } from '../../__tests__/support/platform-resource-cleanup-fixture.ts'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { daemonPlatformServicesFixture } from '../../__tests__/support/platform-services-fixture.ts'; +import { makeAndroidSession } from '../../__tests__/support/session-factories.ts'; +import { makeRecordRuntimeHarness } from './__tests__/record-runtime.fixtures.ts'; +import { + cleanupDownloadableArtifact, + listDownloadableArtifacts, +} from '../../resources/artifact-tracking.ts'; +import { expectOkData } from '../__tests__/replay-suite/session-test-suite.fixtures.ts'; + +test.each([false, true])( + 'a remote suite preserves the timed-out attempt outcome (missing sidecar: %s)', + async (missingSidecar) => { + await getReplayExecution(); + const root = mkdtempForTestSync('suite-recording-cleanup-'); + const script = path.join(root, 'flow.ad'); + fs.writeFileSync(script, 'context platform=android\nopen "Demo"\nclick "Continue"\n'); + const { sessionStore, runtime } = makeRecordRuntimeHarness('suite-recording-provider-'); + const start = runtime.start.getMockImplementation()!; + let onStart = () => {}; + const started = new Promise((resolve) => { + onStart = resolve; + }); + runtime.start.mockImplementation(async (input) => { + const result = await start(input); + onStart(); + return result; + }); + const finish = runtime.finish.getMockImplementation()!; + runtime.finish + .mockRejectedValueOnce(new Error('recorder export needs retry')) + .mockImplementation(async () => { + const outcome = await finish(); + fs.writeFileSync(outcome.result.outPath, 'video-exported-during-close'); + const telemetryPath = deriveRecordingTelemetryPath(outcome.result.outPath); + if (!missingSidecar) fs.writeFileSync(telemetryPath, '{}'); + return { ...outcome, result: { ...outcome.result, telemetryPath } }; + }); + const tenantId = 'recording-suite'; + const clientRoot = path.join(root, 'client'); + vi.useFakeTimers(); + try { + const response = handleSessionCommands({ + host: createTestHostEnvironment({ cwd: root, env: {} }), + createCommandSurface: fakeCreateCommandSurface, + platformServices: daemonPlatformServicesFixture(), + platformResourceCleanup: platformResourceCleanupFixture(), + req: { + token: 'fixture', + session: 'suite', + command: 'test', + positionals: [script], + flags: { platform: 'android', recordVideo: true, timeoutMs: 1_500 }, + meta: { cwd: root, tenantId, clientArtifactPaths: { artifactsDir: clientRoot } }, + internal: { publicNetworkOnly: true }, + }, + sessionName: 'suite', + logPath: path.join(root, 'daemon.log'), + sessionStore, + bindDevice: (device, use) => + [...use.required, ...(use.preferred ?? [])].some((operation) => + operation.startsWith('screenRecording'), + ) + ? runtime.bindDevice(device, use) + : mockBindDeviceRuntime(device, use), + bindExactDevice: runtime.bindExactDevice, + screenRecordingAdmissionLedger: createScreenRecordingAdmissionLedger(), + throwIfCanceled: () => {}, + invoke: async (req) => { + if (req.command === 'open') { + const ref = sessionStore.publish(req.session, makeAndroidSession(req.session)); + req.internal?.onLifetimePublished?.(ref.address, ref.lifetime); + const beforeOpen = await req.internal?.openLifecycle?.beforeDispatch?.(); + if (beforeOpen && !beforeOpen.ok) return beforeOpen; + } + if (req.command === 'click') { + const signal = getRequestSignal(req.meta?.requestId); + if (signal && !signal.aborted) { + await new Promise((resolve) => + signal.addEventListener('abort', () => resolve(), { once: true }), + ); + } + } + return { ok: true, data: { session: req.session } }; + }, + }); + + await Promise.race([ + started, + response.then((result) => { + if (!runtime.start.mock.calls.length) + throw new Error(`Recording start was not reached: ${JSON.stringify(result)}`); + }), + ]); + await vi.advanceTimersByTimeAsync(5_000); + const data = expectOkData(await response); + expect(data.failed).toBe(1); + expect(runtime.finish, JSON.stringify(data.failures)).toHaveBeenCalledTimes(2); + const outputPath = runtime.start.mock.calls[0]![0].outputPath; + expect(fs.readFileSync(outputPath, 'utf8')).toBe('video-exported-during-close'); + expect(data.artifacts).toEqual([expect.objectContaining({ artifactType: 'test-artifacts' })]); + const archiveRoot = data.artifacts?.[0]?.path; + expect(archiveRoot).toBeTypeOf('string'); + expect(outputPath.startsWith(archiveRoot + path.sep)).toBe(false); + const archiveFiles = fs.readdirSync(archiveRoot!, { recursive: true }).map(String); + const archiveRecording = archiveFiles.find((file) => path.basename(file) === 'recording.mp4'); + const inventory = await listDownloadableArtifacts({ tenantId }, {}); + try { + const output = inventory.find((artifact) => artifact.artifactType === 'screen-recording'); + if (missingSidecar) { + expect(runtime.forceCleanup).toHaveBeenCalledOnce(); + expect(output).toBeUndefined(); + expect(data.recordingArtifacts).toBeUndefined(); + expect(archiveRecording).toBeUndefined(); + expect(data.failures).toMatchObject([{ error: { details: { reason: 'timeout' } } }]); + expect( + (data.failures as Array<{ infrastructure?: true }>)[0]!.infrastructure, + ).toBeUndefined(); + } else { + expect(runtime.forceCleanup).not.toHaveBeenCalled(); + expect(output?.id).toBeTypeOf('string'); + expect(archiveRecording).toBeTypeOf('string'); + expect(fs.readFileSync(path.join(archiveRoot!, archiveRecording!), 'utf8')).toBe( + 'video-exported-during-close', + ); + for (const result of [data.tests, data.failures]) { + expect(result).toMatchObject([ + { + error: { + details: { + artifactPaths: expect.arrayContaining([expect.stringContaining(clientRoot)]), + }, + }, + }, + ]); + expect(JSON.stringify(result)).not.toContain(archiveRoot); + expect(JSON.stringify(result)).not.toContain(outputPath); + } + expect(data.recordingArtifacts).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + artifactId: output?.id, + path: expect.stringMatching(/client\/.*\/attempt-1\/recording\.mp4$/), + }), + ]), + ); + } + } finally { + for (const artifact of inventory) cleanupDownloadableArtifact(artifact.id); + } + expect(fs.existsSync(outputPath)).toBe(missingSidecar); + } finally { + vi.useRealTimers(); + } + }, +); diff --git a/packages/daemon/src/sessions/handlers/session-replay-command.ts b/packages/daemon/src/sessions/handlers/session-replay-command.ts index 293b554d70..8251c0c055 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -47,6 +47,7 @@ import type { BoundSnapshotCapture } from '../../core/snapshot-runtime-binding.t import { resolveObservationCapture } from '../../core/observation-capture.ts'; import { handleSessionCloseCommands } from '../session-lifecycle/internal/session-close.ts'; import { onDelegatingLedger } from '../../core/request-ended-leases.ts'; +import { collectSuiteRecordingOutputs } from '../recording-outputs.ts'; import { createReplayTestVideoOwner } from './session-replay-video-owner.ts'; import type { SessionCommandHandler } from './session-command-input.ts'; @@ -136,7 +137,12 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ return ref && sessionStore.resolveCurrent(ref) ? sessionStore.refresh(ref) : undefined; }; const completed = (name: string) => (attempts.get(name)?.running ? undefined : pinned(name)); + const recordingOutputs = new Map< + string, + Awaited>[number] + >(); const video = createReplayTestVideoOwner({ + suiteRequest: req, sessionStore, withSessionExecutionLock, sessionRef: (name, phase) => (phase === 'start' ? running(name) : completed(name)), @@ -153,17 +159,18 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ bindDevice, platformServices, }; - const suiteRequest = req.internal?.publicNetworkOnly - ? { - ...req, - flags: { - ...req.flags, - artifactsDir: resolveSessionTestArtifactsRoot( - sessionStore.resolveSessionDir(sessionName), - ), - }, - } - : req; + const suiteRequest = + req.internal?.publicNetworkOnly || req.meta?.clientArtifactPaths?.artifactsDir + ? { + ...req, + flags: { + ...req.flags, + artifactsDir: resolveSessionTestArtifactsRoot( + sessionStore.resolveSessionDir(sessionName), + ), + }, + } + : req; return await runReplayTestCommand({ ...splitReplayCommandRequest(suiteRequest), host, @@ -212,7 +219,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ return result; }, req), dependencies: replayDaemonDependencies, - cleanupSession: async (name) => { + cleanupSession: async (name, artifactPaths) => { // A timed-out attempt can still hold the lock. Its late cleanup runs after it settles. const lifetime = completed(name)?.lifetime; if (!lifetime) return []; @@ -225,20 +232,30 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ if (ref?.lifetime !== lifetime) return []; await holdDevice(ref.session.device.id); acquiring = false; - return await closeReplayTestSession({ - host, - req, - ref, - logPath, - sessionStore, - leaseRegistry, - leaseLifecycleProvider, - inspectFacts, - bindDevice, - platformServices, - platformResourceCleanup, - deviceShutdownDenied, - }); + try { + return await closeReplayTestSession({ + host, + req, + ref, + logPath, + sessionStore, + leaseRegistry, + leaseLifecycleProvider, + inspectFacts, + bindDevice, + platformServices, + platformResourceCleanup, + deviceShutdownDenied, + }); + } finally { + if (video && req.flags?.recordVideo) { + for (const output of await collectSuiteRecordingOutputs(sessionStore, ref)) { + if (output.path) artifactPaths?.add(output.path); + if (artifactPaths) + recordingOutputs.set(output.artifactId ?? output.path!, output); + } + } + } }, signal, ); @@ -265,7 +282,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ ); } }, - ...(video ? { video } : {}), + ...(video ? { video, recordingOutputs: () => [...recordingOutputs.values()] } : {}), }); }; diff --git a/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts b/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts index fef65d301f..ace0b8aa10 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts @@ -25,6 +25,7 @@ export type ReplayTestVideoOwnerParams = Readonly<{ screenRecordingAdmissionLedger?: ScreenRecordingAdmissionLedger; requestScope?: PlatformRequestScope; throwIfCanceled?: () => void; + suiteRequest?: DaemonRequest; }>; export function createReplayTestVideoOwner( @@ -73,7 +74,12 @@ export function createReplayTestVideoOwner( ); await holdDevice(ref.session.device.id); return await handleRecordCommand({ - req: recordRequest(request), + req: recordRequest(request, params.suiteRequest), + suiteCapture: + params.suiteRequest?.internal?.publicNetworkOnly || + params.suiteRequest?.meta?.clientArtifactPaths?.artifactsDir + ? 'remote' + : 'local', sessionName: ref.address, sessionRef: ref, sessionStore, @@ -102,13 +108,17 @@ export function createReplayTestVideoOwner( }; } -function recordRequest(request: ReplayRecordVideoRequest): DaemonRequest { +function recordRequest(request: ReplayRecordVideoRequest, suite?: DaemonRequest): DaemonRequest { return { token: request.request.token, session: request.sessionName, command: 'record', positionals: request.phase === 'start' ? ['start', request.outputPath] : ['stop'], flags: {}, - meta: request.request.meta, + meta: { + ...request.request.meta, + tenantId: suite?.meta?.tenantId ?? request.request.meta?.tenantId, + }, + internal: { admittedLease: suite?.internal?.admittedLease }, }; } diff --git a/packages/daemon/src/sessions/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts deleted file mode 100644 index 2e2c91a87c..0000000000 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ /dev/null @@ -1,77 +0,0 @@ -import fs from 'node:fs'; -import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; -import type { ScreenRecordingCompletion } from '@agent-device/contracts/screen-recording-runtime'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { errorMessage } from '@agent-device/kernel/errors'; -import type { SessionRef } from '../core/session-state.ts'; -import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../resources/artifact-tracking.ts'; -import { - isLegacyRemoteRecordingOutput, - recordingStopArtifacts, - recordingOutputLeaseVerifier, -} from './handlers/record-runtime-response.ts'; - -/** - * Keeps the export of a recording that a leased session's teardown finished, so a request that sends - * the producing lease's id can still download it (ADR 0024 rule 1). The durable envelope marks - * daemon-owned exports. A caller-owned export stays at the path the caller named. - */ -export function retainLeasedSessionRecording( - ref: SessionRef, - completion: ScreenRecordingCompletion, - metadata: DurableResourceEnvelope['metadata'], -): void { - const lease = ref.session.lease; - if (!lease || metadata?.remoteCaptureOutput !== true || isLegacyRemoteRecordingOutput(completion)) - return; - const owner = recordingOutputLeaseVerifier(metadata); - if (owner === undefined) return; - const storedTenant = metadata?.remoteCaptureTenantId; - const tenantId = - owner !== null && typeof storedTenant === 'string' ? storedTenant : lease.tenantId; - const sessionName = tenantPublicSessionName(lease.tenantId, ref.address); - const artifacts = recordingStopArtifacts(completion).filter( - (artifact) => typeof artifact.path === 'string', - ); - const artifactIds: string[] = []; - try { - for (const artifact of artifacts) { - artifactIds.push( - trackDownloadableArtifact({ - artifactPath: artifact.path!, - tenantId, - ...(owner === null ? {} : { leaseVerifier: owner }), - artifactType: artifact.artifactType, - fileName: artifact.fileName, - sessionName, - }), - ); - } - } catch (error) { - for (const artifactId of artifactIds) cleanupDownloadableArtifact(artifactId); - for (const artifact of artifacts) removeBestEffort(artifact.path!); - emitDiagnostic({ - level: 'warn', - phase: 'leased_session_recording_retention_failed', - data: { session: ref.address, leaseId: lease.leaseId, error: errorMessage(error) }, - }); - return; - } - emitDiagnostic({ - level: 'info', - phase: 'leased_session_recording_retained', - data: { session: ref.address, sessionName, leaseId: lease.leaseId, artifactIds }, - }); -} - -function removeBestEffort(filePath: string): void { - try { - fs.rmSync(filePath, { force: true }); - } catch { - // A file that cannot be removed must not stop the removal of the others. - } -} diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts new file mode 100644 index 0000000000..10ac73827d --- /dev/null +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -0,0 +1,284 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { settleWithin } from '@agent-device/host-kit/settle-within'; +import { + finishPendingScreenRecordingProof, + recordingExportFileIdentity, +} from '@agent-device/capture-kit/screen-recording-session-resource'; +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { + readReplayableStoredCompletion, + readStoredCompletion, +} from '@agent-device/capture-kit/screen-recording-stop-recovery'; +import type { ReplaySuiteRecordingArtifact } from '@agent-device/contracts/replay'; +import type { SessionRef } from '../core/session-state.ts'; +import type { SessionStore } from '../core/session-store.ts'; +import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; +import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { chunkPathAt } from '@agent-device/capture-kit/recording-output-path'; +import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; +import { + ARTIFACT_CLEANUP_TIMEOUT_MS, + commitRecordingFileOutputs, + leasedOutputRefusal, + settleRecordingArchiveCopy, + recordingRegistrySignal, +} from '../resources/artifact-tracking.ts'; +import { + recordingOutputLeaseVerifier, + recordingStopArtifacts, +} from './handlers/record-runtime-response.ts'; + +type RecordingEnvelope = DurableResourceEnvelope<'screen-recording'>; + +function readVerifiedRecording(envelope: RecordingEnvelope) { + const { metadata } = envelope; + const completion = readStoredCompletion(metadata); + const verified = metadata?.remoteCaptureExport; + if ( + envelope.lifecycle !== 'completed' || + !completion || + metadata?.remoteCaptureOutput !== true || + completion.outPath !== metadata.remoteCapturePath || + metadata.remoteCaptureReservation !== envelope.fence.token || + !isRecord(verified) || + !Array.isArray(verified.identities) || + typeof verified.completedAt !== 'number' || + !Number.isFinite(verified.completedAt) + ) + throw leasedOutputRefusal('Recording'); + const { identities } = verified; + const artifacts = recordingStopArtifacts(completion); + if (artifacts.length !== identities.length) throw leasedOutputRefusal('Recording'); + const files = artifacts.map((artifact, index) => { + const sourceIdentity = identities[index]; + if (typeof sourceIdentity !== 'string') throw leasedOutputRefusal('Recording'); + const artifactId = `${envelope.fence.token}-${index + 1}`; + return { ...artifact, path: artifact.path!, sourceIdentity, artifactId }; + }); + return { + completion, + files, + completedAt: verified.completedAt, + producer: recordingProducer(metadata), + }; +} + +export async function retainSessionRecording( + ref: SessionRef, + envelope: RecordingEnvelope, +): Promise { + const { metadata } = envelope; + if ( + metadata?.remoteCaptureOutput !== true || + metadata.remoteCaptureLifetime !== ref.lifetime.journalId + ) + return; + try { + await commitRecordingOutputs( + envelope, + metadata.remoteCaptureTenantId === null ? 'retain' : 'live', + ); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'leased_session_recording_retention_failed', + data: { + session: ref.address, + error: errorMessage(error), + hasExportProof: metadata.remoteCaptureExport !== undefined, + }, + }); + } +} + +function recordingProducer(metadata: RecordingEnvelope['metadata']) { + const leaseVerifier = recordingOutputLeaseVerifier(metadata); + const lifetimeId = metadata?.remoteCaptureLifetime; + const stored = metadata?.remoteCaptureTenantId; + const tenantId = normalizeTenantId(stored); + if ( + leaseVerifier === undefined || + typeof lifetimeId !== 'string' || + (stored === null ? leaseVerifier !== null : !tenantId || tenantId !== stored) + ) { + throw leasedOutputRefusal('Recording'); + } + return { lifetimeId, tenantId, leaseVerifier }; +} + +function publishVerifiedRecording( + envelope: RecordingEnvelope, + recording: ReturnType, + delivery?: 'publish' | 'retain' | 'await-archive', +) { + const { producer, files, completedAt } = recording; + return commitRecordingFileOutputs( + files, + producer, + producer.tenantId + ? tenantPublicSessionName(producer.tenantId, envelope.sessionId) + : envelope.sessionId, + completedAt, + envelope.fence.token, + delivery, + ); +} + +export async function commitRecordingOutputs( + envelope: RecordingEnvelope, + context: 'live' | 'replay' | 'retain', +) { + const delivery = + context === 'live' && typeof envelope.metadata?.suiteRecordingArchivePath === 'string' + ? 'await-archive' + : context === 'retain' + ? 'retain' + : 'publish'; + return publishVerifiedRecording(envelope, readVerifiedRecording(envelope), delivery); +} + +export async function collectSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { + try { + return await readSuiteRecordingOutputs(store, ref); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'suite_recording_collection_failed', + data: { session: ref.address, error: errorMessage(error) }, + }); + return []; + } +} + +async function readSuiteRecordingOutputs( + store: SessionStore, + ref: SessionRef, +): Promise { + const resourcePath = screenRecordingResourceStore.resolvePath( + store.resolveSessionDir(ref.address), + ); + const record = screenRecordingResourceStore.read(resourcePath); + if (record.status !== 'decoded') return []; + let { envelope } = record; + if (envelope.metadata?.suiteRecordingLifetime !== ref.lifetime.journalId) return []; + if (envelope.metadata.phase === 'export-proof-pending') { + envelope = await finishPendingScreenRecordingProof(resourcePath, envelope); + } + if (envelope.lifecycle !== 'completed') return []; + if (envelope.metadata?.remoteCaptureOutput !== true) { + const completion = readReplayableStoredCompletion(envelope.metadata); + return completion + ? recordingStopArtifacts(completion).map(({ path }) => ({ session: ref.address, path })) + : []; + } + + const recording = readVerifiedRecording(envelope); + const archivePath = envelope.metadata.suiteRecordingArchivePath; + const hasArchive = typeof archivePath === 'string'; + const committed = await publishVerifiedRecording( + envelope, + recording, + hasArchive ? 'await-archive' : 'publish', + ); + let paths: readonly string[] = []; + if (hasArchive) { + const signal = recordingRegistrySignal(); + try { + paths = await copySuiteRecording(archivePath, recording); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'suite_recording_archive_copy_failed', + data: { session: ref.address, error: errorMessage(error) }, + }); + } finally { + if (!signal.aborted) settleRecordingArchiveCopy(recording.files); + } + } + return committed.map(({ artifactId, fileName }, index) => ({ + session: ref.address, + artifactId, + fileName, + path: paths[index], + })); +} + +async function copySuiteRecording( + archivePath: string, + { files, completedAt, completion }: ReturnType, +): Promise { + const expiresAt = completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS; + const paths = [ + archivePath, + ...(completion.chunks?.slice(1).map(({ index }) => chunkPathAt(archivePath, index)) ?? []), + ...(completion.telemetryPath ? [deriveRecordingTelemetryPath(archivePath)] : []), + ]; + const signal = recordingRegistrySignal(); + const copy = async () => { + const scratch = await fs.promises.mkdtemp( + path.join(path.dirname(completion.outPath), '.recording-archive-'), + ); + try { + const staged = []; + for (const [index, file] of files.entries()) { + signal.throwIfAborted(); + if (Date.now() >= expiresAt) + throw new AppError('COMMAND_FAILED', 'Recording archive copy expired.'); + const target = path.join(scratch, String(index)); + await verifyArchiveSource(file); + await fs.promises.copyFile( + file.path, + target, + fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE, + ); + await verifyArchiveSource(file); + staged.push(target); + } + signal.throwIfAborted(); + if (Date.now() >= expiresAt) + throw new AppError('COMMAND_FAILED', 'Recording archive copy expired.'); + fs.mkdirSync(path.dirname(archivePath), { recursive: true }); + const linked: string[] = []; + try { + for (const [index, destination] of paths.entries()) { + fs.linkSync(staged[index]!, destination); + linked.push(destination); + } + } catch (error) { + for (const destination of linked) fs.unlinkSync(destination); + throw error; + } + return paths; + } finally { + await fs.promises.rm(scratch, { recursive: true, force: true }).catch(() => {}); + } + }; + let abort!: () => void; + const pending = new Promise((resolve, reject) => { + abort = () => reject(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + if (signal.aborted) abort(); + else void copy().then(resolve, reject); + }); + try { + const outcome = await settleWithin(() => pending, expiresAt - Date.now(), { keepAlive: false }); + if (outcome.kind === 'deadline') + throw new AppError('COMMAND_FAILED', 'Recording archive copy expired.'); + return outcome.value; + } finally { + signal.removeEventListener('abort', abort); + } +} + +async function verifyArchiveSource(file: { path: string; sourceIdentity: string }) { + if (recordingExportFileIdentity(await fs.promises.lstat(file.path)) !== file.sourceIdentity) + throw new AppError( + 'COMMAND_FAILED', + 'Recording export changed during archive materialization.', + ); +} diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 07c0fca721..74a34d13c5 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -249,14 +249,23 @@ async function finishSessionScreenRecording(params: { await screenRecordingDurableResource.confirmLiveMissing({ binding, resource: recording }); return; } - const completion = await finishLiveScreenRecording({ + await finishLiveScreenRecording({ binding, intent: 'disposal', confirmedMissing, }); - if (!params.ref.session.lease) return; - const { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); - retainLeasedSessionRecording(params.ref, completion, recording.envelope.metadata); + const record = screenRecordingDurableResource.store.read( + screenRecordingDurableResource.store.resolvePath(binding.sessionDir), + ); + if ( + record.status !== 'decoded' || + record.envelope.lifecycle !== 'completed' || + record.envelope.fence.token !== recording.envelope.fence.token || + record.envelope.fence.generation !== recording.envelope.fence.generation + ) + return; + const { retainSessionRecording } = await import('./recording-outputs.ts'); + await retainSessionRecording(params.ref, record.envelope); } async function finishSessionAudioProbe(params: { diff --git a/packages/platform-android/src/recording/chunk-path.ts b/packages/platform-android/src/recording/chunk-path.ts deleted file mode 100644 index 881991d57a..0000000000 --- a/packages/platform-android/src/recording/chunk-path.ts +++ /dev/null @@ -1,16 +0,0 @@ -import path from 'node:path'; - -/** - * The host path of a recording's `index`th file (1-based). The first file keeps the base path and each - * later one takes a `.part-NNN` suffix. Pulled, served and journaled chunk sets all follow this one - * rule from their own base, which is what lets an attempt that never ran the pull name the files a - * previous attempt left behind. - */ -export function chunkPathAt(basePath: string, index: number): string { - if (index === 1) return basePath; - const parsed = path.parse(basePath); - return path.join( - parsed.dir, - `${parsed.name}.part-${String(index).padStart(3, '0')}${parsed.ext || '.mp4'}`, - ); -} diff --git a/packages/platform-android/src/recording/chunks.ts b/packages/platform-android/src/recording/chunks.ts index f958645ffd..7729d43d21 100644 --- a/packages/platform-android/src/recording/chunks.ts +++ b/packages/platform-android/src/recording/chunks.ts @@ -2,7 +2,7 @@ import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runti import { provesAndroidScreenRecordTermination } from '@agent-device/contracts/screen-recording-runtime-host'; import type { NativePathDisposition } from '@agent-device/contracts/recording-native-path'; import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; -import { chunkPathAt } from './chunk-path.ts'; +import { chunkPathAt } from '@agent-device/capture-kit/recording-output-path'; import type { NativeChunk } from './manifest.ts'; type Transport = Awaited>; diff --git a/packages/platform-android/src/recording/finalize.ts b/packages/platform-android/src/recording/finalize.ts index 9454da7194..bbe1931a0b 100644 --- a/packages/platform-android/src/recording/finalize.ts +++ b/packages/platform-android/src/recording/finalize.ts @@ -11,7 +11,7 @@ import type { import type { ScreenRecordingFinalization } from '@agent-device/contracts/recording-stop-progress'; import { stopAndExportScreenRecording } from '@agent-device/capture-kit/recording-stop-sequence'; import { measureCapturedWindow } from './captured-window.ts'; -import { chunkPathAt } from './chunk-path.ts'; +import { chunkPathAt } from '@agent-device/capture-kit/recording-output-path'; import { cleanupChunks, nativeChunksDisposition, diff --git a/packages/platform-android/src/recording/manifest-validation.ts b/packages/platform-android/src/recording/manifest-validation.ts index c8ad5fc90b..c33492d4d1 100644 --- a/packages/platform-android/src/recording/manifest-validation.ts +++ b/packages/platform-android/src/recording/manifest-validation.ts @@ -5,7 +5,7 @@ import type { ScreenRecordingChunk, ScreenRecordingCompletion, } from '@agent-device/contracts/screen-recording-runtime'; -import { chunkPathAt } from './chunk-path.ts'; +import { chunkPathAt } from '@agent-device/capture-kit/recording-output-path'; import type { AndroidRecordingDescriptor, NativeChunk, NativeManifest } from './manifest.ts'; const nativeRecordingPath = diff --git a/packages/replay-port/src/daemon-port/command-types.ts b/packages/replay-port/src/daemon-port/command-types.ts index 5f8c7fa9d8..60981495d4 100644 --- a/packages/replay-port/src/daemon-port/command-types.ts +++ b/packages/replay-port/src/daemon-port/command-types.ts @@ -1,3 +1,5 @@ +import type { ReplaySuiteRecordingArtifact } from '@agent-device/contracts/replay'; +import type { ReplayTestCleanupSession } from '@agent-device/contracts/replay-test-execution'; import type { DaemonWireRequest } from '@agent-device/contracts/command'; import type { ReplayDivergenceResume, ReplayRepairHint } from '@agent-device/contracts/divergence'; import type { @@ -97,8 +99,6 @@ export type ReplayTestVideoOwner = Readonly<{ throwIfCanceled: () => void; }>; -type ReplayTestSessionCleanup = (sessionName: string) => Promise; - export type ReplayTestCommand = ReplayCommand & Readonly<{ createSession: ReplayTestSessionFactory; @@ -107,6 +107,7 @@ export type ReplayTestCommand = ReplayCommand & requestId: string | undefined, task: () => Promise, ) => Promise; - cleanupSession: ReplayTestSessionCleanup; + cleanupSession: ReplayTestCleanupSession; video?: ReplayTestVideoOwner; + recordingOutputs?: () => readonly ReplaySuiteRecordingArtifact[]; }>; diff --git a/packages/replay-port/src/daemon-port/session-replay-video-recording.ts b/packages/replay-port/src/daemon-port/session-replay-video-recording.ts index 2a424c0763..9cb81bbc42 100644 --- a/packages/replay-port/src/daemon-port/session-replay-video-recording.ts +++ b/packages/replay-port/src/daemon-port/session-replay-video-recording.ts @@ -108,7 +108,9 @@ export async function finalizeReplayTestVideoRecording( const stopResponse = await params.video.record( replayVideoRecordRequest({ req, sessionName, phase: 'stop' }), ); - collectReplayActionArtifactPaths(stopResponse).forEach((entry) => artifactPaths.add(entry)); + if (!stopResponse.ok || !stopResponse.data?.artifacts?.some(({ artifactId }) => artifactId)) { + collectReplayActionArtifactPaths(stopResponse).forEach((entry) => artifactPaths.add(entry)); + } appendVideoTimingEvent(appendTimingEvent, { type: 'video_recording_stop', session: sessionName, diff --git a/packages/replay-port/src/daemon-port/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 46e3756d09..f4831c993e 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -8,6 +8,7 @@ import type { CommandFlags, DaemonWireRequest } from '@agent-device/contracts/co import type { ReplayDispatchOptions, ReplaySuiteResult, + ReplaySuiteRecordingArtifact, ReplayScriptSourceBundle, } from '@agent-device/contracts/replay'; import { REPLAY_SCRIPT_SOURCE_REQUIRED_MESSAGE } from '@agent-device/replay-port/script-source'; @@ -184,7 +185,9 @@ export async function runReplayTestCommand(command: ReplayTestCommand): Promise< try { suiteRequest = { ...toReplayTestSuiteRequest(req, sessionName, command.host.cwd), - ...(command.publicNetworkOnly ? { suiteInvocationId: randomUUID() } : {}), + ...(command.publicNetworkOnly || req.meta?.clientArtifactPaths?.artifactsDir + ? { suiteInvocationId: randomUUID() } + : {}), }; sourceBundles = requireReplayTestScriptSources(req); } catch (error) { @@ -298,7 +301,15 @@ export async function runReplayTestCommand(command: ReplayTestCommand): Promise< cleanupSession, }); return outcome.status === 'completed' - ? { ok: true, data: attachRemoteReplayTestArtifacts(outcome.data, req) } + ? { + ok: true, + data: attachRemoteReplayTestArtifacts( + outcome.data, + req, + command.recordingOutputs?.(), + command.publicNetworkOnly, + ), + } : errorResponse(outcome.error.code, outcome.error.message); } @@ -375,41 +386,65 @@ function withOriginalTestRefusalGuidance( export function attachRemoteReplayTestArtifacts( data: ReplaySuiteResult, req: DaemonWireRequest, + recordings: readonly ReplaySuiteRecordingArtifact[] = [], + publicNetworkOnly = false, ): DaemonResponseData { const clientRoot = req.meta?.clientArtifactPaths?.artifactsDir; const daemonRoot = data.artifactsDir; - if (!clientRoot || !daemonRoot) return data; - - // The directory the client will actually extract the download into, on ITS filesystem — - // `clientRoot` plus the same invocation-id segment `daemonRoot` ends in (see doc comment). - const clientSuiteRoot = path.join(clientRoot, path.basename(daemonRoot)); - const remapArtifactsDir = (candidate: string): string => - candidate === daemonRoot || candidate.startsWith(daemonRoot + path.sep) + if (!clientRoot && !publicNetworkOnly) { + return recordings.length > 0 ? { ...data, recordingArtifacts: recordings } : data; + } + const clientSuiteRoot = daemonRoot + ? path.join(clientRoot ?? '', path.basename(daemonRoot)) + : undefined; + const project = (candidate: string) => + daemonRoot && + clientSuiteRoot && + (candidate === daemonRoot || candidate.startsWith(daemonRoot + path.sep)) ? clientSuiteRoot + candidate.slice(daemonRoot.length) - : candidate; - // `tests` and `failures` both come from the scheduler's own `results` array - // (`summarizeReplayTestResults`) and share object references for every failed entry — each - // array is rewritten independently so both, not just whichever a caller happens to read, carry - // the caller-local path. + : path.basename(candidate); + + const projectResult = (test: T): T => { + const artifactPaths = test.status === 'failed' && test.error.details?.artifactPaths; + return { + ...test, + ...('artifactsDir' in test && test.artifactsDir + ? { artifactsDir: project(test.artifactsDir) } + : {}), + ...(test.status === 'failed' && Array.isArray(artifactPaths) + ? { + error: { + ...test.error, + details: { + ...test.error.details, + artifactPaths: artifactPaths + .filter((value): value is string => typeof value === 'string') + .map(project), + }, + }, + } + : {}), + }; + }; const rewritten: DaemonResponseData = { ...data, artifactsDir: clientSuiteRoot, - tests: data.tests.map((test) => - 'artifactsDir' in test && test.artifactsDir - ? { ...test, artifactsDir: remapArtifactsDir(test.artifactsDir) } - : test, - ), - failures: data.failures.map((failure) => - failure.artifactsDir - ? { ...failure, artifactsDir: remapArtifactsDir(failure.artifactsDir) } - : failure, - ), + ...(recordings.length > 0 + ? { + recordingArtifacts: recordings.map(({ path: recordingPath, ...recording }) => ({ + ...recording, + ...(clientRoot && recordingPath ? { path: project(recordingPath) } : {}), + })), + } + : {}), + tests: data.tests.map(projectResult), + failures: data.failures.map(projectResult), }; // No attempt ever ran (e.g. every source was filtered out), so the directory the client would // try to download was never created — the rewritten paths above are still correct (they name // where the suite WOULD have put its output), just nothing to register a download for. - if (!fs.existsSync(daemonRoot)) return rewritten; + if (!clientRoot || !daemonRoot || !fs.existsSync(daemonRoot)) return rewritten; return { ...rewritten, diff --git a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts index 67eb19ec58..92a7d706ea 100644 --- a/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts +++ b/packages/replay-test/src/internal/__tests__/session-test-runtime.test.ts @@ -100,7 +100,7 @@ test('runReplayTestAttempt keeps cancellation active until a timed-out replay se // the scheduler stops the suite instead of retrying into a contended session. expect(result.infrastructure).toBe(true); } - expect(cleanupSession).toHaveBeenCalledWith('default:test:timeout'); + expect(cleanupSession).toHaveBeenCalledWith('default:test:timeout', expect.any(Set)); expect(finalizeAttempt).toHaveBeenCalledWith( expect.objectContaining({ sessionName: 'default:test:timeout', @@ -154,7 +154,7 @@ test('runReplayTestAttempt keeps a passing replay passed when finalization fails expect(result.status).toBe('passed'); if (result.status !== 'passed') throw new Error(result.error.message); expect(result.warnings).toEqual(['Replay test finalization failed: failed to stop recording']); - expect(cleanupSession).toHaveBeenCalledWith('default:test:pass'); + expect(cleanupSession).toHaveBeenCalledWith('default:test:pass', expect.any(Set)); }); test('runReplayTestAttempt marks a failed cleanup as infrastructure so the scheduler cannot retry into its session', async () => { @@ -182,7 +182,7 @@ test('runReplayTestAttempt marks a failed cleanup as infrastructure so the sched expect(result.error.message).toBe('open "System Settings" failed'); expect(result.infrastructure).toBe(true); } - expect(cleanupSession).toHaveBeenCalledWith('default:test:cleanup-failure'); + expect(cleanupSession).toHaveBeenCalledWith('default:test:cleanup-failure', expect.any(Set)); }); // #1478 P3 characterization: attempt finalization happens before cleanup, always, and the @@ -232,8 +232,11 @@ test('runReplayTestAttempt cleans up once when a timed-out replay settles inside resolveReplay = resolve; }); const lifecycleEvents: string[] = []; - const cleanupSession = vi.fn(async () => { + const recording = path.join(artifactsDir, 'recording.mp4'); + const cleanupSession = vi.fn(async (_name: string, artifactPaths?: Set) => { lifecycleEvents.push('cleanup'); + fs.writeFileSync(recording, 'late-export'); + artifactPaths?.add(recording); }); const attemptPromise = runReplayTestAttempt({ @@ -263,6 +266,8 @@ test('runReplayTestAttempt cleans up once when a timed-out replay settles inside expect(result.error.details?.reason).toBe('timeout'); expect(result.error.details?.timeoutCleanupPending).toBe(undefined); expect(result.error.details?.timeoutMode).toBe('cooperative'); + expect(result.error.details?.artifactPaths).toContain(recording); + expect(result.artifactPaths).toContain(recording); expect(result.infrastructure).toBe(false); } expect(lifecycleEvents).toEqual(['finalize', 'cleanup']); @@ -292,7 +297,7 @@ test('runReplayTestAttempt cleans up without a finalizer and adds no finalizatio expect(result.status).toBe('passed'); if (result.status !== 'passed') throw new Error(result.error.message); expect(result.warnings).toEqual([]); - expect(cleanupSession).toHaveBeenCalledWith('default:test:no-finalizer'); + expect(cleanupSession).toHaveBeenCalledWith('default:test:no-finalizer', expect.any(Set)); }); test.each(['passed', 'failed'] as const)( diff --git a/packages/replay-test/src/internal/session-test-runtime.ts b/packages/replay-test/src/internal/session-test-runtime.ts index df4d4cc309..6d64e592e6 100644 --- a/packages/replay-test/src/internal/session-test-runtime.ts +++ b/packages/replay-test/src/internal/session-test-runtime.ts @@ -171,7 +171,7 @@ export async function runReplayTestAttempt( ts: new Date().toISOString(), session: sessionName, }); - const cleanupWarnings = await cleanupSession(sessionName); + const cleanupWarnings = await cleanupSession(sessionName, artifactPaths); if (outcome && cleanupWarnings) for (const warning of cleanupWarnings) outcome = appendReplayTestWarning(outcome, warning); appendReplayTestTimingEvent(tracePath, { @@ -210,16 +210,19 @@ function finishReplayTestAttempt( timedOut: boolean, artifactPaths: Set, ): ReplayTestAttemptOutcome { - if (timedOut && outcome?.status === 'failed') { - const paths = [...artifactPaths]; - return { - ...outcome, - artifactPaths: paths, - error: { - ...outcome.error, - details: { ...outcome.error.details, artifactPaths: paths }, - }, - }; + if (outcome) { + const paths = [...new Set([...outcome.artifactPaths, ...artifactPaths])]; + if (timedOut && outcome.status === 'failed') { + return { + ...outcome, + artifactPaths: paths, + error: { + ...outcome.error, + details: { ...outcome.error.details, artifactPaths: paths }, + }, + }; + } + return { ...outcome, artifactPaths: paths }; } return ( outcome ?? diff --git a/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index d47606954f..6eb87be0da 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -10,6 +10,8 @@ "packages/contracts/src/daemon-http.ts#buildDaemonHttpTenantHeaders": "sha256:e38a5f0b5ab07ee3a5fe3db229d0de750888660c55bf31692e100002be96de1d", "packages/contracts/src/daemon-http.ts#buildDaemonHttpUrl": "sha256:d38f1f8877588fbcb1fea8c52a5cb7dc205043e3fc698b3d78fdcf821fa80471", "packages/contracts/src/daemon-http.ts#isTenantOwnedSessionName": "sha256:c3cff883507d462548846554b89779cb815ceb265714575e57bee022b57c4bd1", + "packages/contracts/src/replay.ts#ReplaySuiteRecordingArtifact": "sha256:763f721f6f741cd7ed4ff9c5d7f823e52e57f360c1a3b730af5c82294dfe0952", + "packages/contracts/src/replay.ts#ReplaySuiteRecordingArtifacts": "sha256:de96749dcbc8b027b0dc1941244f7586ba368073ebcb275bc6e9c81465cf584a", "packages/contracts/src/request-progress.ts#CommandProgressEvent": "sha256:5ed7aee1157326d6ed99232c4b14375640ca7aef829131eb6c98bb54f3b1aed0", "packages/contracts/src/request-progress.ts#ReplayTestProgressEvent": "sha256:61df00308d0e21f2acfc4f73cb2c07cd0c251e827f1c87628e2d08338e1b5c84", "packages/contracts/src/request-progress.ts#ReplayTestSuiteProgressEvent": "sha256:2d6599bfcf1e94596c61f85a8a986874b59b8c05e82e5e00dd31e381a5b0fe84", @@ -78,7 +80,7 @@ "packages/daemon-client/src/daemon-client-transport.ts#readRemoteDaemonHealth": "sha256:bf9ca0ecb9dc00f18d0bf4acab30d544d680246b8cdacbc50f684db182b6f23b", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpAuthorizer": "sha256:1b2702a929ca9170db2ca97c08e3ab67e17edb3ee75325a576c4c1b9cdbebb44", "packages/daemon/src/server/downloadable-artifact-http.ts#DownloadableArtifactHttpRoute": "sha256:e63c4581ccde668913914149c9092d16ecf8a5cbd7ab33c6eb8617e77fc1015e", - "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:488d9fa81e423fdc5f323a3cf0ecabebc8b0785649667c21122401aaf2b2e745", + "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload": "sha256:70c9bdbc0cc57d5b91a0710e45cf4e4db0edc8e26be335a48e74abc746054de1", "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory": "sha256:38c9db160852bea71de8250e4c15f8d34b6fb3de2a5f59e69a91ae8885784c58", "packages/daemon/src/server/downloadable-artifact-http.ts#readArtifactId": "sha256:3472ee52d951fdf7ef00ee500298602c68f0e1e3b8c44ff51b09981efabf348c", "packages/daemon/src/server/downloadable-artifact-http.ts#readRequestPathname": "sha256:6b3a49c72365cf7da4552abef59862c073461f746025e28d409048815dd586f2", @@ -236,6 +238,16 @@ "packages/daemon/src/core/request-session-intake.ts#resolveRequestSessionAtIntake": "sha256:d620b6ee56a8c2f74d2c161016fa19974cbc833e3b87fa522411e35b381d9bc9" }, "compatibleChanges": [ + { + "declaration": "packages/contracts/src/replay.ts#ReplaySuiteRecordingArtifact", + "digest": "sha256:763f721f6f741cd7ed4ff9c5d7f823e52e57f360c1a3b730af5c82294dfe0952", + "rationale": "The optional suite recording list adds a filename and can omit the client-local archive path when no destination was supplied. Released peers ignore the list and still receive the same test-artifacts archive." + }, + { + "declaration": "packages/contracts/src/replay.ts#ReplaySuiteRecordingArtifacts", + "digest": "sha256:de96749dcbc8b027b0dc1941244f7586ba368073ebcb275bc6e9c81465cf584a", + "rationale": "Adds an optional suite result member describing a recording that finished in an attempt or its cleanup. A released client ignores the new member and still downloads the original test-artifacts archive. A released daemon omits the member, which stays optional." + }, { "declaration": "packages/kernel/src/contracts.ts#DaemonRequestMeta", "digest": "sha256:c2b14225388041f3a6e708c898c512f91b9b20e51a2656a1fa0d5bfa5989fa30", @@ -283,8 +295,8 @@ }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactDownload", - "digest": "sha256:488d9fa81e423fdc5f323a3cf0ecabebc8b0785649667c21122401aaf2b2e745", - "rationale": "Implementation-only daemon changes under ADR 0006: #3753 passes the runtime host environment into archiving; #4165 uses a bounded, abortable Node pipeline and validates the declared byte length, with idempotent reader release after completion or failed setup. The handler waits for file readiness before setting headers and starting the pipeline, so open errors use the existing JSON error response. Setup errors clear artifact-only headers first. Successful status codes, headers and artifact bytes retain their existing contracts. Failed or incomplete streaming reads close the HTTP transfer instead of hanging; released clients already treat an interrupted download as failure. Routes, authorization and error JSON shapes are unchanged, so no peer must parse a new payload or send a new field. Implementation-only follow-up to #4165 under ADR 0006: response close cancels artifact preparation and streaming through an internal AbortSignal. Shared builds continue for other downloads. The existing streamed failure helper now owns the same pre-header JSON error and post-header connection destruction. Successful status, headers, bytes, routes and authorization retain their existing contracts; disconnected clients receive no new payload. A response that has finished writing is not cancelled by its normal close event, so successful pipeline completion keeps its existing success semantics. Caller cancellation is normalized to the existing request_canceled error instead of forwarding caller-supplied reasons. Artifact expiry and download deadlines keep their existing reasons. The shared HTTP disconnect helper preserves typed cancellation on aborted requests and unfinished response closes. Directory preparation counts inventory and download callers together, so one disconnected download cannot abort an inventory caller's build; successful response fields and authorization stay unchanged. #4912 reads the existing x-agent-device-lease-id request header. A download of an artifact that a lease produced needs that lease id, else it fails with the existing 401 REST error shape and reason LEASE_OUTPUT_MISMATCH. Released clients since 0.21.28 send the header from the request that produced the artifact. A caller that omits it fails clearly and misreads no payload. Unleased artifacts keep their tenant rule. The size-mismatch failure reads artifact_size_mismatch from its ReasonTable row, preserving the published reason value." + "digest": "sha256:70c9bdbc0cc57d5b91a0710e45cf4e4db0edc8e26be335a48e74abc746054de1", + "rationale": "A recording download persists consumption before releasing the completed file. A receipt write failure interrupts the stream through the existing transfer failure path. Successful headers, bytes, authorization, and download framing stay compatible." }, { "declaration": "packages/daemon/src/server/downloadable-artifact-http.ts#handleArtifactInventory", diff --git a/test/wire-compat/surface.ts b/test/wire-compat/surface.ts index 0de517479e..01a8a2c062 100644 --- a/test/wire-compat/surface.ts +++ b/test/wire-compat/surface.ts @@ -312,6 +312,11 @@ export const WIRE_SURFACE: readonly WireSurfaceGroup[] = [ 'ScriptDeliveryFailure', 'readScriptDeliveryFailure', ), + ...from( + 'packages/contracts/src/replay.ts', + 'ReplaySuiteRecordingArtifacts', + 'ReplaySuiteRecordingArtifact', + ), ...from( KERNEL_ERRORS, 'DaemonError', diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index dc5650ee51..d1f9ce5531 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -105,6 +105,15 @@ list the artifact and the download fails with `UNAUTHORIZED` and reason `LEASE_O The same header is required to read the diagnostics record of a request on a leased session. This holds after the session closes, for as long as the daemon keeps the file. +After a remote recording finishes, its video, chunks, and telemetry stay available for up to +15 minutes or until downloaded. If a lease produced the recording, send that lease ID to +list or download it, including after the session closes. A recorded test suite includes exports +that finish during cleanup in its artifact archive. + +Stop and download active remote recordings before upgrading the daemon. If you upgrade during a +recording and `record stop` returns `LEASE_OUTPUT_MISMATCH`, recover any finished files from the +daemon host or start a fresh recording for remote download. + By default, artifacts leave the inventory after download or after 15 minutes. `AGENT_DEVICE_RETAIN_ARTIFACTS` keeps downloaded artifacts in inventory until expiry. Downloads already in progress can finish before their files are removed, including overlapping downloads of a directory archive. diff --git a/website/docs/docs/replay-e2e.md b/website/docs/docs/replay-e2e.md index 82a563fae9..44123a36dd 100644 --- a/website/docs/docs/replay-e2e.md +++ b/website/docs/docs/replay-e2e.md @@ -189,6 +189,7 @@ agent-device test ./workflows --reporter default --reporter junit:./tmp/junit.xm - `--platform` filters which files run; with a filter, files without a `context platform=` header are skipped. When filtering leaves no runnable sources, the no-match error reports how many sources were skipped for having no `context platform=` header versus how many declared another platform. Add the header to run a file under a filter, or omit `--platform` and let the selected device decide. - Set `context timeout=...` and `context retries=...` per script; CLI flags override them. Retries are capped at `3`, and duplicate keys in the context header fail fast instead of silently overriding each other. - By default, suite artifacts are written under `.agent-device/test-artifacts//...`. Each attempt writes `replay.ad`, `result.txt`, and `replay-timing.ndjson`. Failed attempts also keep copied logs and artifact files when the replay produced them. +- With remote `test --record-video --json`, `recordingArtifacts` includes verified recordings that finish during a test or its cleanup. You can download each `artifactId` separately with the producing lease, even after downloading the suite archive. - Copied diagnostic artifacts receive numbered filenames when their names collide with another artifact, a replay source, timing trace, or attempt manifest. `result.txt` lists the retained names in `copiedArtifacts`. - `replay-timing.ndjson` records attempt, cleanup, and per-step start/stop events with durations. Upload it from CI even for passing runs when comparing local and CI performance. - When an attempt hits its timeout, it is marked failed and the replay gets a short grace period to stop before the session is cleaned up.