From e7f4a8495518b6bc0081f4e8081ed3c9a35b83e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 10:55:50 +0100 Subject: [PATCH 1/5] fix(daemon): publish direct recordings with producer proof --- .../0024-screen-recording-provable-signal.md | 16 +- .../screen-recording-stop-recovery.test.ts | 12 +- .../screen-recording-session-resource.ts | 51 +++- .../screen-recording-stop-recovery.ts | 68 ++--- .../src/durable-capture/definition.ts | 6 +- .../src/durable-capture/recovery.ts | 2 +- .../src/durable-capture/transitions.ts | 12 +- .../capture-kit/src/recording/output-path.ts | 15 ++ .../src/recording/output-schemas.ts | 2 +- packages/contracts/src/recording.ts | 2 +- ...screen-recording-resource-recovery.test.ts | 162 +++++++----- packages/daemon/src/core/session-store.ts | 9 +- .../daemon/src/resources/artifact-tracking.ts | 84 ++++-- .../http-server-capture-publication.test.ts | 31 ++- .../http/http-server-capture-tenant.test.ts | 113 +++++++- .../http/http-server-remote-output.test.ts | 56 ++-- packages/daemon/src/server/request-router.ts | 10 +- ...tion.test.ts => recording-outputs.test.ts} | 119 ++++----- .../__tests__/record-runtime.fixtures.ts | 4 +- .../handlers/record-runtime-response.ts | 33 +-- .../src/sessions/handlers/record-runtime.ts | 244 ++++++++++-------- .../sessions/leased-recording-retention.ts | 77 ------ .../daemon/src/sessions/recording-outputs.ts | 98 +++++++ .../daemon/src/sessions/session-teardown.ts | 17 +- packages/host-kit/src/file.ts | 8 + .../src/recording/chunk-path.ts | 16 -- .../platform-android/src/recording/chunks.ts | 2 +- .../src/recording/finalize.ts | 2 +- .../src/recording/manifest-validation.ts | 2 +- website/docs/docs/remote-proxy.md | 5 + 30 files changed, 805 insertions(+), 473 deletions(-) rename packages/daemon/src/sessions/__tests__/{leased-recording-retention.test.ts => recording-outputs.test.ts} (82%) delete mode 100644 packages/daemon/src/sessions/leased-recording-retention.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..b6475b0807 100644 --- a/docs/adr/0024-screen-recording-provable-signal.md +++ b/docs/adr/0024-screen-recording-provable-signal.md @@ -287,12 +287,16 @@ 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). -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 remote recording reserves a daemon path and records its producing lifetime, tenant, and lease. +A live producer records the file identities in the same manifest write as the completed recording. +Startup recovery can settle a completed native recording without granting download access. +If teardown cannot record file identities, it completes the recording and leaves the files on the host. + +The daemon registers verified outputs when an authorized stop or teardown finishes. +Only a request with the producing lease ID can list or download leased output (ADR 0007). +The artifact registry owns expiry and download consumption. +A stop retry can return the IDs that the current daemon still holds. +A new daemon cannot restore remote download IDs from the manifest alone. ### 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 b94f1b9a6a..03c139d883 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,7 @@ +import fs from 'node:fs'; +import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { outputFileIdentity } from '@agent-device/host-kit/file'; 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'; @@ -18,6 +22,8 @@ import type { DurableCaptureRecoveryControl, DurableCaptureSessionBinding, } from '../durable-capture/index.ts'; +import { chunkPathAt } from '../recording/output-path.ts'; +import { deriveRecordingTelemetryPath } from '../recording/telemetry.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'; @@ -34,7 +40,7 @@ export const screenRecordingDurableResource = createDurableCaptureResource< resourceKind: 'screen-recording', displayName: 'screen recording', store: screenRecordingResourceStore, - completionMetadata: encodeScreenRecordingCompletionMetadata, + completionMetadata: recordingCompletionMetadata, // 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,49 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } +function recordingCompletionMetadata( + result: ScreenRecordingCompletion, + metadata: JsonObject | undefined, + producer?: DurableCaptureFinishIntent, +): JsonObject { + const completion = encodeScreenRecordingCompletionMetadata(result); + const reservedPath = metadata?.remoteCapturePath; + if (!producer || typeof reservedPath !== 'string') return completion; + try { + if ( + result.outPath !== reservedPath || + result.chunks?.some( + (chunk, offset) => + chunk.index !== offset + 1 || chunk.path !== chunkPathAt(reservedPath, chunk.index), + ) || + (result.telemetryPath !== undefined && + result.telemetryPath !== deriveRecordingTelemetryPath(reservedPath)) + ) + throw new Error('Recording export does not match its reservation.'); + const files = [ + reservedPath, + ...(result.chunks?.slice(1).map(({ path }) => path) ?? []), + ...(result.telemetryPath ? [result.telemetryPath] : []), + ]; + const identities = files.map((file) => { + const stat = fs.lstatSync(file); + if (!stat.isFile()) throw new Error('Recording export is not a regular file.'); + return outputFileIdentity(stat); + }); + return { ...completion, remoteCaptureExport: { completedAt: Date.now(), identities } }; + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'screen_recording_export_proof_failed', + data: { error: errorMessage(error) }, + }); + if (producer === 'disposal') return completion; + throw new AppError('COMMAND_FAILED', 'Recording export proof could not be recorded.', { + retriable: true, + }); + } +} + export function encodeScreenRecordingCompletionMetadata( completion: ScreenRecordingCompletion, ): JsonObject { diff --git a/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts b/packages/capture-kit/src/capture-admission/screen-recording-stop-recovery.ts index 4e0383fa74..c305eafb29 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,13 +53,27 @@ 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 !== 'decoded') return { kind: 'none' }; assertManifestBelongsToRequest(params, record.envelope); - if (record.envelope.lifecycle !== 'completed') return { kind: 'open', resourcePath }; - const completion = readReplayableStoredCompletion(record.envelope.metadata); + if (record.envelope.lifecycle !== 'completed') + return { kind: 'open', resourcePath, envelope: record.envelope }; + const { metadata } = record.envelope; + const completion = + metadata?.remoteCaptureOutput === true + ? readStoredCompletion(metadata) + : readReplayableStoredCompletion(metadata); if (completion === undefined) { emitDiagnostic({ level: 'warn', @@ -65,7 +82,7 @@ export function resolveScreenRecordingStopRecovery( }); return { kind: 'none' }; } - return { kind: 'completed', completion }; + return { kind: 'completed', completion, envelope: record.envelope }; } /** Whether the session's manifest recorded a terminal recording, even one with no serveable file. */ @@ -74,21 +91,6 @@ export function screenRecordingManifestIsTerminal(params: ScreenRecordingManifes return record.status === 'decoded' && record.envelope.lifecycle === 'completed'; } -/** - * The device a stop without a held session must be answered on: the one the session's durable - * manifest names, when a decodable manifest exists. `undefined` means there is nothing to recover - * from, and a caller that addressed a session answers on the session instead of choosing a device. - * The caller still resolves this identity against the host to recover the live device fields, and - * `assertManifestBelongsToRequest` still fails the request closed when the resolved device or the - * session address does not match what the manifest recorded. - */ -export function screenRecordingManifestDevice( - params: ScreenRecordingManifestParams, -): DeviceIdentity | undefined { - const { record } = readSessionManifest(params); - return record.status === 'decoded' ? record.envelope.device : undefined; -} - function readSessionManifest(params: ScreenRecordingManifestParams): Readonly<{ resourcePath: string; record: DurableCaptureResourceRecord<'screen-recording'>; @@ -132,6 +134,13 @@ function assertManifestBelongsToRequest( */ export function readReplayableStoredCompletion( metadata: JsonObject | undefined, +): ScreenRecordingCompletion | undefined { + const completion = readStoredCompletion(metadata); + return completion && fs.existsSync(completion.outPath) ? completion : undefined; +} + +export function readStoredCompletion( + metadata: JsonObject | undefined, ): ScreenRecordingCompletion | undefined { const stored = metadata?.[SCREEN_RECORDING_COMPLETION_METADATA_KEY]; if ( @@ -142,8 +151,7 @@ export function readReplayableStoredCompletion( ) { return undefined; } - const completion = stored as unknown as ScreenRecordingCompletion; - return fs.existsSync(completion.outPath) ? completion : undefined; + return stored as unknown as ScreenRecordingCompletion; } /** The values a stop response computes on rather than repeats. */ diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index f9adebf12a..f0dbed063f 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -56,7 +56,11 @@ export type DurableCaptureRecordDefinition = Readonly<{ resourceKind: K; displayName: string; store: DurableCaptureResourceStore; - completionMetadata(result: C): JsonObject; + completionMetadata( + result: C, + metadata: DurableResourceEnvelope['metadata'], + producer?: DurableCaptureFinishIntent, + ): JsonObject; /** * 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/recovery.ts b/packages/capture-kit/src/durable-capture/recovery.ts index 805f32ff84..0de50c2768 100644 --- a/packages/capture-kit/src/durable-capture/recovery.ts +++ b/packages/capture-kit/src/durable-capture/recovery.ts @@ -193,7 +193,7 @@ async function settleRecoveryAuthority { cleanupPending = true; @@ -75,6 +76,7 @@ export async function finishDurableCaptureHandle< fence: ResourceOwnershipFence; resourcePath: string; intent: DurableCaptureFinishIntent; + producer?: true; confirmedMissing?: () => boolean; onCleanupPending?(outcome: Extract): void; }, @@ -132,7 +134,12 @@ export async function finishDurableCaptureHandle< throw finishError; } if (finishOutcome.status === 'completed') { - transitionFinishOutcome(definition, lease, finishOutcome); + transitionFinishOutcome( + definition, + lease, + finishOutcome, + params.producer ? params.intent : undefined, + ); return finishOutcome.result; } transitionFinishOutcome(definition, lease, finishOutcome); @@ -350,12 +357,13 @@ export function transitionFinishOutcome( definition: DurableCaptureRecordDefinition, lease: DurableCaptureOpenResourceFenceLease, outcome: FinishOutcome, + producer?: DurableCaptureFinishIntent, ): void { if (outcome.status === 'completed') { lease.transition('completed', { metadata: { ...(lease.envelope.metadata ?? {}), - ...definition.completionMetadata(outcome.result), + ...definition.completionMetadata(outcome.result, lease.envelope.metadata, producer), 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/recording/output-schemas.ts b/packages/command-surface/src/recording/output-schemas.ts index bd8ad1f247..3fe51ab4e5 100644 --- a/packages/command-surface/src/recording/output-schemas.ts +++ b/packages/command-surface/src/recording/output-schemas.ts @@ -46,7 +46,7 @@ export const RECORDING_COMMAND_OUTPUT_SCHEMAS = { activeSessionApp: looseObjectSchema(), showTouches: booleanSchema(), }, - ['recording', 'outPath', 'sessionStateDir', 'showTouches'], + ['recording', 'outPath', 'showTouches'], ), objectSchema( { diff --git a/packages/contracts/src/recording.ts b/packages/contracts/src/recording.ts index 2b54f9851d..d07998d9b2 100644 --- a/packages/contracts/src/recording.ts +++ b/packages/contracts/src/recording.ts @@ -11,7 +11,7 @@ export type RecordingAppIdentity = { export type RecordingStartCommandResult = { recording: 'started'; outPath: string; - sessionStateDir: string; + sessionStateDir?: string; recordingBackend?: string; recordingScope?: RecordingScope; recordOnlySession?: boolean; diff --git a/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts b/packages/daemon/src/core/__tests__/screen-recording-resource-recovery.test.ts index 6b64c2c288..23b9269808 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 @@ -1,3 +1,4 @@ +import fs from 'node:fs'; import path from 'node:path'; import { expect, test, vi } from 'vitest'; import { applicationLifecycleOperationFacts } from '@agent-device/contracts/application-lifecycle-runtime'; @@ -26,79 +27,102 @@ const scope = { progress: { report: () => {} }, }; -test('recovery cleans a recording through its exact runtime owner', async () => { - const sessionsDir = mkdtempForTestSync('screen-recording-recovery-'); - const session = { name: 'session', device }; - const resource = makeTestScreenRecordingResource(session); - const resourcePath = screenRecordingResourceStore.resolvePath( - path.join(sessionsDir, session.name), - ); - screenRecordingResourceStore.write(resourcePath, resource.envelope); - const bind = vi.fn(async ({ device: boundDevice }) => ({ - device: boundDevice, - owner: localRuntimeOwner('android'), - facts: { - device: { - family: 'android' as const, - kind: boundDevice.kind, - providerMode: 'local' as const, +test.each(['active', 'completed'] as const)( + 'recovery settles a native recording that reattaches as %s through its exact owner', + async (reattached) => { + const sessionsDir = mkdtempForTestSync('screen-recording-recovery-'); + const session = { name: 'session', device }; + const outPath = path.join(sessionsDir, 'recording.mp4'); + const resource = makeTestScreenRecordingResource(session, { outPath }); + const resourcePath = screenRecordingResourceStore.resolvePath( + path.join(sessionsDir, session.name), + ); + fs.writeFileSync(outPath, 'recovered file without producer proof'); + screenRecordingResourceStore.write(resourcePath, { + ...resource.envelope, + metadata: { + ...resource.envelope.metadata, + remoteCaptureOutput: true, + remoteCapturePath: outPath, + remoteCaptureReservation: resource.envelope.fence.token, + }, + }); + const bind = vi.fn(async ({ device: boundDevice }) => ({ + device: boundDevice, + owner: localRuntimeOwner('android'), + facts: { + device: { + family: 'android' as const, + kind: boundDevice.kind, + providerMode: 'local' as const, + }, + operations: { + appLogInspect: unavailable, + appLogDoctor: unavailable, + appLogStart: unavailable, + appLogReattach: unavailable, + appLogCleanup: unavailable, + appState: unavailable, + networkDump: unavailable, + screenRecordingStart: unavailable, + screenRecordingReattach: { available: true as const }, + screenRecordingCleanup: { available: true as const }, + ensureReady: unavailable, + bootTarget: unavailable, + bootTargetHeadless: unavailable, + listApps: unavailable, + ...unavailableDeploymentSnapshotAndShutdownOperationFacts, + ...applicationLifecycleOperationFacts({ + resolveOpenTarget: unavailable, + prepareApplicationOpen: unavailable, + openApplication: unavailable, + applyRuntimeHints: unavailable, + clearRuntimeHints: unavailable, + closeApplication: unavailable, + finalizeApplicationClose: unavailable, + prepareAppleRunner: unavailable, + configureProviderPortReverse: unavailable, + }), + }, }, operations: { - appLogInspect: unavailable, - appLogDoctor: unavailable, - appLogStart: unavailable, - appLogReattach: unavailable, - appLogCleanup: unavailable, - appState: unavailable, - networkDump: unavailable, - screenRecordingStart: unavailable, - screenRecordingReattach: { available: true as const }, - screenRecordingCleanup: { available: true as const }, - ensureReady: unavailable, - bootTarget: unavailable, - bootTargetHeadless: unavailable, - listApps: unavailable, - ...unavailableDeploymentSnapshotAndShutdownOperationFacts, - ...applicationLifecycleOperationFacts({ - resolveOpenTarget: unavailable, - prepareApplicationOpen: unavailable, - openApplication: unavailable, - applyRuntimeHints: unavailable, - clearRuntimeHints: unavailable, - closeApplication: unavailable, - finalizeApplicationClose: unavailable, - prepareAppleRunner: unavailable, - configureProviderPortReverse: unavailable, - }), + screenRecordingReattach: async () => { + if (reattached === 'active') + return { status: 'active' as const, handle: resource.handle }; + const completion = await resource.handle.finish(); + if (completion.status !== 'completed') throw new Error('Expected completed fixture'); + return completion; + }, + screenRecordingCleanup: async () => ({ status: 'cleaned' as const }), + }, + [Symbol.asyncDispose]: async () => {}, + })); + const gateway: DeviceRuntimeGateway = { + inspectFacts: async () => { + throw new Error('unused'); }, - }, - operations: { - screenRecordingReattach: async () => ({ status: 'active' as const, handle: resource.handle }), - screenRecordingCleanup: async () => ({ status: 'cleaned' as const }), - }, - [Symbol.asyncDispose]: async () => {}, - })); - const gateway: DeviceRuntimeGateway = { - inspectFacts: async () => { - throw new Error('unused'); - }, - bind, - shutdown: async () => {}, - }; + bind, + shutdown: async () => {}, + }; - await expect( - recoverScreenRecordingResourceAfterDaemonLock({ - sessionsDir, - resourcePath, - gateway, - scope, - }), - ).resolves.toBe('recovered'); - expect(screenRecordingResourceStore.read(resourcePath)).toMatchObject({ - status: 'decoded', - envelope: { lifecycle: 'completed' }, - }); -}); + await expect( + recoverScreenRecordingResourceAfterDaemonLock({ + sessionsDir, + resourcePath, + gateway, + scope, + }), + ).resolves.toBe('recovered'); + const settled = screenRecordingResourceStore.read(resourcePath); + expect(settled).toMatchObject({ status: 'decoded', envelope: { lifecycle: 'completed' } }); + if (settled.status !== 'decoded') throw new Error('Expected terminal manifest'); + expect(settled.envelope.metadata).not.toHaveProperty('remoteCaptureExport'); + if (reattached === 'completed') { + expect(settled.envelope.metadata?.completion).toMatchObject({ outPath }); + expect(fs.readFileSync(outPath, 'utf8')).toBe('recovered file without producer proof'); + } + }, +); const unavailable = Object.freeze({ available: false as const, 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..cc822dc38d 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -1,3 +1,4 @@ +import { outputFileIdentity } from '@agent-device/host-kit/file'; import { runtimeSlot } from '@agent-device/host-kit/runtime-slots'; import crypto from 'node:crypto'; import fs from 'node:fs'; @@ -177,7 +178,7 @@ type ArtifactEntry = { artifactPath: string; tenantId?: string; leaseVerifier?: string; - reservation?: Readonly<{ directory: string; lifetimeId: string }>; + reservation?: Readonly<{ directory?: string; lifetimeId: string }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ output: string | undefined; artifactType: DaemonArtifactType | undefined; @@ -306,7 +307,7 @@ export function reserveFileOutput( fileName: delivery.fileName, displayRotation, }, - outputIdentity(stat), + outputFileIdentity(stat), { remainingEntries: 1, deleteAfterDownload: true }, { directory, lifetimeId }, ); @@ -323,6 +324,50 @@ export function reserveFileOutput( }; } +type RecordingFile = DaemonArtifact & { path: string; artifactId: string; sourceIdentity: string }; + +/** Registers the producer's identities. A replay can only reference entries this daemon retains. */ +export function commitRecordingFileOutputs( + files: readonly RecordingFile[], + producer: FileOutputProducer, + sessionName: string, + completedAt: number, + publish: boolean, +): DaemonArtifact[] { + const artifacts = pendingArtifacts(); + for (const { artifactId } of files) { + const entry = artifacts.get(artifactId); + if ( + completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now() || + entry?.cleanupRequested || + (!publish && !entry) + ) { + throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); + } + } + return 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 }, + completedAt, + ); + } + return { ...delivery, artifactId }; + }); +} + /** What a request presents to list or download artifacts. */ export type DownloadableArtifactReader = { tenantId?: string; leaseId?: string }; @@ -368,12 +413,15 @@ function addArtifactEntry( output: string | undefined, sourceCleanup: ArtifactSourceCleanup, reservation?: ArtifactEntry['reservation'], + createdAt = Date.now(), ): void { - const createdAt = Date.now(); - const timer = setTimeout(() => { - const entry = artifacts.get(artifactId); - if (entry) requestArtifactCleanup(artifacts, artifactId, entry); - }, ARTIFACT_CLEANUP_TIMEOUT_MS); + const timer = setTimeout( + () => { + const entry = artifacts.get(artifactId); + if (entry) requestArtifactCleanup(artifacts, artifactId, entry); + }, + Math.max(0, createdAt + ARTIFACT_CLEANUP_TIMEOUT_MS - Date.now()), + ); timer.unref(); artifacts.set(artifactId, { artifactPath: params.artifactPath, @@ -388,7 +436,7 @@ function addArtifactEntry( sourceCleanup, activeDownloads: new Set(), cleanupRequested: false, - awaitingDelivery: reservation !== undefined, + awaitingDelivery: reservation?.directory !== undefined, createdAt, timer, }); @@ -424,15 +472,9 @@ function findArtifactSourceCleanup( return undefined; } -/** 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 { - const inode = `${stat.dev}:${stat.ino}`; - return stat.isDirectory() ? inode : `${inode}:${stat.size}:${stat.mtimeMs}`; -} - function readOutputIdentity(artifactPath: string, noFollow = false): string | undefined { try { - return outputIdentity(noFollow ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath)); + return outputFileIdentity(noFollow ? fs.lstatSync(artifactPath) : fs.statSync(artifactPath)); } catch { return undefined; } @@ -443,7 +485,7 @@ export function retainPerfReportSource(source: string, leaseVerifier: string | n const canonical = fs.realpathSync(source); const stat = fs.statSync(canonical); artifactTracking().retainedPerformanceSources.set(canonical, { - output: outputIdentity(stat), + output: outputFileIdentity(stat), birthtimeMs: stat.birthtimeMs, leaseVerifier, }); @@ -455,7 +497,7 @@ export function assertTrackedPerformanceSourceLease( source: fs.Stats, caller: string | null, ): void { - const identity = outputIdentity(source); + const identity = outputFileIdentity(source); const state = artifactTracking(); for (const [retainedPath, entry] of state.retainedPerformanceSources) { if ( @@ -542,7 +584,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() || outputFileIdentity(stat) !== entry.output) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -597,7 +639,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 (outputFileIdentity(stat) === entry.output) return stat; } catch { // A missing output is cleaned up like a replaced one. } @@ -646,7 +688,7 @@ function readDownloadableArtifactEntry( cleanupDownloadableArtifact(artifactId); throw new AppError('COMMAND_FAILED', `Artifact file is missing: ${entry.artifactPath}`); } - if (outputIdentity(stat) !== entry.output) { + if (outputFileIdentity(stat) !== entry.output) { cleanupDownloadableArtifact(artifactId); throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -838,7 +880,7 @@ function requestArtifactCleanup( ) { removeBestEffort(entry.artifactPath); } - if (entry.reservation) { + if (entry.reservation?.directory) { try { fs.rmdirSync(entry.reservation.directory); } catch { diff --git a/packages/daemon/src/server/http/http-server-capture-publication.test.ts b/packages/daemon/src/server/http/http-server-capture-publication.test.ts index 022233f64c..2fd6285f86 100644 --- a/packages/daemon/src/server/http/http-server-capture-publication.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-publication.test.ts @@ -18,8 +18,10 @@ import { screenshotRuntimeFixture } from '../../__tests__/support/screenshot-run import { screenshotCommandSurface } from '../../__tests__/support/screenshot-command-surface-fake.ts'; import { sessionLeaseOf } from '../../core/lease-context.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; -import { trackDownloadableArtifact } from '../../resources/artifact-tracking.ts'; -import { finalizeDaemonResponse } from '../request-finalization.ts'; +import { + settleCommittedFileOutputs, + trackDownloadableArtifact, +} from '../../resources/artifact-tracking.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; import { successfulData, withHttp } from './http-output.fixtures.ts'; @@ -276,17 +278,29 @@ test('direct HTTP recording replay requires known remote output provenance', asy const { remoteCaptureLease: _owner, ...metadata } = record.envelope.metadata ?? {}; screenRecordingResourceStore.write(resourcePath, { ...record.envelope, metadata }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + async (request) => { + const response = await harness.run( + request.positionals, + request.meta, + request.flags, + request.internal, + ); + if (response.ok) settleCommittedFileOutputs(response.data?.artifacts, true); + return response; + }, async (post, base) => { const replay = async () => await post({ command: 'record', positionals: ['stop'] }, false); expect((await replay()).error?.data?.details).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH', }); + const { remoteCaptureReservation: _reservation, ...unreserved } = metadata; + screenRecordingResourceStore.write(resourcePath, { + ...record.envelope, + metadata: { ...unreserved, remoteCaptureLease: 'unleased' }, + }); + expect((await replay()).error?.data?.details).toMatchObject({ + reason: 'LEASE_OUTPUT_MISMATCH', + }); const savedCompletion = metadata.completion; if ( !savedCompletion || @@ -318,6 +332,7 @@ test('direct HTTP recording replay requires known remote output provenance', asy const data = successfulData(await replay()); expect(data.artifacts?.[0]?.localPath).toBe(clientPath); const id = data.artifacts?.[0]?.artifactId; + expect(id).toBe(`${record.envelope.fence.token}-1`); const download = await fetch(`${base}/artifacts/${id}`, { headers: { authorization: 'Bearer test-token' }, }); diff --git a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts index 89642bd698..fffb4bc835 100644 --- a/packages/daemon/src/server/http/http-server-capture-tenant.test.ts +++ b/packages/daemon/src/server/http/http-server-capture-tenant.test.ts @@ -10,6 +10,8 @@ import { } from '@agent-device/test-kit'; import { createTestDeviceInventoryGateways } from '@agent-device/device-selection/inventory-gateways-fixtures'; import { DAEMON_HTTP_LEASE_HEADER } from '@agent-device/contracts/daemon-http'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { markRequestCanceled } from '@agent-device/host-kit/request'; import { defineUse } from '@agent-device/contracts/platform-runtime-operations'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { createDaemonHttpServer } from './http-server.ts'; @@ -20,12 +22,16 @@ import { tenantScopedSessionName } from '../../core/session-tenant-scope.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { listDownloadableArtifacts, - trackDownloadableArtifact, + cleanupDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; -test.each([false, true])( - 'local stop keeps the producing tenant for a remote recording (client destination: %s)', - async (clientDestination) => { +test.each([ + { clientDestination: false, cancelStop: false }, + { clientDestination: true, cancelStop: false }, + { clientDestination: true, cancelStop: true }, +])( + 'local stop keeps the producing tenant for a remote recording ($clientDestination, stop canceled: $cancelStop)', + async ({ clientDestination, cancelStop }) => { const root = mkdtempForTestSync('capture-producing-tenant-'); const tenantId = 'tenant-a'; const sessionName = tenantScopedSessionName(tenantId, 'capture'); @@ -42,6 +48,32 @@ test.each([false, true])( fs.writeFileSync(input.outputPath, 'private-recording'); return await start(input); }); + const finish = harness.runtime.finish.getMockImplementation()!; + const canceledStopId = 'recording-response-canceled'; + let cancelNextFinish = cancelStop; + harness.runtime.finish.mockImplementation(async () => { + const stopped = await finish(); + if (cancelNextFinish) { + cancelNextFinish = false; + markRequestCanceled(canceledStopId); + } + const { result } = stopped; + const chunk = result.outPath.replace(/\.mp4$/, '.part-002.mp4'); + const telemetryPath = deriveRecordingTelemetryPath(result.outPath); + fs.writeFileSync(chunk, 'second-chunk'); + fs.writeFileSync(telemetryPath, '{"events":[]}'); + return { + ...stopped, + result: { + ...result, + telemetryPath, + chunks: [ + { index: 1, path: result.outPath }, + { index: 2, path: chunk }, + ], + }, + }; + }); const recordingUse = defineUse({ required: ['screenRecordingStart', 'screenRecordingReattach', 'screenRecordingCleanup'], }); @@ -69,7 +101,9 @@ test.each([false, true])( bind: async ({ device }) => await recordingBinding(device), shutdown: async () => {}, }, - trackDownloadableArtifact, + trackDownloadableArtifact: () => { + throw new Error('Recording must be committed before request finalization'); + }, }); const hookPath = path.join(root, 'auth-hook.mjs'); fs.writeFileSync( @@ -108,19 +142,42 @@ test.each([false, true])( const startBody = await started.json(); expect(startBody.result?.ok, JSON.stringify(startBody)).toBe(true); - const stop = async () => + const stop = async (requestId?: string) => await handleRequest({ token: 'capture-token', session: sessionName, command: 'record', positionals: ['stop'], - meta: { leaseId: lease.leaseId }, + meta: { leaseId: lease.leaseId, requestId }, + }); + if (cancelStop) { + expect(await stop(canceledStopId)).toMatchObject({ + ok: false, + error: { details: { reason: 'request_canceled' } }, }); + const owner = { tenantId, leaseId: lease.leaseId }; + const retained = await listDownloadableArtifacts(owner, {}); + expect(retained.map((entry) => entry.artifactType)).toEqual([ + 'screen-recording', + 'screen-recording-chunk', + 'screen-recording-telemetry', + ]); + expect(await listDownloadableArtifacts({ tenantId }, {})).toEqual([]); + expect(await listDownloadableArtifacts({ tenantId, leaseId: 'f'.repeat(32) }, {})).toEqual( + [], + ); + expect(await listDownloadableArtifacts({ ...owner, tenantId: 'tenant-b' }, {})).toEqual([]); + } const stopped = await stop(); expect(stopped.ok, JSON.stringify(stopped)).toBe(true); if (!stopped.ok) return; const artifactId = stopped.data?.artifacts?.[0]?.artifactId; expect(artifactId).toBeTypeOf('string'); + expect(stopped.data?.artifacts?.map(({ field, path }) => [field, path])).toEqual([ + ['outPath', undefined], + ['chunkPath', undefined], + ['telemetryPath', undefined], + ]); expect(await listDownloadableArtifacts({ tenantId: 'tenant-b' }, {})).toEqual([]); expect( (await listDownloadableArtifacts({ tenantId, leaseId: lease.leaseId }, {})).some( @@ -137,6 +194,16 @@ test.each([false, true])( headers: { authorization: 'Bearer capture-token', 'x-tenant': 'tenant-b' }, }); expect(otherTenant.status).toBe(401); + for (const leaseId of [undefined, 'f'.repeat(32)]) { + const denied = await fetch(`${base}/artifacts/${artifactId}`, { + headers: { + authorization: 'Bearer capture-token', + ...(leaseId ? { [DAEMON_HTTP_LEASE_HEADER]: leaseId } : {}), + }, + }); + expect(denied.status).toBe(401); + expect(await denied.json()).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH' }); + } const ownTenant = await fetch(`${base}/artifacts/${artifactId}`, { headers: { authorization: 'Bearer capture-token', @@ -146,6 +213,38 @@ test.each([false, true])( }); expect(ownTenant.status).toBe(200); expect(await ownTenant.text()).toBe('private-recording'); + const sourcePath = harness.runtime.start.mock.calls[0]![0].outputPath; + // A consumed export cannot be re-minted from a replacement written at that path. + await expect.poll(() => fs.existsSync(sourcePath)).toBe(false); + expect(await stop()).toMatchObject({ + ok: false, + error: { code: 'COMMAND_FAILED', details: { reason: 'RESOURCE_EXPIRED' } }, + }); + fs.writeFileSync(sourcePath, 'unrelated-replacement'); + expect(await stop()).toMatchObject({ ok: false }); + expect(fs.readFileSync(sourcePath, 'utf8')).toBe('unrelated-replacement'); + for (const [index, bytes] of [ + [1, 'second-chunk'], + [2, '{"events":[]}'], + ] as const) { + const sidecar = await fetch( + `${base}/artifacts/${stopped.data?.artifacts?.[index]?.artifactId}`, + { + headers: { + authorization: 'Bearer capture-token', + [DAEMON_HTTP_LEASE_HEADER]: lease.leaseId, + }, + }, + ); + expect(sidecar.status).toBe(200); + expect(await sidecar.text()).toBe(bytes); + } + for (const { id } of await listDownloadableArtifacts( + { tenantId, leaseId: lease.leaseId }, + {}, + )) { + cleanupDownloadableArtifact(id); + } } finally { await closeLoopbackServer(server); } diff --git a/packages/daemon/src/server/http/http-server-remote-output.test.ts b/packages/daemon/src/server/http/http-server-remote-output.test.ts index f4d219b406..93eaa2d650 100644 --- a/packages/daemon/src/server/http/http-server-remote-output.test.ts +++ b/packages/daemon/src/server/http/http-server-remote-output.test.ts @@ -32,10 +32,10 @@ import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { cleanupDownloadableArtifact, listDownloadableArtifacts, + settleCommittedFileOutputs, trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { localEnv, successfulData, withHttp } from './http-output.fixtures.ts'; -import { finalizeDaemonResponse } from '../request-finalization.ts'; import { runBatchCommands } from '../../sessions/handlers/session-batch.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; @@ -258,6 +258,20 @@ test('local HTTP still honors capture destinations and cwd', async () => { ); }); +async function handleRecordingRequest( + harness: ReturnType, + request: DaemonRequest, +) { + const response = await harness.run( + request.positionals, + request.meta, + request.flags, + request.internal, + ); + if (response.ok) settleCommittedFileOutputs(response.data?.artifacts, true); + return response; +} + test('remote recording without client metadata stays in its session and downloads by ID', async () => { const harness = makeRecordRuntimeHarness('remote-record-output-'); const root = mkdtempForTestSync('remote-record-victim-'); @@ -269,12 +283,7 @@ test('remote recording without client metadata stays in its session and download return await start(input); }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + (request) => handleRecordingRequest(harness, request), async (post, base) => { const started = await post({ command: 'record', @@ -282,14 +291,16 @@ test('remote recording without client metadata stays in its session and download meta: { cwd: root }, }); expect(started.result?.ok).toBe(true); - const output = started.result?.data?.outPath as string; - expect(path.dirname(output)).toBe( + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(path.dirname(source)).toBe( harness.sessionStore.resolveSessionDir(harness.sessionName), ); - expect(output).toMatch(/recording-[0-9a-f-]+\.mp4$/); + expect(started.result?.data?.outPath).toBe(path.basename(source)); + expect(started.result?.data?.sessionStateDir).toBeUndefined(); expect(fs.readFileSync(victim, 'utf8')).toBe('protected-content'); const stopped = await post({ command: 'record', positionals: ['stop'] }); expect(stopped.result?.ok).toBe(true); + expect(stopped.result?.data?.outPath).toBe(path.basename(source)); const artifact = stopped.result?.data?.artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { @@ -313,12 +324,7 @@ test.each(['local', 'local-client-destination', 'remote'] as const)( return await start(input); }); await withHttp( - async (request) => - finalizeDaemonResponse( - request, - await harness.run(request.positionals, request.meta, request.flags, request.internal), - trackDownloadableArtifact, - ), + (request) => handleRecordingRequest(harness, request), async (post) => { const started = await post( { @@ -331,10 +337,11 @@ test.each(['local', 'local-client-destination', 'remote'] as const)( origin === 'remote', ); expect(started.result?.ok, JSON.stringify(started)).toBe(true); - const stopped = await post( - { command: 'record', positionals: ['stop'] }, - origin !== 'remote', - ); + if (origin !== 'remote') { + const refused = await post({ command: 'record', positionals: ['stop'] }, true); + expect(refused.error?.data?.details).toMatchObject({ reason: 'LEASE_OUTPUT_MISMATCH' }); + } + const stopped = await post({ command: 'record', positionals: ['stop'] }, false); expect(stopped.result?.ok, JSON.stringify(stopped)).toBe(true); const artifactId = stopped.result?.data?.artifacts?.[0]?.artifactId; if (origin === 'remote') { @@ -687,12 +694,11 @@ test('batch recording keeps remote origin and generates a session-owned destinat async (request) => await harness.run(request.positionals, request.meta, request.flags, request.internal), ); - expect(response.ok).toBe(true); - if (!response.ok) return; + if (!response.ok) throw new Error(response.error.message); const results = response.data?.results as Array<{ data: { outPath: string } }>; - expect(path.dirname(results[0]!.data.outPath)).toBe( - harness.sessionStore.resolveSessionDir(harness.sessionName), - ); + const source = harness.runtime.start.mock.calls[0]![0].outputPath; + expect(path.dirname(source)).toBe(harness.sessionStore.resolveSessionDir(harness.sessionName)); + expect(results[0]!.data.outPath).toBe(path.basename(source)); await harness.run(['stop']); }); diff --git a/packages/daemon/src/server/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__/recording-outputs.test.ts similarity index 82% rename from packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts rename to packages/daemon/src/sessions/__tests__/recording-outputs.test.ts index f7487e568d..6f460c6f24 100644 --- a/packages/daemon/src/sessions/__tests__/leased-recording-retention.test.ts +++ b/packages/daemon/src/sessions/__tests__/recording-outputs.test.ts @@ -1,4 +1,5 @@ import fs from 'node:fs'; +import { randomUUID } from 'node:crypto'; import http from 'node:http'; import path from 'node:path'; import { afterEach, expect, test, vi } from 'vitest'; @@ -28,30 +29,12 @@ import { cleanupDownloadableArtifact, leaseVerifier, listDownloadableArtifacts, - trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; -import { withCaptureOutputOwnership } from '../../core/capture-output-ownership.ts'; import { tryHandleDownloadableArtifactHttpRoute } from '../../server/downloadable-artifact-http.ts'; -import { finalizeDaemonResponse } from '../../server/request-finalization.ts'; -import { buildRecordingStopResponse } from '../handlers/record-runtime-response.ts'; +import { 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 +46,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 +80,8 @@ function publishRecordingSession( finishFails?: boolean; unleasedProducer?: boolean; producerTenant?: string; + omitTelemetry?: boolean; + legacy?: 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); @@ -144,20 +127,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), }, @@ -167,7 +165,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) { @@ -201,6 +199,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 +269,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,34 +293,22 @@ 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, false); - 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' }), ]); - // The replay registers under the lease of the manifest, so it opens no second way to the files. expect(await listDownloadableArtifacts({ tenantId: TENANT }, process.env)).toEqual([]); + cleanupDownloadableArtifact(retained[0]!.id); + expect(() => commitRecordingOutputs(record.envelope, false)).toThrow( + expect.objectContaining({ details: expect.objectContaining({ reason: 'RESOURCE_EXPIRED' }) }), + ); }); test.each([undefined, '/client/local-copy.mp4'])( @@ -412,25 +400,26 @@ 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'); }, ); 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..fccc286d12 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime-response.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime-response.ts @@ -8,7 +8,6 @@ import type { } from '@agent-device/contracts/screen-recording-runtime'; import type { RuntimeOperationUnavailability } from '@agent-device/contracts/platform-runtime'; import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; -import { isRemoteTempArtifactPath } from '@agent-device/contracts/daemon-http'; export const UNLEASED_CAPTURE = 'unleased'; @@ -22,24 +21,19 @@ export function recordingOutputLeaseVerifier( return undefined; } -export function isLegacyRemoteRecordingOutput(completion: ScreenRecordingCompletion): boolean { - return ( - completion.clientOutPath !== undefined && - isRemoteTempArtifactPath(completion.outPath, 'recording', path.extname(completion.outPath)) - ); -} - export function buildRecordingStartResponse( snapshot: ScreenRecordingLiveSnapshot, sessionStateDir: string, requestedOutPath: string, + remote = false, ): DaemonResponse { return { ok: true, data: { recording: 'started', - outPath: snapshot.clientOutPath ?? requestedOutPath, - sessionStateDir, + outPath: + snapshot.clientOutPath ?? (remote ? path.basename(requestedOutPath) : requestedOutPath), + ...(!remote ? { sessionStateDir } : {}), recordingBackend: snapshot.backend, recordingScope: snapshot.scope, recordOnlySession: snapshot.recordOnlySession, @@ -73,14 +67,23 @@ export function buildRecordingUnsupportedResponse( }; } -export function buildRecordingStopResponse(completion: ScreenRecordingCompletion): DaemonResponse { +export function buildRecordingStopResponse( + completion: ScreenRecordingCompletion, + artifacts = recordingStopArtifacts(completion), + remote = false, +): DaemonResponse { return { ok: true, data: { recording: 'stopped', - outPath: completion.outPath, - telemetryPath: completion.telemetryPath, - artifacts: recordingStopArtifacts(completion), + outPath: remote + ? (artifacts[0]?.localPath ?? path.basename(completion.outPath)) + : completion.outPath, + telemetryPath: remote + ? (artifacts.find(({ field }) => field === 'telemetryPath')?.localPath ?? + (completion.telemetryPath ? path.basename(completion.telemetryPath) : undefined)) + : completion.telemetryPath, + artifacts, recordingBackend: completion.backend, recordingScope: completion.scope, recordOnlySession: completion.recordOnlySession, @@ -102,7 +105,7 @@ export function buildRecordingStopResponse(completion: ScreenRecordingCompletion overlayWarning: completion.overlayWarning, chunks: completion.chunks?.map((chunk) => ({ index: chunk.index, - path: chunk.clientOutPath ?? chunk.path, + path: chunk.clientOutPath ?? (remote ? path.basename(chunk.path) : chunk.path), })), } satisfies RecordingCommandResult, }; diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index a5a11a488c..fc7eb0e30a 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, @@ -39,7 +36,7 @@ import { } from '@agent-device/capture-kit/screen-recording-session-resource'; import { resolveScreenRecordingStopRecovery, - screenRecordingManifestDevice, + readStoredCompletion, screenRecordingManifestIsTerminal, } from '@agent-device/capture-kit/screen-recording-stop-recovery'; import { resolveSessionScope } from '../session-routing.ts'; @@ -71,14 +68,13 @@ import { recordingExtensionForPlatform, resolveRecordingOutputPaths, } from '@agent-device/capture-kit/recording-output-path'; -import { isRemoteTempArtifactPath } from '@agent-device/contracts/daemon-http'; +import { isRemoteTempArtifactPath, normalizeTenantId } from '@agent-device/contracts/daemon-http'; import { randomUUID } from 'node:crypto'; import { buildRecordingStartResponse, buildRecordingStartedAction, buildRecordingStopResponse, buildRecordingUnsupportedResponse, - isLegacyRemoteRecordingOutput, recordingOutputLeaseVerifier, UNLEASED_CAPTURE, } from './record-runtime-response.ts'; @@ -89,7 +85,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; }>; @@ -136,7 +132,9 @@ async function handleRecordCommandUnsafe( ) { return missingAppSessionResponse(req); } - const resolvedSession = await resolveRecordingSession(params, existingRef, plan); + const authorized = plan.kind === 'start' ? undefined : readStopEnvelope(params); + if (authorized) assertRequestMayStopRecording(params, authorized); + const resolvedSession = await resolveRecordingSession(params, existingRef, authorized?.device); const { session } = resolvedSession; if (plan.kind === 'start') { return await startRecording( @@ -154,6 +152,7 @@ async function handleRecordCommandUnsafe( resolvedSession.ref, plan.kind, resolvedSession.needsReadiness, + authorized, ); } @@ -172,51 +171,27 @@ function resolveRecordPlan(req: DaemonRequest, session: SessionState | undefined async function resolveRecordingSession( params: RecordRuntimeHandlerParams, ref: SessionRef | undefined, - plan: ReturnType['plan'], + recorded: DeviceIdentity | undefined, ): Promise> { if (ref) return { session: params.sessionStore.requireCurrent(ref), ref, needsReadiness: false }; - const device = await resolveUnheldRecordingDevice(params, plan); + const device = await resolveUnheldRecordingDevice(params, recorded); await params.retainDeviceExecutionLock(device.id); return { session: createRecordOnlySession(params, device), needsReadiness: true }; } -/** - * The device an unheld record request is answered on, and the single place the record handler - * applies the named-session rule (#3674) at its only device selection. - * - * A request that names a session this daemon does not hold and states no device is answered from - * the durable manifest the session address finds, never from a sweep of every device on the host: - * a decodable manifest is re-resolved with the request's scope and lease keys under the manifest's - * family (admission proved the request states no device), and a start or a stop with no decodable - * manifest to recover from refuses with the named-session error. - * `assertManifestBelongsToRequest` owns the proof that the resolved device - * and session address match the manifest. - * - * The two shapes that keep their chosen target are unchanged: a request that never named a - * session resolves sessionlessly from its flags, and one that states a device selector resolves - * from it. - */ async function resolveUnheldRecordingDevice( params: RecordRuntimeHandlerParams, - plan: ReturnType['plan'], + recorded: DeviceIdentity | undefined, ): Promise { const { req, sessionName } = params; if (!namesSessionWithoutTarget(req)) return await resolveRequestTargetDevice(req, { env: params.sessionStore.host.env }); - if (plan.kind === 'stop-recovery') { - const recorded = screenRecordingManifestDevice({ - sessionName, - sessionStore: params.sessionStore, - }); - if (recorded) { - return await resolveManifestDevice(params, recorded); - } - } + // A named unheld session only selects the device from its authorized manifest (#3674). + if (recorded) return await resolveManifestDevice(params, recorded); const { namedSessionNotFoundError } = await import('../../core/explicit-session-resolution.ts'); throw namedSessionNotFoundError(sessionName); } -/** Whether this request is addressed to a session and leaves its device to the session. */ function namesSessionWithoutTarget(req: DaemonRequest): boolean { return namesSessionExplicitly(req) && !hasDeviceSelectionInput(req.flags); } @@ -257,14 +232,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 +271,7 @@ async function startRecording( owner: runtime.owner, fence, ...started, - envelope: withCaptureOwner(started.envelope, params.req, outputPaths.daemonOwned === true), + envelope: withCaptureOwner(started.envelope, params.req, outputPaths, lifetimeId), throwIfCanceled: params.throwIfCanceled, }); const adoptedRef = ref ?? draft!.requireRef(); @@ -316,6 +289,7 @@ async function startRecording( snapshot, params.sessionStore.ensureSessionDir(params.sessionName), outputPaths.requestedPath, + outputPaths.daemonOwned === true, ); } @@ -326,17 +300,26 @@ async function startRecording( function withCaptureOwner( envelope: DurableResourceEnvelope<'screen-recording'>, req: DaemonRequest, - daemonOwned: boolean, + output: RecordingStartPaths, + lifetimeId: string, ): DurableResourceEnvelope<'screen-recording'> { const lease = req.internal?.admittedLease; - const tenantId = lease?.tenantId ?? req.meta?.tenantId; + const tenantId = normalizeTenantId(lease?.tenantId ?? req.meta?.tenantId); const leaseId = lease?.leaseId; return { ...envelope, metadata: { ...envelope.metadata, - ...(daemonOwned ? { remoteCaptureOutput: true } : {}), - ...(tenantId ? { remoteCaptureTenantId: tenantId } : {}), + ...(output.daemonOwned + ? { + remoteCaptureOutput: true, + remoteCapturePath: output.outputPath, + remoteCaptureReservation: envelope.fence.token, + remoteCaptureLifetime: lifetimeId, + remoteCaptureTenantId: tenantId ?? null, + } + : {}), + ...(!output.daemonOwned && tenantId ? { remoteCaptureTenantId: tenantId } : {}), remoteCaptureLease: leaseId ? leaseVerifier(leaseId) : UNLEASED_CAPTURE, }, }; @@ -444,27 +427,21 @@ async function stopRecording( ref: SessionRef | undefined, kind: 'stop-live' | 'stop-recovery', needsReadiness: boolean, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, ): Promise { - const leaseOwner = assertRequestMayStopRecording(params); let stopped: ScreenRecordingStop; try { stopped = kind === 'stop-live' - ? { - completion: await finishLiveScreenRecording({ - intent: 'capture', - binding: bindSessionScreenRecording(params.sessionStore, ref!), - }), - recordsSessionAction: true, - } - : await finishRecovered(params, session, needsReadiness); + ? await finishAuthorizedLiveRecording(params, ref!, authorized) + : await finishRecovered(params, session, needsReadiness, authorized); } catch (error) { deleteTerminalRecordOnlySession(params, ref); throw error; } - const completion = stopped.completion; - const response = buildRecordingStopResponse(completion); - const { daemonOwned, tenantId } = readRecordingOutput(params, completion, leaseOwner, ref); + const { envelope } = stopped; + const completion = readStoredCompletion(envelope.metadata); + if (!completion) throw leasedOutputRefusal('Recording'); if (stopped.recordsSessionAction) { recordSessionAction(params.sessionStore, ref, params.req, params.req.command, { action: 'stop', @@ -479,69 +456,112 @@ 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 + const remote = + isRemoteRecordingRequest(params) || envelope.metadata?.remoteCaptureOutput === true; + const artifacts = remote + ? (await import('../recording-outputs.ts')).commitRecordingOutputs( + envelope, + kind === 'stop-live', + ) + : undefined; + const response = buildRecordingStopResponse(completion, artifacts, remote); + return !remote && response.ok && response.data ? { ...response, data: withCaptureOutputOwnership( response.data, - daemonOwned ? 'daemon' : 'caller', - tenantId, - leaseOwner, + 'caller', + undefined, + recordingOutputLeaseVerifier(envelope.metadata), ), } : response; } -function readRecordingOutput( +async function finishAuthorizedLiveRecording( params: RecordRuntimeHandlerParams, - completion: ScreenRecordingCompletion, - leaseOwner: string | null | undefined, - ref: SessionRef | undefined, -): { daemonOwned: boolean; tenantId?: string } { - const resourcePath = screenRecordingDurableResource.resourcePath( - params.sessionStore, - params.sessionName, + ref: SessionRef, + authorized: DurableResourceEnvelope<'screen-recording'> | undefined, +): Promise { + const binding = bindSessionScreenRecording(params.sessionStore, ref); + const active = binding.read(); + if (!authorized || !active || !sameRecordingFence(active.envelope, authorized)) + throw leasedOutputRefusal('Recording'); + await finishLiveScreenRecording({ intent: 'capture', binding }); + return { envelope: requireFinishedEnvelope(params, authorized), recordsSessionAction: true }; +} + +function isRemoteRecordingRequest(params: RecordRuntimeHandlerParams): boolean { + return ( + 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 === 'unreattachable') throw leasedOutputRefusal('Recording'); + 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 ); - const record = screenRecordingDurableResource.store.read(resourcePath); - const daemonOwned = - record.status === 'decoded' && record.envelope.metadata?.remoteCaptureOutput === true; - if (isLegacyRemoteRecordingOutput(completion) || (daemonOwned && leaseOwner === undefined)) { +} + +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 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 }; + assertRequestMayStopRecording(params, envelope); + return envelope; } /** - * Refuses a stop that the owner of the recording did not send, and returns the verifier of the - * lease that owns the export. A completed export needs only the lease id of its owner, also after + * A stopped export needs only the lease id of its owner, also after * that lease ended. A recording that still runs needs the admitted lease. */ function assertRequestMayStopRecording( params: RecordRuntimeHandlerParams, -): string | null | undefined { - const record = screenRecordingDurableResource.store.read( - screenRecordingDurableResource.resourcePath(params.sessionStore, params.sessionName), - ); - if (record.status !== 'decoded') return undefined; - const { metadata, lifecycle } = record.envelope; + envelope: DurableResourceEnvelope<'screen-recording'>, +): void { + const { metadata, lifecycle } = envelope; const owner = recordingOutputLeaseVerifier(metadata); - if (owner === undefined && metadata?.remoteCaptureOutput === true) { + if ( + isRemoteRecordingRequest(params) && + (owner === undefined || metadata?.remoteCaptureOutput !== true) + ) { throw leasedOutputRefusal('Recording'); } - if (typeof owner !== 'string') return owner; + if ( + metadata?.remoteCaptureOutput === true && + typeof metadata.remoteCaptureTenantId === 'string' && + metadata.remoteCaptureTenantId !== + normalizeTenantId(params.req.internal?.admittedLease?.tenantId ?? params.req.meta?.tenantId) + ) + throw leasedOutputRefusal('Recording'); + if (typeof owner !== 'string') return; const presented = lifecycle === 'completed' - ? resolveLeaseScope(params.req).leaseId + ? (resolveLeaseScope(params.req).leaseId ?? params.req.internal?.admittedLease?.leaseId) : params.req.internal?.admittedLease?.leaseId; if (!requestHoldsOutputLease(owner, presented)) throw leasedOutputRefusal('Recording'); - return owner; } function deleteTerminalRecordOnlySession( @@ -573,24 +593,32 @@ 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'); - } - const completion = await finishRecoveredScreenRecording({ + if (recovery.kind === 'none') throw new AppError('INVALID_ARGS', 'no active recording'); + if (recovery.kind === 'completed') + return { envelope: recovery.envelope, recordsSessionAction: false }; + 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 leasedOutputRefusal('Recording'); + 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/leased-recording-retention.ts b/packages/daemon/src/sessions/leased-recording-retention.ts deleted file mode 100644 index 2e2c91a87c..0000000000 --- a/packages/daemon/src/sessions/leased-recording-retention.ts +++ /dev/null @@ -1,77 +0,0 @@ -import fs from 'node:fs'; -import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; -import type { ScreenRecordingCompletion } from '@agent-device/contracts/screen-recording-runtime'; -import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { errorMessage } from '@agent-device/kernel/errors'; -import type { SessionRef } from '../core/session-state.ts'; -import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; -import { - cleanupDownloadableArtifact, - trackDownloadableArtifact, -} from '../resources/artifact-tracking.ts'; -import { - isLegacyRemoteRecordingOutput, - recordingStopArtifacts, - recordingOutputLeaseVerifier, -} from './handlers/record-runtime-response.ts'; - -/** - * Keeps the export of a recording that a leased session's teardown finished, so a request that sends - * the producing lease's id can still download it (ADR 0024 rule 1). The durable envelope marks - * daemon-owned exports. A caller-owned export stays at the path the caller named. - */ -export function retainLeasedSessionRecording( - ref: SessionRef, - completion: ScreenRecordingCompletion, - metadata: DurableResourceEnvelope['metadata'], -): void { - const lease = ref.session.lease; - if (!lease || metadata?.remoteCaptureOutput !== true || isLegacyRemoteRecordingOutput(completion)) - return; - const owner = recordingOutputLeaseVerifier(metadata); - if (owner === undefined) return; - const storedTenant = metadata?.remoteCaptureTenantId; - const tenantId = - owner !== null && typeof storedTenant === 'string' ? storedTenant : lease.tenantId; - const sessionName = tenantPublicSessionName(lease.tenantId, ref.address); - const artifacts = recordingStopArtifacts(completion).filter( - (artifact) => typeof artifact.path === 'string', - ); - const artifactIds: string[] = []; - try { - for (const artifact of artifacts) { - artifactIds.push( - trackDownloadableArtifact({ - artifactPath: artifact.path!, - tenantId, - ...(owner === null ? {} : { leaseVerifier: owner }), - artifactType: artifact.artifactType, - fileName: artifact.fileName, - sessionName, - }), - ); - } - } catch (error) { - for (const artifactId of artifactIds) cleanupDownloadableArtifact(artifactId); - for (const artifact of artifacts) removeBestEffort(artifact.path!); - emitDiagnostic({ - level: 'warn', - phase: 'leased_session_recording_retention_failed', - data: { session: ref.address, leaseId: lease.leaseId, error: errorMessage(error) }, - }); - return; - } - emitDiagnostic({ - level: 'info', - phase: 'leased_session_recording_retained', - data: { session: ref.address, sessionName, leaseId: lease.leaseId, artifactIds }, - }); -} - -function removeBestEffort(filePath: string): void { - try { - fs.rmSync(filePath, { force: true }); - } catch { - // A file that cannot be removed must not stop the removal of the others. - } -} diff --git a/packages/daemon/src/sessions/recording-outputs.ts b/packages/daemon/src/sessions/recording-outputs.ts new file mode 100644 index 0000000000..a4ce6f4599 --- /dev/null +++ b/packages/daemon/src/sessions/recording-outputs.ts @@ -0,0 +1,98 @@ +import { normalizeTenantId } from '@agent-device/contracts/daemon-http'; +import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { readStoredCompletion } from '@agent-device/capture-kit/screen-recording-stop-recovery'; +import type { SessionRef } from '../core/session-state.ts'; +import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; +import { errorMessage } from '@agent-device/kernel/errors'; +import { isRecord } from '@agent-device/kernel/record'; +import { tenantPublicSessionName } from '../core/session-tenant-scope.ts'; +import { commitRecordingFileOutputs, leasedOutputRefusal } from '../resources/artifact-tracking.ts'; +import { + recordingOutputLeaseVerifier, + recordingStopArtifacts, +} from './handlers/record-runtime-response.ts'; + +type RecordingEnvelope = DurableResourceEnvelope<'screen-recording'>; + +function readVerifiedRecording(envelope: RecordingEnvelope) { + const { metadata } = envelope; + const completion = readStoredCompletion(metadata); + const verified = metadata?.remoteCaptureExport; + if ( + envelope.lifecycle !== 'completed' || + !completion || + metadata?.remoteCaptureOutput !== true || + completion.outPath !== metadata.remoteCapturePath || + metadata.remoteCaptureReservation !== envelope.fence.token || + !isRecord(verified) || + !Array.isArray(verified.identities) || + typeof verified.completedAt !== 'number' || + !Number.isFinite(verified.completedAt) + ) + throw leasedOutputRefusal('Recording'); + const { identities } = verified; + const artifacts = recordingStopArtifacts(completion); + if (artifacts.length !== identities.length) throw leasedOutputRefusal('Recording'); + const files = artifacts.map((artifact, index) => { + const sourceIdentity = identities[index]; + if (typeof sourceIdentity !== 'string') throw leasedOutputRefusal('Recording'); + const artifactId = `${envelope.fence.token}-${index + 1}`; + return { ...artifact, path: artifact.path!, sourceIdentity, artifactId }; + }); + return { + files, + completedAt: verified.completedAt, + producer: recordingProducer(metadata), + }; +} + +export function retainSessionRecording(ref: SessionRef, envelope: RecordingEnvelope): void { + const { metadata } = envelope; + if ( + metadata?.remoteCaptureOutput !== true || + metadata.remoteCaptureLifetime !== ref.lifetime.journalId || + metadata.remoteCaptureTenantId === null + ) + return; + try { + commitRecordingOutputs(envelope, true); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'leased_session_recording_retention_failed', + data: { + session: ref.address, + error: errorMessage(error), + hasExportProof: metadata.remoteCaptureExport !== undefined, + }, + }); + } +} + +function recordingProducer(metadata: RecordingEnvelope['metadata']) { + const leaseVerifier = recordingOutputLeaseVerifier(metadata); + const lifetimeId = metadata?.remoteCaptureLifetime; + const stored = metadata?.remoteCaptureTenantId; + const tenantId = normalizeTenantId(stored); + if ( + leaseVerifier === undefined || + typeof lifetimeId !== 'string' || + (stored === null ? leaseVerifier !== null : !tenantId || tenantId !== stored) + ) { + throw leasedOutputRefusal('Recording'); + } + return { lifetimeId, tenantId, leaseVerifier }; +} + +export function commitRecordingOutputs(envelope: RecordingEnvelope, publish: boolean) { + const { producer, files, completedAt } = readVerifiedRecording(envelope); + return commitRecordingFileOutputs( + files, + producer, + producer.tenantId + ? tenantPublicSessionName(producer.tenantId, envelope.sessionId) + : envelope.sessionId, + completedAt, + publish, + ); +} diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index 07c0fca721..c7d6a72821 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -249,14 +249,23 @@ async function finishSessionScreenRecording(params: { await screenRecordingDurableResource.confirmLiveMissing({ binding, resource: recording }); return; } - const completion = await finishLiveScreenRecording({ + await finishLiveScreenRecording({ binding, intent: 'disposal', confirmedMissing, }); - if (!params.ref.session.lease) return; - const { retainLeasedSessionRecording } = await import('./leased-recording-retention.ts'); - retainLeasedSessionRecording(params.ref, completion, recording.envelope.metadata); + const record = screenRecordingDurableResource.store.read( + screenRecordingDurableResource.store.resolvePath(binding.sessionDir), + ); + if ( + record.status !== 'decoded' || + record.envelope.lifecycle !== 'completed' || + record.envelope.fence.token !== recording.envelope.fence.token || + record.envelope.fence.generation !== recording.envelope.fence.generation + ) + return; + const { retainSessionRecording } = await import('./recording-outputs.ts'); + retainSessionRecording(params.ref, record.envelope); } async function finishSessionAudioProbe(params: { diff --git a/packages/host-kit/src/file.ts b/packages/host-kit/src/file.ts index 5ca3e34c54..77128bd52a 100644 --- a/packages/host-kit/src/file.ts +++ b/packages/host-kit/src/file.ts @@ -1,3 +1,5 @@ +import type { Stats } from 'node:fs'; + export { isAtomicPublishTemporaryPath, publishDurableFileSync, @@ -34,3 +36,9 @@ export { type ProcessLockRelease, PROCESS_LOCK_REASONS, } from './internal/process-lock.ts'; + +/** Identifies the current output at a path. Directory identity stays stable as entries change. */ +export function outputFileIdentity(stat: Stats): string { + const inode = `${stat.dev}:${stat.ino}`; + return stat.isDirectory() ? inode : `${inode}:${stat.size}:${stat.mtimeMs}`; +} 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/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index dc5650ee51..e95df27131 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. +Download finished remote recordings before restarting or upgrading the daemon. +The download IDs expire when the daemon stops. +If a recording finishes during recovery and remote `record stop` returns `LEASE_OUTPUT_MISMATCH`, +check the daemon host for the finished files. + 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 7031f3b47fba9c5b07f6ad1df55bb8ec5de3b791 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 11:10:17 +0100 Subject: [PATCH 2/5] fix(recording): defer proof helpers and reject stale replay IDs --- .../screen-recording-session-resource.ts | 10 +-- .../src/durable-capture/definition.ts | 2 +- .../src/durable-capture/finish-recovered.ts | 2 +- .../src/durable-capture/recovery.ts | 5 +- .../src/durable-capture/transitions.ts | 10 +-- .../daemon/src/resources/artifact-tracking.ts | 2 +- .../http-server-capture-publication.test.ts | 65 +++++++++++++++++++ .../http/http-server-capture-tenant.test.ts | 3 +- .../http/http-server-remote-output.test.ts | 27 +------- .../daemon/src/sessions/session-teardown.ts | 1 + 10 files changed, 87 insertions(+), 40 deletions(-) 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 03c139d883..fc5ec87ba3 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,8 +22,6 @@ import type { DurableCaptureRecoveryControl, DurableCaptureSessionBinding, } from '../durable-capture/index.ts'; -import { chunkPathAt } from '../recording/output-path.ts'; -import { deriveRecordingTelemetryPath } from '../recording/telemetry.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'; @@ -78,15 +76,19 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } -function recordingCompletionMetadata( +async function recordingCompletionMetadata( result: ScreenRecordingCompletion, metadata: JsonObject | undefined, producer?: DurableCaptureFinishIntent, -): JsonObject { +): Promise { const completion = encodeScreenRecordingCompletionMetadata(result); const reservedPath = metadata?.remoteCapturePath; if (!producer || typeof reservedPath !== 'string') return completion; try { + const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ + import('../recording/output-path.ts'), + import('../recording/telemetry.ts'), + ]); if ( result.outPath !== reservedPath || result.chunks?.some( diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index f0dbed063f..acbea4e477 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<{ result: C, metadata: DurableResourceEnvelope['metadata'], producer?: DurableCaptureFinishIntent, - ): JsonObject; + ): 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 0de50c2768..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, producer?: DurableCaptureFinishIntent, -): void { +): Promise { if (outcome.status === 'completed') { lease.transition('completed', { metadata: { ...(lease.envelope.metadata ?? {}), - ...definition.completionMetadata(outcome.result, lease.envelope.metadata, producer), + ...(await definition.completionMetadata(outcome.result, lease.envelope.metadata, producer)), phase: 'completed', }, }); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index cc822dc38d..bdabb7c9f4 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -340,7 +340,7 @@ export function commitRecordingFileOutputs( if ( completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now() || entry?.cleanupRequested || - (!publish && !entry) + (!publish && (!entry || readOutputIdentity(entry.artifactPath, true) !== entry.output)) ) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } 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 2fd6285f86..cee5470934 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 @@ -19,10 +19,12 @@ import { screenshotCommandSurface } from '../../__tests__/support/screenshot-com import { sessionLeaseOf } from '../../core/lease-context.ts'; import { LeaseRegistry } from '../../resources/lease-registry.ts'; import { + cleanupDownloadableArtifact, settleCommittedFileOutputs, trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; +import { runBatchCommands } from '../../sessions/handlers/session-batch.ts'; import { successfulData, withHttp } from './http-output.fixtures.ts'; test.each(['caller destination', 'remote placeholder', 'public remote', 'public digest'])( @@ -342,6 +344,69 @@ test('direct HTTP recording replay requires known remote output provenance', asy ); }); +test('batch recording keeps remote origin and generates a session-owned destination', async () => { + const harness = makeRecordRuntimeHarness('remote-batch-record-'); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'recorded-video'); + return await start(input); + }); + const response = await runBatchCommands( + { + token: 'test-token', + session: harness.sessionName, + command: 'batch', + positionals: [], + flags: { batchSteps: [{ command: 'record', positionals: ['start'] }] }, + meta: { cwd: '/client/chosen-root' }, + internal: { publicNetworkOnly: true }, + }, + harness.sessionName, + async (request) => + await harness.run(request.positionals, request.meta, request.flags, request.internal), + ); + if (!response.ok) throw new Error(response.error.message); + const results = response.data?.results as Array<{ data: { outPath: string } }>; + 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)); + const stopped = await harness.run(['stop']); + if (!stopped.ok) throw new Error(stopped.error.message); + for (const { artifactId } of stopped.data?.artifacts ?? []) { + if (artifactId) cleanupDownloadableArtifact(artifactId); + } +}); + +test('record stop replay refuses an artifact whose file has been replaced', async () => { + const harness = makeRecordRuntimeHarness('replaced-remote-recording-'); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'recorded-video'); + return await start(input); + }); + await withHttp( + async (request) => + await harness.run(request.positionals, request.meta, request.flags, request.internal), + async (post) => { + successfulData(await post({ command: 'record', positionals: ['start'] })); + const stop = () => post({ command: 'record', positionals: ['stop'] }); + const { artifacts } = successfulData(await stop()); + expect(artifacts?.[0]?.artifactId).toBeTypeOf('string'); + const capturePath = harness.runtime.start.mock.calls[0]![0].outputPath; + fs.writeFileSync(capturePath + '.replacement', 'replacement'); + fs.renameSync(capturePath + '.replacement', capturePath); + try { + expect((await stop()).error?.data?.details).toMatchObject({ reason: 'RESOURCE_EXPIRED' }); + expect(fs.readFileSync(capturePath, 'utf8')).toBe('replacement'); + } finally { + for (const { artifactId } of artifacts ?? []) { + if (artifactId) cleanupDownloadableArtifact(artifactId); + } + } + }, + ); +}); + test.each(['leased at start', 'unleased'])( 'a downloadable trace preserves producer ownership when the session is %s', async (scenario) => { 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 fffb4bc835..d71687d495 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,7 +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 { clearRequestCanceled, 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'; @@ -246,6 +246,7 @@ test.each([ cleanupDownloadableArtifact(id); } } finally { + clearRequestCanceled(canceledStopId); 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 93eaa2d650..17b16cb9bc 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 @@ -35,9 +35,8 @@ import { settleCommittedFileOutputs, trackDownloadableArtifact, } from '../../resources/artifact-tracking.ts'; -import { localEnv, successfulData, withHttp } from './http-output.fixtures.ts'; -import { runBatchCommands } from '../../sessions/handlers/session-batch.ts'; import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; +import { localEnv, successfulData, withHttp } from './http-output.fixtures.ts'; const outputCases = [ { command: 'screenshot', positionals: ['/host/screenshot.png'] }, @@ -678,30 +677,6 @@ test.each([ }, ); -test('batch recording keeps remote origin and generates a session-owned destination', async () => { - const harness = makeRecordRuntimeHarness('remote-batch-record-'); - const response = await runBatchCommands( - { - token: 'test-token', - session: harness.sessionName, - command: 'batch', - positionals: [], - flags: { batchSteps: [{ command: 'record', positionals: ['start'] }] }, - meta: { cwd: '/client/chosen-root' }, - internal: { publicNetworkOnly: true }, - }, - harness.sessionName, - async (request) => - await harness.run(request.positionals, request.meta, request.flags, request.internal), - ); - if (!response.ok) throw new Error(response.error.message); - const results = response.data?.results as Array<{ data: { outPath: string } }>; - 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']); -}); - test('remote perf memory output reaches the runtime only as a session artifact and downloads by ID', async () => { const root = mkdtempForTestSync('remote-perf-memory-'); const victim = path.join(root, 'protected.hprof'); diff --git a/packages/daemon/src/sessions/session-teardown.ts b/packages/daemon/src/sessions/session-teardown.ts index c7d6a72821..81940b3bdd 100644 --- a/packages/daemon/src/sessions/session-teardown.ts +++ b/packages/daemon/src/sessions/session-teardown.ts @@ -260,6 +260,7 @@ async function finishSessionScreenRecording(params: { if ( record.status !== 'decoded' || record.envelope.lifecycle !== 'completed' || + record.envelope.sessionId !== recording.envelope.sessionId || record.envelope.fence.token !== recording.envelope.fence.token || record.envelope.fence.generation !== recording.envelope.fence.generation ) From bb6328ca7fb3520a36b5db91076b41eb136c9d27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 11:31:52 +0100 Subject: [PATCH 3/5] fix(recording): scope unnamed recordings to unnamed callers --- packages/daemon/src/core/tenant-owned-entry.ts | 14 ++++++++++++-- packages/daemon/src/resources/artifact-tracking.ts | 9 +++++---- .../server/http/http-server-remote-output.test.ts | 11 +++++++++++ website/docs/docs/remote-proxy.md | 8 +++++--- 4 files changed, 33 insertions(+), 9 deletions(-) diff --git a/packages/daemon/src/core/tenant-owned-entry.ts b/packages/daemon/src/core/tenant-owned-entry.ts index 15018221c3..ba615e0c96 100644 --- a/packages/daemon/src/core/tenant-owned-entry.ts +++ b/packages/daemon/src/core/tenant-owned-entry.ts @@ -5,7 +5,17 @@ export const TENANT_RESOURCE_REASONS = { expired: { reason: 'RESOURCE_EXPIRED' }, } as const satisfies ReasonTable<'daemon resources'>; -type TenantOwnedEntry = { tenantId?: string }; +type TenantOwnedEntry = { tenantId?: string | null }; + +/** An explicit null owner restricts access to the shared, unnamed tenant scope. */ +export function matchesTenantOwnedEntry( + entry: TenantOwnedEntry, + tenantId: string | undefined, +): boolean { + return entry.tenantId === null + ? tenantId === undefined + : !entry.tenantId || entry.tenantId === tenantId; +} export type TenantOwnedResourceKind = { label: string; @@ -35,7 +45,7 @@ export function requireTenantOwnedEntry( if (!entry) { throw expiredTenantOwnedEntryError(kind, id); } - if (entry.tenantId && entry.tenantId !== tenantId) { + if (!matchesTenantOwnedEntry(entry, tenantId)) { throw new AppError( 'UNAUTHORIZED', `${kind.label} ${kind.plural ? 'belong' : 'belongs'} to a different tenant`, diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index bdabb7c9f4..6635b359c0 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -17,6 +17,7 @@ import type { DaemonArtifactInventoryEntry } from '@agent-device/contracts/obser import type { PackedGzipTar } from '@agent-device/host-kit/gzip-tar'; import { expiredTenantOwnedEntryError, + matchesTenantOwnedEntry, requireTenantOwnedEntry, type TenantOwnedResourceKind, } from '../core/tenant-owned-entry.ts'; @@ -176,7 +177,7 @@ type ArtifactDownload = { type ArtifactEntry = { artifactPath: string; - tenantId?: string; + tenantId?: string | null; leaseVerifier?: string; reservation?: Readonly<{ directory?: string; lifetimeId: string }>; /** The output that was registered. Another output written to `artifactPath` is not this artifact. */ @@ -354,7 +355,7 @@ export function commitRecordingFileOutputs( artifactPath, artifactType: delivery.artifactType, fileName: delivery.fileName, - tenantId: producer.tenantId, + tenantId: producer.tenantId ?? null, leaseVerifier: producer.leaseVerifier ?? undefined, sessionName, }, @@ -409,7 +410,7 @@ export function trackDownloadableArtifact(params: DownloadableArtifactRegistrati function addArtifactEntry( artifacts: Map, artifactId: string, - params: DownloadableArtifactRegistration, + params: Omit & Pick, output: string | undefined, sourceCleanup: ArtifactSourceCleanup, reservation?: ArtifactEntry['reservation'], @@ -828,7 +829,7 @@ function canReadArtifact(entry: ArtifactEntry, reader: DownloadableArtifactReade return ( !entry.cleanupRequested && !entry.awaitingDelivery && - (!entry.tenantId || entry.tenantId === reader.tenantId) && + matchesTenantOwnedEntry(entry, reader.tenantId) && requestHoldsOutputLease(entry.leaseVerifier, reader.leaseId) ); } 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 17b16cb9bc..ae567a7b65 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 @@ -302,6 +302,17 @@ test('remote recording without client metadata stays in its session and download expect(stopped.result?.data?.outPath).toBe(path.basename(source)); const artifact = stopped.result?.data?.artifacts?.[0]; expect(artifact?.artifactId).toBeTypeOf('string'); + const tenantHeaders = { + authorization: 'Bearer test-token', + [DAEMON_HTTP_TENANT_HEADER]: 'named-tenant', + }; + const inventory = await fetch(`${base}/artifacts`, { headers: tenantHeaders }); + expect(inventory.status).toBe(200); + expect(await inventory.json()).toMatchObject({ artifacts: [] }); + const denied = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { + headers: tenantHeaders, + }); + expect(denied.status).toBe(401); const download = await fetch(`${base}/artifacts/${artifact?.artifactId}`, { headers: { authorization: 'Bearer test-token' }, }); diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index e95df27131..43cca2d713 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -104,11 +104,13 @@ send the lease id in the `x-agent-device-lease-id` header: without it, `GET /art list the artifact and the download fails with `UNAUTHORIZED` and reason `LEASE_OUTPUT_MISMATCH`. 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. +Use the same tenant to capture and download a recording. A recording made without a tenant is +available only to a request without a tenant. -Download finished remote recordings before restarting or upgrading the daemon. +Stop and download remote recordings before restarting or upgrading the daemon. The download IDs expire when the daemon stops. -If a recording finishes during recovery and remote `record stop` returns `LEASE_OUTPUT_MISMATCH`, -check the daemon host for the finished files. +If `record stop` returns `LEASE_OUTPUT_MISMATCH` for a recording started before an upgrade or +completed during recovery, check the daemon host for the finished files. 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 From 0f387473f8c4737a83309a3631f580d8c483089b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 12:17:18 +0100 Subject: [PATCH 4/5] fix(recording): bind export proof to the first producer finish --- .../screen-recording-session-resource.ts | 119 ++++++---- .../src/durable-capture/definition.ts | 16 +- .../src/durable-capture/finish-recovered.ts | 2 +- .../src/durable-capture/recovery.ts | 5 +- .../src/durable-capture/transitions.ts | 31 ++- .../daemon/src/resources/artifact-tracking.ts | 50 ++-- .../http/http-server-recording-proof.test.ts | 217 ++++++++++++++++++ .../__tests__/record-runtime.fixtures.ts | 7 +- .../src/sessions/handlers/record-runtime.ts | 39 ++-- 9 files changed, 367 insertions(+), 119 deletions(-) create mode 100644 packages/daemon/src/server/http/http-server-recording-proof.test.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 fc5ec87ba3..0587804864 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,7 +1,12 @@ import fs from 'node:fs'; -import { AppError, errorMessage } from '@agent-device/kernel/errors'; +import { errorMessage } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { outputFileIdentity } from '@agent-device/host-kit/file'; +import type { + DurableCaptureProgress, + LiveResourceHandle, +} from '@agent-device/contracts/durable-resource'; +import type { ScreenRecordingFinalization } from '@agent-device/contracts/recording-stop-progress'; 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'; @@ -38,7 +43,8 @@ export const screenRecordingDurableResource = createDurableCaptureResource< resourceKind: 'screen-recording', displayName: 'screen recording', store: screenRecordingResourceStore, - completionMetadata: recordingCompletionMetadata, + completionMetadata: encodeScreenRecordingCompletionMetadata, + finishLive: finishRecordingExport, // 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 @@ -76,51 +82,78 @@ export function finishLiveScreenRecording(params: { return screenRecordingDurableResource.finishLive(params); } -async function recordingCompletionMetadata( - result: ScreenRecordingCompletion, - metadata: JsonObject | undefined, - producer?: DurableCaptureFinishIntent, -): Promise { - const completion = encodeScreenRecordingCompletionMetadata(result); - const reservedPath = metadata?.remoteCapturePath; - if (!producer || typeof reservedPath !== 'string') return completion; - try { - const [{ chunkPathAt }, { deriveRecordingTelemetryPath }] = await Promise.all([ +type RecordingExportProof = Readonly<{ completedAt: number; identities: string[] }>; +const liveExportProofs = new WeakMap< + LiveResourceHandle, + RecordingExportProof | null +>(); + +async function finishRecordingExport( + handle: LiveResourceHandle, + progress: DurableCaptureProgress, +) { + const reservedPath = progress.learned?.remoteCapturePath; + if (typeof reservedPath !== 'string') return { outcome: await handle.finish(progress) }; + const [{ chunkPathAt }, { deriveRecordingTelemetryPath }, { readStopCheckpoints }] = + await Promise.all([ import('../recording/output-path.ts'), import('../recording/telemetry.ts'), + import('../recording/stop-checkpoints.ts'), ]); - if ( - result.outPath !== reservedPath || - result.chunks?.some( - (chunk, offset) => - chunk.index !== offset + 1 || chunk.path !== chunkPathAt(reservedPath, chunk.index), - ) || - (result.telemetryPath !== undefined && - result.telemetryPath !== deriveRecordingTelemetryPath(reservedPath)) - ) - throw new Error('Recording export does not match its reservation.'); - const files = [ - reservedPath, - ...(result.chunks?.slice(1).map(({ path }) => path) ?? []), - ...(result.telemetryPath ? [result.telemetryPath] : []), - ]; - const identities = files.map((file) => { - const stat = fs.lstatSync(file); - if (!stat.isFile()) throw new Error('Recording export is not a regular file.'); - return outputFileIdentity(stat); - }); - return { ...completion, remoteCaptureExport: { completedAt: Date.now(), identities } }; - } catch (error) { - emitDiagnostic({ - level: 'warn', - phase: 'screen_recording_export_proof_failed', - data: { error: errorMessage(error) }, - }); - if (producer === 'disposal') return completion; - throw new AppError('COMMAND_FAILED', 'Recording export proof could not be recorded.', { - retriable: true, - }); + if (readStopCheckpoints(progress.learned).exportPath && !liveExportProofs.has(handle)) { + liveExportProofs.set(handle, null); } + const rememberExport = ( + outPath: string, + { chunks, telemetryPath }: ScreenRecordingFinalization, + ) => { + if (liveExportProofs.has(handle)) return; + try { + if ( + outPath !== reservedPath || + chunks?.some( + (chunk, offset) => + chunk.index !== offset + 1 || chunk.path !== chunkPathAt(reservedPath, chunk.index), + ) || + (telemetryPath !== undefined && + telemetryPath !== deriveRecordingTelemetryPath(reservedPath)) + ) { + throw new Error('Recording export does not match its reservation.'); + } + const files = [ + reservedPath, + ...(chunks?.slice(1).map(({ path }) => path) ?? []), + ...(telemetryPath ? [telemetryPath] : []), + ]; + liveExportProofs.set(handle, { + completedAt: Date.now(), + identities: files.map((file) => { + const stat = fs.lstatSync(file); + if (!stat.isFile()) throw new Error('Recording export is not a regular file.'); + return outputFileIdentity(stat); + }), + }); + } catch (error) { + liveExportProofs.set(handle, null); + emitDiagnostic({ + level: 'warn', + phase: 'screen_recording_export_proof_failed', + data: { error: errorMessage(error) }, + }); + } + }; + const outcome = await handle.finish({ + ...progress, + record: (fact) => { + const { exportPath, finalization } = readStopCheckpoints(fact); + if (exportPath) rememberExport(exportPath, finalization ?? {}); + progress.record(fact); + }, + }); + if (outcome.status !== 'completed' || outcome.alreadyCompleted) return { outcome }; + rememberExport(outcome.result.outPath, outcome.result); + const proof = liveExportProofs.get(handle); + return { outcome, ...(proof ? { metadata: { remoteCaptureExport: proof } } : {}) }; } export function encodeScreenRecordingCompletionMetadata( diff --git a/packages/capture-kit/src/durable-capture/definition.ts b/packages/capture-kit/src/durable-capture/definition.ts index acbea4e477..78b32ffa0d 100644 --- a/packages/capture-kit/src/durable-capture/definition.ts +++ b/packages/capture-kit/src/durable-capture/definition.ts @@ -1,5 +1,10 @@ import type { JsonObject } from '@agent-device/contracts/client'; import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; +import type { + DurableCaptureProgress, + FinishOutcome, + LiveResourceHandle, +} from '@agent-device/contracts/durable-resource'; import type { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; import type { ResourceOwnershipFence, @@ -56,11 +61,12 @@ export type DurableCaptureRecordDefinition = Readonly<{ resourceKind: K; displayName: string; store: DurableCaptureResourceStore; - completionMetadata( - result: C, - metadata: DurableResourceEnvelope['metadata'], - producer?: DurableCaptureFinishIntent, - ): JsonObject | Promise; + completionMetadata(result: C): JsonObject; + /** Runs only for the live producer. Its metadata is written with the terminal result. */ + finishLive?( + handle: LiveResourceHandle, + progress: DurableCaptureProgress, + ): Promise<{ outcome: FinishOutcome; metadata?: JsonObject }>; /** * 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 7fa396910b..98db3919f9 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) => { - await transitionFinishOutcome(definition, lease, { + 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 aa1701ef29..805f32ff84 100644 --- a/packages/capture-kit/src/durable-capture/recovery.ts +++ b/packages/capture-kit/src/durable-capture/recovery.ts @@ -193,10 +193,7 @@ async function settleRecoveryAuthority; + let finished: { outcome: FinishOutcome; metadata?: JsonObject }; try { - finishOutcome = await params.handle.finish(progress); + finished = + params.producer && definition.finishLive + ? await definition.finishLive(params.handle, progress) + : { outcome: await params.handle.finish(progress) }; } catch (finishError) { settleIfMissing(lease); await respondToFailedFinish(definition, lease, params, finishError, params.intent); throw finishError; } - if (finishOutcome.status === 'completed') { - await transitionFinishOutcome( - definition, - lease, - finishOutcome, - params.producer ? params.intent : undefined, - ); - return finishOutcome.result; - } - await transitionFinishOutcome(definition, lease, finishOutcome); - const finishError = cleanupPendingError(definition, finishOutcome); + const { outcome, metadata } = finished; + transitionFinishOutcome(definition, lease, outcome, metadata); + if (outcome.status === 'completed') return outcome.result; + const finishError = cleanupPendingError(definition, outcome); settleIfMissing(lease); await respondToFailedFinish(definition, lease, params, finishError, params.intent); throw finishError; @@ -353,17 +349,18 @@ function cleanupPendingError( ); } -export async function transitionFinishOutcome( +export function transitionFinishOutcome( definition: DurableCaptureRecordDefinition, lease: DurableCaptureOpenResourceFenceLease, outcome: FinishOutcome, - producer?: DurableCaptureFinishIntent, -): Promise { + producerMetadata?: JsonObject, +): void { if (outcome.status === 'completed') { lease.transition('completed', { metadata: { ...(lease.envelope.metadata ?? {}), - ...(await definition.completionMetadata(outcome.result, lease.envelope.metadata, producer)), + ...definition.completionMetadata(outcome.result), + ...producerMetadata, phase: 'completed', }, }); diff --git a/packages/daemon/src/resources/artifact-tracking.ts b/packages/daemon/src/resources/artifact-tracking.ts index 6635b359c0..113330ea67 100644 --- a/packages/daemon/src/resources/artifact-tracking.ts +++ b/packages/daemon/src/resources/artifact-tracking.ts @@ -336,12 +336,15 @@ export function commitRecordingFileOutputs( publish: boolean, ): DaemonArtifact[] { const artifacts = pendingArtifacts(); - for (const { artifactId } of files) { + const expired = completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now(); + for (const { artifactId, path: artifactPath, sourceIdentity } of files) { const entry = artifacts.get(artifactId); if ( - completedAt + ARTIFACT_CLEANUP_TIMEOUT_MS <= Date.now() || + expired || entry?.cleanupRequested || - (!publish && (!entry || readOutputIdentity(entry.artifactPath, true) !== entry.output)) + (!publish && !entry) || + (entry && (entry.artifactPath !== artifactPath || entry.output !== sourceIdentity)) || + readOutputIdentity(artifactPath, true) !== sourceIdentity ) { throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } @@ -577,23 +580,23 @@ export async function openDownloadableArtifact( } function openRegisteredFile(artifactId: string, entry: ArtifactEntry): fs.ReadStream { - const fd = fs.openSync( - entry.artifactPath, - fs.constants.O_RDONLY | - fs.constants.O_NONBLOCK | - (entry.reservation ? fs.constants.O_NOFOLLOW : 0), - ); + let fd: number | undefined; try { + fd = fs.openSync( + entry.artifactPath, + fs.constants.O_RDONLY | + fs.constants.O_NONBLOCK | + (entry.reservation ? fs.constants.O_NOFOLLOW : 0), + ); const stat = fs.fstatSync(fd); - if (!stat.isFile() || outputFileIdentity(stat) !== entry.output) { - cleanupDownloadableArtifact(artifactId); - throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); - } - return fs.createReadStream(entry.artifactPath, { fd }); - } catch (error) { - fs.closeSync(fd); - throw error; + if (stat.isFile() && outputFileIdentity(stat) === entry.output) + return fs.createReadStream(entry.artifactPath, { fd }); + } catch { + // The file is no longer readable through the registered identity. } + if (fd !== undefined) fs.closeSync(fd); + cleanupDownloadableArtifact(artifactId); + throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); } function cancelArtifactDownload( @@ -682,17 +685,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 (outputFileIdentity(stat) !== entry.output) { - cleanupDownloadableArtifact(artifactId); - throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); - } + const stat = statRegisteredOutput(artifactId, entry); + if (!stat) throw expiredTenantOwnedEntryError(DOWNLOADABLE_ARTIFACT_RESOURCE, artifactId); return { entry, stat }; } diff --git a/packages/daemon/src/server/http/http-server-recording-proof.test.ts b/packages/daemon/src/server/http/http-server-recording-proof.test.ts new file mode 100644 index 0000000000..f5e2623038 --- /dev/null +++ b/packages/daemon/src/server/http/http-server-recording-proof.test.ts @@ -0,0 +1,217 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { stopAndExportScreenRecording } from '@agent-device/capture-kit/recording-stop-sequence'; +import { deriveRecordingTelemetryPath } from '@agent-device/capture-kit/recording-telemetry'; +import { cleanupDownloadableArtifact } from '../../resources/artifact-tracking.ts'; +import { makeRecordRuntimeHarness } from '../../sessions/handlers/__tests__/record-runtime.fixtures.ts'; +import { successfulData, withHttp } from './http-output.fixtures.ts'; + +const RECORD = { command: 'record' }; +const START = { ...RECORD, positionals: ['start'] }; +const STOP = { ...RECORD, positionals: ['stop'] }; +const HEADERS = { authorization: 'Bearer test-token' }; + +async function withRecording( + run: ( + harness: ReturnType, + post: Parameters[1]>[0], + base: string, + capturePath: string, + ) => Promise, +) { + const harness = makeRecordRuntimeHarness('recording-proof-'); + const start = harness.runtime.start.getMockImplementation()!; + harness.runtime.start.mockImplementation(async (input) => { + fs.writeFileSync(input.outputPath, 'producer-video'); + return await start(input); + }); + await withHttp( + (request) => harness.run(request.positionals, request.meta, request.flags, request.internal), + async (post, base) => { + successfulData(await post(START)); + await run(harness, post, base, harness.runtime.start.mock.calls[0]![0].outputPath); + }, + ); +} + +test.each(['live stop', 'completed retry', 'successor session'] as const)( + 'a remote recording refuses an unauthorized %s', + async (operation) => { + await withRecording(async (harness, post, base) => { + const namedStop = { ...STOP, meta: { tenantId: 'another-tenant' } }; + const refusal = { reason: 'LEASE_OUTPUT_MISMATCH' }; + if (operation === 'live stop') { + expect((await post(namedStop)).error?.data?.details).toMatchObject(refusal); + expect(harness.runtime.finish).not.toHaveBeenCalled(); + } + const { artifacts } = successfulData(await post(STOP)); + const id = artifacts?.[0]?.artifactId; + expect(id).toBeTypeOf('string'); + try { + if (operation === 'completed retry') { + expect((await post(namedStop)).error?.data?.details).toMatchObject(refusal); + } + if (operation === 'successor session') { + const previous = harness.sessionStore.lookup(harness.sessionName)!; + harness.sessionStore.retire(previous); + const successor = harness.sessionStore.publish(harness.sessionName, harness.session); + expect(successor.lifetime.journalId).not.toBe(previous.lifetime.journalId); + expect((await post(STOP)).error?.data?.details).toMatchObject(refusal); + } + const download = await fetch(`${base}/artifacts/${id}`, { headers: HEADERS }); + expect(download.status).toBe(200); + expect(await download.text()).toBe('producer-video'); + } finally { + if (id) cleanupDownloadableArtifact(id); + } + }); + }, +); + +test('a replayed producer completion without proof cannot acquire a remote download ID', async () => { + await withRecording(async (harness, post, base, capturePath) => { + const finish = harness.runtime.finish.getMockImplementation()!; + harness.runtime.finish.mockImplementation(async () => ({ + ...(await finish()), + alreadyCompleted: true, + })); + expect((await post(STOP)).error?.data?.details).toMatchObject({ + reason: 'LEASE_OUTPUT_MISMATCH', + }); + expect(await (await fetch(`${base}/artifacts`, { headers: HEADERS })).json()).toMatchObject({ + artifacts: [], + }); + expect(fs.readFileSync(capturePath, 'utf8')).toBe('producer-video'); + }); +}); + +test.each(['terminal write', 'native marker'] as const)( + 'a retry after a failed %s cannot certify replacement bytes', + async (failedStep) => { + await withRecording(async (harness, post, base, capturePath) => { + const finish = harness.runtime.finish.getMockImplementation()!; + const { sessionName, sessionStore } = harness; + const manifest = screenRecordingResourceStore.resolvePath( + sessionStore.resolveSessionDir(sessionName), + ); + const rename = fs.renameSync; + const failTerminal = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { + if ( + failedStep === 'terminal write' && + to === manifest && + fs.readFileSync(from, 'utf8').includes('"lifecycle":"completed"') + ) { + throw new Error('Terminal write failed'); + } + rename(from, to); + }); + const finalize = vi.fn(async () => ({ nativePathDisposition: 'retired' as const })); + if (failedStep === 'native marker') { + harness.runtime.finish.mockImplementation(async (progress) => { + const { result } = await finish(); + const outcome = await stopAndExportScreenRecording({ + snapshot: { ...result, gestureEvents: [] }, + progress, + steps: { + stop: async () => ({ observation: { recorder: 'confirmed' } }), + collect: async () => {}, + finalize, + discard: async () => {}, + }, + }); + if (harness.runtime.finish.mock.calls.length === 1) + throw new Error('Native marker write failed'); + return { ...outcome, result: { ...result, ...outcome.result, scope: 'app' } }; + }); + } + try { + expect((await post(STOP)).error).toBeDefined(); + } finally { + failTerminal.mockRestore(); + } + fs.writeFileSync(capturePath + '.replacement', 'replacement'); + fs.renameSync(capturePath + '.replacement', capturePath); + expect((await post(STOP)).error?.data?.details).toMatchObject({ reason: 'RESOURCE_EXPIRED' }); + if (failedStep === 'native marker') expect(finalize).toHaveBeenCalledOnce(); + expect(await (await fetch(`${base}/artifacts`, { headers: HEADERS })).json()).toMatchObject({ + artifacts: [], + }); + expect(fs.readFileSync(capturePath, 'utf8')).toBe('replacement'); + }); + }, +); + +test('the first stop validates the whole committed set before publishing any ID', async () => { + await withRecording(async (harness, post, base, capturePath) => { + const finish = harness.runtime.finish.getMockImplementation()!; + const telemetryPath = deriveRecordingTelemetryPath(capturePath); + harness.runtime.finish.mockImplementation(async () => { + fs.writeFileSync(telemetryPath, '{}'); + const outcome = await finish(); + return { ...outcome, result: { ...outcome.result, telemetryPath } }; + }); + const manifest = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(harness.sessionName), + ); + const rename = fs.renameSync; + const replaceAfterCommit = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { + const completed = + to === manifest && fs.readFileSync(from, 'utf8').includes('"lifecycle":"completed"'); + rename(from, to); + if (completed) fs.rmSync(telemetryPath); + }); + try { + expect((await post(STOP)).error?.data?.details).toMatchObject({ reason: 'RESOURCE_EXPIRED' }); + } finally { + replaceAfterCommit.mockRestore(); + } + expect(await (await fetch(`${base}/artifacts`, { headers: HEADERS })).json()).toMatchObject({ + artifacts: [], + }); + expect(fs.readFileSync(capturePath, 'utf8')).toBe('producer-video'); + }); +}); + +test.each(['missing lookup', 'missing open', 'symlink open'] as const)( + 'a recording download retires a %s with a path-free expiry', + async (failure) => { + await withRecording(async (_harness, post, base, capturePath) => { + const { artifacts } = successfulData(await post(STOP)); + const id = artifacts?.[0]?.artifactId; + expect(id).toBeTypeOf('string'); + const open = fs.openSync; + const replacement = path.join(path.dirname(capturePath), 'replacement.mp4'); + const removeCapture = () => { + fs.unlinkSync(capturePath); + if (failure === 'symlink open') { + fs.writeFileSync(replacement, 'replacement'); + fs.symlinkSync(replacement, capturePath); + } + }; + if (failure === 'missing lookup') removeCapture(); + const removeBeforeOpen = vi.spyOn(fs, 'openSync').mockImplementation((file, flags, mode) => { + if (file === capturePath && failure !== 'missing lookup') removeCapture(); + return open(file, flags, mode); + }); + const download = () => fetch(`${base}/artifacts/${id}`, { headers: HEADERS }); + try { + for (let attempt = 0; attempt < 2; attempt++) { + const response = await download(); + const body = await response.text(); + expect(body).not.toContain(capturePath); + expect(response.status).toBe(404); + expect(JSON.parse(body)).toMatchObject({ reason: 'RESOURCE_EXPIRED' }); + } + } finally { + removeBeforeOpen.mockRestore(); + if (id) cleanupDownloadableArtifact(id); + } + if (failure === 'symlink open') { + expect(fs.lstatSync(capturePath).isSymbolicLink()).toBe(true); + expect(fs.readFileSync(replacement, 'utf8')).toBe('replacement'); + } + }); + }, +); 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..0b3d8ecf1b 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts @@ -2,7 +2,10 @@ import { daemonPlatformServicesFixture } from '../../../__tests__/support/platfo import { expect, vi, type Mock } from 'vitest'; import { applicationLifecycleOperationFacts } from '@agent-device/contracts/application-lifecycle-runtime'; import { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle'; -import type { CleanupOutcome } from '@agent-device/contracts/durable-resource'; +import type { + CleanupOutcome, + DurableCaptureProgress, +} from '@agent-device/contracts/durable-resource'; import { type DeviceBinding, type RuntimeOperationUnavailability, @@ -150,7 +153,7 @@ function makeRuntime(session: SessionState, options: RuntimeOptions = {}) { setTouchReferenceFrame: () => {}, setRunnerSessionId: () => {}, invalidate: () => {}, - finish: vi.fn(async () => { + finish: vi.fn(async (_progress?: DurableCaptureProgress) => { if (options.finishError) throw options.finishError; return { status: 'completed' as const, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index fc7eb0e30a..cfcf1f8491 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -133,7 +133,7 @@ async function handleRecordCommandUnsafe( return missingAppSessionResponse(req); } const authorized = plan.kind === 'start' ? undefined : readStopEnvelope(params); - if (authorized) assertRequestMayStopRecording(params, authorized); + if (authorized) assertRequestMayStopRecording(params, authorized, existingRef); const resolvedSession = await resolveRecordingSession(params, existingRef, authorized?.device); const { session } = resolvedSession; if (plan.kind === 'start') { @@ -434,7 +434,7 @@ async function stopRecording( stopped = kind === 'stop-live' ? await finishAuthorizedLiveRecording(params, ref!, authorized) - : await finishRecovered(params, session, needsReadiness, authorized); + : await finishRecovered(params, session, needsReadiness, authorized, ref); } catch (error) { deleteTerminalRecordOnlySession(params, ref); throw error; @@ -488,7 +488,7 @@ async function finishAuthorizedLiveRecording( if (!authorized || !active || !sameRecordingFence(active.envelope, authorized)) throw leasedOutputRefusal('Recording'); await finishLiveScreenRecording({ intent: 'capture', binding }); - return { envelope: requireFinishedEnvelope(params, authorized), recordsSessionAction: true }; + return { envelope: requireFinishedEnvelope(params, authorized, ref), recordsSessionAction: true }; } function isRemoteRecordingRequest(params: RecordRuntimeHandlerParams): boolean { @@ -520,6 +520,7 @@ function sameRecordingFence( function requireFinishedEnvelope( params: RecordRuntimeHandlerParams, expected: DurableResourceEnvelope<'screen-recording'>, + ref?: SessionRef, ) { const envelope = readStopEnvelope(params); if ( @@ -529,7 +530,7 @@ function requireFinishedEnvelope( envelope.metadata?.remoteCapturePath !== expected.metadata?.remoteCapturePath ) throw leasedOutputRefusal('Recording'); - assertRequestMayStopRecording(params, envelope); + assertRequestMayStopRecording(params, envelope, ref); return envelope; } @@ -540,27 +541,26 @@ function requireFinishedEnvelope( function assertRequestMayStopRecording( params: RecordRuntimeHandlerParams, envelope: DurableResourceEnvelope<'screen-recording'>, + ref?: SessionRef, ): void { const { metadata, lifecycle } = envelope; const owner = recordingOutputLeaseVerifier(metadata); - if ( - isRemoteRecordingRequest(params) && - (owner === undefined || metadata?.remoteCaptureOutput !== true) - ) { + const remote = metadata?.remoteCaptureOutput === true; + const admitted = params.req.internal?.admittedLease; + if (isRemoteRecordingRequest(params) && (owner === undefined || !remote)) throw leasedOutputRefusal('Recording'); + if (remote) { + const tenant = normalizeTenantId(admitted?.tenantId ?? params.req.meta?.tenantId) ?? null; + if (tenant !== metadata.remoteCaptureTenantId) throw leasedOutputRefusal('Recording'); + if (ref && ref.lifetime.journalId !== metadata.remoteCaptureLifetime) + 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 admittedLeaseId = admitted?.leaseId; const presented = lifecycle === 'completed' - ? (resolveLeaseScope(params.req).leaseId ?? params.req.internal?.admittedLease?.leaseId) - : params.req.internal?.admittedLease?.leaseId; + ? (resolveLeaseScope(params.req).leaseId ?? admittedLeaseId) + : admittedLeaseId; if (!requestHoldsOutputLease(owner, presented)) throw leasedOutputRefusal('Recording'); } @@ -594,6 +594,7 @@ async function finishRecovered( session: SessionState, needsReadiness: boolean, authorized: DurableResourceEnvelope<'screen-recording'> | undefined, + ref?: SessionRef, ): Promise { if (!authorized) throw new AppError('INVALID_ARGS', 'no active recording'); const recovery = resolveScreenRecordingStopRecovery({ @@ -611,12 +612,12 @@ async function finishRecovered( scope: params.requestScope, acquireControl: (envelope, scope) => { if (!sameRecordingFence(envelope, recovery.envelope)) throw leasedOutputRefusal('Recording'); - assertRequestMayStopRecording(params, envelope); + assertRequestMayStopRecording(params, envelope, ref); return acquire(envelope, scope); }, }); return { - envelope: requireFinishedEnvelope(params, authorized), + envelope: requireFinishedEnvelope(params, authorized, ref), recordsSessionAction: true, }; } From 118d16f4a7021e0b4cf4ae670de9868f0df85273 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Wed, 25 Nov 2026 13:08:31 +0100 Subject: [PATCH 5/5] fix(recording): retain proof only after the export checkpoint lands --- .../screen-recording-session-resource.ts | 22 ++++--- .../http/http-server-recording-proof.test.ts | 59 +++++++++++++++++++ 2 files changed, 73 insertions(+), 8 deletions(-) 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 0587804864..9f5bc454c3 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 @@ -103,11 +103,10 @@ async function finishRecordingExport( if (readStopCheckpoints(progress.learned).exportPath && !liveExportProofs.has(handle)) { liveExportProofs.set(handle, null); } - const rememberExport = ( + const readExportProof = ( outPath: string, { chunks, telemetryPath }: ScreenRecordingFinalization, - ) => { - if (liveExportProofs.has(handle)) return; + ): RecordingExportProof | null => { try { if ( outPath !== reservedPath || @@ -125,33 +124,40 @@ async function finishRecordingExport( ...(chunks?.slice(1).map(({ path }) => path) ?? []), ...(telemetryPath ? [telemetryPath] : []), ]; - liveExportProofs.set(handle, { + return { completedAt: Date.now(), identities: files.map((file) => { const stat = fs.lstatSync(file); if (!stat.isFile()) throw new Error('Recording export is not a regular file.'); return outputFileIdentity(stat); }), - }); + }; } catch (error) { - liveExportProofs.set(handle, null); emitDiagnostic({ level: 'warn', phase: 'screen_recording_export_proof_failed', data: { error: errorMessage(error) }, }); + return null; } }; const outcome = await handle.finish({ ...progress, record: (fact) => { const { exportPath, finalization } = readStopCheckpoints(fact); - if (exportPath) rememberExport(exportPath, finalization ?? {}); + const proof = + exportPath && !liveExportProofs.has(handle) + ? readExportProof(exportPath, finalization ?? {}) + : undefined; progress.record(fact); + // A failed checkpoint can cause retry to produce a new export. + if (proof !== undefined) liveExportProofs.set(handle, proof); }, }); if (outcome.status !== 'completed' || outcome.alreadyCompleted) return { outcome }; - rememberExport(outcome.result.outPath, outcome.result); + if (!liveExportProofs.has(handle)) { + liveExportProofs.set(handle, readExportProof(outcome.result.outPath, outcome.result)); + } const proof = liveExportProofs.get(handle); return { outcome, ...(proof ? { metadata: { remoteCaptureExport: proof } } : {}) }; } diff --git a/packages/daemon/src/server/http/http-server-recording-proof.test.ts b/packages/daemon/src/server/http/http-server-recording-proof.test.ts index f5e2623038..d5b6dbc8c4 100644 --- a/packages/daemon/src/server/http/http-server-recording-proof.test.ts +++ b/packages/daemon/src/server/http/http-server-recording-proof.test.ts @@ -143,6 +143,65 @@ test.each(['terminal write', 'native marker'] as const)( }, ); +test('a failed export checkpoint allows downloading the re-produced recording', async () => { + await withRecording(async (harness, post, base, capturePath) => { + const finish = harness.runtime.finish.getMockImplementation()!; + const rename = fs.renameSync; + const finalize = vi.fn(async () => { + const next = `${capturePath}.producer`; + fs.writeFileSync(next, `producer-video-${finalize.mock.calls.length}`); + rename(next, capturePath); + return { nativePathDisposition: 'retired' as const }; + }); + harness.runtime.finish.mockImplementation(async (progress) => { + const { result } = await finish(); + const outcome = await stopAndExportScreenRecording({ + snapshot: { ...result, gestureEvents: [] }, + progress, + steps: { + stop: async () => ({ observation: { recorder: 'confirmed' } }), + collect: async () => {}, + finalize, + discard: async () => {}, + }, + }); + return { ...outcome, result: { ...result, ...outcome.result, scope: 'app' } }; + }); + const manifest = screenRecordingResourceStore.resolvePath( + harness.sessionStore.resolveSessionDir(harness.sessionName), + ); + let checkpointFailed = false; + const failCheckpoint = vi.spyOn(fs, 'renameSync').mockImplementation((from, to) => { + if (!checkpointFailed && to === manifest) { + const pending = JSON.parse(fs.readFileSync(from, 'utf8')); + if (pending.lifecycle === 'open' && pending.metadata?.exportPath === capturePath) { + checkpointFailed = true; + throw new Error('Export checkpoint rename failed'); + } + } + rename(from, to); + }); + try { + expect((await post(STOP)).error).toBeDefined(); + expect(checkpointFailed).toBe(true); + expect(finalize).toHaveBeenCalledOnce(); + const { artifacts } = successfulData(await post(STOP)); + expect(finalize).toHaveBeenCalledTimes(2); + const id = artifacts?.[0]?.artifactId; + expect(id).toBeTypeOf('string'); + try { + const download = await fetch(`${base}/artifacts/${id}`, { headers: HEADERS }); + expect(download.status).toBe(200); + expect(await download.text()).toBe('producer-video-2'); + } finally { + if (id) cleanupDownloadableArtifact(id); + } + } finally { + failCheckpoint.mockRestore(); + } + }); +}); + test('the first stop validates the whole committed set before publishing any ID', async () => { await withRecording(async (harness, post, base, capturePath) => { const finish = harness.runtime.finish.getMockImplementation()!;