Skip to content

Commit 0054479

Browse files
authored
fix(android): recognize exited screenrecord processes (#4450)
* fix(android): recognize exited screenrecord processes * fix(android): retain inconclusive recording identity probes
1 parent 880cea7 commit 0054479

4 files changed

Lines changed: 199 additions & 67 deletions

File tree

‎src/platform-runtime-screen-recording-android-host.test.ts‎

Lines changed: 104 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,23 +65,31 @@ test('uses the request-scoped Android ADB executor rather than a host fallback',
6565
expect(calls).toEqual([
6666
['shell', expect.stringContaining('screenrecord --bit-rate 8000000')],
6767
['shell', 'test', '-d', '/proc/42'],
68-
['shell', 'cat', '/proc/42/stat'],
6968
['shell', 'cat', '/proc/42/cmdline'],
69+
['shell', 'cat', '/proc/42/stat'],
7070
['shell', 'test', '-e', '/sdcard/capture.mp4'],
7171
['shell', 'stat', '-c', '%s', '/sdcard/capture.mp4'],
7272
]);
7373
});
7474

7575
test('finds only exact screenrecord processes for the canonical remote path', async () => {
7676
const remotePath = '/sdcard/agent-device-recording-123.mp4';
77+
let candidateExited = false;
78+
const candidateCalls: string[] = [];
7779
await withAndroidAdbProvider(
7880
{
7981
exec: async (args) => {
8082
const command = args.slice(1).join(' ');
81-
if (command === 'ps -A -o pid=') return result('41\n42\n43\n44\n');
83+
if (command.includes('/proc/45')) candidateCalls.push(command);
84+
if (command === 'ps -A -o pid=') return result('41\n42\n43\n44\n45\n');
85+
if (command === 'test -d /proc/45') return result('', '', candidateExited ? 1 : 0);
8286
if (/^test -d \/proc\/\d+$/.test(command)) return result();
8387
const pid = /\/proc\/(\d+)\//.exec(command)?.[1];
8488
if (!pid) return result('', 'unexpected command', 1);
89+
if (pid === '45') {
90+
candidateExited = true;
91+
return result('', 'process exited', 1);
92+
}
8593
if (command.endsWith('/stat')) return result(procStat(Number(pid), pid));
8694
const commandLines: Record<string, string> = {
8795
'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
111119
],
112120
conclusive: true,
113121
});
122+
expect(candidateCalls).toContain('cat /proc/45/cmdline');
123+
expect(candidateCalls).toContain('cat /proc/45/stat');
124+
expect(candidateCalls.filter((command) => command === 'test -d /proc/45')).toHaveLength(2);
114125
},
115126
);
116127
});
@@ -247,6 +258,45 @@ test('distinguishes a missing proc directory from an unavailable identity probe'
247258
);
248259
});
249260

