Skip to content

Commit 9f48ee2

Browse files
committed
fix: keep the emulator focus helper best effort
The osascript helper only hands focus back to the app that was frontmost before a windowed launch. It now starts through runCmdDetachedMonitored, and a spawn failure, synchronous or reported later on its exit, emits android_emulator_focus_return_failed and never fails the launch or stops the booting emulator. No step after the emulator spawn can throw, so the launch path no longer terminates on failure. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4
1 parent 83ee1d6 commit 9f48ee2

2 files changed

Lines changed: 79 additions & 34 deletions

File tree

‎src/platform-runtime-android-emulator-host.test.ts‎

Lines changed: 46 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,27 @@
11
import { beforeEach, expect, test, vi } from 'vitest';
22

3-
const { runCmd, runCmdDetached } = vi.hoisted(() => ({
3+
const { runCmd, runCmdDetached, runCmdDetachedMonitored, emitDiagnostic } = vi.hoisted(() => ({
44
runCmd: vi.fn(async (_cmd: string, args: readonly string[]) => ({
55
stdout: args[0] === 'front' ? 'ASN:0x0-0xa26a26:\n' : '"pid"=17044\n',
66
stderr: '',
77
exitCode: 0,
88
})),
99
runCmdDetached: vi.fn(() => 4242),
10+
runCmdDetachedMonitored: vi.fn((_cmd: string, _args: readonly string[]) => ({
11+
pid: 5151,
12+
exited: Promise.resolve<{ pid: number; exitCode?: number; error?: string }>({
13+
pid: 5151,
14+
exitCode: 0,
15+
}),
16+
})),
17+
emitDiagnostic: vi.fn(),
18+
}));
19+
vi.mock('@agent-device/host-kit/command', () => ({
20+
runCmd,
21+
runCmdDetached,
22+
runCmdDetachedMonitored,
1023
}));
11-
vi.mock('@agent-device/host-kit/command', () => ({ runCmd, runCmdDetached }));
24+
vi.mock('@agent-device/host-kit/diagnostics', () => ({ emitDiagnostic }));
1225
const { readProcessIdentityFacts, stopProcessAndConfirmExit } = vi.hoisted(() => ({
1326
readProcessIdentityFacts: vi.fn(async () => ({
1427
startTime: 'Mon Nov 9 10:00:00 2026',
@@ -27,6 +40,8 @@ import { createAndroidEmulatorHost } from './platform-runtime-android-emulator-h
2740
beforeEach(() => {
2841
runCmd.mockClear();
2942
runCmdDetached.mockClear();
43+
runCmdDetachedMonitored.mockClear();
44+
emitDiagnostic.mockClear();
3045
stopProcessAndConfirmExit.mockClear();
3146
});
3247

@@ -40,9 +55,9 @@ test('a windowed macOS launch hands focus back to the app frontmost before launc
4055
['info', '-only', 'pid', 'ASN:0x0-0xa26a26:'],
4156
expect.anything(),
4257
);
43-
expect(runCmdDetached).toHaveBeenCalledTimes(2);
44-
expect(runCmdDetached).toHaveBeenNthCalledWith(1, 'emulator', ['-avd', 'Pixel_9']);
45-
expect(runCmdDetached).toHaveBeenNthCalledWith(2, 'osascript', [
58+
expect(runCmdDetached).toHaveBeenCalledOnce();
59+
expect(runCmdDetached).toHaveBeenCalledWith('emulator', ['-avd', 'Pixel_9']);
60+
expect(runCmdDetachedMonitored).toHaveBeenCalledWith('osascript', [
4661
'-l',
4762
'JavaScript',
4863
'-e',
@@ -59,6 +74,7 @@ test('a macOS launch with no readable frontmost app starts no focus watcher', as
5974
await createAndroidEmulatorHost('darwin').launch('Pixel_9', false, 90_000);
6075

6176
expect(runCmdDetached).toHaveBeenCalledOnce();
77+
expect(runCmdDetachedMonitored).not.toHaveBeenCalled();
6278
});
6379

6480
test('a failed frontmost-app read still launches the emulator, without a focus watcher', async () => {
@@ -70,6 +86,7 @@ test('a failed frontmost-app read still launches the emulator, without a focus w
7086

7187
expect(runCmdDetached).toHaveBeenCalledOnce();
7288
expect(runCmdDetached).toHaveBeenCalledWith('emulator', ['-avd', 'Pixel_9']);
89+
expect(runCmdDetachedMonitored).not.toHaveBeenCalled();
7390
});
7491

7592
test('a headless launch has no window to keep in the background', async () => {
@@ -90,6 +107,7 @@ test('a launch on another host leaves window focus alone', async () => {
90107

91108
expect(runCmd).not.toHaveBeenCalled();
92109
expect(runCmdDetached).toHaveBeenCalledOnce();
110+
expect(runCmdDetachedMonitored).not.toHaveBeenCalled();
93111
});
94112

95113
test('terminate stops only the emulator this host launched, by its recorded identity', async () => {
@@ -139,19 +157,32 @@ test('a terminate that could not prove the exit keeps the launch for a retry', a
139157
expect(stopProcessAndConfirmExit).toHaveBeenCalledTimes(2);
140158
});
141159

142-
test('a launch that fails after spawning stops its own emulator before it rethrows', async () => {
143-
runCmdDetached
144-
.mockImplementationOnce(() => 4242)
145-
.mockImplementationOnce(() => {
160+
// The focus helper only hands focus back to the previous app, so it is best effort: a helper that
161+
// cannot start never fails the launch or stops the booting emulator.
162+
test.each([
163+
[
164+
'throws on spawn',
165+
() => {
146166
throw new Error('osascript missing');
147-
});
167+
},
168+
],
169+
[
170+
'reports a spawn error after it starts',
171+
() => ({
172+
pid: 0,
173+
exited: Promise.resolve({ pid: 0, error: 'spawn osascript ENOENT' }),
174+
}),
175+
],
176+
] as const)('a focus helper that %s still returns the emulator pid', async (_name, spawn) => {
177+
runCmdDetachedMonitored.mockImplementationOnce(spawn);
148178
const host = createAndroidEmulatorHost('darwin');
149179

150-
await expect(host.launch('Pixel_9', false, 90_000)).rejects.toThrow('osascript missing');
180+
await expect(host.launch('Pixel_9', false, 90_000)).resolves.toBe(4242);
151181

152-
expect(stopProcessAndConfirmExit).toHaveBeenCalledOnce();
153-
expect(stopProcessAndConfirmExit).toHaveBeenCalledWith(
154-
expect.objectContaining({ pid: 4242 }),
155-
expect.anything(),
182+
await vi.waitFor(() =>
183+
expect(emitDiagnostic).toHaveBeenCalledWith(
184+
expect.objectContaining({ phase: 'android_emulator_focus_return_failed' }),
185+
),
156186
);
187+
expect(stopProcessAndConfirmExit).not.toHaveBeenCalled();
157188
});

‎src/platform-runtime-android-emulator-host.ts‎

Lines changed: 33 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import type { DeviceReadinessRuntimeHost } from '@agent-device/contracts/device-readiness-runtime';
22
import { listLocalDeviceInventory } from '@agent-device/device-selection/device-inventory-context';
3-
import { runCmd, runCmdDetached } from '@agent-device/host-kit/command';
3+
import { runCmd, runCmdDetached, runCmdDetachedMonitored } from '@agent-device/host-kit/command';
44
import { emitDiagnostic } from '@agent-device/host-kit/diagnostics';
55
import {
66
readProcessIdentityFacts,
@@ -82,30 +82,44 @@ export function createAndroidEmulatorHost(
8282
avdName,
8383
startTime: readProcessIdentityFacts(pid).then((facts) => facts.startTime),
8484
});
85-
// A caller learns the pid only from a launch that returns, so a launch that fails after the
86-
// spawn stops its own emulator before it rethrows.
87-
try {
88-
if (frontmostPid !== undefined) {
89-
runCmdDetached('osascript', [
90-
'-l',
91-
'JavaScript',
92-
'-e',
93-
RETURN_FOCUS_SCRIPT,
94-
String(pid),
95-
String(frontmostPid),
96-
String(bootBudgetMs),
97-
]);
98-
}
99-
} catch (error) {
100-
await terminate(pid);
101-
throw error;
102-
}
85+
if (frontmostPid !== undefined) returnFocusAfterLaunch(pid, frontmostPid, bootBudgetMs);
10386
return pid;
10487
},
10588
terminate,
10689
});
10790
}
10891

92+
/**
93+
* Hands focus back to the app that was frontmost before a windowed launch. This is best effort: a
94+
* focus helper that fails to start never fails the launch or stops the booting emulator, and only
95+
* leaves a diagnostic.
96+
*/
97+
function returnFocusAfterLaunch(pid: number, frontmostPid: number, bootBudgetMs: number): void {
98+
const reportFailure = (error: string): void => {
99+
emitDiagnostic({
100+
level: 'warn',
101+
phase: 'android_emulator_focus_return_failed',
102+
data: { pid, error },
103+
});
104+
};
105+
try {
106+
const helper = runCmdDetachedMonitored('osascript', [
107+
'-l',
108+
'JavaScript',
109+
'-e',
110+
RETURN_FOCUS_SCRIPT,
111+
String(pid),
112+
String(frontmostPid),
113+
String(bootBudgetMs),
114+
]);
115+
void helper.exited.then((exit) => {
116+
if (exit.error !== undefined) reportFailure(exit.error);
117+
});
118+
} catch (error) {
119+
reportFailure(error instanceof Error ? error.message : String(error));
120+
}
121+
}
122+
109123
function isEmulatorCommandFor(command: string, avdName: string): boolean {
110124
const args = command.split(/\s+/);
111125
const avdFlag = args.indexOf('-avd');

0 commit comments

Comments
 (0)