Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 20 additions & 5 deletions docs/adr/0024-screen-recording-provable-signal.md
Original file line number Diff line number Diff line change
Expand Up @@ -287,12 +287,27 @@ Artifact cleanup is a separate, explicit decision (rule 6).
Session teardown and failed-start rollback dispose through the backend under the fence.
They do this only after the manifest records that no recoverable export is lost.

A leased session's teardown that commits an export at a remote temp path registers it, and its telemetry, as downloadable artifacts of that lease (rule 1, #2281).
Only a request that sends the id of the ended lease lists or downloads them (ADR 0007).
A remote recording reserves a daemon-chosen destination at start.
The manifest records the producing lifetime, a tenant or explicit global marker, and a lease verifier or unleased marker.
The completed manifest records the verified file identities of the video, later chunks, and telemetry.
If verification cannot read a finished export, keep its completion and reservation for an exact-owner retry.
Explicit stop and teardown commit the verified files under that producer's authority.
The producer can discover committed recordings after a canceled or failed response.
The inventory names the session, and the usual delete-after-download and 15-minute expiry apply.
A later `record stop` replay of that manifest serves the same artifact ids.
If registration fails, teardown deletes the files.
A failed teardown finish still runs forced cleanup (disposal intent) and registers nothing.
If registry delivery fails during teardown, expire the verified standalone export at the same deadline.
Only remove files that still match the original proof.
A retry for consumed or expired bytes returns `RESOURCE_EXPIRED`.
A retry uses the artifact IDs derived from the persisted reservation and the original deadline.
The download records consumption before releasing its file.
Only the original lease credential can list or download leased exports (ADR 0007).
A manifest must carry explicit producer scope, completion time, and file identities before it can serve a remote export.
After a daemon upgrade, remote `record stop` returns `LEASE_OUTPUT_MISMATCH` for an older manifest that lacks producer evidence, including for client-destination recordings.
The daemon keeps any finished files on the host for local recovery.
The old destination and lease verifier alone cannot prove the identity of the finished files.
A failed teardown finish still runs forced cleanup (disposal intent) and publishes no recording.
A suite includes recordings committed by cleanup in its result and archive.
Each remote suite gets a fresh daemon directory.
The recording stays in its reservation. The suite copies verified bytes into the archive so each download has its own lifetime.

### 2.6 Native markers

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,10 @@ import { expect, test, vi } from 'vitest';
import { PendingTransferGuard } from '@agent-device/contracts/async-lifecycle';
import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime';
import type { ScreenRecordingLiveHandle } from '@agent-device/contracts/screen-recording-runtime';
import {
createStopProgress,
withDurableCaptureResourceFence,
} from '../../durable-capture/fence.ts';
import { createDurableResourceEnvelope } from '../../durable-resource-envelope.ts';
import { createScreenRecordingLiveHandle } from '../../screen-recording-live-handle.ts';
import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts';
Expand All @@ -13,6 +17,8 @@ import { createScreenRecordingAdmissionLedger } from '../screen-recording-admiss
import {
adoptStartedScreenRecording,
finishLiveScreenRecording,
finishRecoveredScreenRecording,
screenRecordingDurableResource,
} from '../screen-recording-session-resource.ts';
import { screenRecordingResourceStore } from '../screen-recording-resource-store.ts';
import type { DeviceInfo } from '@agent-device/kernel/device';
Expand Down Expand Up @@ -276,6 +282,115 @@ test('a record stop that fails after collecting resumes through the fence withou
expect(sessionStore.get(sessionName)?.screenRecording).toBeUndefined();
});