261+
for (const failure of ['cmdline', 'stat', 'empty-stat'] as const) {
262+
const field = failure === 'cmdline' ? 'cmdline' : 'stat';
263+
test.each([
264+
['absent', 1, 'already-missing'],
265+
['present', 0, 'uncertain'],
266+
['interrupted', null, 'uncertain'],
267+
] as const)(
268+
`rechecks process presence after ${failure}: %s`,
269+
async (_presence, probeExit, expected) => {
270+
const commands: string[] = [];
271+
let probes = 0;
272+
adbExecutor.override = async (args) => {
273+
const command = args.slice(1).join(' ');
274+
commands.push(command);
275+
if (command === 'test -d /proc/42') {
276+
return ++probes === 1 ? result() : { stdout: '', stderr: '', exitCode: probeExit };
277+
}
278+
if (command === `cat /proc/42/${field}`) {
279+
return failure === 'empty-stat' ? result('') : result('', 'read failed', 1);
280+
}
281+
if (command.endsWith('/stat')) return result(procStat(42, '42'));
282+
return result(['/system/bin/screenrecord', '/sdcard/capture.mp4', ''].join('\0'));
283+
};
284+
try {
285+
const transport = await createAndroidScreenRecordingTransport(
286+
android,
287+
createLiveTestHostEnvironment(),
288+
);
289+
await expect(
290+
transport.stop({ pid: '42', remotePath: '/sdcard/capture.mp4', startTime: '42' }),
291+
).resolves.toBe(expected);
292+
expect(commands.some((command) => command.startsWith('kill '))).toBe(false);
293+
} finally {
294+
adbExecutor.override = undefined;
295+
}
296+
},
297+
);
298+
}
299+
250300
test('retains an interrupted empty-stderr presence probe as uncertain', async () => {
251301
adbExecutor.override = async (args) => {
252302
expect(args).toEqual(['shell', 'test', '-d', '/proc/44']);
@@ -314,7 +364,7 @@ test('retains an interrupted empty-stderr manifest probe as unavailable', async
314364
}
315365
});
316366

317-
test('proves termination from each ownership-lost producer without signalling', async () => {
367+
test('does not signal an exited or reassigned recorder', async () => {
318368
const commands: string[] = [];
319369
const recorded = { pid: '4004', remotePath: '/sdcard/capture.mp4', startTime: '3766' };
320370
const reassignedPid = {
@@ -349,27 +399,32 @@ test('proves termination from each ownership-lost producer without signalling',
349399
}
350400
identity = exitedTask;
351401
await expect(transport.stop(recorded)).resolves.toBe('ownership-lost');
402+
identity = { stat: procStat(4004, '3766', 'Z'), cmdline: '' };
403+
await expect(transport.inspect(recorded)).resolves.toBe('missing');
404+
await expect(transport.stop(recorded)).resolves.toBe('already-missing');
352405
expect(commands.some((command) => command.startsWith('kill '))).toBe(false);
353406
},
354407
);
355408
});
356409

357-
test('classifies a replacement recorder on the same path as a foreign writer and never signals it', async () => {
410+
test('never signals a recorder whose pid was reused during the command-line read', async () => {
358411
const commands: string[] = [];
359412
const recorded = { pid: '4004', remotePath: '/sdcard/capture.mp4', startTime: '3766' };
360-
const replacementRecorder = {
361-
stat: procStat(4004, '9911'),
362-
cmdline: ['/system/bin/screenrecord', '--bit-rate', '8000000', recorded.remotePath, ''].join(
363-
'\0',
364-
),
365-
};
413+
let currentStart = recorded.startTime;
366414
await withAndroidAdbProvider(
367415
{
368416
exec: async (args) => {
369417
const command = args.slice(1).join(' ');
370418
commands.push(command);
371-
if (command.endsWith('/stat')) return result(replacementRecorder.stat);
372-
if (command.endsWith('/cmdline')) return result(replacementRecorder.cmdline);
419+
if (command.endsWith('/stat')) return result(procStat(4004, currentStart));
420+
if (command.endsWith('/cmdline')) {
421+
currentStart = '9911';
422+
return result(
423+
['/system/bin/screenrecord', '--bit-rate', '8000000', recorded.remotePath, ''].join(
424+
'\0',
425+
),
426+
);
427+
}
373428
return result('');
374429
},
375430
},
@@ -379,15 +434,15 @@ test('classifies a replacement recorder on the same path as a foreign writer and
379434
android,
380435
createLiveTestHostEnvironment(),
381436
);
382-
await expect(transport.inspect(recorded)).resolves.toBe('foreign-writer');
383437
await expect(transport.stop(recorded)).resolves.toBe('ownership-lost');
438+
await expect(transport.inspect(recorded)).resolves.toBe('foreign-writer');
384439
expect(commands.some((command) => command.startsWith('kill '))).toBe(false);
385440
},
386441
);
387442
});
388443

389-
function procStat(pid: number, startTime: string): string {
390-
return `${pid} (screenrecord) S ${Array.from({ length: 18 }, () => '0').join(' ')} ${startTime}`;
444+
function procStat(pid: number, startTime: string, state = 'S'): string {
445+
return `${pid} (screenrecord) ${state} ${Array.from({ length: 18 }, () => '0').join(' ')} ${startTime}`;
391446
}
392447

393448
function result(
@@ -440,3 +495,37 @@ test('retains unavailable manifest reads and confirms manifest deletion', async
440495
);
441496
expect(commands).toHaveLength(2);
442497
});
498+
499+
for (const interruptedAt of ['initial', 'recheck'] as const) {
500+
test(`retains legal provider interruption on the ${interruptedAt} presence probe`, async () => {
501+
const commands: string[] = [];
502+
let probes = 0;
503+
await withAndroidAdbProvider(
504+
{
505+
exec: async (args) => {
506+
const command = args.slice(1).join(' ');
507+
commands.push(command);
508+
if (command === 'test -d /proc/42') {
509+
return ++probes === 1 && interruptedAt === 'recheck'
510+
? result()
511+
: { stdout: '', stderr: '', exitCode: 1, signal: 'SIGTERM' };
512+
}
513+
if (command.endsWith('/cmdline')) return result('', 'read failed', 1);
514+
if (command.endsWith('/stat')) return result(procStat(42, '42'));
515+
throw new Error('unexpected command');
516+
},
517+
},
518+
{ serial: android.id },
519+
async () => {
520+
const transport = await createAndroidScreenRecordingTransport(
521+
android,
522+
createLiveTestHostEnvironment(),
523+
);
524+
await expect(
525+
transport.stop({ pid: '42', remotePath: '/sdcard/capture.mp4', startTime: '42' }),
526+
).resolves.toBe('uncertain');
527+
expect(commands.some((command) => command.startsWith('kill '))).toBe(false);
528+
},
529+
);
530+
});
531+
}

‎src/platform-runtime-screen-recording-android-host.ts‎

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,9 @@ export async function createAndroidScreenRecordingTransport(
153153
type AndroidShell = (
154154
words: readonly ShellWord[],
155155
signal?: AbortSignal,
156-
) => Promise<Readonly<{ stdout: string; stderr: string; exitCode: number | null }>>;
156+
) => Promise<
157+
Readonly<{ stdout: string; stderr: string; exitCode: number | null; signal?: string }>
158+
>;
157159

158160
async function inspectAndroidScreenRecordingProcess(
159161
shell: AndroidShell,
@@ -167,21 +169,31 @@ async function inspectAndroidScreenRecordingProcess(
167169
> {
168170
const presence = await probeAndroidProcessPresence(shell, expected.pid, signal);
169171
if (presence !== 'present') return { status: presence };
170-
const stat = await shell(['cat', `/proc/${expected.pid}/stat`], signal);
171-
if (stat.exitCode !== 0) return { status: 'uncertain' };
172-
const startTime = parseProcStartTime(stat.stdout);
173-
if (!startTime) return { status: 'uncertain' };
174172
const command = await shell(['cat', `/proc/${expected.pid}/cmdline`], signal);
175-
if (command.exitCode !== 0) return { status: 'uncertain' };
173+
const stat = await shell(['cat', `/proc/${expected.pid}/stat`], signal);
174+
const identity = stat.exitCode === 0 ? parseProcIdentity(stat.stdout) : undefined;
175+
if (command.exitCode !== 0 || !identity) {
176+
return {
177+
status:
178+
(await probeAndroidProcessPresence(shell, expected.pid, signal)) === 'missing'
179+
? 'missing'
180+
: 'uncertain',
181+
};
182+
}
183+
if (identity.state === 'Z') return { status: 'missing' };
176184
if (!matchesScreenRecordingCommand(command.stdout, expected.remotePath)) {
177185
return { status: 'ownership-lost' };
178186
}
179-
if (expected.startTime.length > 0 && expected.startTime !== startTime) {
187+
if (expected.startTime.length > 0 && expected.startTime !== identity.startTime) {
180188
return { status: 'foreign-writer' };
181189
}
182190
return {
183191
status: 'owned-alive',
184-
process: Object.freeze({ pid: expected.pid, remotePath: expected.remotePath, startTime }),
192+
process: Object.freeze({
193+
pid: expected.pid,
194+
remotePath: expected.remotePath,
195+
startTime: identity.startTime,
196+
}),
185197
};
186198
}
187199

@@ -191,6 +203,7 @@ async function probeAndroidProcessPresence(
191203
signal?: AbortSignal,
192204
): Promise<'present' | 'missing' | 'uncertain'> {
193205
const result = await shell(['test', '-d', `/proc/${pid}`], signal);
206+
if (result.signal) return 'uncertain';
194207
if (result.exitCode === 0) return 'present';
195208
return result.exitCode === 1 && result.stderr.trim() === '' ? 'missing' : 'uncertain';
196209
}
@@ -205,13 +218,15 @@ function matchesScreenRecordingCommand(commandLine: string, remotePath: string):
205218
);
206219
}
207220

208-
function parseProcStartTime(stat: string): string | undefined {
221+
function parseProcIdentity(stat: string) {
209222
const close = stat.lastIndexOf(')');
210223
if (close < 0) return undefined;
211224
const fieldsAfterCommand = stat
212225
.slice(close + 1)
213226
.trim()
214227
.split(/\s+/);
215228
const startTime = fieldsAfterCommand[19];
216-
return startTime && /^\d+$/.test(startTime) ? startTime : undefined;
229+
return startTime && /^\d+$/.test(startTime)
230+
? { startTime, state: fieldsAfterCommand[0] }
231+
: undefined;
217232
}

‎test/integration/provider-scenarios/android-recording.test.ts‎

Lines changed: 69 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -17,48 +17,76 @@ import {
1717
type PullCall,
1818
} from './android-recording-provider-fixtures.ts';
1919

20-
test('Provider-backed integration Android record start and stop use the composed scoped runtime', async () => {
21-
await withAndroidRecordingScenario(
22-
'agent-device-provider-scenario-android-record-',
23-
async (tmpDir) => {
24-
const calls: string[][] = [];
25-
const pulls: PullCall[] = [];
26-
const outputPath = path.join(tmpDir, 'sessionless.mp4');
27-
const daemon = await createAndroidRecordingScenarioHarness(
28-
{
29-
androidAdbProvider: () => createAndroidRecordingProvider({ calls, pulls }),
30-
deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID],
31-
},
32-
tmpDir,
33-
);
34-
try {
35-
const started = await daemon.callCommand('record', ['start', outputPath], {
36-
platform: 'android',
37-
serial: PROVIDER_SCENARIO_ANDROID.id,
38-
recordingScope: 'device',
39-
quality: 'high',
40-
});
41-
assert.equal(assertRpcOk<{ recording?: unknown }>(started).recording, 'started');
42-
const stopped = await stopAndroidRecording(daemon, outputPath);
43-
assert.equal(
44-
assertRpcOk<{ recording?: unknown; outPath?: unknown }>(stopped).recording,
45-
'stopped',
20+
test.each(['running', 'zombie'] as const)(
21+
'Provider-backed integration Android record start and stop with a %s recorder',
22+
async (state) => {
23+
await withAndroidRecordingScenario(
24+
'agent-device-provider-scenario-android-record-',
25+
async (tmpDir) => {
26+
const calls: string[][] = [];
27+
const pulls: PullCall[] = [];
28+
const outputPath = path.join(tmpDir, 'sessionless.mp4');
29+
const provider = createAndroidRecordingProvider({ calls, pulls });
30+
let exited = false;
31+
const daemon = await createAndroidRecordingScenarioHarness(
32+
{
33+
androidAdbProvider: () => ({
34+
exec: async (args, options) => {
35+
const command = args.join(' ');
36+
if (
37+
exited &&
38+
(command === 'shell cat /proc/4321/stat' ||
39+
command === 'shell cat /proc/4321/cmdline')
40+
) {
41+
calls.push([...args]);
42+
return {
43+
stdout: command.endsWith('/stat')
44+
? '4321 (screenrecord) Z 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 101'
45+
: '',
46+
stderr: '',
47+
exitCode: 0,
48+
};
49+
}
50+
return await provider.exec(args, options);
51+
},
52+
}),
53+
deviceInventoryProvider: async () => [PROVIDER_SCENARIO_ANDROID],
54+
},
55+
tmpDir,
4656
);
47-
assert.equal(assertRpcOk<{ outPath?: unknown }>(stopped).outPath, outputPath);
48-
assert.ok(calls.some((args) => args[1]?.startsWith('screenrecord --bit-rate 20000000 ')));
49-
assert.ok(calls.some((args) => args.join(' ') === 'shell kill -2 4321'));
50-
assert.equal(pulls.length, 1);
51-
// The recorder's chunks land on a collected sibling and the caller's path is written from a
52-
// copy of them, which is what lets a failed stop leave the export absent (ADR 0024 2.3).
53-
assert.equal(pulls[0]?.localPath, collectedRecordingPath(outputPath));
54-
assert.equal(fs.existsSync(outputPath), true);
55-
assert.equal(fs.existsSync(collectedRecordingPath(outputPath)), false);
56-
} finally {
57-
await daemon.close();
58-
}
59-
},
60-
);
61-
});
57+
try {
58+
const started = await daemon.callCommand('record', ['start', outputPath], {
59+
platform: 'android',
60+
serial: PROVIDER_SCENARIO_ANDROID.id,
61+
recordingScope: 'device',
62+
quality: 'high',
63+
});
64+
assert.equal(assertRpcOk<{ recording?: unknown }>(started).recording, 'started');
65+
exited = state === 'zombie';
66+
const stopped = await stopAndroidRecording(daemon, outputPath);
67+
assert.equal(
68+
assertRpcOk<{ recording?: unknown; outPath?: unknown }>(stopped).recording,
69+
'stopped',
70+
);
71+
assert.equal(assertRpcOk<{ outPath?: unknown }>(stopped).outPath, outputPath);
72+
assert.ok(calls.some((args) => args[1]?.startsWith('screenrecord --bit-rate 20000000 ')));
73+
assert.equal(
74+
calls.some((args) => args.join(' ') === 'shell kill -2 4321'),
75+
state === 'running',
76+
);
77+
assert.equal(pulls.length, 1);
78+
// The recorder's chunks land on a collected sibling and the caller's path is written from a
79+
// copy of them, which is what lets a failed stop leave the export absent (ADR 0024 2.3).
80+
assert.equal(pulls[0]?.localPath, collectedRecordingPath(outputPath));
81+
assert.equal(fs.existsSync(outputPath), true);
82+
assert.equal(fs.existsSync(collectedRecordingPath(outputPath)), false);
83+
} finally {
84+
await daemon.close();
85+
}
86+
},
87+
);
88+
},
89+
);
6290

6391
test('Provider-backed integration Android record stop reattaches a matching durable descriptor', async () => {
6492
await withAndroidRecordingScenario(

0 commit comments

Comments
 (0)