Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/orphaned-recording-start-recovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'agent-device': patch
---

Settle an orphaned screen recording record when a new recording starts. A device that restarted mid-recording could leave its record open with a pending cleanup after the daemon's own recovery ran while the device was still booting. No claim, daemon start or stop retried it, and `record stop` on the old session could not finish it, so every later `record start` on that device refused with `cleanup-unconfirmed` until someone removed the record by hand. `record start` now settles the records on its device that it would refuse on and whose session the daemon no longer holds: it finishes each one as its own `record stop` would, and runs the exact-owner recovery, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, still refuses, and the refusal now names that session. A record that another device left under the same session name is not recovered through the start device: the start refuses and names that device.
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ import type { LiveResourceHandle } from '@agent-device/contracts/durable-resourc
import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime';
import type { DeviceInfo } from '@agent-device/kernel/device';
import type { DurableCaptureAdmissionLedger } from './durable-capture-admission-ledger.ts';
import { createNextDurableCaptureFence } from './durable-capture-start-preflight.ts';
import {
createNextDurableCaptureFence,
listDurableCaptureStartConflicts,
} from './durable-capture-start-preflight.ts';
import { safeSessionName } from '@agent-device/host-kit/session-paths';
import type { DurableSessionResourceKind } from './durable-session-resource-kinds.ts';

Expand Down Expand Up @@ -101,5 +104,38 @@ export function createDurableCaptureResource<
recoverOne(params: SessionCaptureRecoveryParams<K, H, C>, resourcePath: string) {
return recoverDurableCaptureResource(recoveryParams(params), resourcePath);
},
/**
* Finishes the records on `device` that would refuse a start at `resourcePath` and whose
* session the daemon no longer holds, as their own stop would, and runs exact-owner recovery
* only for a record that cannot finish. A held session's record belongs to its own stop or
* close. A record on another device is never recovered through the start device. A record
* left open still refuses.
*/
async settleStartConflicts(
params: Omit<SessionCaptureRecoveryParams<K, H, C>, 'sessionsDir'> &
Readonly<{
resourcePath: string;
device: DeviceInfo;
holdsSession(sessionId: string): boolean;
}>,
): Promise<void> {
const { resourcePath, device, holdsSession, ...recovery } = params;
const conflicts = listDurableCaptureStartConflicts(definition, resourcePath, device);
for (const record of conflicts.records) {
if (!record.onStartDevice || holdsSession(record.envelope.sessionId)) continue;
try {
await finishRecoveredDurableCapture(definition, {
resourcePath: record.resourcePath,
scope: recovery.scope,
acquireControl: recovery.acquireControl,
});
} catch {
Comment thread
sylvain-abadie marked this conversation as resolved.
Resolved
await recoverDurableCaptureResource(
recoveryParams({ ...recovery, sessionsDir: conflicts.sessionsDir }),
record.resourcePath,
);
}
}
},
});
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import crypto from 'node:crypto';
import path from 'node:path';
import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope';
import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime';
import { deviceIdentity, deviceIdentityKey, type DeviceInfo } from '@agent-device/kernel/device';
import { deviceIdentity, sameDeviceIdentity, type DeviceInfo } from '@agent-device/kernel/device';
import { AppError } from '@agent-device/kernel/errors';
import {
capitalizeDurableCaptureLabel,
Expand All @@ -26,13 +27,36 @@ export function createNextDurableCaptureFence<K extends string, C>(
});
}