test.each([
{ route: 'startup recovery', proof: 'present' },
{ route: 'recovered stop', proof: 'present' },
{ route: 'recovered stop', proof: 'replaced' },
{ route: 'startup recovery', proof: 'absent' },
{ route: 'recovered stop', proof: 'absent' },
])(
'$route checks the manifest and export after native completion with $proof producer proof',
async ({ route, proof }) => {
const sessionsDir = mkdtempForTestSync('screen-recording-completed-recovery-');
const sessionDir = path.join(sessionsDir, 'recording');
const resourcePath = screenRecordingResourceStore.resolvePath(sessionDir);
const outPath = path.join(sessionDir, 'recording.mp4');
const fence = { token: 'recording-fence', generation: 1 };
const envelope = createDurableResourceEnvelope({
resourceKind: 'screen-recording',
sessionId: 'recording',
device: { id: device.id, family: 'android', kind: 'emulator' },
owner: localRuntimeOwner('android'),
fence,
lifecycle: 'open',
descriptor: { version: 1, body: { recordingId: 'recording-id' } },
metadata: { remoteCapturePath: outPath, remoteCaptureReservation: fence.token },
});
screenRecordingResourceStore.write(resourcePath, envelope);
// Android publishes native completion only after this sequence returns. Leave the host
// manifest open to model a daemon that exits before its durable finish transition.
const nativeCompletion = await withDurableCaptureResourceFence({
store: screenRecordingResourceStore,
resourcePath,
expected: fence,
onCompleted: () => {
throw new Error('Expected an open manifest');
},
run: (lease) =>
stopAndExportScreenRecording({
snapshot: {
backend: 'android',
outPath,
startedAt: 1,
scope: 'app',
showTouches: false,
recordOnlySession: false,
gestureEvents: [],
},
progress: proof === 'absent' ? undefined : createStopProgress(lease),
steps: {
stop: async () => ({ observation: { recorder: 'confirmed' } }),
collect: async () => {},
finalize: async () => {
fs.writeFileSync(outPath, 'producer export');
return { nativePathDisposition: 'retirable' };
},
discard: async () => {},
},
}),
});
const scope = {
signal: new AbortController().signal,
diagnostics: { emit: () => {} },
progress: { report: () => {} },
};
const acquireControl = async () => ({
reattach: async () => nativeCompletion,
cleanup: async () => ({ status: 'cleaned' as const }),
[Symbol.asyncDispose]: async () => {},
});
const stop = () => finishRecoveredScreenRecording({ resourcePath, scope, acquireControl });

if (proof === 'replaced') {
fs.writeFileSync(outPath, 'different bytes at the reserved path');
await expect(stop()).rejects.toThrow('Recording export does not match its stored proof.');
expect(screenRecordingResourceStore.read(resourcePath)).toMatchObject({
envelope: { lifecycle: 'open' },
});
return;
}
if (route === 'startup recovery') {
await expect(
screenRecordingDurableResource.recoverOne(
{ sessionsDir, scope, acquireControl },
resourcePath,
),
).resolves.toBe('recovered');
} else {
await expect(stop()).resolves.toEqual(nativeCompletion.result);
}
const settled = screenRecordingResourceStore.read(resourcePath);
expect(settled).toMatchObject({
envelope: {
lifecycle: 'completed',
metadata: {
completion: { outPath },
},
},
});
if (settled.status !== 'decoded') throw new Error('Expected the settled recording manifest');
if (proof === 'absent') {
expect(settled.envelope.metadata).not.toHaveProperty('remoteCaptureExport');
expect(fs.readFileSync(outPath, 'utf8')).toBe('producer export');
} else {
expect(settled.envelope.metadata?.remoteCaptureExport).toEqual({
completedAt: expect.any(Number),
identities: [expect.any(String)],
});
}
},
);

/**
* What session teardown does with a recording `record stop` already committed: the queued disposal had
* read the session's recording before that stop, so it still holds the handle and the fence the record
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down Expand Up @@ -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);
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@ export function listDurableCaptureStartConflicts<K extends string, C>(
);
}
if (existing.status !== 'decoded' || existing.envelope.lifecycle === 'completed') continue;
if (
existingPath !== resourcePath &&
definition.nativeCleanupSettled?.(existing.envelope.metadata)
)
continue;
const onStartDevice = sameDeviceIdentity(existing.envelope.device, startDevice);
if (onStartDevice || existingPath === resourcePath) {
records.push({ resourcePath: existingPath, envelope: existing.envelope, onStartDevice });
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,33 @@
import type fs from 'node:fs';
import { SCREEN_RECORDING_RESOURCE_KIND } from '@agent-device/contracts/screen-recording-runtime';
import type { JsonObject } from '@agent-device/contracts/client';
import { AppError, errorMessage } from '@agent-device/kernel/errors';
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
import { createDurableCaptureResourceStore } from '../durable-capture/index.ts';

export class RecordingProofIoError extends AppError {
readonly evidence?: JsonObject;

constructor(evidence?: JsonObject) {
super('COMMAND_FAILED', 'Recording ownership proof could not be read.', { retriable: true });
this.evidence = evidence;
}
}

export function recordingCheckpointError(error: unknown): RecordingProofIoError {
emitDiagnostic({
level: 'warn',
phase: 'screen_recording_proof_io_failed',
data: { error: errorMessage(error) },
});
return new RecordingProofIoError();
}

export const screenRecordingResourceStore = createDurableCaptureResourceStore({
resourceKind: SCREEN_RECORDING_RESOURCE_KIND,
fileName: 'screen-recording.resource.json',
displayName: 'screen recording',
checkpointError: recordingCheckpointError,
});

/**
Expand All @@ -13,3 +36,9 @@ export const screenRecordingResourceStore = createDurableCaptureResourceStore({
* `screen-recording-stop-recovery.ts`; both name this key so a replay cannot miss what was written.
*/
export const SCREEN_RECORDING_COMPLETION_METADATA_KEY = 'completion';

