diff --git a/src/platform-runtime-screen-recording-android-host.test.ts b/src/platform-runtime-screen-recording-android-host.test.ts index a493d2db9d..3099b5e7a9 100644 --- a/src/platform-runtime-screen-recording-android-host.test.ts +++ b/src/platform-runtime-screen-recording-android-host.test.ts @@ -65,8 +65,8 @@ test('uses the request-scoped Android ADB executor rather than a host fallback', expect(calls).toEqual([ ['shell', expect.stringContaining('screenrecord --bit-rate 8000000')], ['shell', 'test', '-d', '/proc/42'], - ['shell', 'cat', '/proc/42/stat'], ['shell', 'cat', '/proc/42/cmdline'], + ['shell', 'cat', '/proc/42/stat'], ['shell', 'test', '-e', '/sdcard/capture.mp4'], ['shell', 'stat', '-c', '%s', '/sdcard/capture.mp4'], ]); @@ -74,14 +74,22 @@ test('uses the request-scoped Android ADB executor rather than a host fallback', test('finds only exact screenrecord processes for the canonical remote path', async () => { const remotePath = '/sdcard/agent-device-recording-123.mp4'; + let candidateExited = false; + const candidateCalls: string[] = []; await withAndroidAdbProvider( { exec: async (args) => { const command = args.slice(1).join(' '); - if (command === 'ps -A -o pid=') return result('41\n42\n43\n44\n'); + if (command.includes('/proc/45')) candidateCalls.push(command); + if (command === 'ps -A -o pid=') return result('41\n42\n43\n44\n45\n'); + if (command === 'test -d /proc/45') return result('', '', candidateExited ? 1 : 0); if (/^test -d \/proc\/\d+$/.test(command)) return result(); const pid = /\/proc\/(\d+)\//.exec(command)?.[1]; if (!pid) return result('', 'unexpected command', 1); + if (pid === '45') { + candidateExited = true; + return result('', 'process exited', 1); + } if (command.endsWith('/stat')) return result(procStat(Number(pid), pid)); const commandLines: Record = { '41': ['/system/bin/screenrecord', '--bit-rate', '8000000', remotePath, ''].join('\0'), @@ -111,6 +119,9 @@ test('finds only exact screenrecord processes for the canonical remote path', as ], conclusive: true, }); + expect(candidateCalls).toContain('cat /proc/45/cmdline'); + expect(candidateCalls).toContain('cat /proc/45/stat'); + expect(candidateCalls.filter((command) => command === 'test -d /proc/45')).toHaveLength(2); }, ); }); @@ -247,6 +258,45 @@ test('distinguishes a missing proc directory from an unavailable identity probe' ); }); +for (const failure of ['cmdline', 'stat', 'empty-stat'] as const) { + const field = failure === 'cmdline' ? 'cmdline' : 'stat'; + test.each([ + ['absent', 1, 'already-missing'], + ['present', 0, 'uncertain'], + ['interrupted', null, 'uncertain'], + ] as const)( + `rechecks process presence after ${failure}: %s`, + async (_presence, probeExit, expected) => { + const commands: string[] = []; + let probes = 0; + adbExecutor.override = async (args) => { + const command = args.slice(1).join(' '); + commands.push(command); + if (command === 'test -d /proc/42') { + return ++probes === 1 ? result() : { stdout: '', stderr: '', exitCode: probeExit }; + } + if (command === `cat /proc/42/${field}`) { + return failure === 'empty-stat' ? result('') : result('', 'read failed', 1); + } + if (command.endsWith('/stat')) return result(procStat(42, '42')); + return result(['/system/bin/screenrecord', '/sdcard/capture.mp4', ''].join('\0')); + }; + try { + const transport = await createAndroidScreenRecordingTransport( + android, + createLiveTestHostEnvironment(), + ); + await expect( + transport.stop({ pid: '42', remotePath: '/sdcard/capture.mp4', startTime: '42' }), + ).resolves.toBe(expected); + expect(commands.some((command) => command.startsWith('kill '))).toBe(false); + } finally { + adbExecutor.override = undefined; + } + }, + ); +} + test('retains an interrupted empty-stderr presence probe as uncertain', async () => { adbExecutor.override = async (args) => { expect(args).toEqual(['shell', 'test', '-d', '/proc/44']); @@ -314,7 +364,7 @@ test('retains an interrupted empty-stderr manifest probe as unavailable', async } }); -test('proves termination from each ownership-lost producer without signalling', async () => { +test('does not signal an exited or reassigned recorder', async () => { const commands: string[] = []; const recorded = { pid: '4004', remotePath: '/sdcard/capture.mp4', startTime: '3766' }; const reassignedPid = { @@ -349,27 +399,32 @@ test('proves termination from each ownership-lost producer without signalling', } identity = exitedTask; await expect(transport.stop(recorded)).resolves.toBe('ownership-lost'); + identity = { stat: procStat(4004, '3766', 'Z'), cmdline: '' }; + await expect(transport.inspect(recorded)).resolves.toBe('missing'); + await expect(transport.stop(recorded)).resolves.toBe('already-missing'); expect(commands.some((command) => command.startsWith('kill '))).toBe(false); }, ); }); -test('classifies a replacement recorder on the same path as a foreign writer and never signals it', async () => { +test('never signals a recorder whose pid was reused during the command-line read', async () => { const commands: string[] = []; const recorded = { pid: '4004', remotePath: '/sdcard/capture.mp4', startTime: '3766' }; - const replacementRecorder = { - stat: procStat(4004, '9911'), - cmdline: ['/system/bin/screenrecord', '--bit-rate', '8000000', recorded.remotePath, ''].join( - '\0', - ), - }; + let currentStart = recorded.startTime; await withAndroidAdbProvider( { exec: async (args) => { const command = args.slice(1).join(' '); commands.push(command); - if (command.endsWith('/stat')) return result(replacementRecorder.stat); - if (command.endsWith('/cmdline')) return result(replacementRecorder.cmdline); + if (command.endsWith('/stat')) return result(procStat(4004, currentStart)); + if (command.endsWith('/cmdline')) { + currentStart = '9911'; + return result( + ['/system/bin/screenrecord', '--bit-rate', '8000000', recorded.remotePath, ''].join( + '\0', + ), + ); + } return result(''); }, }, @@ -379,15 +434,15 @@ test('classifies a replacement recorder on the same path as a foreign writer and android, createLiveTestHostEnvironment(), ); - await expect(transport.inspect(recorded)).resolves.toBe('foreign-writer'); await expect(transport.stop(recorded)).resolves.toBe('ownership-lost'); + await expect(transport.inspect(recorded)).resolves.toBe('foreign-writer'); expect(commands.some((command) => command.startsWith('kill '))).toBe(false); }, ); }); -function procStat(pid: number, startTime: string): string { - return `${pid} (screenrecord) S ${Array.from({ length: 18 }, () => '0').join(' ')} ${startTime}`; +function procStat(pid: number, startTime: string, state = 'S'): string { + return `${pid} (screenrecord) ${state} ${Array.from({ length: 18 }, () => '0').join(' ')} ${startTime}`; } function result( @@ -440,3 +495,37 @@ test('retains unavailable manifest reads and confirms manifest deletion', async ); expect(commands).toHaveLength(2); }); + +for (const interruptedAt of ['initial', 'recheck'] as const) { + test(`retains legal provider interruption on the ${interruptedAt} presence probe`, async () => { + const commands: string[] = []; + let probes = 0; + await withAndroidAdbProvider( + { + exec: async (args) => { + const command = args.slice(1).join(' '); + commands.push(command); + if (command === 'test -d /proc/42') { + return ++probes === 1 && interruptedAt === 'recheck' + ? result() + : { stdout: '', stderr: '', exitCode: 1, signal: 'SIGTERM' }; + } + if (command.endsWith('/cmdline')) return result('', 'read failed', 1); + if (command.endsWith('/stat')) return result(procStat(42, '42')); + throw new Error('unexpected command'); + }, + }, + { serial: android.id }, + async () => { + const transport = await createAndroidScreenRecordingTransport( + android, + createLiveTestHostEnvironment(), + ); + await expect( + transport.stop({ pid: '42', remotePath: '/sdcard/capture.mp4', startTime: '42' }), + ).resolves.toBe('uncertain'); + expect(commands.some((command) => command.startsWith('kill '))).toBe(false); + }, + ); + }); +} diff --git a/src/platform-runtime-screen-recording-android-host.ts b/src/platform-runtime-screen-recording-android-host.ts index 0141a07dda..8fa414ec41 100644 --- a/src/platform-runtime-screen-recording-android-host.ts +++ b/src/platform-runtime-screen-recording-android-host.ts @@ -153,7 +153,9 @@ export async function createAndroidScreenRecordingTransport( type AndroidShell = ( words: readonly ShellWord[], signal?: AbortSignal, -) => Promise>; +) => Promise< + Readonly<{ stdout: string; stderr: string; exitCode: number | null; signal?: string }> +>; async function inspectAndroidScreenRecordingProcess( shell: AndroidShell, @@ -167,21 +169,31 @@ async function inspectAndroidScreenRecordingProcess( > { const presence = await probeAndroidProcessPresence(shell, expected.pid, signal); if (presence !== 'present') return { status: presence }; - const stat = await shell(['cat', `/proc/${expected.pid}/stat`], signal); - if (stat.exitCode !== 0) return { status: 'uncertain' }; - const startTime = parseProcStartTime(stat.stdout); - if (!startTime) return { status: 'uncertain' }; const command = await shell(['cat', `/proc/${expected.pid}/cmdline`], signal); - if (command.exitCode !== 0) return { status: 'uncertain' }; + const stat = await shell(['cat', `/proc/${expected.pid}/stat`], signal); + const identity = stat.exitCode === 0 ? parseProcIdentity(stat.stdout) : undefined; + if (command.exitCode !== 0 || !identity) { + return { + status: + (await probeAndroidProcessPresence(shell, expected.pid, signal)) === 'missing' + ? 'missing' + : 'uncertain', + }; + } + if (identity.state === 'Z') return { status: 'missing' }; if (!matchesScreenRecordingCommand(command.stdout, expected.remotePath)) { return { status: 'ownership-lost' }; } - if (expected.startTime.length > 0 && expected.startTime !== startTime) { + if (expected.startTime.length > 0 && expected.startTime !== identity.startTime) { return { status: 'foreign-writer' }; } return { status: 'owned-alive', - process: Object.freeze({ pid: expected.pid, remotePath: expected.remotePath, startTime }), + process: Object.freeze({ + pid: expected.pid, + remotePath: expected.remotePath, + startTime: identity.startTime, + }), }; } @@ -191,6 +203,7 @@ async function probeAndroidProcessPresence( signal?: AbortSignal, ): Promise<'present' | 'missing' | 'uncertain'> { const result = await shell(['test', '-d', `/proc/${pid}`], signal); + if (result.signal) return 'uncertain'; if (result.exitCode === 0) return 'present'; return result.exitCode === 1 && result.stderr.trim() === '' ? 'missing' : 'uncertain'; } @@ -205,7 +218,7 @@ function matchesScreenRecordingCommand(commandLine: string, remotePath: string): ); } -function parseProcStartTime(stat: string): string | undefined { +function parseProcIdentity(stat: string) { const close = stat.lastIndexOf(')'); if (close < 0) return undefined; const fieldsAfterCommand = stat @@ -213,5 +226,7 @@ function parseProcStartTime(stat: string): string | undefined { .trim() .split(/\s+/); const startTime = fieldsAfterCommand[19]; - return startTime && /^\d+$/.test(startTime) ? startTime : undefined; + return startTime && /^\d+$/.test(startTime) + ? { startTime, state: fieldsAfterCommand[0] } + : undefined; } diff --git a/test/integration/provider-scenarios/android-recording.test.ts b/test/integration/provider-scenarios/android-recording.test.ts index aac144926b..62a6f2a9ef 100644 --- a/test/integration/provider-scenarios/android-recording.test.ts +++ b/test/integration/provider-scenarios/android-recording.test.ts @@ -17,48 +17,76 @@ import { type PullCall, } from './android-recording-provider-fixtures.ts'; -test('Provider-backed integration Android record start and stop use the composed scoped runtime', async () => { - await withAndroidRecordingScenario( - 'agent-device-provider-scenario-android-record-', - async (tmpDir) => { - const calls: string[][] = []; - const pulls: PullCall[] = []; - const outputPath = path.join(tmpDir, 'sessionless.mp4'); - const daemon = await createAndroidRecordingScenarioHarness( - { - androidAdbProvider: () => createAndroidRecordingProvider({ calls, pulls }), - deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID], - }, - tmpDir, - ); - try { - const started = await daemon.callCommand('record', ['start', outputPath], { - platform: 'android', - serial: PROVIDER_SCENARIO_ANDROID.id, - recordingScope: 'device', - quality: 'high', - }); - assert.equal(assertRpcOk<{ recording?: unknown }>(started).recording, 'started'); - const stopped = await stopAndroidRecording(daemon, outputPath); - assert.equal( - assertRpcOk<{ recording?: unknown; outPath?: unknown }>(stopped).recording, - 'stopped', +test.each(['running', 'zombie'] as const)( + 'Provider-backed integration Android record start and stop with a %s recorder', + async (state) => { + await withAndroidRecordingScenario( + 'agent-device-provider-scenario-android-record-', + async (tmpDir) => { + const calls: string[][] = []; + const pulls: PullCall[] = []; + const outputPath = path.join(tmpDir, 'sessionless.mp4'); + const provider = createAndroidRecordingProvider({ calls, pulls }); + let exited = false; + const daemon = await createAndroidRecordingScenarioHarness( + { + androidAdbProvider: () => ({ + exec: async (args, options) => { + const command = args.join(' '); + if ( + exited && + (command === 'shell cat /proc/4321/stat' || + command === 'shell cat /proc/4321/cmdline') + ) { + calls.push([...args]); + return { + stdout: command.endsWith('/stat') + ? '4321 (screenrecord) Z 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 101' + : '', + stderr: '', + exitCode: 0, + }; + } + return await provider.exec(args, options); + }, + }), + deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID], + }, + tmpDir, ); - assert.equal(assertRpcOk<{ outPath?: unknown }>(stopped).outPath, outputPath); - assert.ok(calls.some((args) => args[1]?.startsWith('screenrecord --bit-rate 20000000 '))); - assert.ok(calls.some((args) => args.join(' ') === 'shell kill -2 4321')); - assert.equal(pulls.length, 1); - // The recorder's chunks land on a collected sibling and the caller's path is written from a - // copy of them, which is what lets a failed stop leave the export absent (ADR 0024 2.3). - assert.equal(pulls[0]?.localPath, collectedRecordingPath(outputPath)); - assert.equal(fs.existsSync(outputPath), true); - assert.equal(fs.existsSync(collectedRecordingPath(outputPath)), false); - } finally { - await daemon.close(); - } - }, - ); -}); + try { + const started = await daemon.callCommand('record', ['start', outputPath], { + platform: 'android', + serial: PROVIDER_SCENARIO_ANDROID.id, + recordingScope: 'device', + quality: 'high', + }); + assert.equal(assertRpcOk<{ recording?: unknown }>(started).recording, 'started'); + exited = state === 'zombie'; + const stopped = await stopAndroidRecording(daemon, outputPath); + assert.equal( + assertRpcOk<{ recording?: unknown; outPath?: unknown }>(stopped).recording, + 'stopped', + ); + assert.equal(assertRpcOk<{ outPath?: unknown }>(stopped).outPath, outputPath); + assert.ok(calls.some((args) => args[1]?.startsWith('screenrecord --bit-rate 20000000 '))); + assert.equal( + calls.some((args) => args.join(' ') === 'shell kill -2 4321'), + state === 'running', + ); + assert.equal(pulls.length, 1); + // The recorder's chunks land on a collected sibling and the caller's path is written from a + // copy of them, which is what lets a failed stop leave the export absent (ADR 0024 2.3). + assert.equal(pulls[0]?.localPath, collectedRecordingPath(outputPath)); + assert.equal(fs.existsSync(outputPath), true); + assert.equal(fs.existsSync(collectedRecordingPath(outputPath)), false); + } finally { + await daemon.close(); + } + }, + ); + }, +); test('Provider-backed integration Android record stop reattaches a matching durable descriptor', async () => { await withAndroidRecordingScenario( diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index f323245110..5d3fa76b14 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1083,7 +1083,7 @@ agent-device record stop # Stop active recording - iOS recording works on simulators and CoreDevice-backed physical devices. Physical devices capture runner screenshots, not a native video stream: no audio, dropped frames are expected, and the default is 15 FPS. `--fps ` (1-120) caps the rate; a busy app or long command yields fewer frames. - `--quality medium|high` (default `medium`) sets export quality on Android and Limrun; Apple export always keeps the captured resolution. Numeric `5`-`7` map to `medium` and `8`-`10` to `high`. - With touch visualization on, recordings also produce a gesture telemetry sidecar. Burned-in touch overlays export only on macOS hosts; elsewhere `record stop` returns the raw video and telemetry with `overlayWarning`. The overlay renders at most 30 FPS (or `--fps` if lower) within a fixed budget, which also covers the video checks that run before and after it; an export past the budget returns the raw video with `overlayWarning`. On a host that has not run a recording before, part of that budget goes to one-time tool setup, so the first `record stop` of a long recording is more likely to return the raw video. -- Android uses `adb shell screenrecord` (180s limit per clip). Longer recordings are split into MP4 chunks while the daemon stays alive; after a daemon restart, `record stop` recovers only chunks listed in the device manifest. A clip can end before `record stop` when the screen stopped changing; `durationMs` is wall-clock time, and `capturedDurationMs` plus a warning report how much the video covers. +- Android uses `adb shell screenrecord` (180s limit per clip). Longer recordings are split into MP4 chunks while the daemon stays alive; after a daemon restart, `record stop` recovers only chunks listed in the device manifest. A clip can end before `record stop` when the screen stopped changing; `durationMs` is wall-clock time, and `capturedDurationMs` plus a warning report how much the video covers. Stopping an already exited recorder still collects its completed video. - Limrun sessions always record the whole screen and refuse `--fps` and `--hide-touches` with `INVALID_ARGS`. A failed download is retried by the next `record stop`; nothing survives a daemon restart. - A busy iOS simulator recording slot returns non-retriable `DEVICE_IN_USE` with `details.reason: apple_simulator_recording_busy`. Run `record stop` in the session that owns the recording; if no recording is active, ask the host operator to restart the CoreSimulator stream service. - MP4 verification setup runs in the background from `record start`; capture does not wait for it. If setup exceeds the stop budget, stop returns retriable `details.reason: video_validator_compile_timeout`. Run `record stop` again; setup continues and your recording is retained. Hosts without xcrun keep container-only MP4 completion. Other compilation failures, or an unavailable validator executable or AVFoundation during verification, return `details.reason: video_validator_unavailable`. Repair the reported failure and retry `record stop`; a failed compile is retried on the next start or stop.