Skip to content
Open
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
16 changes: 10 additions & 6 deletions docs/adr/0024-screen-recording-provable-signal.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

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
@@ -1,3 +1,12 @@
import fs from 'node:fs';
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';
Expand Down Expand Up @@ -35,6 +44,7 @@ export const screenRecordingDurableResource = createDurableCaptureResource<
displayName: 'screen recording',
store: screenRecordingResourceStore,
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
Expand Down Expand Up @@ -72,6 +82,86 @@ export function finishLiveScreenRecording(params: {
return screenRecordingDurableResource.finishLive(params);
}

type RecordingExportProof = Readonly<{ completedAt: number; identities: string[] }>;
const liveExportProofs = new WeakMap<
LiveResourceHandle<ScreenRecordingCompletion>,
RecordingExportProof | null
>();

async function finishRecordingExport(
handle: LiveResourceHandle<ScreenRecordingCompletion>,
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 (readStopCheckpoints(progress.learned).exportPath && !liveExportProofs.has(handle)) {
liveExportProofs.set(handle, null);
}
const readExportProof = (
outPath: string,
{ chunks, telemetryPath }: ScreenRecordingFinalization,
): RecordingExportProof | null => {
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] : []),
];
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) {
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);
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 };
if (!liveExportProofs.has(handle)) {
liveExportProofs.set(handle, readExportProof(outcome.result.outPath, outcome.result));
}
const proof = liveExportProofs.get(handle);
return { outcome, ...(proof ? { metadata: { remoteCaptureExport: proof } } : {}) };
}

export function encodeScreenRecordingCompletionMetadata(
completion: ScreenRecordingCompletion,
): JsonObject {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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 = [
Expand All @@ -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)
Comment thread
thymikee marked this conversation as resolved.
Resolved
: readReplayableStoredCompletion(metadata);
if (completion === undefined) {
emitDiagnostic({
level: 'warn',
Expand All @@ -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. */
Expand All @@ -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'>;
Expand Down Expand Up @@ -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 (
Expand All @@ -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. */
Expand Down
10 changes: 10 additions & 0 deletions packages/capture-kit/src/durable-capture/definition.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -57,6 +62,11 @@ export type DurableCaptureRecordDefinition<K extends string, C> = Readonly<{
displayName: string;
store: DurableCaptureResourceStore<K>;
completionMetadata(result: C): JsonObject;
/** Runs only for the live producer. Its metadata is written with the terminal result. */
finishLive?(
handle: LiveResourceHandle<C>,
progress: DurableCaptureProgress,
): Promise<{ outcome: FinishOutcome<C>; metadata?: JsonObject }>;
/**
* The completion this kind stored in a record that is already committed, or nothing it can serve.
*
Expand Down
21 changes: 13 additions & 8 deletions packages/capture-kit/src/durable-capture/transitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export async function finishLiveDurableCapture<
fence: active.envelope.fence,
resourcePath,
intent: params.intent,
producer: true,
confirmedMissing: params.confirmedMissing,
onCleanupPending: () => {
cleanupPending = true;
Expand Down Expand Up @@ -75,6 +76,7 @@ export async function finishDurableCaptureHandle<
fence: ResourceOwnershipFence;
resourcePath: string;
intent: DurableCaptureFinishIntent;
producer?: true;
confirmedMissing?: () => boolean;
onCleanupPending?(outcome: Extract<CleanupOutcome, { status: 'cleanup-pending' }>): void;
},
Expand Down Expand Up @@ -123,20 +125,21 @@ export async function finishDurableCaptureHandle<
settleIfMissing(lease);
markCompletingDurableCapture(lease);
const progress = createStopProgress(lease);
let finishOutcome: FinishOutcome<C>;
let finished: { outcome: FinishOutcome<C>; 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') {
transitionFinishOutcome(definition, lease, finishOutcome);
return finishOutcome.result;
}
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;
Expand Down Expand Up @@ -350,12 +353,14 @@ export function transitionFinishOutcome<K extends string, C>(
definition: DurableCaptureRecordDefinition<K, C>,
lease: DurableCaptureOpenResourceFenceLease<K>,
outcome: FinishOutcome<C>,
producerMetadata?: JsonObject,
): void {
if (outcome.status === 'completed') {
lease.transition('completed', {
metadata: {
...(lease.envelope.metadata ?? {}),
...definition.completionMetadata(outcome.result),
...producerMetadata,
phase: 'completed',
},
});
Expand Down
15 changes: 15 additions & 0 deletions packages/capture-kit/src/recording/output-path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'}`,
);
}
2 changes: 1 addition & 1 deletion packages/command-surface/src/recording/output-schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export const RECORDING_COMMAND_OUTPUT_SCHEMAS = {
activeSessionApp: looseObjectSchema(),
showTouches: booleanSchema(),
},
['recording', 'outPath', 'sessionStateDir', 'showTouches'],
['recording', 'outPath', 'showTouches'],
),
objectSchema(
{
Expand Down
2 changes: 1 addition & 1 deletion packages/contracts/src/recording.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export type RecordingAppIdentity = {
export type RecordingStartCommandResult = {
recording: 'started';
outPath: string;
sessionStateDir: string;
sessionStateDir?: string;
recordingBackend?: string;
recordingScope?: RecordingScope;
recordOnlySession?: boolean;
Expand Down
Loading
Loading