From e942eedc4faa3c55beebcbeaa01090276a827f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 23 Nov 2026 22:37:31 +0100 Subject: [PATCH 01/12] fix(daemon): commit recording exports with producer proof --- .../0024-screen-recording-provable-signal.md | 13 +- .../screen-recording-session-resource.ts | 47 ++++++- .../src/durable-capture/definition.ts | 5 +- .../src/durable-capture/finish-recovered.ts | 2 +- .../src/durable-capture/recovery.ts | 5 +- .../src/durable-capture/transitions.ts | 13 +- .../capture-kit/src/recording/output-path.ts | 15 +++ packages/command-surface/src/replay/index.ts | 7 + packages/contracts/src/facades/replay.ts | 1 + .../contracts/src/replay-test-execution.ts | 5 +- packages/contracts/src/replay.ts | 12 +- packages/daemon/src/core/session-store.ts | 9 +- .../daemon/src/resources/artifact-tracking.ts | 111 ++++++++++++---- .../__tests__/request-finalization.test.ts | 88 +++++++------ .../http-server-capture-publication.test.ts | 22 ++-- .../http/http-server-capture-tenant.test.ts | 70 +++++++++- .../http/http-server-remote-output.test.ts | 30 +++-- .../daemon/src/server/request-finalization.ts | 4 +- packages/daemon/src/server/request-router.ts | 10 +- .../leased-recording-retention.test.ts | 97 +++++++------- .../record-runtime-stop-recovery.test.ts | 4 - .../__tests__/record-runtime.fixtures.ts | 4 +- .../handlers/record-runtime-response.ts | 7 +- .../src/sessions/handlers/record-runtime.ts | 119 ++++++++--------- ...n-replay-command-recording-cleanup.test.ts | 123 ++++++++++++++++++ .../handlers/session-replay-command.ts | 70 ++++++---- .../handlers/session-replay-video-owner.ts | 11 +- .../sessions/leased-recording-retention.ts | 68 +++------- .../daemon/src/sessions/recording-outputs.ts | 111 ++++++++++++++++ .../daemon/src/sessions/session-teardown.ts | 13 +- .../src/recording/chunk-path.ts | 16 --- .../platform-android/src/recording/chunks.ts | 2 +- .../src/recording/finalize.ts | 2 +- .../src/recording/manifest-validation.ts | 2 +- .../src/daemon-port/command-types.ts | 7 +- .../src/daemon-port/test-command.ts | 18 ++- .../__tests__/session-test-runtime.test.ts | 15 ++- .../src/internal/session-test-runtime.ts | 25 ++-- test/wire-compat/ledger.json | 12 ++ test/wire-compat/surface.ts | 5 + website/docs/docs/remote-proxy.md | 5 + 41 files changed, 847 insertions(+), 358 deletions(-) create mode 100644 packages/daemon/src/sessions/handlers/session-replay-command-recording-cleanup.test.ts create mode 100644 packages/daemon/src/sessions/recording-outputs.ts delete mode 100644 packages/platform-android/src/recording/chunk-path.ts diff --git a/docs/adr/0024-screen-recording-provable-signal.md b/docs/adr/0024-screen-recording-provable-signal.md index 7211d84905..576fef273f 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -287,12 +287,15 @@ 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 and records the producing lifetime, tenant, and lease verifier or unleased marker at start. +The completed manifest records the file identities of the video, later chunks, and telemetry. +Explicit stop and teardown commit the verified files under that producer's authority. 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. +A retry can serve the same artifact IDs while the entries remain available. +Only the original lease credential can list or download leased exports (ADR 0007). +A manifest from an earlier release must carry its explicit owner before it can serve a remote export. +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. ### 2.6 Native markers 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..8e9515cb50 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 @@ -1,3 +1,4 @@ +import fs from 'node:fs'; import type { JsonObject } from '@agent-device/contracts/client'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; @@ -34,7 +35,12 @@ export const screenRecordingDurableResource = createDurableCaptureResource< resourceKind: 'screen-recording', displayName: 'screen recording', store: screenRecordingResourceStore, - completionMetadata: encodeScreenRecordingCompletionMetadata, + completionMetadata: async (result, metadata) => ({ + ...encodeScreenRecordingCompletionMetadata(result), + ...(typeof metadata?.remoteCapturePath === 'string' + ? { remoteCaptureExport: await verifyRecordingExport(metadata.remoteCapturePath, result) } + : {}), + }), // 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 @@ -72,6 +78,45 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } +async function verifyRecordingExport(reservedPath: string, completion: ScreenRecordingCompletion) { + const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ + import('../recording/output-path.ts'), + import('../recording/telemetry.ts'), + ]); + 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)); + return { + completedAt: Date.now(), + identities: matchesReservation ? files.map(readRecordingExportIdentity) : [], + }; +} + +function readRecordingExportIdentity(file: string): string | null { + try { + return recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); + } catch { + return null; + } +} + +export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null { + return stat?.isFile() + ? `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` + : null; +} + export function encodeScreenRecordingCompletionMetadata( completion: ScreenRecordingCompletion, ): JsonObject { diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index f9adebf12a..857fb121c5 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -56,7 +56,10 @@ export type DurableCaptureRecordDefinition = Readonly<{ resourceKind: K; displayName: string; store: DurableCaptureResourceStore; - completionMetadata(result: C): JsonObject; + completionMetadata( + result: C, + metadata: DurableResourceEnvelope['metadata'], + ): JsonObject | Promise; /** * The completion this kind stored in a record that is already committed, or nothing it can serve. * diff --git a/packages/capture-kit/src/durable-capture/finish-recovered.ts b/packages/capture-kit/src/durable-capture/finish-recovered.ts index 98db3919f9..7fa396910b 100644 --- a/packages/capture-kit/src/durable-capture/finish-recovered.ts +++ b/packages/capture-kit/src/durable-capture/finish-recovered.ts @@ -82,7 +82,7 @@ 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..aa1701ef29 100644 --- a/packages/capture-kit/src/durable-capture/recovery.ts +++ b/packages/capture-kit/src/durable-capture/recovery.ts @@ -193,7 +193,10 @@ async function settleRecoveryAuthority( +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), + ...(await definition.completionMetadata(outcome.result, lease.envelope.metadata)), phase: 'completed', }, }); 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/command-surface/src/replay/index.ts b/packages/command-surface/src/replay/index.ts index 3639075eba..1e1b5c08c1 100644 --- a/packages/command-surface/src/replay/index.ts +++ b/packages/command-surface/src/replay/index.ts @@ -150,6 +150,13 @@ 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(), artifactId: stringSchema() }, + ['session', 'path'], + ), + }, 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/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..660e9f326f 100644 --- a/packages/contracts/src/replay.ts +++ b/packages/contracts/src/replay.ts @@ -145,7 +145,17 @@ export type ReplaySuiteTestResult = | ReplaySuiteTestFailed | ReplaySuiteTestSkipped; -export type ReplaySuiteResult = { +export type ReplaySuiteRecordingArtifact = Readonly<{ + session: string; + path: string; + artifactId?: string; +}>; + +type ReplaySuiteRecordingArtifacts = { + recordingArtifacts?: readonly ReplaySuiteRecordingArtifact[]; +}; + +export type ReplaySuiteResult = ReplaySuiteRecordingArtifacts & { total: number; executed: number; passed: number; 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-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index f547049eef..3887150204 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -177,7 +177,7 @@ type ArtifactEntry = { artifactPath: string; tenantId?: string; leaseVerifier?: string; - reservation?: Readonly<{ directory: string; lifetimeId: string }>; + reservation?: Readonly<{ directory?: string; lifetimeId: string; recording?: true }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; artifactType: DaemonArtifactType | undefined; @@ -311,18 +311,72 @@ 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 }); }, }; } +function bindFileOutputDelivery( + artifacts: Map, + artifact: DaemonArtifact & { artifactId: string }, + preserveOnFailure = false, +) { + committedFileOutputDeliveries.set(artifact, (delivered) => { + const entry = artifacts.get(artifact.artifactId); + if (!entry) return; + if (delivered) entry.awaitingDelivery = false; + else if (!preserveOnFailure) requestArtifactCleanup(artifacts, artifact.artifactId, entry); + }); + return artifact; +} + +/** Commits files from an independently durable recording reservation. */ +export function commitRecordingFileOutputs( + files: readonly (DaemonArtifact & { path: string; stat: fs.Stats })[], + producer: FileOutputProducer, + sessionName: string | undefined, + completedAt: number, + deleteAfterDownload: boolean, +): DaemonArtifact[] { + if (completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now()) { + throw new AppError('COMMAND_FAILED', 'Recording output retention expired.'); + } + const artifacts = pendingArtifacts(); + return files.map(({ path: artifactPath, stat, ...delivery }) => { + const output = outputIdentity(stat, true); + const owner = producer.leaseVerifier ?? undefined; + const existing = [...artifacts].find( + ([, entry]) => + !entry.cleanupRequested && + entry.reservation?.lifetimeId === producer.lifetimeId && + entry.artifactPath === artifactPath && + entry.output === output && + entry.tenantId === producer.tenantId && + entry.leaseVerifier === owner, + ); + const artifactId = existing?.[0] ?? crypto.randomUUID(); + if (!existing) { + addArtifactEntry( + artifacts, + artifactId, + { + artifactPath, + artifactType: delivery.artifactType, + fileName: delivery.fileName, + tenantId: producer.tenantId, + leaseVerifier: owner, + sessionName, + }, + output, + { remainingEntries: 1, deleteAfterDownload }, + { lifetimeId: producer.lifetimeId, recording: true }, + completedAt, + ); + } + return bindFileOutputDelivery(artifacts, { ...delivery, artifactId }, true); + }); +} + /** What a request presents to list or download artifacts. */ export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; @@ -368,12 +422,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, @@ -425,14 +482,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?: true): 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?: ArtifactEntry['reservation'], +): string | undefined { try { - return outputIdentity(noFollow ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath)); + return outputIdentity( + reservation ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath), + reservation?.recording, + ); } catch { return undefined; } @@ -542,7 +607,7 @@ 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) !== entry.output) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -597,7 +662,7 @@ export async function listDownloadableArtifacts( function statRegisteredOutput(artifactId: string, entry: ArtifactEntry): fs.Stats | undefined { try { const stat = statArtifactPath(entry); - if (outputIdentity(stat) === entry.output) return stat; + if (outputIdentity(stat, entry.reservation?.recording) === entry.output) return stat; } catch { // A missing output is cleaned up like a replaced one. } @@ -646,7 +711,7 @@ function readDownloadableArtifactEntry( cleanupDownloadableArtifact(artifactId); throw new AppError('COMMAND_FAILED', `Artifact file is missing: ${entry.artifactPath}`); } - if (outputIdentity(stat) !== entry.output) { + if (outputIdentity(stat, entry.reservation?.recording) !== entry.output) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -834,11 +899,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 { 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/http/http-server-capture-publication.test.ts b/packages/daemon/src/server/http/http-server-capture-publication.test.ts index 022233f64c..106fa35cb1 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,12 +278,16 @@ 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({ 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..b307cc27f8 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,7 @@ 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 { defineUse } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createDaemonHttpServer } from './http-server.ts'; @@ -20,7 +21,7 @@ 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])( @@ -42,6 +43,26 @@ test.each([false, true])( fs.writeFileSync(input.outputPath, 'private-recording'); return await start(input); }); + const finish = harness.runtime.finish.getMockImplementation()!; + harness.runtime.finish.mockImplementation(async () => { + const stopped = await finish(); + 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 +90,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( @@ -121,6 +144,11 @@ test.each([false, 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 +165,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 +184,34 @@ 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); + 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..10f8cdf8b8 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', @@ -313,12 +322,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( { 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 index f7487e568d..78362df716 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -2,6 +2,7 @@ import fs from 'node:fs'; import http from 'node:http'; 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, @@ -28,30 +29,13 @@ import { cleanupDownloadableArtifact, leaseVerifier, listDownloadableArtifacts, - trackDownloadableArtifact, + settleCommittedFileOutputs, } 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 { commitRecordingOutputs } from '../recording-outputs.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 }; @@ -63,8 +47,6 @@ afterEach(async () => { cleanupDownloadableArtifact(id); } for (const filePath of createdPaths.splice(0)) fs.rmSync(filePath, { force: true }); - tracking.failOnCall = 0; - tracking.calls = 0; vi.useRealTimers(); }); @@ -99,6 +81,7 @@ function publishRecordingSession( finishFails?: boolean; unleasedProducer?: boolean; producerTenant?: string; + omitTelemetry?: boolean; } = {}, ) { const session: SessionState = makeIosSession(ADDRESS, { @@ -130,7 +113,7 @@ function publishRecordingSession( } createdPaths.push(recordingExport.outPath, recordingExport.telemetryPath); fs.writeFileSync(recordingExport.outPath, 'video'); - fs.writeFileSync(recordingExport.telemetryPath, '{"events":[]}'); + if (!options.omitTelemetry) fs.writeFileSync(recordingExport.telemetryPath, '{"events":[]}'); return { status: 'completed', result: completion } as const; }); const forceCleanup = vi.fn(async () => ({ status: 'cleaned' }) as const); @@ -201,6 +184,9 @@ test('a leased session teardown keeps the remote recording export downloadable b ]); 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) => { @@ -268,16 +254,15 @@ test('a failed teardown finish runs forced cleanup and keeps nothing for downloa 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; +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); + publishRecordingSession(sessionStore, recordingExport, { omitTelemetry: true }); await teardown(sessionStore); expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); - expect(fs.existsSync(recordingExport.outPath)).toBe(false); + expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); expect(fs.existsSync(recordingExport.telemetryPath)).toBe(false); }); @@ -293,28 +278,13 @@ test('a record stop replay after a leased teardown serves the artifacts teardown 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, + const record = screenRecordingResourceStore.read( + screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), ); + if (record.status !== 'decoded') throw new Error('Expected completed recording manifest'); + const artifacts = commitRecordingOutputs(record.envelope, recovery.completion); - expect(replayed.ok && replayed.data?.artifacts?.map((a) => a.artifactId)).toEqual( - retained.map((a) => a.id), - ); + 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' }), @@ -434,3 +404,38 @@ test.each([undefined, 'former-tenant'])( ); }, ); + +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 remote = { publicNetworkOnly: true } as const; + try { + await producer.run(async () => { + expect(await harness.run(['start'], { tenantId: TENANT }, undefined, remote)).toMatchObject({ + ok: true, + }); + expect(await harness.run(['stop'], { tenantId: TENANT }, undefined, remote)).toMatchObject({ + ok: true, + }); + }); + await successor.run(async () => { + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + const stopped = await harness.run(['stop'], { tenantId: 'other' }, undefined, remote); + if (!stopped.ok) throw new Error(stopped.error.message); + settleCommittedFileOutputs(stopped.data?.artifacts, true); + expect(await listDownloadableArtifacts({ tenantId: 'other' }, {})).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([ + expect.objectContaining({ artifactType: 'screen-recording' }), + ]); + }); + } finally { + successor.dispose(); + producer.dispose(); + } +}); 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..81674e7c11 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 @@ -16,8 +16,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 +146,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 () => { 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..86d03d1d33 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts @@ -135,7 +135,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 +168,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..00aa327c4f 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime-response.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime-response.ts @@ -73,14 +73,17 @@ export function buildRecordingUnsupportedResponse( }; } -export function buildRecordingStopResponse(completion: ScreenRecordingCompletion): DaemonResponse { +export function buildRecordingStopResponse( + completion: ScreenRecordingCompletion, + artifacts = recordingStopArtifacts(completion), +): DaemonResponse { return { ok: true, data: { recording: 'stopped', outPath: completion.outPath, telemetryPath: completion.telemetryPath, - artifacts: recordingStopArtifacts(completion), + artifacts, recordingBackend: completion.backend, recordingScope: completion.scope, recordOnlySession: completion.recordOnlySession, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index a5a11a488c..7ad0e4903b 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -52,7 +52,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,7 +70,7 @@ 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, @@ -82,6 +81,7 @@ import { recordingOutputLeaseVerifier, UNLEASED_CAPTURE, } from './record-runtime-response.ts'; +import { commitRecordingOutputs } from '../recording-outputs.ts'; import { resolveRequestTargetDevice } from '../../core/request-device-resolution.ts'; /** @@ -103,6 +103,7 @@ export type RecordRuntimeHandlerParams = Readonly<{ bindExactDevice: BindExactDeviceRuntime; admissionLedger: ScreenRecordingAdmissionLedger; requestScope: PlatformRequestScope; + suiteCapture?: 'local' | 'remote'; retainDeviceExecutionLock(deviceId: string): Promise; throwIfCanceled(): void; }>; @@ -136,6 +137,7 @@ async function handleRecordCommandUnsafe( ) { return missingAppSessionResponse(req); } + if (plan.kind !== 'start') assertRequestMayStopRecording(params); const resolvedSession = await resolveRecordingSession(params, existingRef, plan); const { session } = resolvedSession; if (plan.kind === 'start') { @@ -257,14 +259,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 +298,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(); @@ -325,18 +325,26 @@ 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 } : {}), + ...(output.daemonOwned + ? { + remoteCaptureOutput: true, + remoteCapturePath: output.outputPath, + remoteCaptureLifetime: lifetimeId, + } + : {}), ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(suiteCapture ? { suiteRecordingLifetime: lifetimeId } : {}), remoteCaptureLease: leaseId ? leaseVerifier(leaseId) : UNLEASED_CAPTURE, }, }; @@ -353,12 +361,21 @@ 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 + ? { + ...resolveRecordingOutputPaths({ + requestedPath: params.req.positionals?.[1], + platform: session.device.platform, + cwd: params.sessionStore.host.cwd, + }), + ...(params.suiteCapture === 'remote' ? { daemonOwned: true as const } : {}), + } + : resolveRecordingStartPaths( + params.req, + session.device.platform, + params.sessionStore.host.cwd, + params.sessionStore.ensureSessionDir(params.sessionName), + ), }; } @@ -445,7 +462,6 @@ async function stopRecording( kind: 'stop-live' | 'stop-recovery', needsReadiness: boolean, ): Promise { - const leaseOwner = assertRequestMayStopRecording(params); let stopped: ScreenRecordingStop; try { stopped = @@ -463,8 +479,9 @@ async function stopRecording( throw error; } const completion = stopped.completion; - const response = buildRecordingStopResponse(completion); - const { daemonOwned, tenantId } = readRecordingOutput(params, completion, leaseOwner, ref); + const record = screenRecordingDurableResource.store.read( + screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), + ); if (stopped.recordsSessionAction) { recordSessionAction(params.sessionStore, ref, params.req, params.req.command, { action: 'stop', @@ -479,69 +496,35 @@ 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; -} - -function readRecordingOutput( - params: RecordRuntimeHandlerParams, - completion: ScreenRecordingCompletion, - leaseOwner: string | null | undefined, - ref: SessionRef | undefined, -): { daemonOwned: boolean; tenantId?: string } { - const resourcePath = screenRecordingDurableResource.resourcePath( - params.sessionStore, - params.sessionName, - ); - 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 }; + if (isLegacyRemoteRecordingOutput(completion)) throw leasedOutputRefusal('Recording'); + const envelope = record.status === 'decoded' ? record.envelope : undefined; + const artifacts = + envelope?.metadata?.remoteCaptureOutput === true + ? commitRecordingOutputs(envelope, completion) + : undefined; + return buildRecordingStopResponse(completion, artifacts); } /** - * 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 completed 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 { +function assertRequestMayStopRecording(params: RecordRuntimeHandlerParams): void { const record = screenRecordingDurableResource.store.read( screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), ); - if (record.status !== 'decoded') return undefined; + if (record.status !== 'decoded') return; const { metadata, lifecycle } = record.envelope; const owner = recordingOutputLeaseVerifier(metadata); if (owner === undefined && metadata?.remoteCaptureOutput === true) { throw leasedOutputRefusal('Recording'); } - if (typeof owner !== 'string') return owner; + if (typeof owner !== 'string') return; const presented = lifecycle === 'completed' ? resolveLeaseScope(params.req).leaseId : params.req.internal?.admittedLease?.leaseId; if (!requestHoldsOutputLease(owner, presented)) throw leasedOutputRefusal('Recording'); - return owner; } function deleteTerminalRecordOnlySession( 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..d2d1697674 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/session-replay-command-recording-cleanup.test.ts @@ -0,0 +1,123 @@ +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 { 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('a remote suite reports the recording that close exports after the attempt timed out', async () => { + 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'); + return outcome; + }); + 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(), + 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 output = (await listDownloadableArtifacts({ tenantId }, {})).find( + (artifact) => artifact.artifactType === 'screen-recording', + ); + expect(output?.id).toBeTypeOf('string'); + expect(data.recordingArtifacts).toEqual([ + expect.objectContaining({ + artifactId: output?.id, + path: expect.stringMatching(/client\/.*\/attempt-1\/recording\.mp4$/), + }), + ]); + cleanupDownloadableArtifact(output!.id); + expect(fs.existsSync(outputPath)).toBe(true); + } 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..f2743cb88a 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, + ReturnType[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,29 @@ 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 collectSuiteRecordingOutputs(sessionStore, ref)) { + artifactPaths?.add(output.path); + if (artifactPaths) recordingOutputs.set(output.path, output); + } + } + } }, signal, ); @@ -265,7 +281,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..1283389a2e 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,7 +108,7 @@ export function createReplayTestVideoOwner( }; } -function recordRequest(request: ReplayRecordVideoRequest): DaemonRequest { +function recordRequest(request: ReplayRecordVideoRequest, suite?: DaemonRequest): DaemonRequest { return { token: request.request.token, session: request.sessionName, @@ -110,5 +116,6 @@ function recordRequest(request: ReplayRecordVideoRequest): DaemonRequest { positionals: request.phase === 'start' ? ['start', request.outputPath] : ['stop'], flags: {}, meta: request.request.meta, + 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 index 2e2c91a87c..cde0bc5b29 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -1,77 +1,39 @@ -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 { settleCommittedFileOutputs } from '../resources/artifact-tracking.ts'; import { isLegacyRemoteRecordingOutput, - recordingStopArtifacts, recordingOutputLeaseVerifier, } from './handlers/record-runtime-response.ts'; +import { commitRecordingOutputs } from './recording-outputs.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'], + envelope: DurableResourceEnvelope<'screen-recording'>, ): void { const lease = ref.session.lease; - if (!lease || metadata?.remoteCaptureOutput !== true || isLegacyRemoteRecordingOutput(completion)) + const { metadata } = envelope; + if ( + metadata?.remoteCaptureOutput !== true || + isLegacyRemoteRecordingOutput(completion) || + recordingOutputLeaseVerifier(metadata) === undefined || + (metadata.remoteCaptureLifetime === undefined + ? !lease + : metadata.remoteCaptureLifetime !== ref.lifetime.journalId) + ) 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, - }), - ); - } + const artifacts = commitRecordingOutputs(envelope, completion, lease?.tenantId); + settleCommittedFileOutputs(artifacts, true); } 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) }, + data: { session: ref.address, 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..0577fac59f --- /dev/null +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -0,0 +1,111 @@ +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { readReplayableStoredCompletion } from '@agent-device/capture-kit/screen-recording-stop-recovery'; +import type { SessionRef } from '../core/session-state.ts'; +import type { SessionStore } from '../core/session-store.ts'; +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 { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-recording-session-resource'; +import { AppError } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; +import { + commitRecordingFileOutputs, + leasedOutputRefusal, + settleCommittedFileOutputs, +} from '../resources/artifact-tracking.ts'; +import { + isLegacyRemoteRecordingOutput, + recordingOutputLeaseVerifier, + recordingStopArtifacts, +} from './handlers/record-runtime-response.ts'; + +export function commitRecordingOutputs( + envelope: DurableResourceEnvelope<'screen-recording'>, + completion: ScreenRecordingCompletion, + legacyTenant?: string, +) { + const { metadata } = envelope; + const owner = recordingOutputLeaseVerifier(metadata); + if (owner === undefined || isLegacyRemoteRecordingOutput(completion)) { + throw leasedOutputRefusal('Recording'); + } + const proof = readRecordingExportProof(envelope); + const artifacts = recordingStopArtifacts(completion); + if (proof && proof.identities.length !== artifacts.length) { + throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); + } + const files = artifacts.map((artifact, index) => { + const artifactPath = artifact.path!; + const stat = fs.lstatSync(artifactPath, { throwIfNoEntry: false }); + if ( + !stat?.isFile() || + (proof && proof.identities[index] !== recordingExportFileIdentity(stat)) + ) { + throw new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); + } + return { ...artifact, path: artifactPath, stat }; + }); + const storedTenant = metadata?.remoteCaptureTenantId; + const tenantId = + !proof && owner === null && legacyTenant + ? legacyTenant + : typeof storedTenant === 'string' + ? storedTenant + : proof + ? undefined + : legacyTenant; + return commitRecordingFileOutputs( + files, + { + lifetimeId: proof?.lifetimeId ?? envelope.fence.token, + tenantId, + leaseVerifier: owner, + }, + tenantId ? tenantPublicSessionName(tenantId, envelope.sessionId) : envelope.sessionId, + proof?.completedAt ?? Date.now(), + metadata?.suiteRecordingLifetime === undefined, + ); +} + +function readRecordingExportProof(envelope: DurableResourceEnvelope<'screen-recording'>) { + if (envelope.lifecycle !== 'completed') { + throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); + } + const { metadata } = envelope; + const lifetimeId = metadata?.remoteCaptureLifetime; + if (lifetimeId === undefined && metadata?.remoteCapturePath === undefined) return undefined; + const verified = metadata?.remoteCaptureExport; + if ( + typeof lifetimeId !== 'string' || + !isRecord(verified) || + !Array.isArray(verified.identities) || + typeof verified.completedAt !== 'number' || + !Number.isFinite(verified.completedAt) + ) { + throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); + } + return { lifetimeId, identities: verified.identities, completedAt: verified.completedAt }; +} + +export function collectSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { + const record = screenRecordingResourceStore.read( + screenRecordingResourceStore.resolvePath(store.resolveSessionDir(ref.address)), + ); + if (record.status !== 'decoded' || record.envelope.lifecycle !== 'completed') return []; + const { envelope } = record; + if (envelope.metadata?.suiteRecordingLifetime !== ref.lifetime.journalId) return []; + const completion = readReplayableStoredCompletion(envelope.metadata); + if (!completion) return []; + const artifacts = recordingStopArtifacts(completion); + const committed = + envelope.metadata.remoteCaptureOutput === true + ? commitRecordingOutputs(envelope, completion) + : []; + settleCommittedFileOutputs(committed, true); + return artifacts.map((artifact, index) => ({ + session: ref.address, + path: artifact.path!, + artifactId: committed[index]?.artifactId, + })); +} diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 07c0fca721..108b5e0b82 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -254,9 +254,18 @@ async function finishSessionScreenRecording(params: { intent: 'disposal', confirmedMissing, }); - if (!params.ref.session.lease) return; + 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 { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); - retainLeasedSessionRecording(params.ref, completion, recording.envelope.metadata); + retainLeasedSessionRecording(params.ref, completion, 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/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 46e3756d09..3e362c5a15 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'; @@ -298,7 +299,10 @@ 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?.()), + } : errorResponse(outcome.error.code, outcome.error.message); } @@ -375,10 +379,13 @@ function withOriginalTestRefusalGuidance( export function attachRemoteReplayTestArtifacts( data: ReplaySuiteResult, req: DaemonWireRequest, + recordings: readonly ReplaySuiteRecordingArtifact[] = [], ): DaemonResponseData { const clientRoot = req.meta?.clientArtifactPaths?.artifactsDir; const daemonRoot = data.artifactsDir; - if (!clientRoot || !daemonRoot) return data; + if (!clientRoot || !daemonRoot) { + return recordings.length > 0 ? { ...data, recordingArtifacts: recordings } : 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). @@ -394,6 +401,13 @@ export function attachRemoteReplayTestArtifacts( const rewritten: DaemonResponseData = { ...data, artifactsDir: clientSuiteRoot, + ...(recordings.length > 0 + ? { + recordingArtifacts: recordings + .filter((recording) => recording.path.startsWith(daemonRoot + path.sep)) + .map((recording) => ({ ...recording, path: remapArtifactsDir(recording.path) })), + } + : {}), tests: data.tests.map((test) => 'artifactsDir' in test && test.artifactsDir ? { ...test, artifactsDir: remapArtifactsDir(test.artifactsDir) } 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..c44cdb72d0 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:5dbfc0751ef7c3650b669f11a1755a6715bec31978c83452881d16ebd42ecdcc", + "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", @@ -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:5dbfc0751ef7c3650b669f11a1755a6715bec31978c83452881d16ebd42ecdcc", + "rationale": "An entry in the optional recordingArtifacts member describes an attempt session, client-local archive path, and optional recording artifact ID. Existing archive delivery and recording stop framing are unchanged." + }, + { + "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", 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..e1825eb360 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -105,6 +105,11 @@ 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. + 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. From b2048fee9bc7182b4c90a31ca9b5b06798bb7b24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 08:38:52 +0100 Subject: [PATCH 02/12] fix(daemon): preserve verified recording output across delivery failures --- .../0024-screen-recording-provable-signal.md | 12 +- .../screen-recording-session-resource.ts | 29 ++- .../screen-recording-stop-recovery.ts | 16 +- .../src/resources/artifact-file-storage.ts | 102 ++++++++ .../daemon/src/resources/artifact-tracking.ts | 121 ++++++---- .../http/http-server-capture-tenant.test.ts | 43 +++- .../http/http-server-remote-suite.test.ts | 74 ++++++ .../leased-recording-retention.test.ts | 175 +++++++++++++- .../src/sessions/handlers/record-runtime.ts | 8 +- ...n-replay-command-recording-cleanup.test.ts | 223 ++++++++++-------- .../handlers/session-replay-command.ts | 4 +- .../sessions/leased-recording-retention.ts | 19 +- .../daemon/src/sessions/recording-outputs.ts | 79 +++++-- .../daemon/src/sessions/session-teardown.ts | 2 +- .../src/daemon-port/test-command.ts | 4 +- 15 files changed, 712 insertions(+), 199 deletions(-) create mode 100644 packages/daemon/src/resources/artifact-file-storage.ts create mode 100644 packages/daemon/src/server/http/http-server-remote-suite.test.ts diff --git a/docs/adr/0024-screen-recording-provable-signal.md b/docs/adr/0024-screen-recording-provable-signal.md index 576fef273f..dcafa119d9 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -287,15 +287,23 @@ 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 remote recording reserves a daemon-chosen destination and records the producing lifetime, tenant, and lease verifier or unleased marker at start. -The completed manifest records the file identities of the video, later chunks, and telemetry. +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 fails, keep the manifest open 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. +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 can serve the same artifact IDs while the entries remain available. Only the original lease credential can list or download leased exports (ADR 0007). A manifest from an earlier release must carry its explicit owner before it can serve a remote export. 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. +A suite recording keeps its own retained copy so downloading the archive cannot consume its recording ID. ### 2.6 Native markers 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 8e9515cb50..80ffe1d17d 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 @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { AppError } from '@agent-device/kernel/errors'; import type { JsonObject } from '@agent-device/contracts/client'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; @@ -97,18 +98,30 @@ async function verifyRecordingExport(reservedPath: string, completion: ScreenRec true) && (completion.telemetryPath === undefined || completion.telemetryPath === deriveRecordingTelemetryPath(reservedPath)); - return { - completedAt: Date.now(), - identities: matchesReservation ? files.map(readRecordingExportIdentity) : [], - }; + if (!matchesReservation) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); + } + const identities = files.map(readRecordingExportIdentity); + return { completedAt: Date.now(), identities }; } -function readRecordingExportIdentity(file: string): string | null { +function readRecordingExportIdentity(file: string): string { try { - return recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); - } catch { - return null; + const identity = recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); + if (identity !== null) return identity; + } catch (error) { + throw new AppError( + 'COMMAND_FAILED', + 'Recording export could not be verified.', + { + retriable: true, + }, + error, + ); } + throw new AppError('COMMAND_FAILED', 'Recording export is missing or is not a regular file.', { + retriable: true, + }); } export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null { 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..96230d26de 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 @@ -56,7 +56,11 @@ export function resolveScreenRecordingStopRecovery( 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); + const { metadata } = record.envelope; + const completion = + metadata?.remoteCaptureOutput === true + ? readStoredCompletion(metadata) + : readReplayableStoredCompletion(metadata); if (completion === undefined) { emitDiagnostic({ level: 'warn', @@ -132,6 +136,13 @@ function assertManifestBelongsToRequest( */ export function readReplayableStoredCompletion( metadata: JsonObject | undefined, +): ScreenRecordingCompletion | undefined { + const completion = readStoredCompletion(metadata); + return completion && fs.existsSync(completion.outPath) ? completion : undefined; +} + +function readStoredCompletion( + metadata: JsonObject | undefined, ): ScreenRecordingCompletion | undefined { const stored = metadata?.[SCREEN_RECORDING_COMPLETION_METADATA_KEY]; if ( @@ -142,8 +153,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/daemon/src/resources/artifact-file-storage.ts b/packages/daemon/src/resources/artifact-file-storage.ts new file mode 100644 index 0000000000..c615aac740 --- /dev/null +++ b/packages/daemon/src/resources/artifact-file-storage.ts @@ -0,0 +1,102 @@ +import fs from 'node:fs'; +import crypto from 'node:crypto'; +import type { DaemonArtifact } from '@agent-device/kernel/contracts'; +import { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-recording-session-resource'; +import os from 'node:os'; +import path from 'node:path'; +import { AppError } from '@agent-device/kernel/errors'; +import { TENANT_RESOURCE_REASONS } from '../core/tenant-owned-entry.ts'; + +export type RecordingSource = { sourcePath: string; sourceIdentity: string }; + +export function recordingOutputExpired(): AppError { + return new AppError('COMMAND_FAILED', 'Recording output was consumed or expired.', { + reason: TENANT_RESOURCE_REASONS.expired.reason, + }); +} + +function reserveRecordingCopyDirectory(sourceOutsideArchive: boolean, pendingCount: number) { + return sourceOutsideArchive || pendingCount === 0 + ? undefined + : fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-suite-recording-')); +} + +function stageRecordingFiles( + pending: readonly { artifactId: string; recording: RecordingSource }[], + directory: string | undefined, +) { + try { + return pending.map(({ artifactId, recording: { sourcePath, sourceIdentity } }) => { + if (!directory) return { artifactPath: sourcePath, output: sourceIdentity }; + const artifactPath = path.join(directory, artifactId); + fs.copyFileSync( + sourcePath, + artifactPath, + fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE, + ); + if (recordingExportFileIdentity(fs.lstatSync(sourcePath)) !== sourceIdentity) { + throw new AppError('COMMAND_FAILED', 'Recording export changed while preparing delivery.'); + } + return { artifactPath, output: recordingExportFileIdentity(fs.lstatSync(artifactPath))! }; + }); + } catch (error) { + if (directory) removeBestEffort(directory); + throw error; + } +} + +/** Drops only proven files and only once the producer's retention window has ended. */ +export function expireUnregisteredRecordingFiles( + sources: readonly RecordingSource[], + expiresAt: number, +): void { + const expire = () => { + for (const { sourcePath, sourceIdentity } of sources) { + try { + const stat = fs.lstatSync(sourcePath); + if (stat.isFile() && recordingExportFileIdentity(stat) === sourceIdentity) + fs.unlinkSync(sourcePath); + } catch { + // A missing file has already been consumed or removed by the registry. + } + } + }; + const remaining = expiresAt - Date.now(); + if (remaining <= 0) expire(); + else setTimeout(expire, remaining).unref(); +} + +export function prepareRecordingDelivery( + files: readonly (DaemonArtifact & { path: string; stat: fs.Stats })[], + findExisting: (source: RecordingSource) => string | undefined, + sourceOutsideArchive: boolean, +) { + const pending = []; + const deliveries = []; + for (const { path: sourcePath, stat, ...delivery } of files) { + const sourceIdentity = recordingExportFileIdentity(stat); + if (sourceIdentity === null) throw recordingOutputExpired(); + const recording = { sourcePath, sourceIdentity }; + const existing = findExisting(recording); + const artifactId = existing ?? crypto.randomUUID(); + deliveries.push({ ...delivery, artifactId }); + if (!existing) pending.push({ artifactId, delivery, recording }); + } + // An archive download consumes its directory. Only the independently retained recording + // files get a separate copy, with the same producer and expiration. + const directory = reserveRecordingCopyDirectory(sourceOutsideArchive, pending.length); + const stored = stageRecordingFiles(pending, directory); + return { + directory, + deliveries, + registrations: pending.map((entry, index) => ({ ...entry, ...stored[index]! })), + }; +} + +function removeBestEffort(targetPath: string): void { + try { + fs.rmSync(targetPath, { recursive: true, force: true }); + } catch { + // best-effort cleanup only + } +} diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 3887150204..ae7eb0d54b 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -1,3 +1,4 @@ +import type { RecordingSource } from './artifact-file-storage.ts'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -139,7 +140,7 @@ export function diagnosticsRecordOwner(recordId: string): string | undefined | n // --- 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 +178,11 @@ type ArtifactEntry = { artifactPath: string; tenantId?: string; leaseVerifier?: string; - reservation?: Readonly<{ directory?: string; lifetimeId: string; recording?: true }>; + reservation?: Readonly<{ + directory?: string; + lifetimeId: string; + recording?: RecordingSource; + }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; artifactType: DaemonArtifactType | undefined; @@ -242,7 +247,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; @@ -319,65 +323,76 @@ export function reserveFileOutput( function bindFileOutputDelivery( artifacts: Map, artifact: DaemonArtifact & { artifactId: string }, - preserveOnFailure = false, ) { committedFileOutputDeliveries.set(artifact, (delivered) => { const entry = artifacts.get(artifact.artifactId); if (!entry) return; if (delivered) entry.awaitingDelivery = false; - else if (!preserveOnFailure) requestArtifactCleanup(artifacts, artifact.artifactId, entry); + else requestArtifactCleanup(artifacts, artifact.artifactId, entry); }); return artifact; } -/** Commits files from an independently durable recording reservation. */ -export function commitRecordingFileOutputs( +/** Commits verified recordings independently of the request that delivers their IDs. */ +export async function commitRecordingFileOutputs( files: readonly (DaemonArtifact & { path: string; stat: fs.Stats })[], producer: FileOutputProducer, sessionName: string | undefined, completedAt: number, - deleteAfterDownload: boolean, -): DaemonArtifact[] { + sourceOutsideArchive: boolean, +): Promise { + const { prepareRecordingDelivery, recordingOutputExpired } = + await import('./artifact-file-storage.ts'); if (completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now()) { - throw new AppError('COMMAND_FAILED', 'Recording output retention expired.'); + throw recordingOutputExpired(); } const artifacts = pendingArtifacts(); - return files.map(({ path: artifactPath, stat, ...delivery }) => { - const output = outputIdentity(stat, true); - const owner = producer.leaseVerifier ?? undefined; - const existing = [...artifacts].find( - ([, entry]) => - !entry.cleanupRequested && - entry.reservation?.lifetimeId === producer.lifetimeId && - entry.artifactPath === artifactPath && - entry.output === output && - entry.tenantId === producer.tenantId && - entry.leaseVerifier === owner, + const owner = producer.leaseVerifier ?? undefined; + const { directory, deliveries, registrations } = prepareRecordingDelivery( + files, + (source) => findCommittedRecording(artifacts, producer, source), + sourceOutsideArchive, + ); + for (const { artifactId, delivery, recording, artifactPath, output } of registrations) { + addArtifactEntry( + artifacts, + artifactId, + { + artifactPath, + artifactType: delivery.artifactType, + fileName: delivery.fileName, + tenantId: producer.tenantId, + leaseVerifier: owner, + sessionName, + }, + output, + { remainingEntries: 1, deleteAfterDownload: true }, + { directory, lifetimeId: producer.lifetimeId, recording }, + completedAt, ); - const artifactId = existing?.[0] ?? crypto.randomUUID(); - if (!existing) { - addArtifactEntry( - artifacts, - artifactId, - { - artifactPath, - artifactType: delivery.artifactType, - fileName: delivery.fileName, - tenantId: producer.tenantId, - leaseVerifier: owner, - sessionName, - }, - output, - { remainingEntries: 1, deleteAfterDownload }, - { lifetimeId: producer.lifetimeId, recording: true }, - completedAt, - ); - } - return bindFileOutputDelivery(artifacts, { ...delivery, artifactId }, true); - }); + } + return deliveries; +} + +function findCommittedRecording( + artifacts: Map, + producer: FileOutputProducer, + source: RecordingSource, +): string | undefined { + for (const [id, entry] of artifacts) { + if ( + !entry.cleanupRequested && + entry.reservation?.lifetimeId === producer.lifetimeId && + entry.reservation.recording?.sourcePath === source.sourcePath && + entry.reservation.recording.sourceIdentity === source.sourceIdentity && + entry.tenantId === producer.tenantId && + entry.leaseVerifier === (producer.leaseVerifier ?? undefined) + ) + return id; + } + return undefined; } -/** What a request presents to list or download artifacts. */ export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; type PreparedDownloadableArtifact = { @@ -445,7 +460,7 @@ function addArtifactEntry( sourceCleanup, activeDownloads: new Set(), cleanupRequested: false, - awaitingDelivery: reservation !== undefined, + awaitingDelivery: reservation !== undefined && reservation.recording === undefined, createdAt, timer, }); @@ -482,7 +497,7 @@ 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, recording?: true): string { +function outputIdentity(stat: fs.Stats, recording = false): string { const inode = `${stat.dev}:${stat.ino}`; if (stat.isDirectory()) return inode; const file = `${inode}:${stat.size}:${stat.mtimeMs}`; @@ -491,12 +506,12 @@ function outputIdentity(stat: fs.Stats, recording?: true): string { function readOutputIdentity( artifactPath: string, - reservation?: ArtifactEntry['reservation'], + reservation?: { recording?: RecordingSource }, ): string | undefined { try { return outputIdentity( reservation ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath), - reservation?.recording, + reservation?.recording !== undefined, ); } catch { return undefined; @@ -607,7 +622,10 @@ function openRegisteredFile(artifactId: string, entry: ArtifactEntry): fs.ReadSt ); try { const stat = fs.fstatSync(fd); - if (!stat.isFile() || outputIdentity(stat, entry.reservation?.recording) !== entry.output) { + if ( + !stat.isFile() || + outputIdentity(stat, entry.reservation?.recording !== undefined) !== entry.output + ) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -662,7 +680,8 @@ export async function listDownloadableArtifacts( function statRegisteredOutput(artifactId: string, entry: ArtifactEntry): fs.Stats | undefined { try { const stat = statArtifactPath(entry); - if (outputIdentity(stat, entry.reservation?.recording) === entry.output) return stat; + if (outputIdentity(stat, entry.reservation?.recording !== undefined) === entry.output) + return stat; } catch { // A missing output is cleaned up like a replaced one. } @@ -711,7 +730,7 @@ function readDownloadableArtifactEntry( cleanupDownloadableArtifact(artifactId); throw new AppError('COMMAND_FAILED', `Artifact file is missing: ${entry.artifactPath}`); } - if (outputIdentity(stat, entry.reservation?.recording) !== entry.output) { + if (outputIdentity(stat, entry.reservation?.recording !== undefined) !== entry.output) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -926,8 +945,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/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index b307cc27f8..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 @@ -11,6 +11,7 @@ import { 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'; @@ -24,9 +25,13 @@ import { 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'); @@ -44,8 +49,14 @@ test.each([false, true])( 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); @@ -131,14 +142,32 @@ 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; @@ -187,6 +216,10 @@ test.each([false, true])( 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'); 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/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 78362df716..09454afd1b 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -1,5 +1,6 @@ import fs from 'node:fs'; 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'; @@ -27,6 +28,8 @@ import type { SessionStore } from '../../core/session-store.ts'; import type { SessionState } from '../../core/session-state.ts'; import { cleanupDownloadableArtifact, + commitRecordingFileOutputs, + trackDownloadableArtifact, leaseVerifier, listDownloadableArtifacts, settleCommittedFileOutputs, @@ -282,7 +285,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), ); if (record.status !== 'decoded') throw new Error('Expected completed recording manifest'); - const artifacts = commitRecordingOutputs(record.envelope, recovery.completion); + const artifacts = await commitRecordingOutputs(record.envelope, recovery.completion); expect(artifacts.map((artifact) => artifact.artifactId)).toEqual(retained.map((a) => a.id)); expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ @@ -414,6 +417,7 @@ test('fresh runtime slots can restore an intact recording from its producer mani }); const producer = createRuntimeStateHandle(); const successor = createRuntimeStateHandle(); + const missingScope = createRuntimeStateHandle(); const remote = { publicNetworkOnly: true } as const; try { await producer.run(async () => { @@ -434,8 +438,177 @@ test('fresh runtime slots can restore an intact recording from its producer mani 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('the producing lease downloads its recording after the suite archive is consumed', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const suite = mkdtempForTestSync('archive-recording-retention-'); + const video = path.join(suite, 'recording.mp4'); + fs.writeFileSync(video, 'leased-suite-recording'); + const recording = ( + await commitRecordingFileOutputs( + [ + { + field: 'outPath', + artifactType: 'screen-recording', + path: video, + stat: fs.statSync(video), + }, + ], + { + lifetimeId: 'suite-attempt-lifetime', + tenantId: TENANT, + leaseVerifier: leaseVerifier(LEASE_ID), + }, + 'checkout-flow', + Date.now(), + false, + ) + )[0]!; + settleCommittedFileOutputs([recording], true); + 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 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 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'); + await vi.waitFor(async () => + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]), + ); + } finally { + cleanupDownloadableArtifact(archiveId); + cleanupDownloadableArtifact(recording.artifactId!); + await closeLoopbackServer(server); + } +}); + +test('a transient stat failure leaves a completed export retriable', async () => { + 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 failures = 0; + const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source && failures === 0) { + failures++; + throw Object.assign(new Error('transient stat failure'), { code: 'EIO' }); + } + return lstat(file, options); + }); + try { + expect(await run('stop')).toMatchObject({ ok: false }); + expect(failures).toBe(1); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } finally { + stat.mockRestore(); + } + const result = await run('stop'); + expect(result).toMatchObject({ + ok: true, + data: { recording: 'stopped', artifacts: [{ artifactId: expect.any(String) }] }, + }); + expect(fs.readFileSync(source, 'utf8')).toBe('original-export'); + }); + } finally { + runtime.dispose(); + } +}); + +test.each([false, true])( + 'failed teardown registration expires only the verified original (replaced: %s)', + async (replace) => { + 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); + }); + try { + await teardown(harness.sessionStore); + expect(sourceReads).toBe(2); + expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); + } finally { + stat.mockRestore(); + } + + 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); + } + await vi.advanceTimersByTimeAsync(60 * 1000); + 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/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 7ad0e4903b..579565c69e 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -341,9 +341,13 @@ function withCaptureOwner( remoteCaptureOutput: true, remoteCapturePath: output.outputPath, remoteCaptureLifetime: lifetimeId, + remoteCaptureTenantId: tenantId ?? null, + ...(suiteCapture && req.meta?.clientArtifactPaths?.artifactsDir + ? { remoteCaptureArchive: true } + : {}), } : {}), - ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(!output.daemonOwned && tenantId ? { remoteCaptureTenantId: tenantId } : {}), ...(suiteCapture ? { suiteRecordingLifetime: lifetimeId } : {}), remoteCaptureLease: leaseId ? leaseVerifier(leaseId) : UNLEASED_CAPTURE, }, @@ -500,7 +504,7 @@ async function stopRecording( const envelope = record.status === 'decoded' ? record.envelope : undefined; const artifacts = envelope?.metadata?.remoteCaptureOutput === true - ? commitRecordingOutputs(envelope, completion) + ? await commitRecordingOutputs(envelope, completion) : undefined; return buildRecordingStopResponse(completion, artifacts); } 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 index d2d1697674..85b23d9c27 100644 --- 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 @@ -10,6 +10,8 @@ import { 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'; @@ -19,105 +21,128 @@ import { } from '../../resources/artifact-tracking.ts'; import { expectOkData } from '../__tests__/replay-suite/session-test-suite.fixtures.ts'; -test('a remote suite reports the recording that close exports after the attempt timed out', async () => { - 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'); - return outcome; +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; }); - 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(), - 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 } }; - }, + 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); + 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({ + stopSnapshotHelper: async () => { + if (!missingSidecar) return; + fs.rmSync(deriveRecordingTelemetryPath(runtime.start.mock.calls[0]![0].outputPath)); + }, + }), + 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 output = (await listDownloadableArtifacts({ tenantId }, {})).find( - (artifact) => artifact.artifactType === 'screen-recording', - ); - expect(output?.id).toBeTypeOf('string'); - expect(data.recordingArtifacts).toEqual([ - expect.objectContaining({ - artifactId: output?.id, - path: expect.stringMatching(/client\/.*\/attempt-1\/recording\.mp4$/), - }), - ]); - cleanupDownloadableArtifact(output!.id); - expect(fs.existsSync(outputPath)).toBe(true); - } finally { - vi.useRealTimers(); - } -}); + 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 inventory = await listDownloadableArtifacts({ tenantId }, {}); + try { + const output = inventory.find((artifact) => artifact.artifactType === 'screen-recording'); + expect(output?.id).toBeTypeOf('string'); + if (missingSidecar) { + expect(data.recordingArtifacts).toBeUndefined(); + expect(data.failures).toMatchObject([{ error: { details: { reason: 'timeout' } } }]); + expect( + (data.failures as Array<{ infrastructure?: true }>)[0]!.infrastructure, + ).toBeUndefined(); + } else { + 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(true); + } 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 f2743cb88a..e615a3a6af 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -139,7 +139,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ const completed = (name: string) => (attempts.get(name)?.running ? undefined : pinned(name)); const recordingOutputs = new Map< string, - ReturnType[number] + Awaited>[number] >(); const video = createReplayTestVideoOwner({ suiteRequest: req, @@ -249,7 +249,7 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ }); } finally { if (video && req.flags?.recordVideo) { - for (const output of collectSuiteRecordingOutputs(sessionStore, ref)) { + for (const output of await collectSuiteRecordingOutputs(sessionStore, ref)) { artifactPaths?.add(output.path); if (artifactPaths) recordingOutputs.set(output.path, output); } diff --git a/packages/daemon/src/sessions/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts index cde0bc5b29..f5e6439f98 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -3,18 +3,17 @@ import type { ScreenRecordingCompletion } from '@agent-device/contracts/screen-r import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { errorMessage } from '@agent-device/kernel/errors'; import type { SessionRef } from '../core/session-state.ts'; -import { settleCommittedFileOutputs } from '../resources/artifact-tracking.ts'; import { isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, } from './handlers/record-runtime-response.ts'; -import { commitRecordingOutputs } from './recording-outputs.ts'; +import { commitRecordingOutputs, expireFailedRecordingExport } from './recording-outputs.ts'; -export function retainLeasedSessionRecording( +export async function retainLeasedSessionRecording( ref: SessionRef, completion: ScreenRecordingCompletion, envelope: DurableResourceEnvelope<'screen-recording'>, -): void { +): Promise { const lease = ref.session.lease; const { metadata } = envelope; if ( @@ -27,9 +26,17 @@ export function retainLeasedSessionRecording( ) return; try { - const artifacts = commitRecordingOutputs(envelope, completion, lease?.tenantId); - settleCommittedFileOutputs(artifacts, true); + await commitRecordingOutputs(envelope, completion, lease?.tenantId); } catch (error) { + try { + expireFailedRecordingExport(envelope, completion); + } catch (cleanupError) { + emitDiagnostic({ + level: 'warn', + phase: 'leased_recording_cleanup_unproven', + data: { session: ref.address, error: errorMessage(cleanupError) }, + }); + } emitDiagnostic({ level: 'warn', phase: 'leased_session_recording_retention_failed', diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts index 0577fac59f..e296606d88 100644 --- a/packages/daemon/src/sessions/recording-outputs.ts +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -1,3 +1,9 @@ +import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { + expireUnregisteredRecordingFiles, + recordingOutputExpired, +} from '../resources/artifact-file-storage.ts'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; import { readReplayableStoredCompletion } from '@agent-device/capture-kit/screen-recording-stop-recovery'; import type { SessionRef } from '../core/session-state.ts'; @@ -6,13 +12,13 @@ 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 { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-recording-session-resource'; -import { AppError } from '@agent-device/kernel/errors'; +import { AppError, errorMessage } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; import { + ARTIFACT_CLEANUP_TIMEOUT_MS, commitRecordingFileOutputs, leasedOutputRefusal, - settleCommittedFileOutputs, } from '../resources/artifact-tracking.ts'; import { isLegacyRemoteRecordingOutput, @@ -20,7 +26,7 @@ import { recordingStopArtifacts, } from './handlers/record-runtime-response.ts'; -export function commitRecordingOutputs( +export async function commitRecordingOutputs( envelope: DurableResourceEnvelope<'screen-recording'>, completion: ScreenRecordingCompletion, legacyTenant?: string, @@ -38,23 +44,16 @@ export function commitRecordingOutputs( const files = artifacts.map((artifact, index) => { const artifactPath = artifact.path!; const stat = fs.lstatSync(artifactPath, { throwIfNoEntry: false }); + if (!stat) throw recordingOutputExpired(); if ( - !stat?.isFile() || + !stat.isFile() || (proof && proof.identities[index] !== recordingExportFileIdentity(stat)) ) { throw new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); } return { ...artifact, path: artifactPath, stat }; }); - const storedTenant = metadata?.remoteCaptureTenantId; - const tenantId = - !proof && owner === null && legacyTenant - ? legacyTenant - : typeof storedTenant === 'string' - ? storedTenant - : proof - ? undefined - : legacyTenant; + const tenantId = recordingProducerTenant(envelope, owner, proof !== undefined, legacyTenant); return commitRecordingFileOutputs( files, { @@ -64,7 +63,41 @@ export function commitRecordingOutputs( }, tenantId ? tenantPublicSessionName(tenantId, envelope.sessionId) : envelope.sessionId, proof?.completedAt ?? Date.now(), - metadata?.suiteRecordingLifetime === undefined, + metadata?.remoteCaptureArchive !== true, + ); +} + +function recordingProducerTenant( + envelope: DurableResourceEnvelope<'screen-recording'>, + owner: string | null, + verified: boolean, + legacyTenant?: string, +): string | undefined { + const stored = envelope.metadata?.remoteCaptureTenantId; + const tenant = normalizeTenantId(stored); + if (!verified) return owner === null && legacyTenant ? legacyTenant : (tenant ?? legacyTenant); + if (stored === null && owner === null) return undefined; + if (!tenant || tenant !== stored) throw leasedOutputRefusal('Recording'); + return tenant; +} + +export function expireFailedRecordingExport( + envelope: DurableResourceEnvelope<'screen-recording'>, + completion: ScreenRecordingCompletion, +): void { + if (envelope.metadata?.remoteCaptureArchive === true) return; + const proof = readRecordingExportProof(envelope); + if (!proof) return; + const artifacts = recordingStopArtifacts(completion); + if (artifacts.length !== proof.identities.length) return; + expireUnregisteredRecordingFiles( + artifacts.flatMap(({ path }, index) => { + const sourceIdentity = proof.identities[index]; + return path && typeof sourceIdentity === 'string' + ? [{ sourcePath: path, sourceIdentity }] + : []; + }), + proof.completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS, ); } @@ -88,7 +121,20 @@ function readRecordingExportProof(envelope: DurableResourceEnvelope<'screen-reco return { lifetimeId, identities: verified.identities, completedAt: verified.completedAt }; } -export function collectSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { +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) { const record = screenRecordingResourceStore.read( screenRecordingResourceStore.resolvePath(store.resolveSessionDir(ref.address)), ); @@ -100,9 +146,8 @@ export function collectSuiteRecordingOutputs(store: SessionStore, ref: SessionRe const artifacts = recordingStopArtifacts(completion); const committed = envelope.metadata.remoteCaptureOutput === true - ? commitRecordingOutputs(envelope, completion) + ? await commitRecordingOutputs(envelope, completion) : []; - settleCommittedFileOutputs(committed, true); return artifacts.map((artifact, index) => ({ session: ref.address, path: artifact.path!, diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 108b5e0b82..601b04c2b4 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -265,7 +265,7 @@ async function finishSessionScreenRecording(params: { ) return; const { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); - retainLeasedSessionRecording(params.ref, completion, record.envelope); + await retainLeasedSessionRecording(params.ref, completion, record.envelope); } async function finishSessionAudioProbe(params: { diff --git a/packages/replay-port/src/daemon-port/test-command.ts b/packages/replay-port/src/daemon-port/test-command.ts index 3e362c5a15..f9faf0d635 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -185,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) { From 7196a555485d26692fd24a9ccc8f928fcb82fae7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 08:58:48 +0100 Subject: [PATCH 03/12] Keep recording delivery and expiry with the artifact registry --- .../src/durable-capture/transitions.ts | 62 ++- .../src/resources/artifact-file-storage.ts | 198 ++++++---- .../daemon/src/resources/artifact-tracking.ts | 105 +++-- .../leased-recording-retention.test.ts | 362 +++++++++++++----- .../__tests__/record-runtime.fixtures.ts | 2 + .../src/sessions/handlers/record-runtime.ts | 4 +- ...n-replay-command-recording-cleanup.test.ts | 14 +- .../sessions/leased-recording-retention.ts | 19 +- .../daemon/src/sessions/recording-outputs.ts | 66 ++-- 9 files changed, 525 insertions(+), 307 deletions(-) diff --git a/packages/capture-kit/src/durable-capture/transitions.ts b/packages/capture-kit/src/durable-capture/transitions.ts index 07039a0e50..a8faec6193 100644 --- a/packages/capture-kit/src/durable-capture/transitions.ts +++ b/packages/capture-kit/src/durable-capture/transitions.ts @@ -131,8 +131,29 @@ export async function finishDurableCaptureHandle< await respondToFailedFinish(definition, lease, params, finishError, params.intent); throw finishError; } - await transitionFinishOutcome(definition, lease, finishOutcome); - if (finishOutcome.status === 'completed') return finishOutcome.result; + if (finishOutcome.status === 'completed') { + await commitFinishedCapture(definition, lease, finishOutcome.result, async (proofError) => { + settleIfMissing(lease); + const settled = await respondToFailedFinish( + definition, + lease, + params, + proofError, + params.intent, + ); + 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; + } + transitionCleanupOutcome(lease, finishOutcome); const finishError = cleanupPendingError(definition, finishOutcome); settleIfMissing(lease); await respondToFailedFinish(definition, lease, params, finishError, params.intent); @@ -147,10 +168,10 @@ async function respondToFailedFinish { +): Promise { if (intent === 'capture' && definition.failedFinishPolicy === 'preserve-retry-material') { emitFailedFinishPreservedDiagnostic(definition, params, finishError); - return; + return false; } let cleanup: CleanupOutcome; try { @@ -164,7 +185,7 @@ async function respondToFailedFinish( @@ -349,18 +371,30 @@ export async function transitionFinishOutcome( outcome: FinishOutcome, ): Promise { if (outcome.status === 'completed') { - lease.transition('completed', { - metadata: { - ...(lease.envelope.metadata ?? {}), - ...(await definition.completionMetadata(outcome.result, lease.envelope.metadata)), - phase: 'completed', - }, - }); + await commitFinishedCapture(definition, lease, outcome.result); return; } transitionCleanupOutcome(lease, outcome); } +async function commitFinishedCapture( + definition: DurableCaptureRecordDefinition, + lease: DurableCaptureOpenResourceFenceLease, + result: C, + onProofFailure?: (error: unknown) => Promise, +): Promise { + let completion; + try { + completion = await definition.completionMetadata(result, lease.envelope.metadata); + } catch (error) { + if (onProofFailure) await onProofFailure(error); + throw error; + } + lease.transition('completed', { + metadata: { ...(lease.envelope.metadata ?? {}), ...completion, phase: 'completed' }, + }); +} + /** * 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 diff --git a/packages/daemon/src/resources/artifact-file-storage.ts b/packages/daemon/src/resources/artifact-file-storage.ts index c615aac740..65540e95ab 100644 --- a/packages/daemon/src/resources/artifact-file-storage.ts +++ b/packages/daemon/src/resources/artifact-file-storage.ts @@ -7,96 +7,152 @@ import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; import { TENANT_RESOURCE_REASONS } from '../core/tenant-owned-entry.ts'; -export type RecordingSource = { sourcePath: string; sourceIdentity: string }; +export type RecordingSourceKind = 'original' | 'archive' | 'archive-replay'; +export type RecordingFile = DaemonArtifact & { path: string; sourceIdentity?: string }; +type VerifiedFile = RecordingFile & { sourceIdentity: string }; +type Delivery = DaemonArtifact & { artifactId: string }; -export function recordingOutputExpired(): AppError { +export type RecordingPublication = { + timer: ReturnType; + deliveries?: Delivery[]; + pending?: Promise; +}; + +type Registration = { + delivery: Delivery; + artifactPath: string; + output: string; +}; + +function recordingOutputExpired(): AppError { return new AppError('COMMAND_FAILED', 'Recording output was consumed or expired.', { reason: TENANT_RESOURCE_REASONS.expired.reason, }); } -function reserveRecordingCopyDirectory(sourceOutsideArchive: boolean, pendingCount: number) { - return sourceOutsideArchive || pendingCount === 0 - ? undefined - : fs.mkdtempSync(path.join(os.tmpdir(), 'agent-device-suite-recording-')); +export async function publishRecordingFiles(params: { + publications: Map; + producer: { lifetimeId: string; tenantId?: string; leaseVerifier: string | null }; + files: readonly RecordingFile[]; + expiresAt: number; + sourceKind: RecordingSourceKind; + isAvailable(id: string): boolean; + register(files: Registration[], directory: string | undefined): void; +}): Promise { + const { publications, producer, expiresAt, sourceKind } = params; + const sourceOutsideArchive = sourceKind === 'original'; + // Legacy manifests have no export proof. Do not infer their identity from their path alone. + const provenSources = params.files.filter( + (file): file is VerifiedFile => file.sourceIdentity !== undefined, + ); + const files = params.files.map((file) => + file.sourceIdentity === undefined + ? { ...file, sourceIdentity: readSourceIdentity(file.path) } + : { ...file, sourceIdentity: file.sourceIdentity }, + ); + const key = JSON.stringify([ + producer.lifetimeId, + producer.tenantId, + producer.leaseVerifier, + files.map((file) => [file.path, file.sourceIdentity]), + ]); + let publication = publications.get(key); + if (expiresAt <= Date.now()) throw recordingOutputExpired(); + if (publication?.deliveries) { + if (publication.deliveries.every(({ artifactId }) => params.isAvailable(artifactId))) { + return publication.deliveries; + } + throw recordingOutputExpired(); + } + if (!publication) { + // Archive staging is runtime-owned. A replay may use an existing publication, including a + // retriable attempt, but surviving archive sources alone cannot restore consumed delivery. + if (sourceKind === 'archive-replay') throw recordingOutputExpired(); + const timer = setTimeout(() => { + const current = publications.get(key); + publications.delete(key); + if (!current?.deliveries && sourceOutsideArchive) expireUnregisteredSources(provenSources); + }, expiresAt - Date.now()).unref(); + publication = { timer }; + publications.set(key, publication); + } + publication.pending ??= stageAndRegister(files, sourceOutsideArchive, (stored, directory) => { + if (publications.get(key) !== publication || expiresAt <= Date.now()) { + throw recordingOutputExpired(); + } + params.register(stored, directory); + return (publication.deliveries = stored.map(({ delivery }) => delivery)); + }).finally(() => { + delete publication.pending; + }); + return publication.pending; +} + +function readSourceIdentity(sourcePath: string): string { + const stat = fs.lstatSync(sourcePath, { throwIfNoEntry: false }); + if (!stat) throw recordingOutputExpired(); + return requireFileIdentity(stat); +} + +function requireFileIdentity(stat: fs.Stats): string { + const identity = recordingExportFileIdentity(stat); + if (identity === null) throw changedRecordingOutput(); + return identity; +} + +function changedRecordingOutput(): AppError { + return new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); } -function stageRecordingFiles( - pending: readonly { artifactId: string; recording: RecordingSource }[], - directory: string | undefined, -) { +async function stageAndRegister( + files: readonly VerifiedFile[], + sourceOutsideArchive: boolean, + register: (files: Registration[], directory: string | undefined) => Delivery[], +): Promise { + for (const file of files) { + if (readSourceIdentity(file.path) !== file.sourceIdentity) throw changedRecordingOutput(); + } + // The archive owns its original files. Only the independently downloadable files need staging. + const directory = sourceOutsideArchive + ? undefined + : await fs.promises.mkdtemp(path.join(os.tmpdir(), 'agent-device-suite-recording-')); + const staged: Registration[] = []; try { - return pending.map(({ artifactId, recording: { sourcePath, sourceIdentity } }) => { - if (!directory) return { artifactPath: sourcePath, output: sourceIdentity }; - const artifactPath = path.join(directory, artifactId); - fs.copyFileSync( + for (const { path: sourcePath, sourceIdentity, ...artifact } of files) { + const delivery = { ...artifact, artifactId: crypto.randomUUID() }; + if (!directory) { + staged.push({ delivery, artifactPath: sourcePath, output: sourceIdentity }); + continue; + } + const artifactPath = path.join(directory, delivery.artifactId); + await fs.promises.copyFile( sourcePath, artifactPath, fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE, ); - if (recordingExportFileIdentity(fs.lstatSync(sourcePath)) !== sourceIdentity) { - throw new AppError('COMMAND_FAILED', 'Recording export changed while preparing delivery.'); + if (recordingExportFileIdentity(await fs.promises.lstat(sourcePath)) !== sourceIdentity) { + throw changedRecordingOutput(); } - return { artifactPath, output: recordingExportFileIdentity(fs.lstatSync(artifactPath))! }; - }); + staged.push({ + delivery, + artifactPath, + output: requireFileIdentity(await fs.promises.lstat(artifactPath)), + }); + } + return register(staged, directory); } catch (error) { - if (directory) removeBestEffort(directory); + if (directory) + await fs.promises.rm(directory, { recursive: true, force: true }).catch(() => {}); throw error; } } -/** Drops only proven files and only once the producer's retention window has ended. */ -export function expireUnregisteredRecordingFiles( - sources: readonly RecordingSource[], - expiresAt: number, -): void { - const expire = () => { - for (const { sourcePath, sourceIdentity } of sources) { - try { - const stat = fs.lstatSync(sourcePath); - if (stat.isFile() && recordingExportFileIdentity(stat) === sourceIdentity) - fs.unlinkSync(sourcePath); - } catch { - // A missing file has already been consumed or removed by the registry. - } +function expireUnregisteredSources(files: readonly VerifiedFile[]): void { + for (const { path: sourcePath, sourceIdentity } of files) { + try { + if (readSourceIdentity(sourcePath) === sourceIdentity) fs.unlinkSync(sourcePath); + } catch { + // A missing or inaccessible file cannot be cleaned up safely. } - }; - const remaining = expiresAt - Date.now(); - if (remaining <= 0) expire(); - else setTimeout(expire, remaining).unref(); -} - -export function prepareRecordingDelivery( - files: readonly (DaemonArtifact & { path: string; stat: fs.Stats })[], - findExisting: (source: RecordingSource) => string | undefined, - sourceOutsideArchive: boolean, -) { - const pending = []; - const deliveries = []; - for (const { path: sourcePath, stat, ...delivery } of files) { - const sourceIdentity = recordingExportFileIdentity(stat); - if (sourceIdentity === null) throw recordingOutputExpired(); - const recording = { sourcePath, sourceIdentity }; - const existing = findExisting(recording); - const artifactId = existing ?? crypto.randomUUID(); - deliveries.push({ ...delivery, artifactId }); - if (!existing) pending.push({ artifactId, delivery, recording }); - } - // An archive download consumes its directory. Only the independently retained recording - // files get a separate copy, with the same producer and expiration. - const directory = reserveRecordingCopyDirectory(sourceOutsideArchive, pending.length); - const stored = stageRecordingFiles(pending, directory); - return { - directory, - deliveries, - registrations: pending.map((entry, index) => ({ ...entry, ...stored[index]! })), - }; -} - -function removeBestEffort(targetPath: string): void { - try { - fs.rmSync(targetPath, { recursive: true, force: true }); - } catch { - // best-effort cleanup only } } diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index ae7eb0d54b..ebaa9a5d84 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -1,4 +1,8 @@ -import type { RecordingSource } from './artifact-file-storage.ts'; +import type { + RecordingFile, + RecordingPublication, + RecordingSourceKind, +} from './artifact-file-storage.ts'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -140,7 +144,7 @@ export function diagnosticsRecordOwner(recordId: string): string | undefined | n // --- Downloadable artifact tracking --- -export const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; +const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; const DOWNLOADABLE_ARTIFACT_RESOURCE: TenantOwnedResourceKind = { @@ -181,7 +185,7 @@ type ArtifactEntry = { reservation?: Readonly<{ directory?: string; lifetimeId: string; - recording?: RecordingSource; + recording?: true; }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; @@ -202,6 +206,7 @@ type ArtifactEntry = { type ArtifactTrackingState = { artifacts: Map; reservations: Set<() => void>; + recordingPublications: Map; uploads: Map; retainedPerformanceSources: Map< string, @@ -216,11 +221,14 @@ const artifactTracking = (): ArtifactTrackingState => (): ArtifactTrackingState => ({ artifacts: new Map(), reservations: new Set(), + recordingPublications: new Map(), uploads: new Map(), retainedPerformanceSources: new Map(), }), (state) => { for (const discard of state.reservations) discard(); + for (const { timer } of state.recordingPublications.values()) clearTimeout(timer); + state.recordingPublications.clear(); for (const [id, entry] of state.artifacts) { requestArtifactCleanup(state.artifacts, id, entry); for (const download of entry.activeDownloads) cancelArtifactDownload(id, entry, download); @@ -335,62 +343,49 @@ function bindFileOutputDelivery( /** Commits verified recordings independently of the request that delivers their IDs. */ export async function commitRecordingFileOutputs( - files: readonly (DaemonArtifact & { path: string; stat: fs.Stats })[], + files: readonly RecordingFile[], producer: FileOutputProducer, sessionName: string | undefined, completedAt: number, - sourceOutsideArchive: boolean, + sourceKind: RecordingSourceKind, ): Promise { - const { prepareRecordingDelivery, recordingOutputExpired } = - await import('./artifact-file-storage.ts'); - if (completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now()) { - throw recordingOutputExpired(); - } - const artifacts = pendingArtifacts(); - const owner = producer.leaseVerifier ?? undefined; - const { directory, deliveries, registrations } = prepareRecordingDelivery( + const { publishRecordingFiles } = await import('./artifact-file-storage.ts'); + const { artifacts, recordingPublications } = artifactTracking(); + return publishRecordingFiles({ + publications: recordingPublications, + producer, files, - (source) => findCommittedRecording(artifacts, producer, source), - sourceOutsideArchive, - ); - for (const { artifactId, delivery, recording, artifactPath, output } of registrations) { - addArtifactEntry( - artifacts, - artifactId, - { - artifactPath, - artifactType: delivery.artifactType, - fileName: delivery.fileName, - tenantId: producer.tenantId, - leaseVerifier: owner, - sessionName, - }, - output, - { remainingEntries: 1, deleteAfterDownload: true }, - { directory, lifetimeId: producer.lifetimeId, recording }, - completedAt, - ); - } - return deliveries; -} - -function findCommittedRecording( - artifacts: Map, - producer: FileOutputProducer, - source: RecordingSource, -): string | undefined { - for (const [id, entry] of artifacts) { - if ( - !entry.cleanupRequested && - entry.reservation?.lifetimeId === producer.lifetimeId && - entry.reservation.recording?.sourcePath === source.sourcePath && - entry.reservation.recording.sourceIdentity === source.sourceIdentity && - entry.tenantId === producer.tenantId && - entry.leaseVerifier === (producer.leaseVerifier ?? undefined) - ) - return id; - } - return undefined; + expiresAt: completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS, + sourceKind, + isAvailable: (id) => { + const entry = artifacts.get(id); + return ( + entry !== undefined && + !entry.cleanupRequested && + statRegisteredOutput(id, entry) !== undefined + ); + }, + register: (registrations, directory) => { + for (const { delivery, artifactPath, output } of registrations) { + addArtifactEntry( + artifacts, + delivery.artifactId, + { + artifactPath, + artifactType: delivery.artifactType, + fileName: delivery.fileName, + tenantId: producer.tenantId, + leaseVerifier: producer.leaseVerifier ?? undefined, + sessionName, + }, + output, + { remainingEntries: 1, deleteAfterDownload: true }, + { directory, lifetimeId: producer.lifetimeId, recording: true }, + completedAt, + ); + } + }, + }); } export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; @@ -506,7 +501,7 @@ function outputIdentity(stat: fs.Stats, recording = false): string { function readOutputIdentity( artifactPath: string, - reservation?: { recording?: RecordingSource }, + reservation?: { recording?: true }, ): string | undefined { try { return outputIdentity( diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 09454afd1b..c3dc559d48 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -28,7 +28,6 @@ import type { SessionStore } from '../../core/session-store.ts'; import type { SessionState } from '../../core/session-state.ts'; import { cleanupDownloadableArtifact, - commitRecordingFileOutputs, trackDownloadableArtifact, leaseVerifier, listDownloadableArtifacts, @@ -459,121 +458,199 @@ test('fresh runtime slots can restore an intact recording from its producer mani } }); -test('the producing lease downloads its recording after the suite archive is consumed', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; +async function startSuiteRecording() { const suite = mkdtempForTestSync('archive-recording-retention-'); const video = path.join(suite, 'recording.mp4'); - fs.writeFileSync(video, 'leased-suite-recording'); - const recording = ( - await commitRecordingFileOutputs( - [ - { - field: 'outPath', - artifactType: 'screen-recording', - path: video, - stat: fs.statSync(video), - }, - ], - { - lifetimeId: 'suite-attempt-lifetime', - tenantId: TENANT, - leaseVerifier: leaseVerifier(LEASE_ID), - }, - 'checkout-flow', - Date.now(), - false, - ) - )[0]!; - settleCommittedFileOutputs([recording], true); - const archiveId = trackDownloadableArtifact({ - artifactPath: suite, - artifactType: 'test-artifacts', + 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, - leaseVerifier: leaseVerifier(LEASE_ID), + 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 server = http.createServer((req, res) => { - tryHandleDownloadableArtifactHttpRoute({ - req, - res, - authorize: async () => ({ tenantId: TENANT }), - hostEnv: process.env, - }); + fs.writeFileSync(video, 'leased-suite-recording'); + return { suite, video, stop }; +} + +test('suite recording staging can wait for an asynchronous copy before publishing', async () => { + const { stop } = await startSuiteRecording(); + // Hold the asynchronous full-copy path open so other work can run before publication finishes. + const copy = fs.promises.copyFile; + let releaseCopy = () => {}; + const gate = new Promise((resolve) => { + releaseCopy = resolve; }); - 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 }, - }); + const staging = vi.spyOn(fs.promises, 'copyFile').mockImplementationOnce(async (...args) => { + await gate; + return await copy(...args); + }); + const synchronousCopy = vi.spyOn(fs, 'copyFileSync'); + const stopping = stop(); try { - 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 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'); - await vi.waitFor(async () => - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]), - ); + await vi.waitFor(() => expect(staging).toHaveBeenCalledOnce()); + expect(synchronousCopy).not.toHaveBeenCalled(); + expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); } finally { - cleanupDownloadableArtifact(archiveId); - cleanupDownloadableArtifact(recording.artifactId!); - await closeLoopbackServer(server); + releaseCopy(); + staging.mockRestore(); + synchronousCopy.mockRestore(); } + const stopped = await stopping; + expect(stopped).toMatchObject({ + ok: true, + data: { artifacts: [{ artifactId: expect.any(String) }] }, + }); }); -test('a transient stat failure leaves a completed export retriable', async () => { - 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 failures = 0; - const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { - if (file === source && failures === 0) { - failures++; - throw Object.assign(new Error('transient stat failure'), { code: 'EIO' }); - } - return lstat(file, options); +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, stop } = await startSuiteRecording(); + const stopped = await stop(); + if (!stopped.ok) throw new Error(stopped.error.message); + const recording = stopped.data!.artifacts![0]!; + 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, }); - try { - expect(await run('stop')).toMatchObject({ ok: false }); - expect(failures).toBe(1); - expect(await listDownloadableArtifacts({ tenantId: TENANT }, {})).toEqual([]); - } finally { - stat.mockRestore(); - } - const result = await run('stop'); - expect(result).toMatchObject({ - ok: true, - data: { recording: 'stopped', artifacts: [{ artifactId: expect.any(String) }] }, + }); + 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 }, }); - expect(fs.readFileSync(source, 'utf8')).toBe('original-export'); + 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 { + await consumeRecording(); + 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 leaves the export retriable', + 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); }); - } finally { - runtime.dispose(); - } -}); + 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({ + ok: true, + data: { recording: 'stopped', artifacts: [{ artifactId: expect.any(String) }] }, + }); + expect(fs.readFileSync(source, 'utf8')).toBe('original-export'); + }); + } finally { + runtime.dispose(); + } + }, +); -test.each([false, true])( - 'failed teardown registration expires only the verified original (replaced: %s)', - async (replace) => { +test.each([ + ['teardown', false], + ['teardown', true], + ['stop', false], + ['stop', true], +] as const)( + 'failed %s registration expires only the verified original (replaced: %s)', + async (action, replace) => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); const harness = makeRecordRuntimeHarness('recording-cleanup-expiry-', { sessionName: ADDRESS }); const start = harness.runtime.start.getMockImplementation()!; @@ -593,6 +670,10 @@ test.each([false, true])( return lstat(file, options); }); try { + 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([]); @@ -612,3 +693,80 @@ test.each([false, true])( else expect(fs.existsSync(source)).toBe(false); }, ); + +test('failed registration of a legacy export without recorded identity leaves its file alone', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + const sessionStore = makeSessionStore('recording-legacy-cleanup-'); + const recordingExport = remoteRecordingExport(); + publishRecordingSession(sessionStore, recordingExport); + + const lstat = fs.lstatSync; + let sourceReads = 0; + const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === recordingExport.outPath && ++sourceReads === 2) { + throw Object.assign(new Error('registry stat unavailable'), { code: 'EIO' }); + } + return lstat(file, options); + }); + try { + await teardown(sessionStore); + expect(sourceReads).toBe(2); + expect( + screenRecordingResourceStore.read( + screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), + ), + ).toMatchObject({ status: 'decoded', envelope: { lifecycle: 'completed' } }); + expect(await listDownloadableArtifacts(OWNER, {})).toEqual([]); + } finally { + stat.mockRestore(); + } + await vi.advanceTimersByTimeAsync(15 * 60 * 1000); + expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); + expect(fs.readFileSync(recordingExport.telemetryPath, 'utf8')).toBe('{"events":[]}'); +}); + +test('explicit stop keeps its binding until the advertised sidecar can be verified', 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: true, + data: { + artifacts: [{ artifactId: expect.any(String) }, { artifactId: expect.any(String) }], + }, + }); + }); + } finally { + runtime.dispose(); + } +}); 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 86d03d1d33..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', diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 579565c69e..54925454e1 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -504,7 +504,9 @@ async function stopRecording( const envelope = record.status === 'decoded' ? record.envelope : undefined; const artifacts = envelope?.metadata?.remoteCaptureOutput === true - ? await commitRecordingOutputs(envelope, completion) + ? await commitRecordingOutputs(envelope, completion, { + replay: !stopped.recordsSessionAction, + }) : undefined; return buildRecordingStopResponse(completion, artifacts); } 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 index 85b23d9c27..4ac3167ba6 100644 --- 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 @@ -46,7 +46,7 @@ test.each([false, true])( const outcome = await finish(); fs.writeFileSync(outcome.result.outPath, 'video-exported-during-close'); const telemetryPath = deriveRecordingTelemetryPath(outcome.result.outPath); - fs.writeFileSync(telemetryPath, '{}'); + if (!missingSidecar) fs.writeFileSync(telemetryPath, '{}'); return { ...outcome, result: { ...outcome.result, telemetryPath } }; }); const tenantId = 'recording-suite'; @@ -57,12 +57,7 @@ test.each([false, true])( host: createTestHostEnvironment({ cwd: root, env: {} }), createCommandSurface: fakeCreateCommandSurface, platformServices: daemonPlatformServicesFixture(), - platformResourceCleanup: platformResourceCleanupFixture({ - stopSnapshotHelper: async () => { - if (!missingSidecar) return; - fs.rmSync(deriveRecordingTelemetryPath(runtime.start.mock.calls[0]![0].outputPath)); - }, - }), + platformResourceCleanup: platformResourceCleanupFixture(), req: { token: 'fixture', session: 'suite', @@ -120,14 +115,17 @@ test.each([false, true])( const inventory = await listDownloadableArtifacts({ tenantId }, {}); try { const output = inventory.find((artifact) => artifact.artifactType === 'screen-recording'); - expect(output?.id).toBeTypeOf('string'); if (missingSidecar) { + expect(runtime.forceCleanup).toHaveBeenCalledOnce(); + expect(output).toBeUndefined(); expect(data.recordingArtifacts).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(data.recordingArtifacts).toEqual( expect.arrayContaining([ expect.objectContaining({ diff --git a/packages/daemon/src/sessions/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts index f5e6439f98..c9cd13614d 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -7,7 +7,7 @@ import { isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, } from './handlers/record-runtime-response.ts'; -import { commitRecordingOutputs, expireFailedRecordingExport } from './recording-outputs.ts'; +import { commitRecordingOutputs } from './recording-outputs.ts'; export async function retainLeasedSessionRecording( ref: SessionRef, @@ -26,21 +26,16 @@ export async function retainLeasedSessionRecording( ) return; try { - await commitRecordingOutputs(envelope, completion, lease?.tenantId); + await commitRecordingOutputs(envelope, completion, { legacyTenant: lease?.tenantId }); } catch (error) { - try { - expireFailedRecordingExport(envelope, completion); - } catch (cleanupError) { - emitDiagnostic({ - level: 'warn', - phase: 'leased_recording_cleanup_unproven', - data: { session: ref.address, error: errorMessage(cleanupError) }, - }); - } emitDiagnostic({ level: 'warn', phase: 'leased_session_recording_retention_failed', - data: { session: ref.address, error: errorMessage(error) }, + data: { + session: ref.address, + error: errorMessage(error), + hasExportProof: metadata.remoteCaptureExport !== undefined, + }, }); } } diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts index e296606d88..dbd401c266 100644 --- a/packages/daemon/src/sessions/recording-outputs.ts +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -1,25 +1,15 @@ import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { - expireUnregisteredRecordingFiles, - recordingOutputExpired, -} from '../resources/artifact-file-storage.ts'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; import { readReplayableStoredCompletion } from '@agent-device/capture-kit/screen-recording-stop-recovery'; import type { SessionRef } from '../core/session-state.ts'; import type { SessionStore } from '../core/session-store.ts'; -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 { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-recording-session-resource'; import { AppError, errorMessage } from '@agent-device/kernel/errors'; import { isRecord } from '@agent-device/kernel/record'; import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; -import { - ARTIFACT_CLEANUP_TIMEOUT_MS, - commitRecordingFileOutputs, - leasedOutputRefusal, -} from '../resources/artifact-tracking.ts'; +import { commitRecordingFileOutputs, leasedOutputRefusal } from '../resources/artifact-tracking.ts'; import { isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, @@ -29,7 +19,7 @@ import { export async function commitRecordingOutputs( envelope: DurableResourceEnvelope<'screen-recording'>, completion: ScreenRecordingCompletion, - legacyTenant?: string, + options?: { legacyTenant?: string; replay?: boolean }, ) { const { metadata } = envelope; const owner = recordingOutputLeaseVerifier(metadata); @@ -42,18 +32,22 @@ export async function commitRecordingOutputs( throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); } const files = artifacts.map((artifact, index) => { - const artifactPath = artifact.path!; - const stat = fs.lstatSync(artifactPath, { throwIfNoEntry: false }); - if (!stat) throw recordingOutputExpired(); - if ( - !stat.isFile() || - (proof && proof.identities[index] !== recordingExportFileIdentity(stat)) - ) { - throw new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); + const sourceIdentity = proof?.identities[index]; + if (proof && typeof sourceIdentity !== 'string') { + throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); } - return { ...artifact, path: artifactPath, stat }; + return { + ...artifact, + path: artifact.path!, + sourceIdentity: typeof sourceIdentity === 'string' ? sourceIdentity : undefined, + }; }); - const tenantId = recordingProducerTenant(envelope, owner, proof !== undefined, legacyTenant); + const tenantId = recordingProducerTenant( + envelope, + owner, + proof !== undefined, + options?.legacyTenant, + ); return commitRecordingFileOutputs( files, { @@ -63,7 +57,11 @@ export async function commitRecordingOutputs( }, tenantId ? tenantPublicSessionName(tenantId, envelope.sessionId) : envelope.sessionId, proof?.completedAt ?? Date.now(), - metadata?.remoteCaptureArchive !== true, + metadata?.remoteCaptureArchive !== true + ? 'original' + : options?.replay + ? 'archive-replay' + : 'archive', ); } @@ -81,26 +79,6 @@ function recordingProducerTenant( return tenant; } -export function expireFailedRecordingExport( - envelope: DurableResourceEnvelope<'screen-recording'>, - completion: ScreenRecordingCompletion, -): void { - if (envelope.metadata?.remoteCaptureArchive === true) return; - const proof = readRecordingExportProof(envelope); - if (!proof) return; - const artifacts = recordingStopArtifacts(completion); - if (artifacts.length !== proof.identities.length) return; - expireUnregisteredRecordingFiles( - artifacts.flatMap(({ path }, index) => { - const sourceIdentity = proof.identities[index]; - return path && typeof sourceIdentity === 'string' - ? [{ sourcePath: path, sourceIdentity }] - : []; - }), - proof.completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS, - ); -} - function readRecordingExportProof(envelope: DurableResourceEnvelope<'screen-recording'>) { if (envelope.lifecycle !== 'completed') { throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); @@ -146,7 +124,7 @@ async function readSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { const artifacts = recordingStopArtifacts(completion); const committed = envelope.metadata.remoteCaptureOutput === true - ? await commitRecordingOutputs(envelope, completion) + ? await commitRecordingOutputs(envelope, completion, { replay: true }) : []; return artifacts.map((artifact, index) => ({ session: ref.address, From 94b44744ba440addc893088c0543b20cddf1f1a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 09:12:53 +0100 Subject: [PATCH 04/12] fix(daemon): bound recording staging and preserve verified retries --- .../src/resources/artifact-file-storage.ts | 88 +++++++++-- .../daemon/src/resources/artifact-tracking.ts | 30 ++-- .../leased-recording-retention.test.ts | 148 ++++++++++++++++-- 3 files changed, 221 insertions(+), 45 deletions(-) diff --git a/packages/daemon/src/resources/artifact-file-storage.ts b/packages/daemon/src/resources/artifact-file-storage.ts index 65540e95ab..05e8d5f002 100644 --- a/packages/daemon/src/resources/artifact-file-storage.ts +++ b/packages/daemon/src/resources/artifact-file-storage.ts @@ -5,6 +5,7 @@ import { recordingExportFileIdentity } from '@agent-device/capture-kit/screen-re import os from 'node:os'; import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; +import { settleWithin } from '@agent-device/host-kit/settle-within'; import { TENANT_RESOURCE_REASONS } from '../core/tenant-owned-entry.ts'; export type RecordingSourceKind = 'original' | 'archive' | 'archive-replay'; @@ -13,7 +14,8 @@ type VerifiedFile = RecordingFile & { sourceIdentity: string }; type Delivery = DaemonArtifact & { artifactId: string }; export type RecordingPublication = { - timer: ReturnType; + signal: AbortSignal; + dispose(): void; deliveries?: Delivery[]; pending?: Promise; }; @@ -57,7 +59,10 @@ export async function publishRecordingFiles(params: { files.map((file) => [file.path, file.sourceIdentity]), ]); let publication = publications.get(key); - if (expiresAt <= Date.now()) throw recordingOutputExpired(); + if (expiresAt <= Date.now()) { + if (!publication && sourceOutsideArchive) expireUnregisteredSources(provenSources); + throw recordingOutputExpired(); + } if (publication?.deliveries) { if (publication.deliveries.every(({ artifactId }) => params.isAvailable(artifactId))) { return publication.deliveries; @@ -68,26 +73,74 @@ export async function publishRecordingFiles(params: { // Archive staging is runtime-owned. A replay may use an existing publication, including a // retriable attempt, but surviving archive sources alone cannot restore consumed delivery. if (sourceKind === 'archive-replay') throw recordingOutputExpired(); - const timer = setTimeout(() => { - const current = publications.get(key); - publications.delete(key); - if (!current?.deliveries && sourceOutsideArchive) expireUnregisteredSources(provenSources); - }, expiresAt - Date.now()).unref(); - publication = { timer }; + publication = createRecordingPublication( + expiresAt, + () => publications.delete(key), + sourceOutsideArchive ? provenSources : [], + ); publications.set(key, publication); } - publication.pending ??= stageAndRegister(files, sourceOutsideArchive, (stored, directory) => { - if (publications.get(key) !== publication || expiresAt <= Date.now()) { - throw recordingOutputExpired(); - } - params.register(stored, directory); - return (publication.deliveries = stored.map(({ delivery }) => delivery)); - }).finally(() => { + const assertActive = () => { + publication.signal.throwIfAborted(); + if (expiresAt <= Date.now()) throw recordingOutputExpired(); + }; + publication.pending ??= waitForRecordingPublication( + publication.signal, + expiresAt, + stageAndRegister(files, sourceOutsideArchive, assertActive, (stored, directory) => { + params.register(stored, directory); + return (publication.deliveries = stored.map(({ delivery }) => delivery)); + }), + ).finally(() => { delete publication.pending; }); return publication.pending; } +function createRecordingPublication( + expiresAt: number, + forget: () => void, + provenSources: readonly VerifiedFile[], +): RecordingPublication { + const controller = new AbortController(); + const timer = setTimeout(() => { + forget(); + controller.abort(recordingOutputExpired()); + if (!publication.deliveries) expireUnregisteredSources(provenSources); + }, expiresAt - Date.now()).unref(); + const publication: RecordingPublication = { + signal: controller.signal, + dispose() { + controller.abort(recordingOutputExpired()); + // Verified standalone bytes remain eligible through their manifest deadline. + if (publication.deliveries || provenSources.length === 0) clearTimeout(timer); + }, + }; + return publication; +} + +async function waitForRecordingPublication( + signal: AbortSignal, + expiresAt: number, + writer: Promise, +): Promise { + let abort!: () => void; + const pending = new Promise((resolve, reject) => { + abort = () => reject(signal.reason); + signal.addEventListener('abort', abort, { once: true }); + if (signal.aborted) abort(); + void writer.then(resolve, reject); + }); + try { + // The response has a deadline even when the filesystem writer cannot be interrupted. + const outcome = await settleWithin(() => pending, expiresAt - Date.now(), { keepAlive: false }); + if (outcome.kind === 'deadline') throw recordingOutputExpired(); + return outcome.value; + } finally { + signal.removeEventListener('abort', abort); + } +} + function readSourceIdentity(sourcePath: string): string { const stat = fs.lstatSync(sourcePath, { throwIfNoEntry: false }); if (!stat) throw recordingOutputExpired(); @@ -107,8 +160,10 @@ function changedRecordingOutput(): AppError { async function stageAndRegister( files: readonly VerifiedFile[], sourceOutsideArchive: boolean, + assertActive: () => void, register: (files: Registration[], directory: string | undefined) => Delivery[], ): Promise { + assertActive(); for (const file of files) { if (readSourceIdentity(file.path) !== file.sourceIdentity) throw changedRecordingOutput(); } @@ -119,6 +174,7 @@ async function stageAndRegister( const staged: Registration[] = []; try { for (const { path: sourcePath, sourceIdentity, ...artifact } of files) { + assertActive(); const delivery = { ...artifact, artifactId: crypto.randomUUID() }; if (!directory) { staged.push({ delivery, artifactPath: sourcePath, output: sourceIdentity }); @@ -130,6 +186,7 @@ async function stageAndRegister( artifactPath, fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE, ); + assertActive(); if (recordingExportFileIdentity(await fs.promises.lstat(sourcePath)) !== sourceIdentity) { throw changedRecordingOutput(); } @@ -139,6 +196,7 @@ async function stageAndRegister( output: requireFileIdentity(await fs.promises.lstat(artifactPath)), }); } + assertActive(); return register(staged, directory); } catch (error) { if (directory) diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index ebaa9a5d84..ed96cf66ad 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -227,7 +227,7 @@ const artifactTracking = (): ArtifactTrackingState => }), (state) => { for (const discard of state.reservations) discard(); - for (const { timer } of state.recordingPublications.values()) clearTimeout(timer); + for (const publication of state.recordingPublications.values()) publication.dispose(); state.recordingPublications.clear(); for (const [id, entry] of state.artifacts) { requestArtifactCleanup(state.artifacts, id, entry); @@ -672,13 +672,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.reservation?.recording !== undefined) === entry.output) return stat; - } catch { - // A missing output is cleaned up like a replaced one. + } 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; @@ -718,17 +727,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.reservation?.recording !== undefined) !== 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 }; } diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index c3dc559d48..1a82e5db7d 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -458,7 +458,45 @@ test('fresh runtime slots can restore an intact recording from its producer mani } }); -async function startSuiteRecording() { +test('a fail-once inspection preserves the published recording and its ID', 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) }] }, + }); + 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: { message: 'inspection I/O failed' } }); + expect(fs.readFileSync(video, 'utf8')).toBe('published-video'); + expect(await run('stop')).toEqual(published); + } 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-', { @@ -488,6 +526,15 @@ async function startSuiteRecording() { ok: true, }); fs.writeFileSync(video, 'leased-suite-recording'); + if (withSidecar) { + const telemetryPath = deriveRecordingTelemetryPath(video); + fs.writeFileSync(telemetryPath, '{}'); + const finish = harness.runtime.finish.getMockImplementation()!; + harness.runtime.finish.mockImplementation(async () => { + const outcome = await finish(); + return { ...outcome, result: { ...outcome.result, telemetryPath } }; + }); + } return { suite, video, stop }; } @@ -521,6 +568,54 @@ test('suite recording staging can wait for an asynchronous copy before publishin }); }); +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 } = await runtime.run(() => startSuiteRecording(true)); + 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(stop).then((result) => { + outcome = result; + }); + try { + const target = await entered; + if (end === 'disposal') runtime.dispose(); + await vi.advanceTimersByTimeAsync(end === 'expiry' ? 15 * 60 * 1000 : 0); + expect(outcome).toMatchObject({ + ok: false, + error: { details: { reason: 'RESOURCE_EXPIRED' } }, + }); + 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.readFileSync(video, 'utf8')).toBe('leased-suite-recording'); + 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; @@ -644,13 +739,15 @@ test.each([1, 2])( ); test.each([ - ['teardown', false], - ['teardown', true], - ['stop', false], - ['stop', true], + ['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)', - async (action, replace) => { + '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()!; @@ -669,16 +766,22 @@ test.each([ throw Object.assign(new Error('registry stat unavailable'), { code: 'EIO' }); return lstat(file, options); }); + const runtime = createRuntimeStateHandle(); try { - 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([]); + 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); @@ -688,7 +791,22 @@ test.each([ fs.writeFileSync(unrelated, 'unrelated-recording'); fs.renameSync(unrelated, source); } - await vi.advanceTimersByTimeAsync(60 * 1000); + 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); }, From 47c1e7147c3ff60306a8ad1656dfdf3858ba65f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 09:24:08 +0100 Subject: [PATCH 05/12] fix(daemon): keep artifact inventory available on inspection errors --- .../daemon/src/resources/artifact-tracking.ts | 8 +++---- .../leased-recording-retention.test.ts | 21 ++++++++++++++++++- 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index ed96cf66ad..970ed00295 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -652,9 +652,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, @@ -696,11 +694,11 @@ function statRegisteredOutput( 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; diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 1a82e5db7d..0085b76e8d 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -458,7 +458,7 @@ test('fresh runtime slots can restore an intact recording from its producer mani } }); -test('a fail-once inspection preserves the published recording and its ID', async () => { +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) => @@ -473,6 +473,15 @@ test('a fail-once inspection preserves the published recording and its ID', asyn 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) => { @@ -487,6 +496,16 @@ test('a fail-once inspection preserves the published recording and its ID', asyn expect(result).toMatchObject({ ok: false, error: { message: 'inspection I/O failed' } }); 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(); } From 0a4c503bddb4ff4218d8535a8a1dd6bfad535d89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 10:26:19 +0100 Subject: [PATCH 06/12] fix(daemon): retain recordings by verified reservation --- .../0024-screen-recording-provable-signal.md | 9 +- .../screen-recording-stop-recovery.test.ts | 12 +- .../screen-recording-session-resource.ts | 85 +++++- .../screen-recording-stop-recovery.ts | 61 ++-- .../src/durable-capture/definition.ts | 1 + .../src/durable-capture/transitions.ts | 19 +- .../src/recording/output-schemas.ts | 2 +- packages/command-surface/src/replay/index.ts | 9 +- packages/contracts/src/recording.ts | 2 +- packages/contracts/src/replay.ts | 3 +- .../src/resources/artifact-file-storage.ts | 246 ++++------------ .../daemon/src/resources/artifact-tracking.ts | 102 +++---- .../src/server/downloadable-artifact-http.ts | 15 +- .../http/http-server-remote-output.test.ts | 26 +- .../leased-recording-retention.test.ts | 272 +++++++++++------ .../handlers/record-runtime-response.ts | 18 +- .../src/sessions/handlers/record-runtime.ts | 237 +++++++++------ ...n-replay-command-recording-cleanup.test.ts | 25 +- .../handlers/session-replay-command.ts | 5 +- .../handlers/session-replay-video-owner.ts | 5 +- .../sessions/leased-recording-retention.ts | 10 +- .../daemon/src/sessions/recording-outputs.ts | 277 ++++++++++++------ .../session-replay-video-recording.ts | 4 +- .../src/daemon-port/test-command.ts | 73 +++-- test/wire-compat/ledger.json | 12 +- website/docs/docs/replay-e2e.md | 1 + 26 files changed, 907 insertions(+), 624 deletions(-) diff --git a/docs/adr/0024-screen-recording-provable-signal.md b/docs/adr/0024-screen-recording-provable-signal.md index dcafa119d9..6615023bae 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -290,20 +290,21 @@ They do this only after the manifest records that no recoverable export is lost. 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 fails, keep the manifest open for an exact-owner retry. +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. 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 can serve the same artifact IDs while the entries remain available. +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 from an earlier release must carry its explicit owner before it can serve a remote export. +A manifest must carry explicit producer scope, completion time, and file identities before it can serve a remote export. 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. -A suite recording keeps its own retained copy so downloading the archive cannot consume its recording ID. +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-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/screen-recording-session-resource.ts b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts index 80ffe1d17d..40e86671b4 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 @@ -20,6 +20,7 @@ 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'; @@ -38,10 +39,24 @@ export const screenRecordingDurableResource = createDurableCaptureResource< store: screenRecordingResourceStore, completionMetadata: async (result, metadata) => ({ ...encodeScreenRecordingCompletionMetadata(result), - ...(typeof metadata?.remoteCapturePath === 'string' - ? { remoteCaptureExport: await verifyRecordingExport(metadata.remoteCapturePath, result) } + ...(typeof metadata?.remoteCapturePath === 'string' && + typeof metadata.remoteCaptureReservation === 'string' + ? { + remoteCaptureExport: await verifyRecordingExport( + metadata.remoteCapturePath, + result, + metadata.remoteCaptureReservation, + typeof metadata.remoteCaptureCompletedAt === 'number' + ? metadata.remoteCaptureCompletedAt + : Date.now(), + ), + } : {}), }), + pendingCompletionMetadata: (result, error) => + error instanceof RecordingProofIoError + ? { ...encodeScreenRecordingCompletionMetadata(result), remoteCaptureCompletedAt: Date.now() } + : undefined, // 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 @@ -79,7 +94,12 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } -async function verifyRecordingExport(reservedPath: string, completion: ScreenRecordingCompletion) { +async function verifyRecordingExport( + reservedPath: string, + completion: ScreenRecordingCompletion, + reservation: string, + completedAt: number, +) { const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ import('../recording/output-path.ts'), import('../recording/telemetry.ts'), @@ -102,7 +122,11 @@ async function verifyRecordingExport(reservedPath: string, completion: ScreenRec throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); } const identities = files.map(readRecordingExportIdentity); - return { completedAt: Date.now(), identities }; + return { + completedAt, + identities, + outputIds: files.map((_, index) => `${reservation}-${index + 1}`), + }; } function readRecordingExportIdentity(file: string): string { @@ -110,20 +134,57 @@ function readRecordingExportIdentity(file: string): string { const identity = recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); if (identity !== null) return identity; } catch (error) { - throw new AppError( - 'COMMAND_FAILED', - 'Recording export could not be verified.', - { - retriable: true, - }, - error, - ); + throw new RecordingProofIoError(error); } throw new AppError('COMMAND_FAILED', 'Recording export is missing or is not a regular file.', { retriable: true, }); } +class RecordingProofIoError extends AppError { + constructor(error: unknown) { + super('COMMAND_FAILED', 'Recording export could not be verified.', { retriable: true }, error); + } +} + +export function finishPendingScreenRecordingProof( + resourcePath: string, + expected: DurableResourceEnvelope<'screen-recording'>, +): Promise> { + return withDurableCaptureResourceFence({ + store: screenRecordingResourceStore, + resourcePath, + expected: expected.fence, + onCompleted: ({ envelope }) => envelope, + run: async (lease) => { + const { readStoredCompletion, unreadableRecordingProof } = + await import('./screen-recording-stop-recovery.ts'); + const { metadata } = lease.envelope; + const completion = readStoredCompletion(metadata); + if ( + metadata?.phase !== 'export-proof-pending' || + !completion || + typeof metadata.remoteCapturePath !== 'string' || + typeof metadata.remoteCaptureReservation !== 'string' || + typeof metadata.remoteCaptureCompletedAt !== 'number' + ) + throw unreadableRecordingProof(); + return lease.transition('completed', { + metadata: { + ...metadata, + phase: 'completed', + remoteCaptureExport: await verifyRecordingExport( + metadata.remoteCapturePath, + completion, + metadata.remoteCaptureReservation, + metadata.remoteCaptureCompletedAt, + ), + }, + }); + }, + }); +} + export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null { return stat?.isFile() ? `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` 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 96230d26de..60ffd34271 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,12 +8,7 @@ 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'; @@ -33,8 +28,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,12 +53,23 @@ 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 }; + if (record.envelope.lifecycle !== 'completed') + return { kind: 'open', resourcePath, envelope: record.envelope }; const { metadata } = record.envelope; const completion = metadata?.remoteCaptureOutput === true @@ -69,7 +83,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. */ @@ -78,21 +92,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'>; @@ -141,7 +140,13 @@ export function readReplayableStoredCompletion( return completion && fs.existsSync(completion.outPath) ? completion : undefined; } -function readStoredCompletion( +export function unreadableRecordingProof(): AppError { + return new AppError('COMMAND_FAILED', 'Recording ownership proof could not be read.', { + retriable: true, + }); +} + +export function readStoredCompletion( metadata: JsonObject | undefined, ): ScreenRecordingCompletion | undefined { const stored = metadata?.[SCREEN_RECORDING_COMPLETION_METADATA_KEY]; diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index 857fb121c5..308455304f 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -72,6 +72,7 @@ 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): JsonObject | undefined; completionFromMetadata?(metadata: JsonObject | undefined): C | undefined | Promise; failedFinishPolicy: DurableCaptureFailedFinishPolicy; messages: Readonly<{ diff --git a/packages/capture-kit/src/durable-capture/transitions.ts b/packages/capture-kit/src/durable-capture/transitions.ts index a8faec6193..e6388b5c67 100644 --- a/packages/capture-kit/src/durable-capture/transitions.ts +++ b/packages/capture-kit/src/durable-capture/transitions.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 && + record.envelope.metadata?.phase === 'export-proof-pending')) ) { params.binding.clear(active); } @@ -140,6 +142,7 @@ export async function finishDurableCaptureHandle< params, proofError, params.intent, + definition.pendingCompletionMetadata?.(finishOutcome.result, proofError), ); if (params.intent === 'disposal' && settled) { emitDiagnostic({ @@ -168,6 +171,7 @@ async function respondToFailedFinish { if (intent === 'capture' && definition.failedFinishPolicy === 'preserve-retry-material') { emitFailedFinishPreservedDiagnostic(definition, params, finishError); @@ -188,7 +192,18 @@ async function respondToFailedFinish; diff --git a/packages/daemon/src/resources/artifact-file-storage.ts b/packages/daemon/src/resources/artifact-file-storage.ts index 05e8d5f002..620f8205ee 100644 --- a/packages/daemon/src/resources/artifact-file-storage.ts +++ b/packages/daemon/src/resources/artifact-file-storage.ts @@ -1,216 +1,94 @@ import fs from 'node:fs'; -import crypto from 'node:crypto'; +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 os from 'node:os'; -import path from 'node:path'; import { AppError } from '@agent-device/kernel/errors'; -import { settleWithin } from '@agent-device/host-kit/settle-within'; import { TENANT_RESOURCE_REASONS } from '../core/tenant-owned-entry.ts'; -export type RecordingSourceKind = 'original' | 'archive' | 'archive-replay'; -export type RecordingFile = DaemonArtifact & { path: string; sourceIdentity?: string }; -type VerifiedFile = RecordingFile & { sourceIdentity: string }; -type Delivery = DaemonArtifact & { artifactId: string }; - -export type RecordingPublication = { - signal: AbortSignal; - dispose(): void; - deliveries?: Delivery[]; - pending?: Promise; -}; - -type Registration = { - delivery: Delivery; - artifactPath: string; - output: string; +export type RecordingFile = DaemonArtifact & { + path: string; + sourceIdentity: string; + artifactId: string; }; -function recordingOutputExpired(): AppError { +function expiredRecording(): AppError { return new AppError('COMMAND_FAILED', 'Recording output was consumed or expired.', { reason: TENANT_RESOURCE_REASONS.expired.reason, }); } -export async function publishRecordingFiles(params: { - publications: Map; - producer: { lifetimeId: string; tenantId?: string; leaseVerifier: string | null }; - files: readonly RecordingFile[]; - expiresAt: number; - sourceKind: RecordingSourceKind; - isAvailable(id: string): boolean; - register(files: Registration[], directory: string | undefined): void; -}): Promise { - const { publications, producer, expiresAt, sourceKind } = params; - const sourceOutsideArchive = sourceKind === 'original'; - // Legacy manifests have no export proof. Do not infer their identity from their path alone. - const provenSources = params.files.filter( - (file): file is VerifiedFile => file.sourceIdentity !== undefined, - ); - const files = params.files.map((file) => - file.sourceIdentity === undefined - ? { ...file, sourceIdentity: readSourceIdentity(file.path) } - : { ...file, sourceIdentity: file.sourceIdentity }, - ); - const key = JSON.stringify([ - producer.lifetimeId, - producer.tenantId, - producer.leaseVerifier, - files.map((file) => [file.path, file.sourceIdentity]), - ]); - let publication = publications.get(key); - if (expiresAt <= Date.now()) { - if (!publication && sourceOutsideArchive) expireUnregisteredSources(provenSources); - throw recordingOutputExpired(); - } - if (publication?.deliveries) { - if (publication.deliveries.every(({ artifactId }) => params.isAvailable(artifactId))) { - return publication.deliveries; +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.'); } - throw recordingOutputExpired(); - } - if (!publication) { - // Archive staging is runtime-owned. A replay may use an existing publication, including a - // retriable attempt, but surviving archive sources alone cannot restore consumed delivery. - if (sourceKind === 'archive-replay') throw recordingOutputExpired(); - publication = createRecordingPublication( - expiresAt, - () => publications.delete(key), - sourceOutsideArchive ? provenSources : [], - ); - publications.set(key, publication); } - const assertActive = () => { - publication.signal.throwIfAborted(); - if (expiresAt <= Date.now()) throw recordingOutputExpired(); - }; - publication.pending ??= waitForRecordingPublication( - publication.signal, - expiresAt, - stageAndRegister(files, sourceOutsideArchive, assertActive, (stored, directory) => { - params.register(stored, directory); - return (publication.deliveries = stored.map(({ delivery }) => delivery)); - }), - ).finally(() => { - delete publication.pending; - }); - return publication.pending; -} - -function createRecordingPublication( - expiresAt: number, - forget: () => void, - provenSources: readonly VerifiedFile[], -): RecordingPublication { - const controller = new AbortController(); - const timer = setTimeout(() => { - forget(); - controller.abort(recordingOutputExpired()); - if (!publication.deliveries) expireUnregisteredSources(provenSources); - }, expiresAt - Date.now()).unref(); - const publication: RecordingPublication = { - signal: controller.signal, - dispose() { - controller.abort(recordingOutputExpired()); - // Verified standalone bytes remain eligible through their manifest deadline. - if (publication.deliveries || provenSources.length === 0) clearTimeout(timer); - }, - }; - return publication; } -async function waitForRecordingPublication( - signal: AbortSignal, - expiresAt: number, - writer: Promise, -): Promise { - let abort!: () => void; - const pending = new Promise((resolve, reject) => { - abort = () => reject(signal.reason); - signal.addEventListener('abort', abort, { once: true }); - if (signal.aborted) abort(); - void writer.then(resolve, reject); - }); +function inspectRecordingPath(file: string): fs.Stats | undefined { try { - // The response has a deadline even when the filesystem writer cannot be interrupted. - const outcome = await settleWithin(() => pending, expiresAt - Date.now(), { keepAlive: false }); - if (outcome.kind === 'deadline') throw recordingOutputExpired(); - return outcome.value; - } finally { - signal.removeEventListener('abort', abort); + return fs.lstatSync(file, { throwIfNoEntry: false }); + } catch (error) { + throw new AppError( + 'COMMAND_FAILED', + 'Recording output could not be inspected.', + { retriable: true }, + error, + ); } } -function readSourceIdentity(sourcePath: string): string { - const stat = fs.lstatSync(sourcePath, { throwIfNoEntry: false }); - if (!stat) throw recordingOutputExpired(); - return requireFileIdentity(stat); +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()); } -function requireFileIdentity(stat: fs.Stats): string { - const identity = recordingExportFileIdentity(stat); - if (identity === null) throw changedRecordingOutput(); - return identity; +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 changedRecordingOutput(): AppError { - return new AppError('COMMAND_FAILED', 'Recording export is missing or has changed.'); +function consumptionPath(file: string): string { + return file + '.consumed'; } -async function stageAndRegister( - files: readonly VerifiedFile[], - sourceOutsideArchive: boolean, - assertActive: () => void, - register: (files: Registration[], directory: string | undefined) => Delivery[], -): Promise { - assertActive(); - for (const file of files) { - if (readSourceIdentity(file.path) !== file.sourceIdentity) throw changedRecordingOutput(); - } - // The archive owns its original files. Only the independently downloadable files need staging. - const directory = sourceOutsideArchive - ? undefined - : await fs.promises.mkdtemp(path.join(os.tmpdir(), 'agent-device-suite-recording-')); - const staged: Registration[] = []; - try { - for (const { path: sourcePath, sourceIdentity, ...artifact } of files) { - assertActive(); - const delivery = { ...artifact, artifactId: crypto.randomUUID() }; - if (!directory) { - staged.push({ delivery, artifactPath: sourcePath, output: sourceIdentity }); - continue; - } - const artifactPath = path.join(directory, delivery.artifactId); - await fs.promises.copyFile( - sourcePath, - artifactPath, - fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE, - ); - assertActive(); - if (recordingExportFileIdentity(await fs.promises.lstat(sourcePath)) !== sourceIdentity) { - throw changedRecordingOutput(); - } - staged.push({ - delivery, - artifactPath, - output: requireFileIdentity(await fs.promises.lstat(artifactPath)), - }); - } - assertActive(); - return register(staged, directory); - } catch (error) { - if (directory) - await fs.promises.rm(directory, { recursive: true, force: true }).catch(() => {}); - throw error; - } -} - -function expireUnregisteredSources(files: readonly VerifiedFile[]): void { - for (const { path: sourcePath, sourceIdentity } of files) { +function expireUnregisteredSources(files: readonly RecordingFile[]): void { + for (const { path, sourceIdentity } of files) { try { - if (readSourceIdentity(sourcePath) === sourceIdentity) fs.unlinkSync(sourcePath); + if ( + recordingExportFileIdentity(fs.lstatSync(path, { throwIfNoEntry: false })) === + sourceIdentity + ) { + fs.unlinkSync(path); + } } catch { - // A missing or inaccessible file cannot be cleaned up safely. + // 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 970ed00295..f047f5278b 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -1,8 +1,4 @@ -import type { - RecordingFile, - RecordingPublication, - RecordingSourceKind, -} from './artifact-file-storage.ts'; +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'; @@ -144,7 +140,7 @@ export function diagnosticsRecordOwner(recordId: string): string | undefined | n // --- 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 = { @@ -186,6 +182,7 @@ type ArtifactEntry = { directory?: string; lifetimeId: string; recording?: true; + consume?: () => void; }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; @@ -206,7 +203,8 @@ type ArtifactEntry = { type ArtifactTrackingState = { artifacts: Map; reservations: Set<() => void>; - recordingPublications: Map; + recordingScope: AbortController; + unregisteredRecordings: Map>; uploads: Map; retainedPerformanceSources: Map< string, @@ -221,16 +219,19 @@ const artifactTracking = (): ArtifactTrackingState => (): ArtifactTrackingState => ({ artifacts: new Map(), reservations: new Set(), - recordingPublications: new Map(), + 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 publication of state.recordingPublications.values()) publication.dispose(); - state.recordingPublications.clear(); 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()) { @@ -341,51 +342,53 @@ function bindFileOutputDelivery( return artifact; } +export const recordingRegistrySignal = () => artifactTracking().recordingScope.signal; + /** Commits verified recordings independently of the request that delivers their IDs. */ export async function commitRecordingFileOutputs( files: readonly RecordingFile[], producer: FileOutputProducer, - sessionName: string | undefined, + sessionName: string, completedAt: number, - sourceKind: RecordingSourceKind, + reservationId: string, + retainOnly = false, ): Promise { - const { publishRecordingFiles } = await import('./artifact-file-storage.ts'); - const { artifacts, recordingPublications } = artifactTracking(); - return publishRecordingFiles({ - publications: recordingPublications, - producer, - files, - expiresAt: completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS, - sourceKind, - isAvailable: (id) => { - const entry = artifacts.get(id); - return ( - entry !== undefined && - !entry.cleanupRequested && - statRegisteredOutput(id, entry) !== undefined + 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 (retainOnly) 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, + consume: () => recordConsumption(artifactPath, expiresAt), + }, + completedAt, ); - }, - register: (registrations, directory) => { - for (const { delivery, artifactPath, output } of registrations) { - addArtifactEntry( - artifacts, - delivery.artifactId, - { - artifactPath, - artifactType: delivery.artifactType, - fileName: delivery.fileName, - tenantId: producer.tenantId, - leaseVerifier: producer.leaseVerifier ?? undefined, - sessionName, - }, - output, - { remainingEntries: 1, deleteAfterDownload: true }, - { directory, lifetimeId: producer.lifetimeId, recording: true }, - completedAt, - ); - } - }, + } + return { ...delivery, artifactId }; }); + clearTimeout(unregisteredRecordings.get(reservationId)); + unregisteredRecordings.delete(reservationId); + return results; } export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; @@ -883,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); } 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-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index 10f8cdf8b8..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 @@ -291,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}`, { @@ -335,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') { @@ -691,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/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 0085b76e8d..41c25663dd 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -1,4 +1,5 @@ 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'; @@ -34,7 +35,7 @@ import { settleCommittedFileOutputs, } from '../../resources/artifact-tracking.ts'; import { tryHandleDownloadableArtifactHttpRoute } from '../../server/downloadable-artifact-http.ts'; -import { commitRecordingOutputs } from '../recording-outputs.ts'; +import { collectSuiteRecordingOutputs, commitRecordingOutputs } from '../recording-outputs.ts'; import { teardownSessionResources } from '../session-teardown.ts'; import { makeRecordRuntimeHarness } from '../handlers/__tests__/record-runtime.fixtures.ts'; @@ -84,6 +85,7 @@ function publishRecordingSession( unleasedProducer?: boolean; producerTenant?: string; omitTelemetry?: boolean; + legacy?: boolean; } = {}, ) { const session: SessionState = makeIosSession(ADDRESS, { @@ -129,20 +131,35 @@ function publishRecordingSession( 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: 'recording-fence', generation: 1 }, + 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 } : {}), + ...(recordingExport.daemonOwned + ? { + remoteCaptureOutput: true, + ...(!options.legacy + ? { + remoteCapturePath: recordingExport.outPath, + remoteCaptureLifetime: lifetimeId, + remoteCaptureReservation: path.basename(path.dirname(recordingExport.outPath)), + } + : {}), + } + : {}), ...(options.unleasedProducer && !options.producerTenant ? {} - : { remoteCaptureTenantId: options.producerTenant ?? TENANT }), + : { + remoteCaptureTenantId: + options.leased === false ? null : (options.producerTenant ?? TENANT), + }), remoteCaptureLease: options.leased === false || options.unleasedProducer ? 'unleased' : leaseVerifier(LEASE_ID), }, @@ -152,7 +169,7 @@ function publishRecordingSession( screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), envelope, ); - return { ref: sessionStore.publish(ADDRESS, session), finish, forceCleanup }; + return { ref: sessionStore.publish(ADDRESS, session, lifetimeId), finish, forceCleanup }; } async function teardown(sessionStore: SessionStore) { @@ -284,7 +301,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), ); if (record.status !== 'decoded') throw new Error('Expected completed recording manifest'); - const artifacts = await commitRecordingOutputs(record.envelope, recovery.completion); + const artifacts = await commitRecordingOutputs(record.envelope); expect(artifacts.map((artifact) => artifact.artifactId)).toEqual(retained.map((a) => a.id)); expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([ @@ -384,26 +401,27 @@ test.each([undefined, '/client/downloads/checkout.mp4'])( }, ); -test.each([undefined, 'former-tenant'])( - 'teardown assigns an unleased recording with producer tenant %s to the session lease tenant', - async (producerTenant) => { +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-'); - publishRecordingSession(sessionStore, remoteRecordingExport(), { - unleasedProducer: true, + const output = remoteRecordingExport(); + publishRecordingSession(sessionStore, output, { + legacy: true, + unleasedProducer, 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' }), - ]), - ); + 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'); }, ); @@ -418,19 +436,27 @@ test('fresh runtime slots can restore an intact recording from its producer mani 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, }); - expect(await harness.run(['stop'], { 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([]); - const stopped = await harness.run(['stop'], { tenantId: 'other' }, undefined, remote); + 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([ @@ -458,6 +484,75 @@ test('fresh runtime slots can restore an intact recording from its producer mani } }); +test('close preserves completion for an exact-owner retry when export inspection fails', async () => { + const harness = makeRecordRuntimeHarness('recording-close-proof-io-', { sessionName: ADDRESS }); + 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 inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source) + throw Object.assign(new Error('verification unavailable'), { code: 'EIO' }); + return lstat(file, options); + }); + try { + await teardown(harness.sessionStore); + } 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(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('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(); @@ -493,7 +588,10 @@ test('a transient inspection error preserves the recording and other inventory e }); try { const result = await run('stop'); - expect(result).toMatchObject({ ok: false, error: { message: 'inspection I/O failed' } }); + 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); @@ -544,9 +642,11 @@ async function startSuiteRecording(withSidecar = false) { expect(await harness.run(['start', video], meta, undefined, internal)).toMatchObject({ ok: true, }); - fs.writeFileSync(video, 'leased-suite-recording'); + 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(video); + const telemetryPath = deriveRecordingTelemetryPath(source); fs.writeFileSync(telemetryPath, '{}'); const finish = harness.runtime.finish.getMockImplementation()!; harness.runtime.finish.mockImplementation(async () => { @@ -554,37 +654,37 @@ async function startSuiteRecording(withSidecar = false) { return { ...outcome, result: { ...outcome.result, telemetryPath } }; }); } - return { suite, video, stop }; + const collect = () => + collectSuiteRecordingOutputs(harness.sessionStore, harness.sessionStore.lookup(ADDRESS)!); + return { suite, video, source, stop, collect, harness }; } -test('suite recording staging can wait for an asynchronous copy before publishing', async () => { - const { stop } = await startSuiteRecording(); - // Hold the asynchronous full-copy path open so other work can run before publication finishes. - const copy = fs.promises.copyFile; - let releaseCopy = () => {}; - const gate = new Promise((resolve) => { - releaseCopy = resolve; - }); - const staging = vi.spyOn(fs.promises, 'copyFile').mockImplementationOnce(async (...args) => { - await gate; - return await copy(...args); +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 synchronousCopy = vi.spyOn(fs, 'copyFileSync'); - const stopping = stop(); + const unleasedStop = () => + harness.run(['stop'], { tenantId: TENANT }, undefined, { publicNetworkOnly: true }); try { - await vi.waitFor(() => expect(staging).toHaveBeenCalledOnce()); - expect(synchronousCopy).not.toHaveBeenCalled(); - expect(await listDownloadableArtifacts(OWNER, process.env)).toEqual([]); + 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 { - releaseCopy(); - staging.mockRestore(); - synchronousCopy.mockRestore(); + inspect.mockRestore(); } - const stopped = await stopping; - expect(stopped).toMatchObject({ - ok: true, - data: { artifacts: [{ artifactId: expect.any(String) }] }, - }); }); test.each(['expiry', 'disposal'])( @@ -592,7 +692,8 @@ test.each(['expiry', 'disposal'])( async (end) => { vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); const runtime = createRuntimeStateHandle(); - const { video, stop } = await runtime.run(() => startSuiteRecording(true)); + const { video, stop, collect } = await runtime.run(() => startSuiteRecording(true)); + expect(await runtime.run(stop)).toMatchObject({ ok: true }); let enter!: (target: string) => void; const entered = new Promise((resolve) => { enter = resolve; @@ -607,24 +708,24 @@ test.each(['expiry', 'disposal'])( await gate; await copy(...args); }); - let outcome: Awaited> | undefined; - const stopping = runtime.run(stop).then((result) => { + let outcome: Awaited> | undefined; + const stopping = runtime.run(collect).then((result) => { outcome = result; }); try { const target = await entered; if (end === 'disposal') runtime.dispose(); await vi.advanceTimersByTimeAsync(end === 'expiry' ? 15 * 60 * 1000 : 0); - expect(outcome).toMatchObject({ - ok: false, - error: { details: { reason: 'RESOURCE_EXPIRED' } }, - }); + 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.readFileSync(video, 'utf8')).toBe('leased-suite-recording'); + expect(fs.existsSync(video)).toBe(false); expect(await runtime.run(() => listDownloadableArtifacts(OWNER, {}))).toEqual([]); } finally { release(); @@ -638,10 +739,11 @@ test.each(['expiry', 'disposal'])( 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, stop } = await startSuiteRecording(); + 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 collect()).toMatchObject([{ path: video, artifactId: recording.artifactId }]); const archiveId = trackDownloadableArtifact({ artifactPath: suite, artifactType: 'test-artifacts', @@ -684,7 +786,22 @@ for (const first of ['archive', 'recording']) { expect(await stop()).toMatchObject({ ok: true, data: { artifacts: [recording] } }); await consumeRecording(); } else { - await consumeRecording(); + 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 }), @@ -831,37 +948,6 @@ test.each([ }, ); -test('failed registration of a legacy export without recorded identity leaves its file alone', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); - const sessionStore = makeSessionStore('recording-legacy-cleanup-'); - const recordingExport = remoteRecordingExport(); - publishRecordingSession(sessionStore, recordingExport); - - const lstat = fs.lstatSync; - let sourceReads = 0; - const stat = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { - if (file === recordingExport.outPath && ++sourceReads === 2) { - throw Object.assign(new Error('registry stat unavailable'), { code: 'EIO' }); - } - return lstat(file, options); - }); - try { - await teardown(sessionStore); - expect(sourceReads).toBe(2); - expect( - screenRecordingResourceStore.read( - screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), - ), - ).toMatchObject({ status: 'decoded', envelope: { lifecycle: 'completed' } }); - expect(await listDownloadableArtifacts(OWNER, {})).toEqual([]); - } finally { - stat.mockRestore(); - } - await vi.advanceTimersByTimeAsync(15 * 60 * 1000); - expect(fs.readFileSync(recordingExport.outPath, 'utf8')).toBe('video'); - expect(fs.readFileSync(recordingExport.telemetryPath, 'utf8')).toBe('{"events":[]}'); -}); - test('explicit stop keeps its binding until the advertised sidecar can be verified', async () => { const harness = makeRecordRuntimeHarness('recording-sidecar-retry-'); const finish = harness.runtime.finish.getMockImplementation()!; diff --git a/packages/daemon/src/sessions/handlers/record-runtime-response.ts b/packages/daemon/src/sessions/handlers/record-runtime-response.ts index 00aa327c4f..f84936009f 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime-response.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime-response.ts @@ -33,13 +33,15 @@ 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, @@ -76,13 +78,19 @@ export function buildRecordingUnsupportedResponse( export function buildRecordingStopResponse( completion: ScreenRecordingCompletion, artifacts = recordingStopArtifacts(completion), + remote = false, ): DaemonResponse { return { ok: true, data: { recording: 'stopped', - outPath: completion.outPath, - telemetryPath: completion.telemetryPath, + 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, @@ -105,7 +113,7 @@ export function buildRecordingStopResponse( 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 54925454e1..9991afe1fe 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'; @@ -77,7 +76,6 @@ import { buildRecordingStartedAction, buildRecordingStopResponse, buildRecordingUnsupportedResponse, - isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, UNLEASED_CAPTURE, } from './record-runtime-response.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; }>; @@ -137,8 +135,9 @@ async function handleRecordCommandUnsafe( ) { return missingAppSessionResponse(req); } - if (plan.kind !== 'start') assertRequestMayStopRecording(params); - 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( @@ -156,6 +155,7 @@ async function handleRecordCommandUnsafe( resolvedSession.ref, plan.kind, resolvedSession.needsReadiness, + authorized, ); } @@ -174,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); } @@ -316,6 +292,7 @@ async function startRecording( snapshot, params.sessionStore.ensureSessionDir(params.sessionName), outputPaths.requestedPath, + !params.suiteCapture && outputPaths.daemonOwned === true, ); } @@ -340,10 +317,13 @@ function withCaptureOwner( ? { remoteCaptureOutput: true, remoteCapturePath: output.outputPath, + remoteCaptureReservation: envelope.fence.token, remoteCaptureLifetime: lifetimeId, remoteCaptureTenantId: tenantId ?? null, - ...(suiteCapture && req.meta?.clientArtifactPaths?.artifactsDir - ? { remoteCaptureArchive: true } + ...(suiteCapture === 'remote' && + req.meta?.clientArtifactPaths?.artifactsDir && + req.positionals?.[1] + ? { suiteRecordingArchivePath: req.positionals[1] } : {}), } : {}), @@ -365,21 +345,23 @@ function prepareRecordingStart(params: RecordRuntimeHandlerParams, session: Sess resourcePath, device: session.device, }), - outputPaths: params.suiteCapture - ? { - ...resolveRecordingOutputPaths({ - requestedPath: params.req.positionals?.[1], - platform: session.device.platform, - cwd: params.sessionStore.host.cwd, - }), - ...(params.suiteCapture === 'remote' ? { daemonOwned: true as const } : {}), - } - : 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), + ), }; } @@ -465,27 +447,21 @@ async function stopRecording( ref: SessionRef | undefined, kind: 'stop-live' | 'stop-recovery', needsReadiness: boolean, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, ): Promise { 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 record = screenRecordingDurableResource.store.read( - screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), - ); + 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', @@ -500,35 +476,99 @@ 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); - if (isLegacyRemoteRecordingOutput(completion)) throw leasedOutputRefusal('Recording'); - const envelope = record.status === 'decoded' ? record.envelope : undefined; + const remote = isRemoteRecordingRequest(params); const artifacts = - envelope?.metadata?.remoteCaptureOutput === true - ? await commitRecordingOutputs(envelope, completion, { - replay: !stopped.recordsSessionAction, - }) + envelope.metadata?.remoteCaptureOutput === true && + (remote || envelope.metadata.remoteCaptureExport !== undefined) + ? await commitRecordingOutputs(envelope) : undefined; - return buildRecordingStopResponse(completion, artifacts); + if (remote && !artifacts) throw leasedOutputRefusal('Recording'); + return buildRecordingStopResponse(completion, artifacts, !params.suiteCapture && remote); } -/** - * A completed 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): void { +async function finishAuthorizedLiveRecording( + params: RecordRuntimeHandlerParams, + 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 + ); +} + +function readStopEnvelope(params: RecordRuntimeHandlerParams) { const record = screenRecordingDurableResource.store.read( screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), ); - if (record.status !== 'decoded') return; - const { metadata, lifecycle } = record.envelope; + 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; +} + +/** + * 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, + 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 ( + 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'); } @@ -562,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 index 4ac3167ba6..a2f4e5b832 100644 --- 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 @@ -112,6 +112,11 @@ test.each([false, true])( 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'); @@ -119,6 +124,7 @@ test.each([false, true])( 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, @@ -126,6 +132,23 @@ test.each([false, true])( } 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({ @@ -138,7 +161,7 @@ test.each([false, true])( } finally { for (const artifact of inventory) cleanupDownloadableArtifact(artifact.id); } - expect(fs.existsSync(outputPath)).toBe(true); + 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 e615a3a6af..8251c0c055 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-command.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-command.ts @@ -250,8 +250,9 @@ export const handleReplayTestCommand: SessionCommandHandler = async ({ } finally { if (video && req.flags?.recordVideo) { for (const output of await collectSuiteRecordingOutputs(sessionStore, ref)) { - artifactPaths?.add(output.path); - if (artifactPaths) recordingOutputs.set(output.path, output); + if (output.path) artifactPaths?.add(output.path); + if (artifactPaths) + recordingOutputs.set(output.artifactId ?? output.path!, output); } } } 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 1283389a2e..ace0b8aa10 100644 --- a/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts +++ b/packages/daemon/src/sessions/handlers/session-replay-video-owner.ts @@ -115,7 +115,10 @@ function recordRequest(request: ReplayRecordVideoRequest, suite?: DaemonRequest) 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 index c9cd13614d..ba8dd07033 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -14,19 +14,17 @@ export async function retainLeasedSessionRecording( completion: ScreenRecordingCompletion, envelope: DurableResourceEnvelope<'screen-recording'>, ): Promise { - const lease = ref.session.lease; const { metadata } = envelope; if ( metadata?.remoteCaptureOutput !== true || isLegacyRemoteRecordingOutput(completion) || - recordingOutputLeaseVerifier(metadata) === undefined || - (metadata.remoteCaptureLifetime === undefined - ? !lease - : metadata.remoteCaptureLifetime !== ref.lifetime.journalId) + metadata.remoteCaptureLifetime !== ref.lifetime.journalId ) return; try { - await commitRecordingOutputs(envelope, completion, { legacyTenant: lease?.tenantId }); + const hostGlobal = + recordingOutputLeaseVerifier(metadata) === null && metadata.remoteCaptureTenantId === null; + await commitRecordingOutputs(envelope, hostGlobal); } catch (error) { emitDiagnostic({ level: 'warn', diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts index dbd401c266..c2d2661869 100644 --- a/packages/daemon/src/sessions/recording-outputs.ts +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -1,102 +1,110 @@ +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 } from '@agent-device/capture-kit/screen-recording-stop-recovery'; +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 type { ScreenRecordingCompletion } from '@agent-device/contracts/screen-recording-runtime'; 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 { commitRecordingFileOutputs, leasedOutputRefusal } from '../resources/artifact-tracking.ts'; +import { + ARTIFACT_CLEANUP_TIMEOUT_MS, + commitRecordingFileOutputs, + leasedOutputRefusal, + recordingRegistrySignal, +} from '../resources/artifact-tracking.ts'; import { isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, recordingStopArtifacts, } from './handlers/record-runtime-response.ts'; -export async function commitRecordingOutputs( - envelope: DurableResourceEnvelope<'screen-recording'>, - completion: ScreenRecordingCompletion, - options?: { legacyTenant?: string; replay?: boolean }, -) { +type RecordingEnvelope = DurableResourceEnvelope<'screen-recording'>; + +function readVerifiedRecording(envelope: RecordingEnvelope) { const { metadata } = envelope; - const owner = recordingOutputLeaseVerifier(metadata); - if (owner === undefined || isLegacyRemoteRecordingOutput(completion)) { + const completion = readStoredCompletion(metadata); + const verified = metadata?.remoteCaptureExport; + if ( + envelope.lifecycle !== 'completed' || + !completion || + isLegacyRemoteRecordingOutput(completion) || + completion.outPath !== metadata?.remoteCapturePath || + metadata.remoteCaptureArchive === true || + !isRecord(verified) || + !Array.isArray(verified.identities) || + !Array.isArray(verified.outputIds) || + typeof verified.completedAt !== 'number' || + !Number.isFinite(verified.completedAt) + ) throw leasedOutputRefusal('Recording'); - } - const proof = readRecordingExportProof(envelope); + const { identities, outputIds } = verified; const artifacts = recordingStopArtifacts(completion); - if (proof && proof.identities.length !== artifacts.length) { - throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); - } + if (artifacts.length !== identities.length) throw leasedOutputRefusal('Recording'); const files = artifacts.map((artifact, index) => { - const sourceIdentity = proof?.identities[index]; - if (proof && typeof sourceIdentity !== 'string') { - throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); - } - return { - ...artifact, - path: artifact.path!, - sourceIdentity: typeof sourceIdentity === 'string' ? sourceIdentity : undefined, - }; + const sourceIdentity = identities[index]; + const artifactId = outputIds[index]; + if (typeof sourceIdentity !== 'string' || artifactId !== `${envelope.fence.token}-${index + 1}`) + throw leasedOutputRefusal('Recording'); + return { ...artifact, path: artifact.path!, sourceIdentity, artifactId }; }); - const tenantId = recordingProducerTenant( - envelope, - owner, - proof !== undefined, - options?.legacyTenant, - ); - return commitRecordingFileOutputs( + return { + completion, files, - { - lifetimeId: proof?.lifetimeId ?? envelope.fence.token, - tenantId, - leaseVerifier: owner, - }, - tenantId ? tenantPublicSessionName(tenantId, envelope.sessionId) : envelope.sessionId, - proof?.completedAt ?? Date.now(), - metadata?.remoteCaptureArchive !== true - ? 'original' - : options?.replay - ? 'archive-replay' - : 'archive', - ); -} - -function recordingProducerTenant( - envelope: DurableResourceEnvelope<'screen-recording'>, - owner: string | null, - verified: boolean, - legacyTenant?: string, -): string | undefined { - const stored = envelope.metadata?.remoteCaptureTenantId; - const tenant = normalizeTenantId(stored); - if (!verified) return owner === null && legacyTenant ? legacyTenant : (tenant ?? legacyTenant); - if (stored === null && owner === null) return undefined; - if (!tenant || tenant !== stored) throw leasedOutputRefusal('Recording'); - return tenant; + completedAt: verified.completedAt, + producer: recordingProducer(metadata), + }; } -function readRecordingExportProof(envelope: DurableResourceEnvelope<'screen-recording'>) { - if (envelope.lifecycle !== 'completed') { - throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); - } - const { metadata } = envelope; +function recordingProducer(metadata: RecordingEnvelope['metadata']) { + const leaseVerifier = recordingOutputLeaseVerifier(metadata); const lifetimeId = metadata?.remoteCaptureLifetime; - if (lifetimeId === undefined && metadata?.remoteCapturePath === undefined) return undefined; - const verified = metadata?.remoteCaptureExport; + const stored = metadata?.remoteCaptureTenantId; + const tenantId = normalizeTenantId(stored); if ( + leaseVerifier === undefined || typeof lifetimeId !== 'string' || - !isRecord(verified) || - !Array.isArray(verified.identities) || - typeof verified.completedAt !== 'number' || - !Number.isFinite(verified.completedAt) + (stored === null ? leaseVerifier !== null : !tenantId || tenantId !== stored) ) { - throw new AppError('COMMAND_FAILED', 'Recording export could not be verified.'); + throw leasedOutputRefusal('Recording'); } - return { lifetimeId, identities: verified.identities, completedAt: verified.completedAt }; + return { lifetimeId, tenantId, leaseVerifier }; +} + +function publishVerifiedRecording( + envelope: RecordingEnvelope, + recording: ReturnType, + retainOnly = false, +) { + const { producer, files, completedAt } = recording; + return commitRecordingFileOutputs( + files, + producer, + producer.tenantId + ? tenantPublicSessionName(producer.tenantId, envelope.sessionId) + : envelope.sessionId, + completedAt, + envelope.fence.token, + retainOnly, + ); +} + +export async function commitRecordingOutputs(envelope: RecordingEnvelope, retainOnly = false) { + return publishVerifiedRecording(envelope, readVerifiedRecording(envelope), retainOnly); } export async function collectSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { @@ -112,23 +120,122 @@ export async function collectSuiteRecordingOutputs(store: SessionStore, ref: Ses } } -async function readSuiteRecordingOutputs(store: SessionStore, ref: SessionRef) { - const record = screenRecordingResourceStore.read( - screenRecordingResourceStore.resolvePath(store.resolveSessionDir(ref.address)), +async function readSuiteRecordingOutputs( + store: SessionStore, + ref: SessionRef, +): Promise { + const resourcePath = screenRecordingResourceStore.resolvePath( + store.resolveSessionDir(ref.address), ); - if (record.status !== 'decoded' || record.envelope.lifecycle !== 'completed') return []; - const { envelope } = record; + const record = screenRecordingResourceStore.read(resourcePath); + if (record.status !== 'decoded') return []; + let { envelope } = record; if (envelope.metadata?.suiteRecordingLifetime !== ref.lifetime.journalId) return []; - const completion = readReplayableStoredCompletion(envelope.metadata); - if (!completion) return []; - const artifacts = recordingStopArtifacts(completion); - const committed = - envelope.metadata.remoteCaptureOutput === true - ? await commitRecordingOutputs(envelope, completion, { replay: true }) + 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 })) : []; - return artifacts.map((artifact, index) => ({ + } + + const recording = readVerifiedRecording(envelope); + const committed = await publishVerifiedRecording(envelope, recording); + const archivePath = envelope.metadata.suiteRecordingArchivePath; + let paths: readonly string[] = []; + if (typeof archivePath === 'string') { + try { + paths = await copySuiteRecording(archivePath, recording); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'suite_recording_archive_copy_failed', + data: { session: ref.address, error: errorMessage(error) }, + }); + } + } + return committed.map(({ artifactId, fileName }, index) => ({ session: ref.address, - path: artifact.path!, - artifactId: committed[index]?.artifactId, + 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/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 f9faf0d635..f4831c993e 100644 --- a/packages/replay-port/src/daemon-port/test-command.ts +++ b/packages/replay-port/src/daemon-port/test-command.ts @@ -303,7 +303,12 @@ export async function runReplayTestCommand(command: ReplayTestCommand): Promise< return outcome.status === 'completed' ? { ok: true, - data: attachRemoteReplayTestArtifacts(outcome.data, req, command.recordingOutputs?.()), + data: attachRemoteReplayTestArtifacts( + outcome.data, + req, + command.recordingOutputs?.(), + command.publicNetworkOnly, + ), } : errorResponse(outcome.error.code, outcome.error.message); } @@ -382,50 +387,64 @@ 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) { + if (!clientRoot && !publicNetworkOnly) { return recordings.length > 0 ? { ...data, recordingArtifacts: recordings } : 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) + 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, ...(recordings.length > 0 ? { - recordingArtifacts: recordings - .filter((recording) => recording.path.startsWith(daemonRoot + path.sep)) - .map((recording) => ({ ...recording, path: remapArtifactsDir(recording.path) })), + recordingArtifacts: recordings.map(({ path: recordingPath, ...recording }) => ({ + ...recording, + ...(clientRoot && recordingPath ? { path: project(recordingPath) } : {}), + })), } : {}), - 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, - ), + 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/test/wire-compat/ledger.json b/test/wire-compat/ledger.json index c44cdb72d0..6eb87be0da 100644 --- a/test/wire-compat/ledger.json +++ b/test/wire-compat/ledger.json @@ -10,7 +10,7 @@ "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:5dbfc0751ef7c3650b669f11a1755a6715bec31978c83452881d16ebd42ecdcc", + "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", @@ -80,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", @@ -240,8 +240,8 @@ "compatibleChanges": [ { "declaration": "packages/contracts/src/replay.ts#ReplaySuiteRecordingArtifact", - "digest": "sha256:5dbfc0751ef7c3650b669f11a1755a6715bec31978c83452881d16ebd42ecdcc", - "rationale": "An entry in the optional recordingArtifacts member describes an attempt session, client-local archive path, and optional recording artifact ID. Existing archive delivery and recording stop framing are unchanged." + "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", @@ -295,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/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. From 1e74b954dd3cf53575b036e8db7b44ed2849b0d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 17:10:49 +0100 Subject: [PATCH 07/12] fix(daemon): settle recording proof and archive publication in order --- .../durable-capture-start-preflight.ts | 5 + .../screen-recording-session-resource.ts | 99 ++++++++---- .../src/durable-capture/definition.ts | 3 + .../capture-kit/src/durable-capture/fence.ts | 34 +++- .../src/durable-capture/recovery.ts | 35 +++-- .../src/durable-capture/transitions.ts | 27 +--- .../src/device-claim-reconciliation.test.ts | 27 ++++ .../src/device-claim-reconciliation.ts | 18 ++- ...screen-recording-resource-recovery.test.ts | 31 ++++ .../daemon/src/resources/artifact-tracking.ts | 30 ++-- .../leased-recording-retention.test.ts | 147 ++++++++---------- .../record-runtime-stop-recovery.test.ts | 93 +++++++++++ .../src/sessions/handlers/record-runtime.ts | 2 +- .../sessions/leased-recording-retention.ts | 2 +- .../daemon/src/sessions/recording-outputs.ts | 30 +++- 15 files changed, 409 insertions(+), 174 deletions(-) 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-session-resource.ts b/packages/capture-kit/src/capture-admission/screen-recording-session-resource.ts index 40e86671b4..14a1052c2c 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 @@ -1,6 +1,8 @@ import fs from 'node:fs'; import { AppError } from '@agent-device/kernel/errors'; import type { JsonObject } from '@agent-device/contracts/client'; +import type { DurableCaptureProgress } from '@agent-device/contracts/durable-resource'; +import { isRecord } from '@agent-device/kernel/record'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; @@ -20,7 +22,7 @@ import type { DurableCaptureRecoveryControl, DurableCaptureSessionBinding, } from '../durable-capture/index.ts'; -import { withDurableCaptureResourceFence } from '../durable-capture/fence.ts'; +import { createStopProgress, 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'; @@ -37,7 +39,7 @@ export const screenRecordingDurableResource = createDurableCaptureResource< resourceKind: 'screen-recording', displayName: 'screen recording', store: screenRecordingResourceStore, - completionMetadata: async (result, metadata) => ({ + completionMetadata: async (result, metadata, progress) => ({ ...encodeScreenRecordingCompletionMetadata(result), ...(typeof metadata?.remoteCapturePath === 'string' && typeof metadata.remoteCaptureReservation === 'string' @@ -46,17 +48,16 @@ export const screenRecordingDurableResource = createDurableCaptureResource< metadata.remoteCapturePath, result, metadata.remoteCaptureReservation, - typeof metadata.remoteCaptureCompletedAt === 'number' - ? metadata.remoteCaptureCompletedAt - : Date.now(), + progress, ), } : {}), }), pendingCompletionMetadata: (result, error) => error instanceof RecordingProofIoError - ? { ...encodeScreenRecordingCompletionMetadata(result), remoteCaptureCompletedAt: Date.now() } + ? encodeScreenRecordingCompletionMetadata(result) : 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 @@ -73,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>; @@ -98,7 +106,7 @@ async function verifyRecordingExport( reservedPath: string, completion: ScreenRecordingCompletion, reservation: string, - completedAt: number, + progress: DurableCaptureProgress, ) { const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ import('../recording/output-path.ts'), @@ -121,12 +129,49 @@ async function verifyRecordingExport( if (!matchesReservation) { throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); } - const identities = files.map(readRecordingExportIdentity); - return { - completedAt, - identities, - outputIds: files.map((_, index) => `${reservation}-${index + 1}`), - }; + const outputIds = files.map((_, index) => `${reservation}-${index + 1}`); + const { completedAt, known } = readRecordingExportProgress(progress.learned, outputIds); + const identities: string[] = []; + const save = () => + progress.record({ + remoteCaptureExport: { completedAt, identities: [...identities], outputIds }, + }); + if (!progress.learned?.remoteCaptureExport) save(); + for (const [index, file] of files.entries()) { + const identity = readRecordingExportIdentity(file); + if (index < known.length && identity !== known[index]) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its stored proof.'); + } + identities.push(identity); + if (index >= known.length) save(); + } + return { completedAt, identities, outputIds }; +} + +function readRecordingExportProgress(metadata: JsonObject | undefined, outputIds: string[]) { + const previous = metadata?.remoteCaptureExport; + if (previous === undefined) { + return { + completedAt: + typeof metadata?.remoteCaptureCompletedAt === 'number' + ? metadata.remoteCaptureCompletedAt + : Date.now(), + known: [], + }; + } + const { completedAt, identities, outputIds: storedIds } = isRecord(previous) ? previous : {}; + if ( + typeof completedAt !== 'number' || + !Number.isFinite(completedAt) || + !Array.isArray(identities) || + identities.length > outputIds.length || + !Array.isArray(storedIds) || + storedIds.length !== outputIds.length || + !outputIds.every((id, index) => id === storedIds[index]) + ) { + throw new AppError('COMMAND_FAILED', 'Recording export does not match its stored proof.'); + } + return { completedAt, known: identities }; } function readRecordingExportIdentity(file: string): string { @@ -147,38 +192,40 @@ class RecordingProofIoError extends AppError { } } -export function finishPendingScreenRecordingProof( +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, + unreadableRecordError: unreadableRecordingProof, onCompleted: ({ envelope }) => envelope, run: async (lease) => { - const { readStoredCompletion, unreadableRecordingProof } = - await import('./screen-recording-stop-recovery.ts'); const { metadata } = lease.envelope; const completion = readStoredCompletion(metadata); if ( - metadata?.phase !== 'export-proof-pending' || + !metadata || + !screenRecordingNativeCleanupSettled(metadata) || !completion || typeof metadata.remoteCapturePath !== 'string' || - typeof metadata.remoteCaptureReservation !== 'string' || - typeof metadata.remoteCaptureCompletedAt !== 'number' + typeof metadata.remoteCaptureReservation !== 'string' ) throw unreadableRecordingProof(); + const proof = await verifyRecordingExport( + metadata.remoteCapturePath, + completion, + metadata.remoteCaptureReservation, + createStopProgress(lease), + ); return lease.transition('completed', { metadata: { - ...metadata, + ...lease.envelope.metadata, phase: 'completed', - remoteCaptureExport: await verifyRecordingExport( - metadata.remoteCapturePath, - completion, - metadata.remoteCaptureReservation, - metadata.remoteCaptureCompletedAt, - ), + remoteCaptureExport: proof, }, }); }, diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index 308455304f..d8ead0c215 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 { @@ -59,6 +60,7 @@ export type DurableCaptureRecordDefinition = Readonly<{ 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. @@ -73,6 +75,7 @@ export type DurableCaptureRecordDefinition = Readonly<{ * replay; its callers then get the terminal refusal. */ pendingCompletionMetadata?(result: C, error: unknown): 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..68f023a946 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, @@ -57,13 +59,21 @@ export async function withDurableCaptureResourceFence( store: DurableCaptureResourceStore; resourcePath: string; expected: ResourceOwnershipFence; + unreadableRecordError?: () => Error; /** Answers a run whose record this fence found committed, before any of the run's work. */ onCompleted(lease: DurableCaptureCompletedResourceFenceLease): Result | Promise; run(lease: DurableCaptureOpenResourceFenceLease): Promise; }>, ): 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, + params.unreadableRecordError, + ); + const admitted = read(); if (admitted.envelope.lifecycle === 'completed') { return await params.onCompleted({ envelope: admitted.envelope }); } @@ -77,11 +87,7 @@ 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); } @@ -107,9 +113,13 @@ function requireAdmissibleRecord( store: DurableCaptureResourceStore, resourcePath: string, expected: ResourceOwnershipFence, + unreadableRecordError?: () => Error, ): Extract, { status: 'decoded' }> { const record = store.read(resourcePath); if (record.status !== 'decoded') { + if (record.status === 'unreattachable' && unreadableRecordError) { + throw unreadableRecordError(); + } throw fenceError( store, record.status === 'missing' @@ -123,6 +133,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/recovery.ts b/packages/capture-kit/src/durable-capture/recovery.ts index aa1701ef29..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,17 +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, @@ -239,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/transitions.ts b/packages/capture-kit/src/durable-capture/transitions.ts index e6388b5c67..6be74a2969 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'; @@ -58,7 +58,7 @@ export async function finishLiveDurableCapture< record.status === 'decoded' && (record.envelope.lifecycle === 'completed' || (record.envelope.fence.token === active.envelope.fence.token && - record.envelope.metadata?.phase === 'export-proof-pending')) + definition.nativeCleanupSettled?.(record.envelope.metadata))) ) { params.binding.clear(active); } @@ -400,7 +400,11 @@ async function commitFinishedCapture( ): Promise { let completion; try { - completion = await definition.completionMetadata(result, lease.envelope.metadata); + completion = await definition.completionMetadata( + result, + lease.envelope.metadata, + createStopProgress(lease), + ); } catch (error) { if (onProofFailure) await onProofFailure(error); throw error; @@ -410,23 +414,6 @@ async function commitFinishedCapture( }); } -/** - * 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( - lease: DurableCaptureOpenResourceFenceLease, -): DurableCaptureProgress { - return Object.freeze({ - learned: lease.envelope.metadata, - record: (fact: JsonObject) => { - lease.transition('open', { metadata: { ...(lease.envelope.metadata ?? {}), ...fact } }); - }, - }); -} - /** * The fact that an attempt is in flight, journaled into a record this fence found open. Recovery * reads it to tell an abandoned attempt from one that never started, so it belongs to every entry 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/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index f047f5278b..1279e3a36d 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -31,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' }, @@ -138,8 +135,6 @@ export function diagnosticsRecordOwner(recordId: string): string | undefined | n return owner === UNLEASED_RECORD ? undefined : owner; } -// --- Downloadable artifact tracking --- - export const ARTIFACT_CLEANUP_TIMEOUT_MS = 15 * 60 * 1000; const ARTIFACT_DOWNLOAD_MAX_LIFETIME_MS = 15 * 60 * 1000; @@ -182,6 +177,7 @@ type ArtifactEntry = { directory?: string; lifetimeId: string; recording?: true; + awaitingArchive?: boolean; consume?: () => void; }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ @@ -344,14 +340,13 @@ function bindFileOutputDelivery( export const recordingRegistrySignal = () => artifactTracking().recordingScope.signal; -/** Commits verified recordings independently of the request that delivers their IDs. */ export async function commitRecordingFileOutputs( files: readonly RecordingFile[], producer: FileOutputProducer, sessionName: string, completedAt: number, reservationId: string, - retainOnly = false, + publication: 'publish' | 'retain' | 'await-archive' = 'publish', ): Promise { const { verifyRecordingFiles, recordConsumption, retainUnregisteredRecording } = await import('./artifact-file-storage.ts'); @@ -359,7 +354,7 @@ export async function commitRecordingFileOutputs( const expiresAt = completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS; const unregistered = files.filter(({ artifactId }) => !artifacts.has(artifactId)); retainUnregisteredRecording(unregisteredRecordings, reservationId, unregistered, expiresAt); - if (retainOnly) return []; + if (publication === 'retain') return []; verifyRecordingFiles(files, expiresAt); const results = files.map(({ path: artifactPath, sourceIdentity, artifactId, ...delivery }) => { if (!artifacts.has(artifactId)) { @@ -379,6 +374,7 @@ export async function commitRecordingFileOutputs( { lifetimeId: producer.lifetimeId, recording: true, + awaitingArchive: publication === 'await-archive', consume: () => recordConsumption(artifactPath, expiresAt), }, completedAt, @@ -391,6 +387,14 @@ export async function commitRecordingFileOutputs( 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 = { @@ -407,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); @@ -458,7 +457,8 @@ function addArtifactEntry( sourceCleanup, activeDownloads: new Set(), cleanupRequested: false, - awaitingDelivery: reservation !== undefined && reservation.recording === undefined, + awaitingDelivery: + reservation !== undefined && (!reservation.recording || reservation.awaitingArchive === true), createdAt, timer, }); diff --git a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index 41c25663dd..ea909af220 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -14,6 +14,7 @@ import { } 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'; @@ -32,6 +33,7 @@ import { trackDownloadableArtifact, leaseVerifier, listDownloadableArtifacts, + openDownloadableArtifact, settleCommittedFileOutputs, } from '../../resources/artifact-tracking.ts'; import { tryHandleDownloadableArtifactHttpRoute } from '../../server/downloadable-artifact-http.ts'; @@ -301,7 +303,7 @@ test('a record stop replay after a leased teardown serves the artifacts teardown screenRecordingResourceStore.resolvePath(sessionStore.resolveSessionDir(ADDRESS)), ); if (record.status !== 'decoded') throw new Error('Expected completed recording manifest'); - const artifacts = await commitRecordingOutputs(record.envelope); + 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([ @@ -484,39 +486,6 @@ test('fresh runtime slots can restore an intact recording from its producer mani } }); -test('close preserves completion for an exact-owner retry when export inspection fails', async () => { - const harness = makeRecordRuntimeHarness('recording-close-proof-io-', { sessionName: ADDRESS }); - 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 inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { - if (file === source) - throw Object.assign(new Error('verification unavailable'), { code: 'EIO' }); - return lstat(file, options); - }); - try { - await teardown(harness.sessionStore); - } 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(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('a failed completion manifest read never returns uncommitted remote paths', async () => { const harness = makeRecordRuntimeHarness('recording-completion-proof-io-'); const run = (action: string) => @@ -687,13 +656,69 @@ test('transient manifest I/O cannot bypass a completed recording lease', async ( } }); +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)], + outputIds: [expect.any(String), expect.any(String)], + }, + }, + }, + }); + 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(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)); - expect(await runtime.run(stop)).toMatchObject({ ok: 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; @@ -714,6 +739,11 @@ test.each(['expiry', 'disposal'])( }); 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([ @@ -743,6 +773,7 @@ for (const first of ['archive', 'recording']) { 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, @@ -947,49 +978,3 @@ test.each([ else expect(fs.existsSync(source)).toBe(false); }, ); - -test('explicit stop keeps its binding until the advertised sidecar can be verified', 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: true, - data: { - artifacts: [{ artifactId: expect.any(String) }, { artifactId: expect.any(String) }], - }, - }); - }); - } finally { - runtime.dispose(); - } -}); 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 81674e7c11..c3d7a0396a 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,8 @@ +import { createRuntimeStateHandle } from '@agent-device/host-kit/runtime-slots'; +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'; @@ -763,3 +768,91 @@ test.each([false, true])( } }, ); + +const TENANT = 'tenant-a'; + +test('close preserves completion for an exact-owner retry when export inspection fails', async () => { + 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 inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { + if (file === source) + throw Object.assign(new Error('verification unavailable'), { code: 'EIO' }); + return lstat(file, options); + }); + 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(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 until the advertised sidecar can be verified', 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: true, + data: { + artifacts: [{ artifactId: expect.any(String) }, { artifactId: expect.any(String) }], + }, + }); + }); + } finally { + runtime.dispose(); + } +}); diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index 9991afe1fe..03febb48b9 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -480,7 +480,7 @@ async function stopRecording( const artifacts = envelope.metadata?.remoteCaptureOutput === true && (remote || envelope.metadata.remoteCaptureExport !== undefined) - ? await commitRecordingOutputs(envelope) + ? await commitRecordingOutputs(envelope, ref ? 'live' : 'replay') : undefined; if (remote && !artifacts) throw leasedOutputRefusal('Recording'); return buildRecordingStopResponse(completion, artifacts, !params.suiteCapture && remote); diff --git a/packages/daemon/src/sessions/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts index ba8dd07033..66763da26c 100644 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ b/packages/daemon/src/sessions/leased-recording-retention.ts @@ -24,7 +24,7 @@ export async function retainLeasedSessionRecording( try { const hostGlobal = recordingOutputLeaseVerifier(metadata) === null && metadata.remoteCaptureTenantId === null; - await commitRecordingOutputs(envelope, hostGlobal); + await commitRecordingOutputs(envelope, hostGlobal ? 'retain' : 'live'); } catch (error) { emitDiagnostic({ level: 'warn', diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts index c2d2661869..c69a5f5d70 100644 --- a/packages/daemon/src/sessions/recording-outputs.ts +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -25,6 +25,7 @@ import { ARTIFACT_CLEANUP_TIMEOUT_MS, commitRecordingFileOutputs, leasedOutputRefusal, + settleRecordingArchiveCopy, recordingRegistrySignal, } from '../resources/artifact-tracking.ts'; import { @@ -88,7 +89,7 @@ function recordingProducer(metadata: RecordingEnvelope['metadata']) { function publishVerifiedRecording( envelope: RecordingEnvelope, recording: ReturnType, - retainOnly = false, + delivery?: 'publish' | 'retain' | 'await-archive', ) { const { producer, files, completedAt } = recording; return commitRecordingFileOutputs( @@ -99,12 +100,21 @@ function publishVerifiedRecording( : envelope.sessionId, completedAt, envelope.fence.token, - retainOnly, + delivery, ); } -export async function commitRecordingOutputs(envelope: RecordingEnvelope, retainOnly = false) { - return publishVerifiedRecording(envelope, readVerifiedRecording(envelope), retainOnly); +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) { @@ -143,10 +153,16 @@ async function readSuiteRecordingOutputs( } const recording = readVerifiedRecording(envelope); - const committed = await publishVerifiedRecording(envelope, recording); 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 (typeof archivePath === 'string') { + if (hasArchive) { + const signal = recordingRegistrySignal(); try { paths = await copySuiteRecording(archivePath, recording); } catch (error) { @@ -155,6 +171,8 @@ async function readSuiteRecordingOutputs( 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) => ({ From a555931c3accec015134a79137c7ed9bb72066d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 18:10:21 +0100 Subject: [PATCH 08/12] fix(daemon): require producer evidence on recording proof retry --- .../screen-recording-resource-store.ts | 22 +++ .../screen-recording-session-resource.ts | 78 ++++---- .../screen-recording-stop-recovery.ts | 5 +- .../src/durable-capture/definition.ts | 8 +- .../capture-kit/src/durable-capture/fence.ts | 30 +-- .../src/durable-capture/finish-recovered.ts | 1 - .../capture-kit/src/durable-capture/store.ts | 3 + .../src/durable-capture/transitions.test.ts | 28 +++ .../src/durable-capture/transitions.ts | 77 +++++--- .../src/screen-recording-live-handle.test.ts | 4 + .../src/screen-recording-live-handle.ts | 8 +- .../leased-recording-retention.test.ts | 19 +- .../record-runtime-stop-recovery.test.ts | 183 ++++++++++++++---- 13 files changed, 332 insertions(+), 134 deletions(-) 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..eb0758d1a1 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,32 @@ 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, }); /** 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 14a1052c2c..e40771abfb 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 @@ -22,12 +22,14 @@ import type { DurableCaptureRecoveryControl, DurableCaptureSessionBinding, } from '../durable-capture/index.ts'; -import { createStopProgress, withDurableCaptureResourceFence } from '../durable-capture/fence.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, + recordingCheckpointError, screenRecordingResourceStore, } from './screen-recording-resource-store.ts'; @@ -48,14 +50,15 @@ export const screenRecordingDurableResource = createDurableCaptureResource< metadata.remoteCapturePath, result, metadata.remoteCaptureReservation, + metadata, progress, ), } : {}), }), - pendingCompletionMetadata: (result, error) => + pendingCompletionMetadata: (result, error, completion) => error instanceof RecordingProofIoError - ? encodeScreenRecordingCompletionMetadata(result) + ? (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 @@ -106,7 +109,8 @@ async function verifyRecordingExport( reservedPath: string, completion: ScreenRecordingCompletion, reservation: string, - progress: DurableCaptureProgress, + metadata: JsonObject, + progress?: DurableCaptureProgress, ) { const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ import('../recording/output-path.ts'), @@ -130,40 +134,45 @@ async function verifyRecordingExport( throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); } const outputIds = files.map((_, index) => `${reservation}-${index + 1}`); - const { completedAt, known } = readRecordingExportProgress(progress.learned, outputIds); - const identities: string[] = []; - const save = () => - progress.record({ - remoteCaptureExport: { completedAt, identities: [...identities], outputIds }, - }); - if (!progress.learned?.remoteCaptureExport) save(); - for (const [index, file] of files.entries()) { - const identity = readRecordingExportIdentity(file); - if (index < known.length && identity !== known[index]) { + const stored = metadata.remoteCaptureExport; + if (stored !== undefined) { + const { completedAt, known } = readRecordingExportProgress(stored, outputIds); + if (known.some((identity, index) => readRecordingExportIdentity(files[index]!) !== identity)) { throw new AppError('COMMAND_FAILED', 'Recording export does not match its stored proof.'); } - identities.push(identity); - if (index >= known.length) save(); + if (known.length !== files.length) throw missingProducerProof(); + return { completedAt, identities: known, outputIds }; } - return { completedAt, identities, outputIds }; + if (!progress) throw missingProducerProof(); + return checkpointRecordingExport(files, outputIds, progress); } -function readRecordingExportProgress(metadata: JsonObject | undefined, outputIds: string[]) { - const previous = metadata?.remoteCaptureExport; - if (previous === undefined) { - return { - completedAt: - typeof metadata?.remoteCaptureCompletedAt === 'number' - ? metadata.remoteCaptureCompletedAt - : Date.now(), - known: [], - }; +function checkpointRecordingExport( + files: readonly string[], + outputIds: string[], + progress: DurableCaptureProgress, +) { + const completedAt = Date.now(); + const identities: string[] = []; + const proof = { completedAt, identities, outputIds }; + const evidence = { remoteCaptureExport: proof }; + try { + for (const file of files) identities.push(readRecordingExportIdentity(file)); + progress.record(evidence); + } catch (error) { + if (error instanceof RecordingProofIoError) throw new RecordingProofIoError(evidence); + throw error; } + return proof; +} + +function readRecordingExportProgress(previous: unknown, outputIds: string[]) { const { completedAt, identities, outputIds: storedIds } = isRecord(previous) ? previous : {}; if ( typeof completedAt !== 'number' || !Number.isFinite(completedAt) || !Array.isArray(identities) || + !identities.every((identity): identity is string => typeof identity === 'string') || identities.length > outputIds.length || !Array.isArray(storedIds) || storedIds.length !== outputIds.length || @@ -179,17 +188,13 @@ function readRecordingExportIdentity(file: string): string { const identity = recordingExportFileIdentity(fs.lstatSync(file, { throwIfNoEntry: false })); if (identity !== null) return identity; } catch (error) { - throw new RecordingProofIoError(error); + throw recordingCheckpointError(error); } - throw new AppError('COMMAND_FAILED', 'Recording export is missing or is not a regular file.', { - retriable: true, - }); + throw new RecordingProofIoError(); } -class RecordingProofIoError extends AppError { - constructor(error: unknown) { - super('COMMAND_FAILED', 'Recording export could not be verified.', { retriable: true }, error); - } +function missingProducerProof(): AppError { + return new AppError('COMMAND_FAILED', 'Recording export is missing producer proof.'); } export async function finishPendingScreenRecordingProof( @@ -202,7 +207,6 @@ export async function finishPendingScreenRecordingProof( store: screenRecordingResourceStore, resourcePath, expected: expected.fence, - unreadableRecordError: unreadableRecordingProof, onCompleted: ({ envelope }) => envelope, run: async (lease) => { const { metadata } = lease.envelope; @@ -219,7 +223,7 @@ export async function finishPendingScreenRecordingProof( metadata.remoteCapturePath, completion, metadata.remoteCaptureReservation, - createStopProgress(lease), + metadata, ); return lease.transition('completed', { metadata: { 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 60ffd34271..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 @@ -14,6 +14,7 @@ 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'; @@ -141,9 +142,7 @@ export function readReplayableStoredCompletion( } export function unreadableRecordingProof(): AppError { - return new AppError('COMMAND_FAILED', 'Recording ownership proof could not be read.', { - retriable: true, - }); + return new RecordingProofIoError(); } export function readStoredCompletion( diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index d8ead0c215..3cfa38a303 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -60,7 +60,7 @@ export type DurableCaptureRecordDefinition = Readonly<{ completionMetadata( result: C, metadata: DurableResourceEnvelope['metadata'], - progress: DurableCaptureProgress, + progress?: DurableCaptureProgress, ): JsonObject | Promise; /** * The completion this kind stored in a record that is already committed, or nothing it can serve. @@ -74,7 +74,11 @@ 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): JsonObject | undefined; + pendingCompletionMetadata?( + result: C, + error: unknown, + completion: JsonObject | undefined, + ): JsonObject | undefined; nativeCleanupSettled?(metadata: JsonObject | undefined): boolean; completionFromMetadata?(metadata: JsonObject | undefined): C | undefined | Promise; failedFinishPolicy: DurableCaptureFailedFinishPolicy; diff --git a/packages/capture-kit/src/durable-capture/fence.ts b/packages/capture-kit/src/durable-capture/fence.ts index 68f023a946..9ac6ee1d3a 100644 --- a/packages/capture-kit/src/durable-capture/fence.ts +++ b/packages/capture-kit/src/durable-capture/fence.ts @@ -59,20 +59,13 @@ export async function withDurableCaptureResourceFence( store: DurableCaptureResourceStore; resourcePath: string; expected: ResourceOwnershipFence; - unreadableRecordError?: () => Error; /** Answers a run whose record this fence found committed, before any of the run's work. */ onCompleted(lease: DurableCaptureCompletedResourceFenceLease): Result | Promise; run(lease: DurableCaptureOpenResourceFenceLease): Promise; }>, ): Promise { return await serializeResource(params.resourcePath, async () => { - const read = () => - requireAdmissibleRecord( - params.store, - params.resourcePath, - params.expected, - params.unreadableRecordError, - ); + const read = () => requireAdmissibleRecord(params.store, params.resourcePath, params.expected); const admitted = read(); if (admitted.envelope.lifecycle === 'completed') { return await params.onCompleted({ envelope: admitted.envelope }); @@ -92,13 +85,18 @@ export async function withDurableCaptureResourceFence( 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; }, }); @@ -113,12 +111,16 @@ function requireAdmissibleRecord( store: DurableCaptureResourceStore, resourcePath: string, expected: ResourceOwnershipFence, - unreadableRecordError?: () => Error, ): 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' && unreadableRecordError) { - throw unreadableRecordError(); + if (record.status === 'unreattachable' && store.checkpointError) { + throw store.checkpointError(record.message); } throw fenceError( store, diff --git a/packages/capture-kit/src/durable-capture/finish-recovered.ts b/packages/capture-kit/src/durable-capture/finish-recovered.ts index 7fa396910b..6c85608367 100644 --- a/packages/capture-kit/src/durable-capture/finish-recovered.ts +++ b/packages/capture-kit/src/durable-capture/finish-recovered.ts @@ -85,7 +85,6 @@ export async function finishRecoveredDurableCapture< await transitionFinishOutcome(definition, lease, { status: 'completed', result, - alreadyCompleted: true, }); }, }); 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 6be74a2969..4f4db909ab 100644 --- a/packages/capture-kit/src/durable-capture/transitions.ts +++ b/packages/capture-kit/src/durable-capture/transitions.ts @@ -134,26 +134,30 @@ export async function finishDurableCaptureHandle< throw finishError; } if (finishOutcome.status === 'completed') { - await commitFinishedCapture(definition, lease, finishOutcome.result, async (proofError) => { - settleIfMissing(lease); - const settled = await respondToFailedFinish( - definition, - lease, - params, - proofError, - params.intent, - definition.pendingCompletionMetadata?.(finishOutcome.result, proofError), - ); - 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; - }); + 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; } transitionCleanupOutcome(lease, finishOutcome); @@ -174,6 +178,7 @@ async function respondToFailedFinish { if (intent === 'capture' && definition.failedFinishPolicy === 'preserve-retry-material') { + if (pendingCompletion) preserveCompletionCheckpoint(lease, pendingCompletion); emitFailedFinishPreservedDiagnostic(definition, params, finishError); return false; } @@ -386,7 +391,7 @@ export async function transitionFinishOutcome( outcome: FinishOutcome, ): Promise { if (outcome.status === 'completed') { - await commitFinishedCapture(definition, lease, outcome.result); + await commitFinishedCapture(definition, lease, { ...outcome, alreadyCompleted: true }); return; } transitionCleanupOutcome(lease, outcome); @@ -395,23 +400,39 @@ export async function transitionFinishOutcome( async function commitFinishedCapture( definition: DurableCaptureRecordDefinition, lease: DurableCaptureOpenResourceFenceLease, - result: C, - onProofFailure?: (error: unknown) => Promise, + 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, - createStopProgress(lease), + alreadyCompleted ? undefined : createStopProgress(lease), ); + lease.transition('completed', { + metadata: { ...lease.envelope.metadata, ...completion, phase: 'completed' }, + }); } catch (error) { - if (onProofFailure) await onProofFailure(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; } - lease.transition('completed', { - metadata: { ...(lease.envelope.metadata ?? {}), ...completion, phase: 'completed' }, - }); +} + +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/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/daemon/src/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts index ea909af220..b9229394ae 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts @@ -702,6 +702,11 @@ test('close persists verified files before retrying an unreadable sidecar', asyn 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, @@ -861,7 +866,7 @@ for (const first of ['archive', 'recording']) { } test.each([1, 2])( - 'a transient stat failure on read %d leaves the export retriable', + 'a transient stat failure on read %d permits retry only with producer proof', async (failureRead) => { const harness = makeRecordRuntimeHarness('recording-verification-retry-'); const runtime = createRuntimeStateHandle(); @@ -893,10 +898,14 @@ test.each([1, 2])( stat.mockRestore(); } const result = await run('stop'); - expect(result).toMatchObject({ - ok: true, - data: { recording: 'stopped', artifacts: [{ artifactId: expect.any(String) }] }, - }); + 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 { 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 c3d7a0396a..34974b50b7 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,4 +1,8 @@ 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'; @@ -771,47 +775,83 @@ test.each([false, true])( const TENANT = 'tenant-a'; -test('close preserves completion for an exact-owner retry when export inspection fails', async () => { - 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 inspect = vi.spyOn(fs, 'lstatSync').mockImplementation((file, options) => { - if (file === source) - throw Object.assign(new Error('verification unavailable'), { code: 'EIO' }); - return lstat(file, options); - }); - try { - await teardownSessionResources({ - appLog: 'already-settled', - ref: harness.sessionStore.lookup(harness.sessionName)!, - sessionStore: harness.sessionStore, - platformCleanup: platformResourceCleanupFixture(), +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', }); - } 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(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'); -}); + 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' ? [] : [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 until the advertised sidecar can be verified', async () => { +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 () => { @@ -846,13 +886,70 @@ test('explicit stop keeps its binding until the advertised sidecar can be verifi fs.writeFileSync(deriveRecordingTelemetryPath(video), '{}'); expect(await run('stop')).toMatchObject({ - ok: true, - data: { - artifacts: [{ artifactId: expect.any(String) }, { artifactId: expect.any(String) }], - }, + ok: false, + error: { message: 'Recording export is missing producer 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 }); +}); From ea004573090f94d678a534c6d39ad389d85c4f8b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 18:37:43 +0100 Subject: [PATCH 09/12] docs(recording): explain legacy downloads after daemon upgrades --- docs/adr/0024-screen-recording-provable-signal.md | 3 +++ website/docs/docs/remote-proxy.md | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/docs/adr/0024-screen-recording-provable-signal.md b/docs/adr/0024-screen-recording-provable-signal.md index 6615023bae..274f18caf6 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -301,6 +301,9 @@ A retry uses the artifact IDs derived from the persisted reservation and the ori 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. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index e1825eb360..d1f9ce5531 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -110,6 +110,10 @@ After a remote recording finishes, its video, chunks, and telemetry stay availab 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. From 75899e461c4574dec215bd57dece9f5a7ca9607d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 18:56:40 +0100 Subject: [PATCH 10/12] refactor(daemon): derive recording artifact IDs from their reservation --- .../screen-recording-session-resource.ts | 55 ++++++++----------- .../http-server-capture-publication.test.ts | 9 +++ ...tion.test.ts => recording-outputs.test.ts} | 3 +- .../record-runtime-stop-recovery.test.ts | 7 ++- .../handlers/record-runtime-response.ts | 8 --- .../sessions/leased-recording-retention.ts | 39 ------------- .../daemon/src/sessions/recording-outputs.ts | 43 ++++++++++++--- .../daemon/src/sessions/session-teardown.ts | 6 +- 8 files changed, 77 insertions(+), 93 deletions(-) rename packages/daemon/src/sessions/__tests__/{leased-recording-retention.test.ts => recording-outputs.test.ts} (99%) delete mode 100644 packages/daemon/src/sessions/leased-recording-retention.ts 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 e40771abfb..cc91f7c927 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 @@ -49,7 +49,6 @@ export const screenRecordingDurableResource = createDurableCaptureResource< remoteCaptureExport: await verifyRecordingExport( metadata.remoteCapturePath, result, - metadata.remoteCaptureReservation, metadata, progress, ), @@ -108,7 +107,6 @@ export function finishLiveScreenRecording(params: { async function verifyRecordingExport( reservedPath: string, completion: ScreenRecordingCompletion, - reservation: string, metadata: JsonObject, progress?: DurableCaptureProgress, ) { @@ -133,31 +131,32 @@ async function verifyRecordingExport( if (!matchesReservation) { throw new AppError('COMMAND_FAILED', 'Recording export does not match its reservation.'); } - const outputIds = files.map((_, index) => `${reservation}-${index + 1}`); const stored = metadata.remoteCaptureExport; if (stored !== undefined) { - const { completedAt, known } = readRecordingExportProgress(stored, outputIds); - if (known.some((identity, index) => readRecordingExportIdentity(files[index]!) !== identity)) { + 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 (known.length !== files.length) throw missingProducerProof(); - return { completedAt, identities: known, outputIds }; + if (identities.includes(null)) throw missingProducerProof(); + return { completedAt, identities }; } if (!progress) throw missingProducerProof(); - return checkpointRecordingExport(files, outputIds, progress); + return checkpointRecordingExport(files, progress); } -function checkpointRecordingExport( - files: readonly string[], - outputIds: string[], - progress: DurableCaptureProgress, -) { +function checkpointRecordingExport(files: readonly string[], progress: DurableCaptureProgress) { const completedAt = Date.now(); - const identities: string[] = []; - const proof = { completedAt, identities, outputIds }; + const identities: (string | null)[] = files.map(() => null); + const proof = { completedAt, identities }; const evidence = { remoteCaptureExport: proof }; try { - for (const file of files) identities.push(readRecordingExportIdentity(file)); + for (const [index, file] of files.entries()) + identities[index] = readRecordingExportIdentity(file); progress.record(evidence); } catch (error) { if (error instanceof RecordingProofIoError) throw new RecordingProofIoError(evidence); @@ -166,21 +165,20 @@ function checkpointRecordingExport( return proof; } -function readRecordingExportProgress(previous: unknown, outputIds: string[]) { - const { completedAt, identities, outputIds: storedIds } = isRecord(previous) ? previous : {}; +function readRecordingExportProgress(previous: unknown, fileCount: number) { + const { completedAt, identities } = isRecord(previous) ? previous : {}; if ( typeof completedAt !== 'number' || !Number.isFinite(completedAt) || !Array.isArray(identities) || - !identities.every((identity): identity is string => typeof identity === 'string') || - identities.length > outputIds.length || - !Array.isArray(storedIds) || - storedIds.length !== outputIds.length || - !outputIds.every((id, index) => id === storedIds[index]) + 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, known: identities }; + return { completedAt, identities }; } function readRecordingExportIdentity(file: string): string { @@ -216,15 +214,10 @@ export async function finishPendingScreenRecordingProof( !screenRecordingNativeCleanupSettled(metadata) || !completion || typeof metadata.remoteCapturePath !== 'string' || - typeof metadata.remoteCaptureReservation !== 'string' + metadata.remoteCaptureReservation !== expected.fence.token ) throw unreadableRecordingProof(); - const proof = await verifyRecordingExport( - metadata.remoteCapturePath, - completion, - metadata.remoteCaptureReservation, - metadata, - ); + const proof = await verifyRecordingExport(metadata.remoteCapturePath, completion, metadata); return lease.transition('completed', { metadata: { ...lease.envelope.metadata, 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 106fa35cb1..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 @@ -293,6 +293,14 @@ test('direct HTTP recording replay requires known remote output provenance', asy 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 || @@ -324,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/sessions/__tests__/leased-recording-retention.test.ts b/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts similarity index 99% rename from packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts rename to packages/daemon/src/sessions/__tests__/recording-outputs.test.ts index b9229394ae..1b3822436d 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts @@ -683,8 +683,7 @@ test('close persists verified files before retrying an unreadable sidecar', asyn phase: 'export-proof-pending', cleanupStatus: 'cleaned', remoteCaptureExport: { - identities: [expect.any(String)], - outputIds: [expect.any(String), expect.any(String)], + identities: [expect.any(String), null], }, }, }, 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 34974b50b7..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 @@ -828,7 +828,7 @@ test.each(['first inspection', 'checkpoint write'])( phase: 'export-proof-pending', completion: { outPath: source }, remoteCaptureExport: { - identities: fault === 'first inspection' ? [] : [expect.any(String)], + identities: fault === 'first inspection' ? [null] : [expect.any(String)], }, }, }, @@ -889,6 +889,11 @@ test('explicit stop keeps its binding but never serves an unproved sidecar', asy 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 { diff --git a/packages/daemon/src/sessions/handlers/record-runtime-response.ts b/packages/daemon/src/sessions/handlers/record-runtime-response.ts index f84936009f..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,13 +21,6 @@ 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, 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 66763da26c..0000000000 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ /dev/null @@ -1,39 +0,0 @@ -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 { - isLegacyRemoteRecordingOutput, - recordingOutputLeaseVerifier, -} from './handlers/record-runtime-response.ts'; -import { commitRecordingOutputs } from './recording-outputs.ts'; - -export async function retainLeasedSessionRecording( - ref: SessionRef, - completion: ScreenRecordingCompletion, - envelope: DurableResourceEnvelope<'screen-recording'>, -): Promise { - const { metadata } = envelope; - if ( - metadata?.remoteCaptureOutput !== true || - isLegacyRemoteRecordingOutput(completion) || - metadata.remoteCaptureLifetime !== ref.lifetime.journalId - ) - return; - try { - const hostGlobal = - recordingOutputLeaseVerifier(metadata) === null && metadata.remoteCaptureTenantId === null; - await commitRecordingOutputs(envelope, hostGlobal ? 'retain' : 'live'); - } catch (error) { - emitDiagnostic({ - level: 'warn', - phase: 'leased_session_recording_retention_failed', - data: { - session: ref.address, - error: errorMessage(error), - hasExportProof: metadata.remoteCaptureExport !== undefined, - }, - }); - } -} diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts index c69a5f5d70..10ac73827d 100644 --- a/packages/daemon/src/sessions/recording-outputs.ts +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -29,7 +29,6 @@ import { recordingRegistrySignal, } from '../resources/artifact-tracking.ts'; import { - isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, recordingStopArtifacts, } from './handlers/record-runtime-response.ts'; @@ -43,24 +42,22 @@ function readVerifiedRecording(envelope: RecordingEnvelope) { if ( envelope.lifecycle !== 'completed' || !completion || - isLegacyRemoteRecordingOutput(completion) || - completion.outPath !== metadata?.remoteCapturePath || - metadata.remoteCaptureArchive === true || + metadata?.remoteCaptureOutput !== true || + completion.outPath !== metadata.remoteCapturePath || + metadata.remoteCaptureReservation !== envelope.fence.token || !isRecord(verified) || !Array.isArray(verified.identities) || - !Array.isArray(verified.outputIds) || typeof verified.completedAt !== 'number' || !Number.isFinite(verified.completedAt) ) throw leasedOutputRefusal('Recording'); - const { identities, outputIds } = verified; + 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]; - const artifactId = outputIds[index]; - if (typeof sourceIdentity !== 'string' || artifactId !== `${envelope.fence.token}-${index + 1}`) - throw leasedOutputRefusal('Recording'); + if (typeof sourceIdentity !== 'string') throw leasedOutputRefusal('Recording'); + const artifactId = `${envelope.fence.token}-${index + 1}`; return { ...artifact, path: artifact.path!, sourceIdentity, artifactId }; }); return { @@ -71,6 +68,34 @@ function readVerifiedRecording(envelope: RecordingEnvelope) { }; } +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; diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 601b04c2b4..74a34d13c5 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -249,7 +249,7 @@ async function finishSessionScreenRecording(params: { await screenRecordingDurableResource.confirmLiveMissing({ binding, resource: recording }); return; } - const completion = await finishLiveScreenRecording({ + await finishLiveScreenRecording({ binding, intent: 'disposal', confirmedMissing, @@ -264,8 +264,8 @@ async function finishSessionScreenRecording(params: { record.envelope.fence.generation !== recording.envelope.fence.generation ) return; - const { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); - await retainLeasedSessionRecording(params.ref, completion, record.envelope); + const { retainSessionRecording } = await import('./recording-outputs.ts'); + await retainSessionRecording(params.ref, record.envelope); } async function finishSessionAudioProbe(params: { From a37fcbd6a2299dfe5d224bc9c23ea4201fa60223 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 19:13:53 +0100 Subject: [PATCH 11/12] fix(recording): checkpoint export proof before native completion --- .../screen-recording-session-resource.test.ts | 102 +++++++++++++++ .../screen-recording-resource-store.ts | 7 + .../screen-recording-session-resource.ts | 109 +--------------- .../capture-kit/src/recording/export-proof.ts | 121 ++++++++++++++++++ .../src/recording/stop-sequence.ts | 23 +++- 5 files changed, 253 insertions(+), 109 deletions(-) create mode 100644 packages/capture-kit/src/recording/export-proof.ts 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..db3ccbecdc 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,102 @@ test('a record stop that fails after collecting resumes through the fence withou expect(sessionStore.get(sessionName)?.screenRecording).toBeUndefined(); }); +test.each(['startup recovery', 'recovered stop', 'recovered stop with replacement'] as const)( + '%s uses the recording producer checkpoint after the native recorder finished', + async (route) => { + 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: 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 (route === 'recovered stop with replacement') { + 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); + } + expect(screenRecordingResourceStore.read(resourcePath)).toMatchObject({ + envelope: { + lifecycle: 'completed', + metadata: { + completion: { outPath }, + remoteCaptureExport: { + 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/screen-recording-resource-store.ts b/packages/capture-kit/src/capture-admission/screen-recording-resource-store.ts index eb0758d1a1..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,3 +1,4 @@ +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'; @@ -35,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 cc91f7c927..ee7b5ff43e 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 @@ -1,8 +1,4 @@ -import fs from 'node:fs'; -import { AppError } from '@agent-device/kernel/errors'; import type { JsonObject } from '@agent-device/contracts/client'; -import type { DurableCaptureProgress } from '@agent-device/contracts/durable-resource'; -import { isRecord } from '@agent-device/kernel/record'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import type { PlatformRequestScope } from '@agent-device/contracts/platform-runtime-host'; @@ -29,10 +25,11 @@ import type { ScreenRecordingAdmissionLedger } from './screen-recording-admissio import { SCREEN_RECORDING_COMPLETION_METADATA_KEY, RecordingProofIoError, - recordingCheckpointError, screenRecordingResourceStore, } from './screen-recording-resource-store.ts'; +export { recordingExportFileIdentity } from './screen-recording-resource-store.ts'; + export const screenRecordingDurableResource = createDurableCaptureResource< 'screen-recording', ScreenRecordingLiveHandle, @@ -46,7 +43,7 @@ export const screenRecordingDurableResource = createDurableCaptureResource< ...(typeof metadata?.remoteCapturePath === 'string' && typeof metadata.remoteCaptureReservation === 'string' ? { - remoteCaptureExport: await verifyRecordingExport( + remoteCaptureExport: (await import('../recording/export-proof.ts')).verifyRecordingExport( metadata.remoteCapturePath, result, metadata, @@ -104,97 +101,6 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } -async function verifyRecordingExport( - reservedPath: string, - completion: ScreenRecordingCompletion, - metadata: JsonObject, - progress?: DurableCaptureProgress, -) { - const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ - import('../recording/output-path.ts'), - import('../recording/telemetry.ts'), - ]); - 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.'); - } - 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)) throw missingProducerProof(); - return { completedAt, identities }; - } - if (!progress) throw missingProducerProof(); - return checkpointRecordingExport(files, progress); -} - -function checkpointRecordingExport(files: readonly string[], progress: DurableCaptureProgress) { - const completedAt = Date.now(); - const identities: (string | null)[] = files.map(() => null); - const proof = { completedAt, identities }; - const evidence = { remoteCaptureExport: proof }; - try { - for (const [index, file] of files.entries()) - identities[index] = readRecordingExportIdentity(file); - progress.record(evidence); - } catch (error) { - if (error instanceof RecordingProofIoError) throw new RecordingProofIoError(evidence); - throw error; - } - return proof; -} - -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.'); -} - export async function finishPendingScreenRecordingProof( resourcePath: string, expected: DurableResourceEnvelope<'screen-recording'>, @@ -217,7 +123,8 @@ export async function finishPendingScreenRecordingProof( metadata.remoteCaptureReservation !== expected.fence.token ) throw unreadableRecordingProof(); - const proof = await verifyRecordingExport(metadata.remoteCapturePath, completion, metadata); + const { verifyRecordingExport } = await import('../recording/export-proof.ts'); + const proof = verifyRecordingExport(metadata.remoteCapturePath, completion, metadata); return lease.transition('completed', { metadata: { ...lease.envelope.metadata, @@ -229,12 +136,6 @@ export async function finishPendingScreenRecordingProof( }); } -export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null { - return stat?.isFile() - ? `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}` - : null; -} - export function encodeScreenRecordingCompletionMetadata( completion: ScreenRecordingCompletion, ): JsonObject { 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/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; } From 39d7b51ad163035b0e2a407ad4790be12c826856 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 24 Nov 2026 19:34:13 +0100 Subject: [PATCH 12/12] fix(recording): settle recovered captures without export proof --- .../screen-recording-session-resource.test.ts | 33 +++++++++++++------ .../screen-recording-session-resource.ts | 3 +- 2 files changed, 25 insertions(+), 11 deletions(-) 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 db3ccbecdc..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 @@ -282,9 +282,15 @@ test('a record stop that fails after collecting resumes through the fence withou expect(sessionStore.get(sessionName)?.screenRecording).toBeUndefined(); }); -test.each(['startup recovery', 'recovered stop', 'recovered stop with replacement'] as const)( - '%s uses the recording producer checkpoint after the native recorder finished', - async (route) => { +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); @@ -321,7 +327,7 @@ test.each(['startup recovery', 'recovered stop', 'recovered stop with replacemen recordOnlySession: false, gestureEvents: [], }, - progress: createStopProgress(lease), + progress: proof === 'absent' ? undefined : createStopProgress(lease), steps: { stop: async () => ({ observation: { recorder: 'confirmed' } }), collect: async () => {}, @@ -345,7 +351,7 @@ test.each(['startup recovery', 'recovered stop', 'recovered stop with replacemen }); const stop = () => finishRecoveredScreenRecording({ resourcePath, scope, acquireControl }); - if (route === 'recovered stop with replacement') { + 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({ @@ -363,18 +369,25 @@ test.each(['startup recovery', 'recovered stop', 'recovered stop with replacemen } else { await expect(stop()).resolves.toEqual(nativeCompletion.result); } - expect(screenRecordingResourceStore.read(resourcePath)).toMatchObject({ + const settled = screenRecordingResourceStore.read(resourcePath); + expect(settled).toMatchObject({ envelope: { lifecycle: 'completed', metadata: { completion: { outPath }, - remoteCaptureExport: { - completedAt: expect.any(Number), - identities: [expect.any(String)], - }, }, }, }); + 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)], + }); + } }, ); 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 ee7b5ff43e..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 @@ -41,7 +41,8 @@ export const screenRecordingDurableResource = createDurableCaptureResource< completionMetadata: async (result, metadata, progress) => ({ ...encodeScreenRecordingCompletionMetadata(result), ...(typeof metadata?.remoteCapturePath === 'string' && - typeof metadata.remoteCaptureReservation === 'string' + typeof metadata.remoteCaptureReservation === 'string' && + (progress !== undefined || metadata.remoteCaptureExport !== undefined) ? { remoteCaptureExport: (await import('../recording/export-proof.ts')).verifyRecordingExport( metadata.remoteCapturePath,