From d9ef23d18bcc2f4258a5d6556891389185377cf6 Mon Sep 17 00:00:00 2001 From: Sylvain Abadie <5574617+sylvain-abadie@users.noreply.github.com> Date: Wed, 4 Nov 2026 06:51:07 -0800 Subject: [PATCH 1/5] fix(daemon): settle orphaned recording records when a recording starts A device that restarts mid-recording can leave its screen recording record open with a pending cleanup when the daemon's own recovery ran while the device was still booting. Only daemon start and a device claim reconciliation retried it, and a recovered record stop cannot finish it without a playable artifact, so once the claim was gone every later record start on that device was refused with cleanup-unconfirmed. The start preflight now lists the records it refuses on, and record start runs the exact-owner recovery for the ones whose session the daemon no longer holds, so the settle set cannot drift from the refusal. A recovered stop and this settle share one recovery-control helper. A record whose cleanup cannot be confirmed, or whose session is still held, still refuses the start, and the refusal names that session. --- .../orphaned-recording-start-recovery.md | 5 + .../durable-capture-resource.ts | 28 +++- .../durable-capture-start-preflight.ts | 50 ++++-- .../command-surface/src/recording/index.ts | 2 +- .../record-runtime-orphan-recovery.test.ts | 145 ++++++++++++++++++ .../__tests__/record-runtime.fixtures.ts | 4 +- .../src/sessions/handlers/record-runtime.ts | 50 ++++-- 7 files changed, 259 insertions(+), 25 deletions(-) create mode 100644 .changeset/orphaned-recording-start-recovery.md create mode 100644 packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts diff --git a/.changeset/orphaned-recording-start-recovery.md b/.changeset/orphaned-recording-start-recovery.md new file mode 100644 index 0000000000..250d601c1d --- /dev/null +++ b/.changeset/orphaned-recording-start-recovery.md @@ -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 runs the exact-owner recovery for the records it would refuse on whose session the daemon no longer holds. A record it cannot confirm cleaned, or one whose session is still held, still refuses, and the refusal now names that session. diff --git a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index 8a9800e69c..33411dc070 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts @@ -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'; @@ -101,5 +104,28 @@ export function createDurableCaptureResource< recoverOne(params: SessionCaptureRecoveryParams, resourcePath: string) { return recoverDurableCaptureResource(recoveryParams(params), resourcePath); }, + /** + * Runs exact-owner recovery for the records that would refuse a start at `resourcePath` on + * `device` and whose session the daemon no longer holds. A held session's record belongs to + * its own stop or close; a record recovery cannot confirm stays open and still refuses. + */ + async settleStartConflicts( + params: Omit, 'sessionsDir'> & + Readonly<{ + resourcePath: string; + device: DeviceInfo; + holdsSession(sessionId: string): boolean; + }>, + ): Promise { + const { resourcePath, device, holdsSession, ...recovery } = params; + const conflicts = listDurableCaptureStartConflicts(definition, resourcePath, device); + for (const record of conflicts.records) { + if (holdsSession(record.envelope.sessionId)) continue; + await recoverDurableCaptureResource( + recoveryParams({ ...recovery, sessionsDir: conflicts.sessionsDir }), + record.resourcePath, + ); + } + }, }); } diff --git a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts index 65734602f8..7313b54338 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts @@ -1,5 +1,6 @@ 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 { AppError } from '@agent-device/kernel/errors'; @@ -26,13 +27,27 @@ export function createNextDurableCaptureFence( }); } -function assertNoConflictingManifest( +/** The open records that refuse a start, and the sessions directory they were listed from. */ +export type DurableCaptureStartConflicts = Readonly<{ + sessionsDir: string; + records: readonly Readonly<{ resourcePath: string; envelope: DurableResourceEnvelope }>[]; +}>; + +/** + * 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( definition: DurableCaptureRecordDefinition, resourcePath: string, device: DeviceInfo, -): void { +): DurableCaptureStartConflicts { const selectedDeviceKey = deviceIdentityKey(deviceIdentity(device)); - for (const existingPath of definition.store.list(path.dirname(path.dirname(resourcePath)))) { + const sessionsDir = path.dirname(path.dirname(resourcePath)); + const records: { resourcePath: string; envelope: DurableResourceEnvelope }[] = []; + for (const existingPath of definition.store.list(sessionsDir)) { const existing = definition.store.read(existingPath); if (existing.status === 'unreattachable') { throw new AppError( @@ -51,16 +66,29 @@ function assertNoConflictingManifest( (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.`, - }, - ); + records.push({ resourcePath: existingPath, envelope: existing.envelope }); } } + return { sessionsDir, records }; +} + +function assertNoConflictingManifest( + definition: DurableCaptureRecordDefinition, + resourcePath: string, + device: DeviceInfo, +): void { + const [conflict] = listDurableCaptureStartConflicts(definition, resourcePath, device).records; + if (!conflict) return; + const session = conflict.envelope.sessionId; + 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', + session, + hint: `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' { diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index 435a6f4f5f..c74265e923 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -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 ; 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 [--out ] 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 ; 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 it would refuse on whose session this daemon no longer holds, with the exact-owner recovery a daemon restart runs. 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 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 [--out ] 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), diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts new file mode 100644 index 0000000000..a8c0ec45d3 --- /dev/null +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts @@ -0,0 +1,145 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test } from 'vitest'; +import { mkdtempForTestSync } from '@agent-device/test-kit'; +import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; +import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; +import { localRuntimeOwner } from '@agent-device/contracts/platform-runtime'; +import { deviceIdentity } from '@agent-device/kernel/device'; +import type { SessionState } from '../../../core/session-state.ts'; +import { makeRecordRuntimeHarness, recordingResourcePath } from './record-runtime.fixtures.ts'; + +// Two sessions share one device, so the second start meets the first one's record. +function startOnSecondSession(harness: ReturnType) { + const second: SessionState = { ...harness.session, name: 'second' }; + harness.sessionStore.publish('second', second); + const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-output-'), 'second.mp4'); + return harness.run(['start', outPath], undefined, undefined, undefined, 'second'); +} + +function recordLifecycle( + harness: ReturnType, + sessionName = harness.sessionName, +): string { + const record = screenRecordingResourceStore.read( + recordingResourcePath(harness.sessionStore, sessionName), + ); + if (record.status !== 'decoded') throw new Error('Expected a decoded recording record'); + return record.envelope.lifecycle; +} + +async function leaveOrphanedRecord(harness: ReturnType) { + const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-first-'), 'first.mp4'); + await harness.run(['start', outPath]); + // The daemon forgets the session while its record stays open: the recorder died with its device + // and no claim, startup recovery or stop is left to settle it. + const ref = harness.sessionStore.lookup(harness.sessionName); + if (!ref) throw new Error('Expected the live recording session'); + harness.sessionStore.retire(ref); + expect(recordLifecycle(harness)).toBe('open'); +} + +test('record start settles an orphaned recording record on its device instead of refusing', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-settle-', { + runtime: { reattachActive: true }, + }); + await leaveOrphanedRecord(harness); + + const response = await startOnSecondSession(harness); + + expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); + expect(recordLifecycle(harness)).toBe('completed'); + expect(harness.runtime.reattach).toHaveBeenCalledOnce(); + expect(harness.runtime.forceCleanup).toHaveBeenCalledOnce(); +}); + +test('record start completes an orphaned record whose recording is gone from its device', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-missing-'); + await leaveOrphanedRecord(harness); + + const response = await startOnSecondSession(harness); + + expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); + expect(recordLifecycle(harness)).toBe('completed'); + // Reattach finds no recording, so nothing is left to clean. + expect(harness.runtime.reattach).toHaveBeenCalledOnce(); +}); + +test('record start leaves an orphaned record on another device open', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-elsewhere-', { + runtime: { reattachActive: true }, + }); + const elsewhere = recordingResourcePath(harness.sessionStore, 'elsewhere'); + fs.mkdirSync(path.dirname(elsewhere), { recursive: true }); + screenRecordingResourceStore.write( + elsewhere, + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId: 'elsewhere', + device: deviceIdentity({ + platform: 'android', + id: 'emulator-5556', + kind: 'emulator', + }), + owner: localRuntimeOwner('android'), + fence: { token: 'elsewhere', generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: { recordingId: 'elsewhere' } }, + }), + ); + const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-elsewhere-out-'), 'a.mp4'); + + const response = await harness.run(['start', outPath]); + + expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); + expect(recordLifecycle(harness, 'elsewhere')).toBe('open'); + expect(harness.runtime.reattach).not.toHaveBeenCalled(); +}); + +test('record start still refuses when the orphaned record cannot be confirmed cleaned', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-pending-', { + runtime: { + reattachActive: true, + cleanup: { status: 'cleanup-pending', reason: 'transport-failed' }, + }, + }); + await leaveOrphanedRecord(harness); + + const response = await startOnSecondSession(harness); + + expect(response).toMatchObject({ + ok: false, + error: { details: { reason: 'cleanup-unconfirmed' } }, + }); + expect(recordLifecycle(harness)).toBe('open'); + expect(harness.runtime.start).toHaveBeenCalledOnce(); +}); + +// A held session's record belongs to its own stop or close: with its live recording, and after a +// record stop that could not produce its export kept the record open for a retry. +test.for([ + { held: 'the live recording', dropBinding: false }, + { held: 'the session after its recording binding is gone', dropBinding: true }, +])('record start leaves a record alone while its session holds $held', async ({ dropBinding }) => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-held-', { + runtime: { reattachActive: true }, + }); + const firstOut = path.join(mkdtempForTestSync('record-runtime-orphan-held-first-'), 'first.mp4'); + await harness.run(['start', firstOut]); + if (dropBinding) { + const ref = harness.sessionStore.lookup(harness.sessionName); + if (!ref) throw new Error('Expected the recording session'); + harness.sessionStore.update(ref, { screenRecording: undefined }); + } + + const response = await startOnSecondSession(harness); + + // The refusal names the session whose stop or close owns the record. + expect(response).toMatchObject({ + ok: false, + error: { details: { reason: 'cleanup-unconfirmed', session: harness.sessionName } }, + }); + expect(recordLifecycle(harness)).toBe('open'); + expect(harness.runtime.reattach).not.toHaveBeenCalled(); + expect(harness.runtime.forceCleanup).not.toHaveBeenCalled(); +}); 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 36255f1445..585b0a0661 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime.fixtures.ts @@ -90,13 +90,15 @@ export function makeRecordRuntimeHarness( meta?: DaemonRequest['meta'], flags?: DaemonRequest['flags'], internal?: DaemonRequest['internal'], + asSessionName: string = sessionName, ) => handleRecordCommand({ platformServices: daemonPlatformServicesFixture(), ...common, + sessionName: asSessionName, req: { token: 'token', - session: sessionName, + session: asSessionName, command: 'record', positionals, flags: flags ?? {}, diff --git a/packages/daemon/src/sessions/handlers/record-runtime.ts b/packages/daemon/src/sessions/handlers/record-runtime.ts index ba22819114..2664f5a2b2 100644 --- a/packages/daemon/src/sessions/handlers/record-runtime.ts +++ b/packages/daemon/src/sessions/handlers/record-runtime.ts @@ -1,6 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; 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, @@ -254,6 +255,18 @@ async function startRecording( const startFact = admission.facts.screenRecordingStart; if (!startFact.available) return buildRecordingUnsupportedResponse(startFact); const runtime = await params.bindDevice(session.device, use); + // A recording that died with its device can leave a record that no claim or daemon start + // retries. Settle the records this start would refuse on, unless their session is still held. + await screenRecordingDurableResource.settleStartConflicts({ + resourcePath: screenRecordingDurableResource.resourcePath( + params.sessionStore, + params.sessionName, + ), + device: session.device, + holdsSession: (sessionId) => params.sessionStore.lookup(sessionId) !== undefined, + scope: params.requestScope, + acquireControl: exactRecoveryControl(params, session.device, false), + }); const { fence, outputPaths } = prepareRecordingStart(params, session); binding.assertAdoptable(); const started = await runtime.operations.screenRecordingStart( @@ -503,21 +516,36 @@ async function finishRecovered( const completion = await finishRecoveredScreenRecording({ resourcePath: recovery.resourcePath, scope: params.requestScope, - acquireControl: async (envelope, recoveryScope) => { - const runtime = await params.bindExactDevice( - session.device, - envelope.owner, - envelope.fence, - screenRecordingRecoveryUse, - recoveryScope, - ); - if (needsReadiness) await ensureBoundDeviceReady(runtime, params.platformServices); - return createScreenRecordingRecoveryControl({ runtime, dispose: async () => {} }); - }, + acquireControl: exactRecoveryControl(params, session.device, needsReadiness), }); return { completion, recordsSessionAction: true }; } +/** + * Recovery control bound to a record's own owner and fence, for a recording whose live handle this + * daemon no longer holds. A recovered stop and the start-time settle share it. + */ +function exactRecoveryControl( + params: RecordRuntimeHandlerParams, + device: SessionState['device'], + needsReadiness: boolean, +) { + return async ( + envelope: DurableResourceEnvelope<'screen-recording'>, + recoveryScope: PlatformRequestScope, + ) => { + const runtime = await params.bindExactDevice( + device, + envelope.owner, + envelope.fence, + screenRecordingRecoveryUse, + recoveryScope, + ); + if (needsReadiness) await ensureBoundDeviceReady(runtime, params.platformServices); + return createScreenRecordingRecoveryControl({ runtime, dispose: async () => {} }); + }; +} + function createRecordOnlySession( params: Pick, device: SessionState['device'], From b18cb9fed511239bacd53d359fd8fcb2529a4a55 Mon Sep 17 00:00:00 2001 From: Sylvain Abadie <5574617+sylvain-abadie@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:12:54 -0800 Subject: [PATCH 2/5] fix(capture-kit): keep the start-time settle on the start device A start refuses on a non-completed record at its own session path even when that record names another device. The settle recovered that record through the start device, so a recording still running on the other device could have its only record completed from the wrong one. The settle now recovers only records on the start device. A record that another device left under the same session name still refuses, and the refusal names that device: stop it in that session, or start under another session name. --- .../orphaned-recording-start-recovery.md | 2 +- .../durable-capture-resource.ts | 11 ++- .../durable-capture-start-preflight.ts | 10 ++- .../command-surface/src/recording/index.ts | 2 +- .../record-runtime-orphan-recovery.test.ts | 78 ++++++++++++++----- 5 files changed, 76 insertions(+), 27 deletions(-) diff --git a/.changeset/orphaned-recording-start-recovery.md b/.changeset/orphaned-recording-start-recovery.md index 250d601c1d..9a3ad38450 100644 --- a/.changeset/orphaned-recording-start-recovery.md +++ b/.changeset/orphaned-recording-start-recovery.md @@ -2,4 +2,4 @@ '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 runs the exact-owner recovery for the records it would refuse on whose session the daemon no longer holds. A record it cannot confirm cleaned, or one whose session is still held, still refuses, and the refusal now names that session. +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 runs the exact-owner recovery for the records on its device that it would refuse on and whose session the daemon no longer holds. 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. diff --git a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index 33411dc070..3bc88c627a 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts @@ -15,7 +15,7 @@ import { } from '../durable-capture/index.ts'; import type { LiveResourceHandle } from '@agent-device/contracts/durable-resource'; import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime'; -import type { DeviceInfo } from '@agent-device/kernel/device'; +import { deviceIdentity, deviceIdentityKey, type DeviceInfo } from '@agent-device/kernel/device'; import type { DurableCaptureAdmissionLedger } from './durable-capture-admission-ledger.ts'; import { createNextDurableCaptureFence, @@ -105,9 +105,10 @@ export function createDurableCaptureResource< return recoverDurableCaptureResource(recoveryParams(params), resourcePath); }, /** - * Runs exact-owner recovery for the records that would refuse a start at `resourcePath` on - * `device` and whose session the daemon no longer holds. A held session's record belongs to - * its own stop or close; a record recovery cannot confirm stays open and still refuses. + * Runs exact-owner recovery for the records on `device` that would refuse a start at + * `resourcePath` and whose session the daemon no longer holds. 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, 'sessionsDir'> & @@ -119,8 +120,10 @@ export function createDurableCaptureResource< ): Promise { const { resourcePath, device, holdsSession, ...recovery } = params; const conflicts = listDurableCaptureStartConflicts(definition, resourcePath, device); + const deviceKey = deviceIdentityKey(deviceIdentity(device)); for (const record of conflicts.records) { if (holdsSession(record.envelope.sessionId)) continue; + if (deviceIdentityKey(record.envelope.device) !== deviceKey) continue; await recoverDurableCaptureResource( recoveryParams({ ...recovery, sessionsDir: conflicts.sessionsDir }), record.resourcePath, diff --git a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts index 7313b54338..ce5c76816c 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts @@ -80,13 +80,19 @@ function assertNoConflictingManifest( const [conflict] = listDurableCaptureStartConflicts(definition, resourcePath, device).records; if (!conflict) return; const session = conflict.envelope.sessionId; + const otherDevice = + deviceIdentityKey(conflict.envelope.device) === deviceIdentityKey(deviceIdentity(device)) + ? undefined + : conflict.envelope.device.id; throw new AppError( 'COMMAND_FAILED', - `${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this device has not reached a confirmed terminal state`, + `${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this ${otherDevice ? 'session' : 'device'} has not reached a confirmed terminal state`, { reason: 'cleanup-unconfirmed', session, - hint: `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.`, + 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.`, }, ); } diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index c74265e923..8ddf26e51e 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -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 ; 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 it would refuse on whose session this daemon no longer holds, with the exact-owner recovery a daemon restart runs. 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 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 [--out ] 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 ; 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, with the exact-owner recovery a daemon restart runs. 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; 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 [--out ] 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), diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts index a8c0ec45d3..d0762bf6e6 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts @@ -1,6 +1,6 @@ import fs from 'node:fs'; import path from 'node:path'; -import { expect, test } from 'vitest'; +import { expect, test, vi } from 'vitest'; import { mkdtempForTestSync } from '@agent-device/test-kit'; import { createDurableResourceEnvelope } from '@agent-device/capture-kit'; import { screenRecordingResourceStore } from '@agent-device/capture-kit/screen-recording-resource-store'; @@ -9,6 +9,16 @@ import { deviceIdentity } from '@agent-device/kernel/device'; import type { SessionState } from '../../../core/session-state.ts'; import { makeRecordRuntimeHarness, recordingResourcePath } from './record-runtime.fixtures.ts'; +// A record-only start selects the harness device. +vi.mock('@agent-device/device-selection/dispatch-resolve', () => ({ + resolveTargetDevice: async () => ({ + platform: 'android', + id: 'emulator-5554', + name: 'Pixel', + kind: 'emulator', + }), +})); + // Two sessions share one device, so the second start meets the first one's record. function startOnSecondSession(harness: ReturnType) { const second: SessionState = { ...harness.session, name: 'second' }; @@ -28,6 +38,27 @@ function recordLifecycle( return record.envelope.lifecycle; } +// An open record that a recording on another device left under `sessionId`. +function writeRecordOnOtherDevice( + harness: ReturnType, + sessionId: string, +) { + const resourcePath = recordingResourcePath(harness.sessionStore, sessionId); + fs.mkdirSync(path.dirname(resourcePath), { recursive: true }); + screenRecordingResourceStore.write( + resourcePath, + createDurableResourceEnvelope({ + resourceKind: 'screen-recording', + sessionId, + device: deviceIdentity({ platform: 'android', id: 'emulator-5556', kind: 'emulator' }), + owner: localRuntimeOwner('android'), + fence: { token: sessionId, generation: 1 }, + lifecycle: 'open', + descriptor: { version: 1, body: { recordingId: sessionId } }, + }), + ); +} + async function leaveOrphanedRecord(harness: ReturnType) { const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-first-'), 'first.mp4'); await harness.run(['start', outPath]); @@ -69,24 +100,7 @@ test('record start leaves an orphaned record on another device open', async () = const harness = makeRecordRuntimeHarness('record-runtime-orphan-elsewhere-', { runtime: { reattachActive: true }, }); - const elsewhere = recordingResourcePath(harness.sessionStore, 'elsewhere'); - fs.mkdirSync(path.dirname(elsewhere), { recursive: true }); - screenRecordingResourceStore.write( - elsewhere, - createDurableResourceEnvelope({ - resourceKind: 'screen-recording', - sessionId: 'elsewhere', - device: deviceIdentity({ - platform: 'android', - id: 'emulator-5556', - kind: 'emulator', - }), - owner: localRuntimeOwner('android'), - fence: { token: 'elsewhere', generation: 1 }, - lifecycle: 'open', - descriptor: { version: 1, body: { recordingId: 'elsewhere' } }, - }), - ); + writeRecordOnOtherDevice(harness, 'elsewhere'); const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-elsewhere-out-'), 'a.mp4'); const response = await harness.run(['start', outPath]); @@ -96,6 +110,32 @@ test('record start leaves an orphaned record on another device open', async () = expect(harness.runtime.reattach).not.toHaveBeenCalled(); }); +test('record start refuses on a record of its own session that another device left open', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-same-path-', { + runtime: { reattachActive: true }, + }); + const ref = harness.sessionStore.lookup(harness.sessionName); + if (!ref) throw new Error('Expected the harness session'); + harness.sessionStore.retire(ref); + writeRecordOnOtherDevice(harness, harness.sessionName); + const outPath = path.join(mkdtempForTestSync('record-runtime-orphan-same-path-out-'), 'a.mp4'); + + const response = await harness.run(['start', outPath], undefined, { + recordingScope: 'device', + serial: 'emulator-5554', + }); + + expect(response).toMatchObject({ + ok: false, + error: { + hint: expect.stringContaining('"emulator-5556"'), + details: { reason: 'cleanup-unconfirmed', session: harness.sessionName }, + }, + }); + expect(recordLifecycle(harness)).toBe('open'); + expect(harness.runtime.reattach).not.toHaveBeenCalled(); +}); + test('record start still refuses when the orphaned record cannot be confirmed cleaned', async () => { const harness = makeRecordRuntimeHarness('record-runtime-orphan-pending-', { runtime: { From 570661e621102aea01ff058892f6de09df9b3f64 Mon Sep 17 00:00:00 2001 From: Sylvain Abadie <5574617+sylvain-abadie@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:07:26 -0800 Subject: [PATCH 3/5] fix(capture-kit): finish an orphaned record before a start cleans it The start-time settle ran exact-owner recovery, which force-cleans any capture it can reattach. On an iOS simulator that discarded a video a record stop in the old session could still export, so a new start on the same simulator lost the earlier recording. The settle now does what the record's own stop would: it finishes the record, so the export lands at its output path and a later record stop in that session returns it. Only a record that cannot finish, such as an Android recording whose device restarted, falls back to exact-owner recovery. --- .../orphaned-recording-start-recovery.md | 2 +- .../durable-capture-resource.ts | 25 +++++++++++++------ .../command-surface/src/recording/index.ts | 2 +- .../record-runtime-orphan-recovery.test.ts | 23 +++++++++++++---- 4 files changed, 37 insertions(+), 15 deletions(-) diff --git a/.changeset/orphaned-recording-start-recovery.md b/.changeset/orphaned-recording-start-recovery.md index 9a3ad38450..36de2f8367 100644 --- a/.changeset/orphaned-recording-start-recovery.md +++ b/.changeset/orphaned-recording-start-recovery.md @@ -2,4 +2,4 @@ '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 runs the exact-owner recovery for the records on its device that it would refuse on and whose session the daemon no longer holds. 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. +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 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. diff --git a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index 3bc88c627a..aedba860ed 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts @@ -105,10 +105,11 @@ export function createDurableCaptureResource< return recoverDurableCaptureResource(recoveryParams(params), resourcePath); }, /** - * Runs exact-owner recovery for the records on `device` that would refuse a start at - * `resourcePath` and whose session the daemon no longer holds. 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. + * 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, 'sessionsDir'> & @@ -124,10 +125,18 @@ export function createDurableCaptureResource< for (const record of conflicts.records) { if (holdsSession(record.envelope.sessionId)) continue; if (deviceIdentityKey(record.envelope.device) !== deviceKey) continue; - await recoverDurableCaptureResource( - recoveryParams({ ...recovery, sessionsDir: conflicts.sessionsDir }), - record.resourcePath, - ); + try { + await finishRecoveredDurableCapture(definition, { + resourcePath: record.resourcePath, + scope: recovery.scope, + acquireControl: recovery.acquireControl, + }); + } catch { + await recoverDurableCaptureResource( + recoveryParams({ ...recovery, sessionsDir: conflicts.sessionsDir }), + record.resourcePath, + ); + } } }, }); diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index 8ddf26e51e..b0ddf6b890 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -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 ; 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, with the exact-owner recovery a daemon restart runs. 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; 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 [--out ] 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 ; 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 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; 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 [--out ] 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), diff --git a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts index d0762bf6e6..894313af7d 100644 --- a/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts @@ -70,8 +70,9 @@ async function leaveOrphanedRecord(harness: ReturnType { - const harness = makeRecordRuntimeHarness('record-runtime-orphan-settle-', { +// The start does what the record's own stop would: a recording that can still export is finished. +test('record start finishes an orphaned recording record on its device instead of refusing', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-finish-', { runtime: { reattachActive: true }, }); await leaveOrphanedRecord(harness); @@ -80,7 +81,20 @@ test('record start settles an orphaned recording record on its device instead of expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); expect(recordLifecycle(harness)).toBe('completed'); - expect(harness.runtime.reattach).toHaveBeenCalledOnce(); + expect(harness.runtime.finish).toHaveBeenCalledOnce(); + expect(harness.runtime.forceCleanup).not.toHaveBeenCalled(); +}); + +test('record start cleans an orphaned recording record that cannot finish', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-settle-', { + runtime: { reattachActive: true, finishError: new Error('artifact is not stable') }, + }); + await leaveOrphanedRecord(harness); + + const response = await startOnSecondSession(harness); + + expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); + expect(recordLifecycle(harness)).toBe('completed'); expect(harness.runtime.forceCleanup).toHaveBeenCalledOnce(); }); @@ -92,8 +106,6 @@ test('record start completes an orphaned record whose recording is gone from its expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); expect(recordLifecycle(harness)).toBe('completed'); - // Reattach finds no recording, so nothing is left to clean. - expect(harness.runtime.reattach).toHaveBeenCalledOnce(); }); test('record start leaves an orphaned record on another device open', async () => { @@ -140,6 +152,7 @@ test('record start still refuses when the orphaned record cannot be confirmed cl const harness = makeRecordRuntimeHarness('record-runtime-orphan-pending-', { runtime: { reattachActive: true, + finishError: new Error('artifact is not stable'), cleanup: { status: 'cleanup-pending', reason: 'transport-failed' }, }, }); From c254f79c9a5a7d26f6777a5245a4a72694b515d8 Mon Sep 17 00:00:00 2001 From: Sylvain Abadie <5574617+sylvain-abadie@users.noreply.github.com> Date: Wed, 4 Nov 2026 16:34:53 -0800 Subject: [PATCH 4/5] docs(command-surface): say the start-time fallback discards a recording The record start help and the changeset described the fallback for a record that cannot finish only as the exact-owner recovery a daemon restart runs. Say that this recovery discards what the recording left, so a caller knows a start can delete an unfinished recording. --- .changeset/orphaned-recording-start-recovery.md | 2 +- packages/command-surface/src/recording/index.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.changeset/orphaned-recording-start-recovery.md b/.changeset/orphaned-recording-start-recovery.md index 36de2f8367..c3aea4c265 100644 --- a/.changeset/orphaned-recording-start-recovery.md +++ b/.changeset/orphaned-recording-start-recovery.md @@ -2,4 +2,4 @@ '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 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. +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. diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index b0ddf6b890..c47d4e879e 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -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 ; 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 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; 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 [--out ] 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 ; 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; 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 [--out ] 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), From 2482c01a9f10265c1b589a4845844a4fb48e7559 Mon Sep 17 00:00:00 2001 From: Sylvain Abadie <5574617+sylvain-abadie@users.noreply.github.com> Date: Wed, 4 Nov 2026 19:32:55 -0800 Subject: [PATCH 5/5] refactor(capture-kit): tag start conflicts with their device listDurableCaptureStartConflicts already decided whether each record is on the start device, then dropped that fact, so the start-time settle and the refusal wording each compared device identities again. Return onStartDevice with each record and read it in both places, so what the settle skips and what the refusal calls another device can not drift apart. Compare with sameDeviceIdentity. The record help said only closing the session disposes what a failed record stop keeps. That holds only while the daemon holds the session; once it does not, the next record start on that device settles it. Co-Authored-By: Claude Opus 5.5 --- .../durable-capture-resource.ts | 6 ++-- .../durable-capture-start-preflight.ts | 35 ++++++++++--------- .../command-surface/src/recording/index.ts | 2 +- 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index aedba860ed..1e84672773 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-resource.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts @@ -15,7 +15,7 @@ import { } from '../durable-capture/index.ts'; import type { LiveResourceHandle } from '@agent-device/contracts/durable-resource'; import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime'; -import { deviceIdentity, deviceIdentityKey, type DeviceInfo } from '@agent-device/kernel/device'; +import type { DeviceInfo } from '@agent-device/kernel/device'; import type { DurableCaptureAdmissionLedger } from './durable-capture-admission-ledger.ts'; import { createNextDurableCaptureFence, @@ -121,10 +121,8 @@ export function createDurableCaptureResource< ): Promise { const { resourcePath, device, holdsSession, ...recovery } = params; const conflicts = listDurableCaptureStartConflicts(definition, resourcePath, device); - const deviceKey = deviceIdentityKey(deviceIdentity(device)); for (const record of conflicts.records) { - if (holdsSession(record.envelope.sessionId)) continue; - if (deviceIdentityKey(record.envelope.device) !== deviceKey) continue; + if (!record.onStartDevice || holdsSession(record.envelope.sessionId)) continue; try { await finishRecoveredDurableCapture(definition, { resourcePath: record.resourcePath, diff --git a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts index ce5c76816c..3b19c242b4 100644 --- a/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts +++ b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts @@ -2,7 +2,7 @@ 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, @@ -27,10 +27,19 @@ export function createNextDurableCaptureFence( }); } -/** The open records that refuse a start, and the sessions directory they were listed from. */ +/** + * 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 = Readonly<{ sessionsDir: string; - records: readonly Readonly<{ resourcePath: string; envelope: DurableResourceEnvelope }>[]; + records: readonly DurableCaptureStartConflict[]; +}>; + +type DurableCaptureStartConflict = Readonly<{ + resourcePath: string; + envelope: DurableResourceEnvelope; + onStartDevice: boolean; }>; /** @@ -44,9 +53,9 @@ export function listDurableCaptureStartConflicts( resourcePath: string, device: DeviceInfo, ): DurableCaptureStartConflicts { - const selectedDeviceKey = deviceIdentityKey(deviceIdentity(device)); + const startDevice = deviceIdentity(device); const sessionsDir = path.dirname(path.dirname(resourcePath)); - const records: { resourcePath: string; envelope: DurableResourceEnvelope }[] = []; + const records: DurableCaptureStartConflict[] = []; for (const existingPath of definition.store.list(sessionsDir)) { const existing = definition.store.read(existingPath); if (existing.status === 'unreattachable') { @@ -60,13 +69,10 @@ export function listDurableCaptureStartConflicts( }, ); } - if ( - existing.status === 'decoded' && - existing.envelope.lifecycle !== 'completed' && - (existingPath === resourcePath || - deviceIdentityKey(existing.envelope.device) === selectedDeviceKey) - ) { - records.push({ resourcePath: existingPath, envelope: existing.envelope }); + 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 }; @@ -80,10 +86,7 @@ function assertNoConflictingManifest( const [conflict] = listDurableCaptureStartConflicts(definition, resourcePath, device).records; if (!conflict) return; const session = conflict.envelope.sessionId; - const otherDevice = - deviceIdentityKey(conflict.envelope.device) === deviceIdentityKey(deviceIdentity(device)) - ? undefined - : conflict.envelope.device.id; + 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`, diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index c47d4e879e..4c9be5500c 100644 --- a/packages/command-surface/src/recording/index.ts +++ b/packages/command-surface/src/recording/index.ts @@ -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 ; 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; 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 [--out ] 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 ; 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 [--out ] 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),