export function recordingExportFileIdentity(stat: fs.Stats | undefined): string | null {
return stat?.isFile()
? `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeMs}:${stat.ctimeMs}`
: null;
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,14 +18,18 @@ import type {
DurableCaptureRecoveryControl,
DurableCaptureSessionBinding,
} from '../durable-capture/index.ts';
import { withDurableCaptureResourceFence } from '../durable-capture/fence.ts';
import { createDurableCaptureResource } from './durable-capture-resource.ts';
import type { DurableCaptureFinishIntent } from './durable-capture-resource.ts';
import type { ScreenRecordingAdmissionLedger } from './screen-recording-admission-ledger.ts';
import {
SCREEN_RECORDING_COMPLETION_METADATA_KEY,
RecordingProofIoError,
screenRecordingResourceStore,
} from './screen-recording-resource-store.ts';

export { recordingExportFileIdentity } from './screen-recording-resource-store.ts';

export const screenRecordingDurableResource = createDurableCaptureResource<
'screen-recording',
ScreenRecordingLiveHandle,
Expand All @@ -34,7 +38,26 @@ export const screenRecordingDurableResource = createDurableCaptureResource<
resourceKind: 'screen-recording',
displayName: 'screen recording',
store: screenRecordingResourceStore,
completionMetadata: encodeScreenRecordingCompletionMetadata,
completionMetadata: async (result, metadata, progress) => ({
...encodeScreenRecordingCompletionMetadata(result),
...(typeof metadata?.remoteCapturePath === 'string' &&
typeof metadata.remoteCaptureReservation === 'string' &&
(progress !== undefined || metadata.remoteCaptureExport !== undefined)
? {
remoteCaptureExport: (await import('../recording/export-proof.ts')).verifyRecordingExport(
metadata.remoteCapturePath,
result,
metadata,
progress,
),
}
: {}),
}),
pendingCompletionMetadata: (result, error, completion) =>
error instanceof RecordingProofIoError
? (completion ?? { ...encodeScreenRecordingCompletionMetadata(result), ...error.evidence })
: undefined,
nativeCleanupSettled: screenRecordingNativeCleanupSettled,
// The manifest holds the whole stop response this kind wrote, so a caller that reaches the committed
// record is served the same export the first stop was answered with. That answer is a cold path: the
// record has to be read before anyone can be refused or served, so the reader is reached on demand
Expand All @@ -51,6 +74,13 @@ export const screenRecordingDurableResource = createDurableCaptureResource<
},
});

export function screenRecordingNativeCleanupSettled(metadata: JsonObject | undefined): boolean {
return (
metadata?.phase === 'export-proof-pending' &&
(metadata.cleanupStatus === 'cleaned' || metadata.cleanupStatus === 'already-missing')
);
}

export function adoptStartedScreenRecording(params: {
admissionLedger: ScreenRecordingAdmissionLedger;
binding: DurableCaptureSessionBinding<'screen-recording', ScreenRecordingLiveHandle>;
Expand All @@ -72,6 +102,41 @@ export function finishLiveScreenRecording(params: {
return screenRecordingDurableResource.finishLive(params);
}

export async function finishPendingScreenRecordingProof(
resourcePath: string,
expected: DurableResourceEnvelope<'screen-recording'>,
): Promise<DurableResourceEnvelope<'screen-recording'>> {
const { readStoredCompletion, unreadableRecordingProof } =
await import('./screen-recording-stop-recovery.ts');
return withDurableCaptureResourceFence({
store: screenRecordingResourceStore,
resourcePath,
expected: expected.fence,
onCompleted: ({ envelope }) => envelope,
run: async (lease) => {
const { metadata } = lease.envelope;
const completion = readStoredCompletion(metadata);
if (
!metadata ||
!screenRecordingNativeCleanupSettled(metadata) ||
!completion ||
typeof metadata.remoteCapturePath !== 'string' ||
metadata.remoteCaptureReservation !== expected.fence.token
)
throw unreadableRecordingProof();
const { verifyRecordingExport } = await import('../recording/export-proof.ts');
const proof = verifyRecordingExport(metadata.remoteCapturePath, completion, metadata);
return lease.transition('completed', {
metadata: {
...lease.envelope.metadata,
phase: 'completed',
remoteCaptureExport: proof,
},
});
},
});
}

export function encodeScreenRecordingCompletionMetadata(
completion: ScreenRecordingCompletion,
): JsonObject {
Expand Down
Loading
Loading