Skip to content

Commit e676ade

Browse files
committed
fix(maestro): corroborate a stale foreground read before killApp proceeds
Live emulator replay (agent-device replay --maestro) reproduced a real gap from the PR review: immediately after launchApp, dumpsys window's mCurrentFocus can still name the previous foreground app for one read while dumpsys activity activities already shows the launched app resumed. getAndroidAppState takes whichever dump answers first, so killAndroidPackage's single-sample foreground check could read "backgrounded" for an app that was still genuinely in the foreground, skipping the android-kill-requires- background-app refusal. killAndroidPackage now corroborates a "not the target" read once after a short settle before trusting it, mirroring the existing gone-twice-in-a-row pattern used elsewhere in this file. Also: drop the killAndroidApp re-export from mechanics.ts (no consumer imports it there; the real caller imports directly from app-lifecycle.ts), and add a direct test proving mode: 'kill' reaches the platform close when closeWithoutSession handles close with no stored session. Claude-Session: https://claude.ai/code/session_01NVfRR5Pmmkg8ZstHQUZ2qR
1 parent f894395 commit e676ade

4 files changed

Lines changed: 157 additions & 2 deletions

File tree

‎packages/platform-android/src/__tests__/app-lifecycle-kill.test.ts‎

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ test('killAndroidApp dispatches am kill rather than am force-stop', async () =>
4040
);
4141

4242
assert.deepEqual(calls, [
43+
['shell', 'dumpsys', 'window', 'windows'],
4344
['shell', 'dumpsys', 'window', 'windows'],
4445
['shell', 'am', 'kill', 'com.example.app'],
4546
['shell', 'dumpsys', 'window', 'windows'],
@@ -49,6 +50,53 @@ test('killAndroidApp dispatches am kill rather than am force-stop', async () =>
4950
]);
5051
});
5152

