Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 104 additions & 15 deletions src/platform-runtime-screen-recording-android-host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,23 +65,31 @@ 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'],
]);
});

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);
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
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<string, string> = {
'41': ['/system/bin/screenrecord', '--bit-rate', '8000000', remotePath, ''].join('\0'),
Expand Down Expand Up @@ -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);
},
);
});
Expand Down Expand Up @@ -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']);
Expand Down Expand Up @@ -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 = {
Expand Down Expand Up @@ -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('');
},
},
Expand All @@ -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(
Expand Down Expand Up @@ -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);
},
);
});
}
35 changes: 25 additions & 10 deletions src/platform-runtime-screen-recording-android-host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ export async function createAndroidScreenRecordingTransport(
type AndroidShell = (
words: readonly ShellWord[],
signal?: AbortSignal,
) => Promise<Readonly<{ stdout: string; stderr: string; exitCode: number | null }>>;
) => Promise<
Readonly<{ stdout: string; stderr: string; exitCode: number | null; signal?: string }>
>;

async function inspectAndroidScreenRecordingProcess(
shell: AndroidShell,
Expand All @@ -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,
}),
};
}

Expand All @@ -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';
}
Expand All @@ -205,13 +218,15 @@ 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
.slice(close + 1)
.trim()
.split(/\s+/);
const startTime = fieldsAfterCommand[19];
return startTime && /^\d+$/.test(startTime) ? startTime : undefined;
return startTime && /^\d+$/.test(startTime)
? { startTime, state: fieldsAfterCommand[0] }
: undefined;
}
110 changes: 69 additions & 41 deletions test/integration/provider-scenarios/android-recording.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading
Loading