diff --git a/.changeset/orphaned-recording-start-recovery.md b/.changeset/orphaned-recording-start-recovery.md new file mode 100644 index 0000000000..c3aea4c265 --- /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 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/capture-kit/src/capture-admission/durable-capture-resource.ts b/packages/capture-kit/src/capture-admission/durable-capture-resource.ts index 8a9800e69c..1e84672773 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,38 @@ export function createDurableCaptureResource< recoverOne(params: SessionCaptureRecoveryParams, resourcePath: string) { return recoverDurableCaptureResource(recoveryParams(params), resourcePath); }, + /** + * Finishes the records on `device` that would refuse a start at `resourcePath` and whose + * session the daemon no longer holds, as their own stop would, and runs exact-owner recovery + * only for a record that cannot finish. A held session's record belongs to its own stop or + * close. A record on another device is never recovered through the start device. A record + * left open still refuses. + */ + async settleStartConflicts( + params: Omit, '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 (!record.onStartDevice || holdsSession(record.envelope.sessionId)) continue; + 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/capture-kit/src/capture-admission/durable-capture-start-preflight.ts b/packages/capture-kit/src/capture-admission/durable-capture-start-preflight.ts index 65734602f8..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 @@ -1,7 +1,8 @@ import crypto from 'node:crypto'; import path from 'node:path'; +import type { DurableResourceEnvelope } from '@agent-device/contracts/durable-resource-envelope'; import type { ResourceOwnershipFence } from '@agent-device/contracts/platform-runtime'; -import { deviceIdentity, deviceIdentityKey, type DeviceInfo } from '@agent-device/kernel/device'; +import { deviceIdentity, sameDeviceIdentity, type DeviceInfo } from '@agent-device/kernel/device'; import { AppError } from '@agent-device/kernel/errors'; import { capitalizeDurableCaptureLabel, @@ -26,13 +27,36 @@ export function createNextDurableCaptureFence( }); } -function assertNoConflictingManifest( +/** + * 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 DurableCaptureStartConflict[]; +}>; + +type DurableCaptureStartConflict = Readonly<{ + resourcePath: string; + envelope: DurableResourceEnvelope; + onStartDevice: boolean; +}>; + +/** + * The records a start at `resourcePath` on `device` must wait for: every non-completed record + * at that path or on that device. The start refusal and the start-time settle both read this + * list, so what a start settles is exactly what it would refuse on. An unreattachable record + * throws, because no replacement capture is safe beside it. + */ +export function listDurableCaptureStartConflicts( definition: DurableCaptureRecordDefinition, resourcePath: string, device: DeviceInfo, -): void { - const selectedDeviceKey = deviceIdentityKey(deviceIdentity(device)); - for (const existingPath of definition.store.list(path.dirname(path.dirname(resourcePath)))) { +): DurableCaptureStartConflicts { + const startDevice = deviceIdentity(device); + const sessionsDir = path.dirname(path.dirname(resourcePath)); + const records: DurableCaptureStartConflict[] = []; + for (const existingPath of definition.store.list(sessionsDir)) { const existing = definition.store.read(existingPath); if (existing.status === 'unreattachable') { throw new AppError( @@ -45,22 +69,35 @@ function assertNoConflictingManifest( }, ); } - if ( - existing.status === 'decoded' && - existing.envelope.lifecycle !== 'completed' && - (existingPath === resourcePath || - deviceIdentityKey(existing.envelope.device) === selectedDeviceKey) - ) { - throw new AppError( - 'COMMAND_FAILED', - `${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this device has not reached a confirmed terminal state`, - { - reason: 'cleanup-unconfirmed', - hint: `Retry exact-owner cleanup using the existing ${definition.displayName} manifest before starting a replacement.`, - }, - ); + if (existing.status !== 'decoded' || existing.envelope.lifecycle === 'completed') continue; + const onStartDevice = sameDeviceIdentity(existing.envelope.device, startDevice); + if (onStartDevice || existingPath === resourcePath) { + records.push({ resourcePath: existingPath, envelope: existing.envelope, onStartDevice }); } } + return { sessionsDir, records }; +} + +function assertNoConflictingManifest( + definition: DurableCaptureRecordDefinition, + resourcePath: string, + device: DeviceInfo, +): void { + const [conflict] = listDurableCaptureStartConflicts(definition, resourcePath, device).records; + if (!conflict) return; + const session = conflict.envelope.sessionId; + const otherDevice = conflict.onStartDevice ? undefined : conflict.envelope.device.id; + throw new AppError( + 'COMMAND_FAILED', + `${capitalizeDurableCaptureLabel(articleFor(definition.displayName))} ${definition.displayName} resource for this ${otherDevice ? 'session' : 'device'} has not reached a confirmed terminal state`, + { + reason: 'cleanup-unconfirmed', + session, + hint: otherDevice + ? `The open ${definition.displayName} record of session "${session}" is on device "${otherDevice}". Stop it in that session, or start this one under another session name.` + : `The open ${definition.displayName} record belongs to session "${session}". Stop or close that session, or retry once its device is reachable; exact-owner cleanup must confirm it before a replacement starts.`, + }, + ); } function articleFor(value: string): 'a' | 'an' { diff --git a/packages/command-surface/src/recording/index.ts b/packages/command-surface/src/recording/index.ts index 435a6f4f5f..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. 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), 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..894313af7d --- /dev/null +++ b/packages/daemon/src/sessions/handlers/__tests__/record-runtime-orphan-recovery.test.ts @@ -0,0 +1,198 @@ +import fs from 'node:fs'; +import path from 'node:path'; +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'; +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'; + +// 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' }; + 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; +} + +// 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]); + // 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'); +} + +// 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); + + const response = await startOnSecondSession(harness); + + expect(response).toMatchObject({ ok: true, data: { recording: 'started' } }); + expect(recordLifecycle(harness)).toBe('completed'); + 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(); +}); + +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'); +}); + +test('record start leaves an orphaned record on another device open', async () => { + const harness = makeRecordRuntimeHarness('record-runtime-orphan-elsewhere-', { + runtime: { reattachActive: true }, + }); + writeRecordOnOtherDevice(harness, '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 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: { + reattachActive: true, + finishError: new Error('artifact is not stable'), + 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'],