diff --git a/packages/platform-android/src/recording/chunks.ts b/packages/platform-android/src/recording/chunks.ts index 43f51fb58b..99080334d0 100644 --- a/packages/platform-android/src/recording/chunks.ts +++ b/packages/platform-android/src/recording/chunks.ts @@ -18,6 +18,18 @@ export class AndroidScreenRecordingStartRollbackUnconfirmed extends Error { } } +/** + * Refusal raised when the recording's stop was claimed before a chunk launch was dispatched. It is + * how the launch owner reports that the stop outran it, so the rotation withdraws without starting a + * recorder. Only `startPendingChunk` raises it: a commit already in flight runs to its real outcome, + * because cancelling the host command cannot prove what the device's rename did. + */ +export class AndroidScreenRecordingStopClaimed extends Error { + constructor() { + super('Android screenrecord rotation refused: the recording stop was already claimed'); + } +} + export function candidateRemotePaths( preferredDir: string | undefined, now = Date.now(), diff --git a/packages/platform-android/src/recording/finalize.ts b/packages/platform-android/src/recording/finalize.ts index c598c9fce8..9454da7194 100644 --- a/packages/platform-android/src/recording/finalize.ts +++ b/packages/platform-android/src/recording/finalize.ts @@ -53,6 +53,12 @@ export async function finalizeAndroidRecording( startedAtMs: number; progress?: DurableCaptureProgress; reachedLimit?: boolean; + /** + * Whether a rotation retired the active chunk's recorder itself and withdrew before replacing + * it. That retirement explains an already-gone active recorder, so its absence is not the + * platform's 180 s limit truncating a recording that was still running. + */ + activeRecorderRetired?: boolean; }>, ): Promise> { const { host, transport, evidence, recording, startedAtMs, progress } = params; @@ -66,7 +72,9 @@ export async function finalizeAndroidRecording( // growing is the evidence the recorder stopped writing (ADR 0024 2.2). The platform limit is // disclosed here rather than at the export because it is a fact about the recorder, and the // journal is what keeps it attached to a stop that has to be driven again. - reachedLimit = (await stopOwnedChunks(transport, evidence.chunks)) || reachedLimit; + const activeRecorderAlreadyGone = await stopOwnedChunks(transport, evidence.chunks); + reachedLimit = + (activeRecorderAlreadyGone && params.activeRecorderRetired !== true) || reachedLimit; await waitForStableArtifacts(transport, evidence.chunks); return { observation: { recorder: 'confirmed' }, diff --git a/packages/platform-android/src/recording/fixtures.ts b/packages/platform-android/src/recording/fixtures.ts index 57662a9f63..9d22012bd7 100644 --- a/packages/platform-android/src/recording/fixtures.ts +++ b/packages/platform-android/src/recording/fixtures.ts @@ -88,8 +88,11 @@ export function recordingHost(overrides: Record): PlatformRunti legacy.readManifest ? await legacy.readManifest(manifestPath) : { status: 'missing' as const }, - writeManifest: async (request: { manifestPath: string; contents: string }) => { - await legacy.writeManifest?.(request); + writeManifest: async ( + request: { manifestPath: string; contents: string }, + signal?: AbortSignal, + ) => { + await legacy.writeManifest?.(request, signal); }, removeManifest: async (manifestPath: string) => legacy.removeManifest ? await legacy.removeManifest(manifestPath) : true, diff --git a/packages/platform-android/src/recording/launch.ts b/packages/platform-android/src/recording/launch.ts index d0e6001f75..9a5dc45238 100644 --- a/packages/platform-android/src/recording/launch.ts +++ b/packages/platform-android/src/recording/launch.ts @@ -3,6 +3,7 @@ import type { PlatformRuntimeHost } from '@agent-device/contracts/platform-runti import type { ScreenRecordingStartInput } from '@agent-device/contracts/screen-recording-runtime'; import { AndroidScreenRecordingStartRollbackUnconfirmed, + AndroidScreenRecordingStopClaimed, candidateRemotePaths, rollbackChunks, startChunkAt, @@ -99,20 +100,37 @@ export async function startPendingChunk(params: { chunks: readonly NativeChunk[]; manifestPath: string; preferredDir: string; + // Refuses a device start once the recording's stop has been claimed. + launchAdmission: AbortSignal; }): Promise { - const { transport, device, input, startedAt, chunks, manifestPath, preferredDir } = params; + const { + transport, + device, + input, + startedAt, + chunks, + manifestPath, + preferredDir, + launchAdmission, + } = params; let last: unknown; for (const remotePath of candidateRemotePaths(preferredDir)) { + if (launchAdmission.aborted) throw new AndroidScreenRecordingStopClaimed(); await persistNativeManifest( transport, manifestPath, createNativeManifest(device, input, startedAt, chunks, remotePath, transport.mode), ); try { + // The pending evidence is on the device, but the stop may have been claimed while it was being + // written. Refuse here rather than dispatch a recorder the recording has already given up. + if (launchAdmission.aborted) throw new AndroidScreenRecordingStopClaimed(); return await startChunkAt(transport, remotePath, input); } catch (error) { if (error instanceof AndroidScreenRecordingStartRollbackUnconfirmed) throw error; try { + // Clears the pending marker, which names a recorder nothing launched when the refusal raised + // this error. await persistNativeManifest( transport, manifestPath, diff --git a/packages/platform-android/src/recording/manifest.ts b/packages/platform-android/src/recording/manifest.ts index e93ff91e20..5f0f121161 100644 --- a/packages/platform-android/src/recording/manifest.ts +++ b/packages/platform-android/src/recording/manifest.ts @@ -90,6 +90,23 @@ export const androidScreenRecordingDescriptorCodec = Object.freeze({ : ({ status: 'invalid', message: 'Invalid Android screen-recording descriptor' } as const), }); +/** + * The requested recording options, carried unchanged by every durable record of the recording: an + * option recorded in one place and not another would make that record disagree about what was asked. + */ +export function recordingRequestFields(input: ScreenRecordingStartInput) { + return { + outputPath: input.outputPath, + ...(input.clientOutputPath === undefined ? {} : { clientOutputPath: input.clientOutputPath }), + scope: input.scope, + showTouches: input.showTouches, + recordOnlySession: input.recordOnlySession, + ...(input.activeSessionApp === undefined ? {} : { activeSessionApp: input.activeSessionApp }), + ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), + ...(input.fps === undefined ? {} : { fps: input.fps }), + }; +} + export function createNativeManifest( device: DeviceInfo, input: ScreenRecordingStartInput, @@ -106,14 +123,7 @@ export function createNativeManifest( sessionId: input.sessionId, deviceId: device.id, startedAt, - outputPath: input.outputPath, - ...(input.clientOutputPath === undefined ? {} : { clientOutputPath: input.clientOutputPath }), - scope: input.scope, - showTouches: input.showTouches, - recordOnlySession: input.recordOnlySession, - ...(input.activeSessionApp === undefined ? {} : { activeSessionApp: input.activeSessionApp }), - ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), - ...(input.fps === undefined ? {} : { fps: input.fps }), + ...recordingRequestFields(input), chunks, ...(pendingRemotePath === undefined ? {} : { pendingRemotePath }), transportMode, diff --git a/packages/platform-android/src/recording/runtime.test.ts b/packages/platform-android/src/recording/runtime.test.ts index 19ef2409bc..93f43f74bb 100644 --- a/packages/platform-android/src/recording/runtime.test.ts +++ b/packages/platform-android/src/recording/runtime.test.ts @@ -190,6 +190,516 @@ test('serializes a failed rotation so finish cannot publish completion', async ( } }); +/** + * Holds the manifest write that would commit the second chunk, standing in for the transport's + * `printf %s … > tmp && mv -f tmp manifest`, which publishes on the device only once its command + * finishes. Aborting the host command cannot undo that rename or prove it never ran. + */ +function pauseChunkCommit() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (contents: string) => { + if (paused) return; + const written = JSON.parse(contents) as { chunks?: unknown[] }; + if (written.chunks?.length !== 2) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** + * Holds the manifest write that names the next chunk as pending, before any recorder for it is + * launched, so a stop can be claimed between the marker reaching the device and the launch. + */ +function pausePendingEvidence() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (contents: string) => { + if (paused) return; + const written = JSON.parse(contents) as { chunks?: unknown[]; pendingRemotePath?: string }; + if (written.chunks?.length !== 1 || written.pendingRemotePath === undefined) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** Holds the graceful stop of the recorder a sequential rotation is retiring. */ +function pauseChunkRetirement(pid: string) { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async (stoppedPid: string) => { + if (stoppedPid !== pid || paused) return; + paused = true; + await released; + }, + isPaused: () => paused, + release: () => release(), + }; +} + +/** Pauses the launch of the next chunk, so a stop can be claimed before that child is reported. */ +function pauseNextLaunch() { + let paused = false; + let release!: () => void; + const released = new Promise((resolve) => { + release = resolve; + }); + return { + intercept: async () => { + paused = true; + await released; + }, + isWaiting: () => paused, + release: () => release(), + }; +} + +test('does not start a chunk after finish when a successful rotation is still in flight', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await commit.intercept(contents); + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(JSON.parse(manifest)).toMatchObject({ + chunks: [{ remotePid: '42' }, { remotePid: '43' }], + }); + } finally { + vi.useRealTimers(); + } +}); + +test('does not start a chunk after force cleanup when a successful rotation is still in flight', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const stopped = new Set(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await commit.intercept(contents); + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + removeManifest: async () => { + manifest = ''; + return true; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const cleaning = handle.forceCleanup(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(cleaning).resolves.toEqual({ status: 'cleaned' }); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + // The rotation's recorder was signaled whichever way its commit settled: adopted then cleaned, or + // refused then rolled back. Either way no recorder outlives the cleanup. + expect(stopped).toEqual(new Set(['42', '43'])); + expect(manifest).toBe(''); + } finally { + vi.useRealTimers(); + } +}); + +test('rolls back the chunk a rotation launched after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const launch = pauseNextLaunch(); + const startedPaths: string[] = []; + const removed: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + if (starts > 1) await launch.intercept(); + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + remove: async (remotePath: string) => { + removed.push(remotePath); + return true; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(launch.isWaiting()).toBe(true); + const finishing = handle.finish(); + launch.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + expect(starts).toBe(2); + expect(stopped).toEqual(new Set(['42', '43'])); + expect(removed).toContain(startedPaths[1]); + expect(JSON.parse(manifest).chunks).toHaveLength(1); + } finally { + vi.useRealTimers(); + } +}); + +test('does not launch the sequential fallback after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const retirement = pauseChunkRetirement('42'); + const stopped = new Set(); + const runtime = await start({ + start: async () => { + starts += 1; + if (starts > 1) throw new Error('concurrent start unavailable'); + return recordingProcess('42'); + }, + stop: async ({ pid }: { pid: string }) => { + await retirement.intercept(pid); + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(3); + expect(retirement.isPaused()).toBe(true); + const finishing = handle.finish(); + retirement.release(); + await vi.advanceTimersByTimeAsync(5_000); + const outcome = await finishing; + expect(outcome).toMatchObject({ status: 'completed' }); + // The rotation retired this recorder itself, so its absence is not the 180 s platform limit. + expect((outcome as { result?: { warning?: string } }).result?.warning ?? '').not.toMatch( + /platform limit/, + ); + expect(starts).toBe(3); + expect(JSON.parse(manifest).chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + } finally { + vi.useRealTimers(); + } +}); + +test('still discloses the platform limit when the recorder a fallback retired had already exited', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const retirement = pauseChunkRetirement('42'); + const runtime = await start({ + start: async () => { + starts += 1; + if (starts > 1) throw new Error('concurrent start unavailable'); + return recordingProcess('42'); + }, + // The platform's 180 s cap ended this recorder just before the rotation reached it, so the + // retirement is told the recorder was already gone rather than confirming a stop of its own. + stop: async ({ pid }: { pid: string }) => { + await retirement.intercept(pid); + return 'already-missing' as const; + }, + inspect: async () => 'missing' as const, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(3); + expect(retirement.isPaused()).toBe(true); + const finishing = handle.finish(); + retirement.release(); + await vi.advanceTimersByTimeAsync(5_000); + const outcome = await finishing; + expect(outcome).toMatchObject({ status: 'completed' }); + // The recorder died of the platform limit before the retirement ran, so that disclosure must + // survive the rotation that tried to retire it. + expect((outcome as { result?: { warning?: string } }).result?.warning ?? '').toMatch( + /platform limit/, + ); + expect(starts).toBe(3); + expect(JSON.parse(manifest).chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + } finally { + vi.useRealTimers(); + } +}); + +test('does not dispatch a chunk launch whose pending evidence was written after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const pending = pausePendingEvidence(); + const runtime = await start({ + start: async () => { + starts += 1; + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + manifest = contents; + await pending.intercept(contents); + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(pending.isPaused()).toBe(true); + const finishing = handle.finish(); + pending.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + expect(starts).toBe(1); + // The refusal clears the pending marker through the normal rollback, so the device is never left + // naming a recorder nothing launched. + expect(JSON.parse(manifest)).toEqual( + expect.objectContaining({ chunks: [expect.objectContaining({ remotePid: '42' })] }), + ); + expect(JSON.parse(manifest)).not.toHaveProperty('pendingRemotePath'); + } finally { + vi.useRealTimers(); + } +}); + +test('collects a chunk whose commit published while the stop was in flight', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + // What the device's marker actually holds. A publication runs `printf %s … > tmp && mv -f tmp + // manifest`: the rename commits the marker on the device while the host command is still running, + // and aborting that command would make the host reject even though the rename already happened. + // The commit therefore takes no stop signal at all, and this mock holds that write in flight + // across the stop to show its real outcome decides what the recording keeps. + const deviceWrites: string[] = []; + const commit = pauseChunkCommit(); + const startedPaths: string[] = []; + const pulled: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + await commit.intercept(contents); + deviceWrites.push(contents); + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + pullPlayable: async ({ remotePath }: { remotePath: string }) => { + pulled.push(remotePath); + return { stdout: '', stderr: '', exitCode: 0, playable: true }; + }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + commit.release(); + await vi.advanceTimersByTimeAsync(5_000); + await expect(finishing).resolves.toMatchObject({ status: 'completed' }); + // The rename committed the chunk on the device while the stop was in flight, so the recording + // keeps it: finish collects both chunks and stops both recorders. + expect(pulled).toEqual([startedPaths[0], startedPaths[1]]); + expect(stopped).toEqual(new Set(['42', '43'])); + const finalMarker = JSON.parse(deviceWrites.at(-1)!); + expect(finalMarker.chunks).toEqual([ + expect.objectContaining({ remotePid: '42' }), + expect.objectContaining({ remotePid: '43' }), + ]); + expect(finalMarker).not.toHaveProperty('pendingRemotePath'); + expect(finalMarker).toHaveProperty('completion'); + } finally { + vi.useRealTimers(); + } +}); + +test('retains the child when the rotation commit fails after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const startedPaths: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + await commit.intercept(contents); + // The commit itself fails: a real write failure, not a stop refusing it. + if ((JSON.parse(contents) as { chunks: unknown[] }).chunks.length === 2) + throw new Error('rotation manifest failed'); + manifest = contents; + }, + stop: async ({ pid }: { pid: string }) => { + // The child's recorder cannot be confirmed gone, so its rollback stays unconfirmed. + if (pid === '43') return 'uncertain' as const; + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + pid === '43' || !stopped.has(pid) ? ('owned-alive' as const) : ('missing' as const), + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(starts).toBe(2); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + const refused = expect(finishing).rejects.toThrow('rotation manifest failed'); + commit.release(); + await vi.advanceTimersByTimeAsync(20_000); + // A failed commit is a rotation failure even after a claimed stop: finish cannot report success + // while the child's recorder is unaccounted for. + await refused; + // The unconfirmed child stays in the recovery evidence as pending, so disposal can settle it. + const marker = JSON.parse(manifest); + expect(marker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(marker).toMatchObject({ pendingRemotePath: startedPaths[1] }); + const cleaning = handle.forceCleanup(); + const pending = expect(cleaning).resolves.toMatchObject({ status: 'cleanup-pending' }); + await vi.advanceTimersByTimeAsync(30_000); + await pending; + expect(manifest).not.toBe(''); + } finally { + vi.useRealTimers(); + } +}); + +test('retains the child when its artifact removal fails after the stop was claimed', async () => { + vi.useFakeTimers(); + try { + let starts = 0; + let manifest = ''; + const commit = pauseChunkCommit(); + const startedPaths: string[] = []; + const stopped = new Set(); + const runtime = await start({ + start: async ({ remotePath }: { remotePath: string }) => { + starts += 1; + startedPaths.push(remotePath); + return recordingProcess(String(41 + starts)); + }, + writeManifest: async ({ contents }: { contents: string }) => { + await commit.intercept(contents); + if ((JSON.parse(contents) as { chunks: unknown[] }).chunks.length === 2) + throw new Error('rotation manifest failed'); + manifest = contents; + }, + stop: async ({ pid }: { pid: string }) => { + if (stopped.has(pid)) return 'already-missing' as const; + stopped.add(pid); + return 'stopped' as const; + }, + inspect: async ({ pid }: { pid: string }) => + stopped.has(pid) ? ('missing' as const) : ('owned-alive' as const), + // The recorder is gone but the device will not give the file back, so the rollback stays + // unconfirmed and the file keeps its name in the evidence. + remove: async (remotePath: string) => remotePath !== startedPaths[1], + readManifest: async () => + manifest ? { status: 'read' as const, contents: manifest } : { status: 'missing' as const }, + }); + const handle = (await runtime.screenRecordingStart(recordingInput())).pendingHandle.transfer(); + await vi.advanceTimersByTimeAsync(170_000); + expect(commit.isPaused()).toBe(true); + const finishing = handle.finish(); + const refused = expect(finishing).rejects.toThrow('rotation manifest failed'); + commit.release(); + await vi.advanceTimersByTimeAsync(20_000); + await refused; + const marker = JSON.parse(manifest); + expect(marker.chunks).toEqual([expect.objectContaining({ remotePid: '42' })]); + expect(marker).toMatchObject({ pendingRemotePath: startedPaths[1] }); + expect(stopped.has('43')).toBe(true); + // Disposal re-attempts the file the device still holds and stays pending while it cannot. + const cleaning = handle.forceCleanup(); + const pending = expect(cleaning).resolves.toMatchObject({ status: 'cleanup-pending' }); + await vi.advanceTimersByTimeAsync(30_000); + await pending; + expect(manifest).not.toBe(''); + } finally { + vi.useRealTimers(); + } +}); + test('falls back to sequential rotation when concurrent start is unavailable', async () => { vi.useFakeTimers(); try { diff --git a/packages/platform-android/src/recording/runtime.ts b/packages/platform-android/src/recording/runtime.ts index cc0223858a..4ea5facdc8 100644 --- a/packages/platform-android/src/recording/runtime.ts +++ b/packages/platform-android/src/recording/runtime.ts @@ -16,9 +16,10 @@ import { import { androidScreenRecordingDescriptorCodec, createNativeManifest, + recordingRequestFields, type NativeChunk, } from './manifest.ts'; -import { rollbackChunks, stopChunk } from './chunks.ts'; +import { AndroidScreenRecordingStopClaimed, rollbackChunks, stopChunk } from './chunks.ts'; import { startInitialTransaction, startPendingChunk } from './launch.ts'; import { persistNativeManifest } from './manifest-store.ts'; import { snapshot } from './live-snapshot.ts'; @@ -28,6 +29,14 @@ import { cleanupAndroidRecording, reattachAndroidRecording, readLiveEvidence } f const ROTATE_AFTER_MS = 170_000; +/** + * The rotation lifecycle of one recording. `recording` may still start a chunk, `stopping` has been + * asked to stop and is settling the rotation it accepted, `finished` has committed its native + * evidence. Only `claimStop` and `confirmNativeCleanup` move it, so one owner decides whether a + * rotation may still start a chunk on the device. + */ +type RecordingPhase = 'recording' | 'stopping' | 'finished'; + export async function bindAndroidScreenRecordingRuntime(params: { host: PlatformRuntimeHost; device: DeviceInfo; @@ -70,8 +79,39 @@ async function startAndroidRecording(params: { let timer: ReturnType | undefined; let rotation: Promise | undefined; let rotationFailure: unknown; - let nativeCleanupConfirmed = false; + let phase: RecordingPhase = 'recording'; + /** + * Whether a rotation retired the active chunk's recorder itself, confirmed by that stop, and then + * withdrew without replacing it. Finalization must read that recorder's absence as this recording's + * own retirement, not as the platform's 180 s limit cutting a recorder short. A retirement that + * found the recorder already gone is not this recording's doing and records nothing. + */ + let retiredActiveRecorder = false; + /** + * The recording's launch admission. It is aborted the moment either stop operation begins, so the + * launch owner refuses at the device call it is about to make and a claimed stop never starts + * another recorder. The commit boundary deliberately does not use it: aborting the host command + * cannot prove the on-device rename did not happen, so only that write's real outcome decides what + * the marker holds. + */ + const stopAdmission = new AbortController(); + /** + * Stops accepting rotations and arms nothing that could start one. The claim is synchronous, so the + * rotation already in flight cannot launch a chunk behind the stop that interrupted it. A commit + * already in flight may still commit, and the stop collects that chunk like any other. + */ + const claimStop = () => { + if (timer) clearTimeout(timer); + stopAdmission.abort(); + if (phase === 'recording') phase = 'stopping'; + }; + const acceptsRotations = () => phase === 'recording'; + /** Marks the native evidence settled, which is the only way out of `stopping`. */ + const confirmNativeCleanup = () => { + phase = 'finished'; + }; const schedule = () => { + if (!acceptsRotations()) return; timer = setTimeout(() => { rotation = rotate().catch((error: unknown) => { rotationFailure = error; @@ -79,96 +119,158 @@ async function startAndroidRecording(params: { }, ROTATE_AFTER_MS); timer.unref?.(); }; - const rotate = async () => { - const previous = chunks.at(-1); - if (!previous) throw new Error('Android recording has no active chunk'); - let previousStopped = false; - let next: NativeChunk; + /** + * The active marker for the chunk set the recording currently owns. `pendingRemotePath` names a + * recorder the device holds that the marker has not committed, which is what keeps a chunk started + * during a claimed stop, or one whose rollback is unconfirmed, recoverable. + */ + const activeEvidence = (chunkList: readonly NativeChunk[], pendingRemotePath?: string) => + createNativeManifest(device, input, startedAt, chunkList, pendingRemotePath, transport.mode); + const launchChunk = async (previous: NativeChunk) => + await startPendingChunk({ + transport, + device, + input, + startedAt, + chunks, + manifestPath, + preferredDir: path.posix.dirname(previous.remotePath), + launchAdmission: stopAdmission.signal, + }); + /** + * Launches the next chunk, falling back to a sequential launch when the device refuses a second + * concurrent recorder. Reports whether that fallback had to retire the chunk being replaced. + */ + const launchRotationChunk = async ( + previous: NativeChunk, + ): Promise> => { try { - next = await startPendingChunk({ - transport, - device, - input, - startedAt, - chunks, - manifestPath, - preferredDir: path.posix.dirname(previous.remotePath), - }); + return { chunk: await launchChunk(previous), previousStopped: false }; } catch (concurrentStartError) { - await stopChunk(transport, previous); - previousStopped = true; + // The stop refused this rotation before it dispatched anything. It must not retire the chunk + // being replaced either: the stop owns that recorder now. + if (concurrentStartError instanceof AndroidScreenRecordingStopClaimed) + throw concurrentStartError; + // The stop owns the current recorder now, so do not begin retiring it for a replacement this + // recording has already given up on. Finalization will stop it like any active chunk. + if (stopAdmission.signal.aborted) throw new AndroidScreenRecordingStopClaimed(); + // Retiring this recorder is this recording's own doing, so a later finalization must not read + // its absence as the platform's 180 s limit, whether or not the replacement this retirement was + // made for ever launches. Only a stop that confirmed the recorder was live counts: one already + // gone means the recorder ended on its own, and that disclosure must survive this rotation. + if (!(await stopChunk(transport, previous))) retiredActiveRecorder = true; try { - next = await startPendingChunk({ - transport, - device, - input, - startedAt, - chunks, - manifestPath, - preferredDir: path.posix.dirname(previous.remotePath), - }); + return { chunk: await launchChunk(previous), previousStopped: true }; } catch (sequentialStartError) { throw sequentialStartError instanceof Error ? sequentialStartError : concurrentStartError; } } - const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; + }; + /** + * Gives up a chunk the stop refused while it was launching, so its recorder cannot outlive the + * recording. An abandoned chunk that cannot be cleaned is a rotation failure: the marker still + * names it as pending, and only disposal may then settle it. + */ + const abandonUncommittedChunk = async (chunk: NativeChunk) => { + await rollbackChunks(transport, [chunk]); + await persistNativeManifest(transport, manifestPath, activeEvidence(chunks)).catch(() => {}); + }; + /** + * Rewinds the marker to what the recording was before this rotation, once its commit failed. The + * child may never be dropped from the evidence: when its rollback cannot be confirmed, the marker + * names its path as pending, which is what keeps an unaccounted recorder recoverable and makes the + * rotation failure the stop reports rather than a clean finish. + */ + const undoRotationCommit = async ( + next: NativeChunk, + previous: NativeChunk, + previousStopped: boolean, + ): Promise => { + const rollbackUncertain = await rollbackChunks(transport, [next]).then( + () => false, + () => true, + ); + // An uncertain rollback leaves the child's recorder, its artifact, or both on the device, so the + // marker must keep naming them as pending. + if (rollbackUncertain || previousStopped) { + await persistNativeManifest( + transport, + manifestPath, + activeEvidence(chunks, next.remotePath), + ).catch(() => {}); + return; + } try { + await persistNativeManifest(transport, manifestPath, activeEvidence(chunks)); + } catch { + // The recorder this rotation was replacing is the only writer left, so the marker names the + // abandoned chunk as pending rather than claiming a chunk set the device no longer holds. + await stopChunk(transport, previous).catch(() => {}); await persistNativeManifest( transport, manifestPath, - createNativeManifest(device, input, startedAt, nextChunks, undefined, transport.mode), - ); + activeEvidence(chunks, next.remotePath), + ).catch(() => {}); + } + }; + const rotate = async () => { + const previous = chunks.at(-1); + if (!previous) throw new Error('Android recording has no active chunk'); + let next: NativeChunk; + let previousStopped: boolean; + try { + ({ chunk: next, previousStopped } = await launchRotationChunk(previous)); } catch (error) { - await rollbackChunks(transport, [next]).catch(() => {}); - if (!previousStopped) { - try { - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), - ); - } catch { - await stopChunk(transport, previous).catch(() => {}); - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, next.remotePath, transport.mode), - ).catch(() => {}); - } - } else { - await persistNativeManifest( - transport, - manifestPath, - createNativeManifest(device, input, startedAt, chunks, next.remotePath, transport.mode), - ).catch(() => {}); - } + // The stop outran this rotation before it dispatched a device start. It launched nothing, so + // the stop owns the recording's evidence and this is not a rotation failure. + if (error instanceof AndroidScreenRecordingStopClaimed) return; + throw error; + } + if (!acceptsRotations()) { + await abandonUncommittedChunk(next); + return; + } + const nextChunks = [...chunks, { ...next, index: chunks.length + 1 }]; + try { + // No stop signal reaches this write. Aborting the host command cannot undo the on-device rename + // or prove it never ran, so the write runs to its real outcome: success means the device + // committed the chunk, whatever the stop did while the write was in flight. + await persistNativeManifest(transport, manifestPath, activeEvidence(nextChunks)); + } catch (error) { + await undoRotationCommit(next, previous, previousStopped); throw error; } + // The write committed this chunk on the device, so the recording keeps it and the stop collects + // it like every other committed chunk. A committed chunk is never discarded. chunks = nextChunks; + // The active chunk is this freshly launched one now, so a retirement recorded earlier can no + // longer explain its absence. + retiredActiveRecorder = false; if (!previousStopped) await stopChunk(transport, previous); schedule(); }; schedule(); const handle = createScreenRecordingLiveHandle(snapshot(input, startedAt), { finish: async (current, progress) => { - if (timer) clearTimeout(timer); + claimStop(); await rotation; if (rotationFailure) throw rotationFailure; const outcome = await finalizeAndroidRecording({ host, transport, - evidence: createNativeManifest(device, input, startedAt, chunks, undefined, transport.mode), + evidence: activeEvidence(chunks), manifestPath, recording: current, startedAtMs: initial.startedAtMs, progress, + activeRecorderRetired: retiredActiveRecorder, }); - nativeCleanupConfirmed = true; + confirmNativeCleanup(); return outcome; }, forceCleanup: async () => { - if (timer) clearTimeout(timer); - if (nativeCleanupConfirmed) return { status: 'cleaned' } as const; + claimStop(); + if (phase === 'finished') return { status: 'cleaned' } as const; try { await rotation; } catch (error) { @@ -197,18 +299,7 @@ async function startAndroidRecording(params: { descriptor: encodeDurableDescriptor(androidScreenRecordingDescriptorCodec, { backend: 'adb-screenrecord', manifestPath, - outputPath: input.outputPath, - ...(input.clientOutputPath === undefined - ? {} - : { clientOutputPath: input.clientOutputPath }), - scope: input.scope, - showTouches: input.showTouches, - recordOnlySession: input.recordOnlySession, - ...(input.activeSessionApp === undefined - ? {} - : { activeSessionApp: input.activeSessionApp }), - ...(input.exportQuality === undefined ? {} : { exportQuality: input.exportQuality }), - ...(input.fps === undefined ? {} : { fps: input.fps }), + ...recordingRequestFields(input), transportMode: transport.mode, }), }),