53+
// Live evidence (2026-09-25, Android 16 emulator): immediately after `launchApp`,
54+
// `dumpsys window`'s `mCurrentFocus` still named the previous foreground app for one read while
55+
// `dumpsys activity activities` already showed the launched app resumed. A single "not the target"
56+
// foreground read is not proof the target left the foreground, so `killAndroidApp` corroborates it
57+
// once before trusting it enough to skip the `android-kill-requires-background-app` refusal.
58+
test('killAndroidApp refuses when a corroborating read shows the target back in the foreground', async () => {
59+
const device: DeviceInfo = {
60+
platform: 'android',
61+
id: 'emulator-5554',
62+
name: 'Pixel',
63+
kind: 'emulator',
64+
booted: true,
65+
};
66+
let foregroundReads = 0;
67+
68+
await withAndroidAdbProvider(
69+
{
70+
exec: async (args) => {
71+
if (args.join(' ') === 'shell dumpsys window windows') {
72+
foregroundReads += 1;
73+
const stdout =
74+
foregroundReads === 1
75+
? 'mCurrentFocus=Window{43 u0 com.android.launcher/.Launcher}\n'
76+
: 'mCurrentFocus=Window{44 u0 com.example.app/.MainActivity}\n';
77+
return { stdout, stderr: '', exitCode: 0 };
78+
}
79+
return { stdout: '', stderr: '', exitCode: 0 };
80+
},
81+
reverse: {
82+
ensure: async () => {},
83+
remove: async () => {},
84+
removeAllOwned: async () => {},
85+
},
86+
},
87+
{ serial: 'emulator-5554' },
88+
async () => {
89+
await assertRejectsAppError(() => killAndroidApp(device, 'com.example.app'), {
90+
code: 'COMMAND_FAILED',
91+
hint: /Background the app before killApp/,
92+
details: { reason: 'android-kill-requires-background-app' },
93+
});
94+
},
95+
);
96+
97+
assert.equal(foregroundReads, 2);
98+
});
99+
52100
test('killAndroidApp refuses a foreground target before killing', async () => {
53101
const device: DeviceInfo = {
54102
platform: 'android',

‎packages/platform-android/src/app-lifecycle.ts‎

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ const ANDROID_CLOSE_FOCUS_POLL_MS = 50;
3333
const ANDROID_CLOSE_PROCESS_TIMEOUT_MS = 2_000;
3434
const ANDROID_CLOSE_PROCESS_POLL_MS = 50;
3535
const ANDROID_CLOSE_PROCESS_GONE_STABLE_MS = 150;
36+
const ANDROID_KILL_FOREGROUND_STABLE_MS = 150;
3637

3738
export async function listAndroidApps(
3839
device: DeviceInfo,
@@ -509,7 +510,7 @@ export async function killAndroidApp(device: DeviceInfo, app: string): Promise<v
509510
}
510511

511512
async function killAndroidPackage(device: DeviceInfo, packageName: string): Promise<void> {
512-
const foreground = await readAndroidForegroundApp(device);
513+
const foreground = await readAndroidForegroundAppSettled(device, packageName);
513514
if (foreground?.package === packageName) {
514515
throw new AppError('COMMAND_FAILED', `Cannot kill foreground app ${packageName}`, {
515516
reason: 'android-kill-requires-background-app',
@@ -561,6 +562,28 @@ async function readAndroidForegroundApp(device: DeviceInfo): Promise<AppStateRun
561562
return foreground.package ? foreground : null;
562563
}
563564

565+
/**
566+
* `killAndroidPackage`'s precondition needs the opposite corroboration from
567+
* `waitForAndroidPackageProcessGone`'s "gone twice in a row counts": here a read naming a
568+
* different app is not enough on its own to trust "safe to kill". Live evidence (2026-09-25,
569+
* Android 16 emulator): immediately after `launchApp`, `dumpsys window`'s `mCurrentFocus` still
570+
* named the previous foreground app for one read while `dumpsys activity activities` already
571+
* showed the launched app resumed — `getAndroidAppState` takes whichever dump answers first, so
572+
* that stale window-focus read alone would have skipped the `android-kill-requires-background-app`
573+
* refusal against a target still genuinely in the foreground. A same-app read is trusted
574+
* immediately (refusing early is always safe); a different-app or unreadable read is corroborated
575+
* once after a short settle before this lets `killAndroidPackage` proceed.
576+
*/
577+
async function readAndroidForegroundAppSettled(
578+
device: DeviceInfo,
579+
packageName: string,
580+
): Promise<AppStateRuntimeResult | null> {
581+
const first = await readAndroidForegroundApp(device);
582+
if (first?.package === packageName) return first;
583+
await sleep(ANDROID_KILL_FOREGROUND_STABLE_MS);
584+
return await readAndroidForegroundApp(device);
585+
}
586+
564587
async function waitForAndroidPackageProcessGone(
565588
device: DeviceInfo,
566589
packageName: string,

‎packages/platform-android/src/mechanics.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,6 @@ export async function listAndroidAppsWithAdb(
8383
export {
8484
closeAndroidApp,
8585
isAmStartError,
86-
killAndroidApp,
8786
openAndroidApp,
8887
openAndroidDevice,
8988
parseAndroidLaunchComponent,
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { test, expect, vi } from 'vitest';
2+
3+
import path from 'node:path';
4+
import type { DeviceInfo } from '@agent-device/kernel/device';
5+
import type { DaemonRequest, DaemonResponse } from '../../../daemon-request.ts';
6+
import { SessionStore } from '../../../session-store.ts';
7+
import { mkdtempForTestSync } from '../../../../__tests__/test-utils/tmp-dir.ts';
8+
9+
const mockResolveTargetDevice = vi.hoisted(() => vi.fn());
10+
11+
vi.mock('@agent-device/device-selection/dispatch-resolve', async (importOriginal) => {
12+
const actual =
13+
await importOriginal<typeof import('@agent-device/device-selection/dispatch-resolve')>();
14+
const { selectionFromResolveTargetDevice } =
15+
await import('../../../__tests__/device-selection-stub.ts');
16+
return {
17+
...actual,
18+
resolveTargetDevice: mockResolveTargetDevice,
19+
resolveTargetDeviceSelection: vi.fn(selectionFromResolveTargetDevice(mockResolveTargetDevice)),
20+
};
21+
});
22+
23+
import {
24+
handleSessionCommands,
25+
mockBindDeviceRuntime,
26+
} from '../../../handlers/__tests__/session-command-harness.ts';
27+
28+
const noopInvoke = async (_req: DaemonRequest): Promise<DaemonResponse> => ({ ok: true, data: {} });
29+
30+
const ANDROID_DEVICE: DeviceInfo = {
31+
platform: 'android',
32+
id: 'emulator-5554',
33+
name: 'Pixel',
34+
kind: 'emulator',
35+
target: 'mobile',
36+
booted: true,
37+
};
38+
39+
function makeSessionStore(): SessionStore {
40+
const root = mkdtempForTestSync('agent-device-session-close-without-session-');
41+
return new SessionStore(path.join(root, 'sessions'));
42+
}
43+
44+
// #2749 review: `closeWithoutSession` (session-close.ts) is a second `mode: 'kill'` dispatch site
45+
// alongside `dispatchTargetedPlatformClose`, exercised only when no session is stored for the
46+
// requested name (`close <app>` straight from flags). Nothing previously proved it threads
47+
// `killApp` into the platform `closeApplication` call the way the stored-session path is proven.
48+
test('an app-only kill close with no stored session still carries mode kill to the platform close', async () => {
49+
const sessionStore = makeSessionStore();
50+
mockResolveTargetDevice.mockResolvedValue(ANDROID_DEVICE);
51+
const seenModes: Array<unknown> = [];
52+
const baseBind = mockBindDeviceRuntime.getMockImplementation();
53+
mockBindDeviceRuntime.mockImplementationOnce(async (device, use) => {
54+
const binding = await baseBind!(device, use);
55+
const innerClose = binding.operations.closeApplication;
56+
if (!innerClose) return binding;
57+
return {
58+
...binding,
59+
operations: {
60+
...binding.operations,
61+
closeApplication: async (input: Parameters<typeof innerClose>[0]) => {
62+
seenModes.push(input.mode);
63+
},
64+
},
65+
};
66+
});
67+
68+
const response = await handleSessionCommands({
69+
req: {
70+
token: 't',
71+
session: 'no-such-session',
72+
command: 'close',
73+
positionals: ['com.example.app'],
74+
flags: { serial: 'emulator-5554' },
75+
internal: { closeAppOnly: true, killApp: true },
76+
},
77+
sessionName: 'no-such-session',
78+
logPath: path.join(mkdtempForTestSync('daemon'), 'daemon.log'),
79+
sessionStore,
80+
invoke: noopInvoke,
81+
});
82+
83+
expect(response?.ok).toBe(true);
84+
expect(seenModes).toEqual(['kill']);
85+
});

0 commit comments

Comments
 (0)