function assertNoConflictingManifest<K extends string, C>(
/**
* The open records that refuse a start, and the sessions directory they were listed from.
* `onStartDevice` is false only for a record at the start's own path that another device left.
*/
export type DurableCaptureStartConflicts<K extends string> = Readonly<{
sessionsDir: string;
records: readonly DurableCaptureStartConflict<K>[];
}>;

type DurableCaptureStartConflict<K extends string> = Readonly<{
resourcePath: string;
envelope: DurableResourceEnvelope<K>;
onStartDevice: boolean;
}>;

/**
* The records a start at `resourcePath` on `device` must wait for: every non-completed record
* at that path or on that device. The start refusal and the start-time settle both read this
* list, so what a start settles is exactly what it would refuse on. An unreattachable record
* throws, because no replacement capture is safe beside it.
*/
export function listDurableCaptureStartConflicts<K extends string, C>(
definition: DurableCaptureRecordDefinition<K, C>,
resourcePath: string,
device: DeviceInfo,
): void {
const selectedDeviceKey = deviceIdentityKey(deviceIdentity(device));
for (const existingPath of definition.store.list(path.dirname(path.dirname(resourcePath)))) {
): DurableCaptureStartConflicts<K> {
const startDevice = deviceIdentity(device);
const sessionsDir = path.dirname(path.dirname(resourcePath));
const records: DurableCaptureStartConflict<K>[] = [];
for (const existingPath of definition.store.list(sessionsDir)) {
const existing = definition.store.read(existingPath);
if (existing.status === 'unreattachable') {
throw new AppError(
Expand All @@ -45,22 +69,35 @@ function assertNoConflictingManifest<K extends string, C>(
},
);
}
if (
existing.status === 'decoded' &&
existing.envelope.lifecycle !== 'completed' &&
(existingPath === resourcePath ||
deviceIdentityKey(existing.envelope.device) === selectedDeviceKey)
) {
throw new AppError(
'COMMAND_FAILED',
`${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this device has not reached a confirmed terminal state`,
{
reason: 'cleanup-unconfirmed',
hint: `Retry exact-owner cleanup using the existing ${definition.displayName} manifest before starting a replacement.`,
},
);
if (existing.status !== 'decoded' || existing.envelope.lifecycle === 'completed') continue;
const onStartDevice = sameDeviceIdentity(existing.envelope.device, startDevice);
if (onStartDevice || existingPath === resourcePath) {
records.push({ resourcePath: existingPath, envelope: existing.envelope, onStartDevice });
}
}
return { sessionsDir, records };
}

function assertNoConflictingManifest<K extends string, C>(
definition: DurableCaptureRecordDefinition<K, C>,
resourcePath: string,
device: DeviceInfo,
): void {
const [conflict] = listDurableCaptureStartConflicts(definition, resourcePath, device).records;
if (!conflict) return;
const session = conflict.envelope.sessionId;
const otherDevice = conflict.onStartDevice ? undefined : conflict.envelope.device.id;
throw new AppError(
'COMMAND_FAILED',
`${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this ${otherDevice ? 'session' : 'device'} has not reached a confirmed terminal state`,
{
reason: 'cleanup-unconfirmed',
session,
hint: otherDevice
? `The open ${definition.displayName} record of session "${session}" is on device "${otherDevice}". Stop it in that session, or start this one under another session name.`
: `The open ${definition.displayName} record belongs to session "${session}". Stop or close that session, or retry once its device is reachable; exact-owner cleanup must confirm it before a replacement starts.`,
},
);
}

function articleFor(value: string): 'a' | 'an' {
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/recording/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,7 +127,7 @@ export const recordCommandFacet = defineCommandFacet({
text: {
summary: 'Start or stop screen recording',
cliDetail:
'The default --scope app requires an active app session from open <app>; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; only closing the session disposes them. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet <video.mp4> [--out <sheet.png>] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.',
'The default --scope app requires an active app session from open <app>; use --scope device/system to explicitly request whole-screen recording where the selected backend supports it. Android record start publishes a durable device manifest, recordings longer than the 180s adb screenrecord limit are returned as multiple MP4 chunks while the daemon stays alive, and daemon-restart recovery uses only manifest-owned chunks. Android screenrecord encodes a frame only when the screen changes, so a clip can end at the last frame the recorder encoded instead of at record stop; durationMs is host wall clock from record start until the export finished, and capturedDurationMs reports the video timeline when it can be measured, with a warning naming how much of the window that video covers. An Android manifest left by an unreachable recording is retired on the next start once its recorders are proven gone; one still owned refuses with non-retriable DEVICE_IN_USE and reason native_recovery_evidence_open naming the session to run record stop for, and a recorder that is still writing an artifact refuses with DEVICE_IN_USE and reason native_recording_artifact_claimed, which clears itself once that recorder ends at the 180s limit. HarmonyOS supports whole-screen recording on physical devices only: use --scope device/system; --fps, --quality, and --hide-touches are unsupported. Use --quality to choose medium or high export quality on supported backends. The touch overlay renders at most 30 frames a second, or at --fps when lower; a lower --fps makes record stop faster on a long recording, and an overlay export that runs past its budget returns the raw video with an overlayWarning. An iOS simulator host recording lock returns non-retriable DEVICE_IN_USE with reason apple_simulator_recording_busy. Stop the recording in its owning session; if a dead recorder left the host locked, ask the host operator to restart the CoreSimulator stream service. On any backend, record start first settles the open recording records on its device that it would refuse on and whose session this daemon no longer holds: it finishes each one as its own record stop would, so the export lands at the output path of that recording and a later record stop in that session returns it, and runs the exact-owner recovery a daemon restart runs, which discards what that recording left, only for a record that cannot finish. A record it cannot confirm cleaned, or one whose session is still held, refuses the start with reason cleanup-unconfirmed and names that session: stop or close it, then retry. A record that another device left under the same session name is never settled from this device: the start refuses and names that device, so stop it in that session or record under another session name. A record stop that cannot produce its export keeps what a retry reads back — on Android the device-side artifact and the native manifest — leaves the recording manifest of that session open, and returns its own error, so retry record stop in that session; while this daemon holds that session, only closing it disposes them, and once it does not, the next record start on that device settles them as described above. Every stopped recording also reports what became of its recorder and of the file that recorder writes to: recorder is confirmed, or lost when the session holding it died, and nativePathDisposition is retirable while that file still owes a removal or retired once its removal was verified. Both are optional disclosures, not failures; ADR 0024 declares further states (unconfirmed, pending) for the steps that gain those probes, and no stop reports them yet. record contact-sheet <video.mp4> [--out <sheet.png>] is a local report over a file you already exported: it decodes frames out of that MP4 and writes one PNG holding the cells where the screen visibly changed, each labeled with its elapsed time on the clip timeline. It needs no session and no device, rebuilds any past recording, and works for every backend that exports MP4; a WebM recording is refused with reason contact_sheet_container_unsupported. The sample grid is bounded and spread across the whole clip, so it reports coverage rather than a review: a flash that opens and closes entirely between two sample times is not in the sheet, which is why the result also reports how many times it sampled and how many frames came back. Frame decoding is Apple AVFoundation tooling, so the command runs only on macOS hosts and refuses elsewhere with reason contact_sheet_unsupported_host.',
},
metadata: recordCommandMetadata,
run: (client, input) => client.recording.record(input as RecordOptions),
Expand Down
Loading
Loading