Skip to content

Commit 290b28b

Browse files
committed
fix(android): retry only the bare host refusal, inside the remaining budget
- match only stderr that is exactly adb's device-offline refusal, empty stdout, no timeout, so device output never triggers a rerun - wait takes half of the remaining budget; no budget left, refusal stands - wait uses the command's adb server and env - timeouts and cancels keep the stayed-offline mark - key the mark by adb server and serial
1 parent f38a95d commit 290b28b

3 files changed

Lines changed: 134 additions & 39 deletions

File tree

‎packages/platform-android/src/adb-failure.ts‎

Lines changed: 20 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -182,17 +182,28 @@ export function attachAndroidHelperInstallTimeoutHint<T>(error: T): T {
182182
return classified;
183183
}
184184

185-
/** True when adb refused a command because the device was offline, as a result or as the thrown error. */
186-
export function isAndroidAdbDeviceOffline(outcome: unknown): boolean {
185+
/** The entire stderr of a command the host adb refused because the device was offline. */
186+
const ADB_DEVICE_OFFLINE_REFUSAL = /^(?:adb|error): device (?:'[^']*' )?offline$/;
187+
188+
/**
189+
* True when the host adb refused a command because the device was offline, as a result or as the
190+
* thrown error. Only the bare refusal counts, so output of a command that ran on the device never
191+
* matches, and neither does a timeout's partial output.
192+
*/
193+
export function isAndroidAdbDeviceOfflineRefusal(outcome: unknown): boolean {
187194
if (outcome instanceof AppError) {
188-
return (
189-
outcome.code === 'COMMAND_FAILED' &&
190-
classifyAdbCommandError(outcome)?.reason === 'device_offline'
191-
);
195+
if (outcome.code !== 'COMMAND_FAILED' || outcome.details?.timeoutMs !== undefined) return false;
196+
return isBareDeviceOfflineRefusal(outcome.details?.stdout, outcome.details?.stderr);
192197
}
193-
const result = outcome as Partial<Pick<AndroidAdbExecutorResult, 'stderr' | 'stdout'>>;
194-
if (typeof result?.stderr !== 'string') return false;
195-
return classifyAndroidAdbFailure(result.stderr, result.stdout ?? '')?.reason === 'device_offline';
198+
if (!outcome || typeof outcome !== 'object') return false;
199+
const { stdout, stderr } = outcome as Partial<AndroidAdbExecutorResult>;
200+
return isBareDeviceOfflineRefusal(stdout, stderr);
201+
}
202+
203+
/** Whether the streams hold nothing but the host adb's device-offline refusal. */
204+
function isBareDeviceOfflineRefusal(stdout: unknown, stderr: unknown): boolean {
205+
if (stdout !== undefined && stdout !== '') return false;
206+
return typeof stderr === 'string' && ADB_DEVICE_OFFLINE_REFUSAL.test(stderr.trim());
196207
}
197208

198209
// Timeout wins over text matchers: the exec layer deliberately builds timeout

‎packages/platform-android/src/adb-provider-scope.test.ts‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,17 +212,81 @@ test('a caller that aborts during the wait gets no retry', async () => {
212212
expect(commands).toEqual(['install', 'wait-for-device']);
213213
});
214214

215+
test('device output that mentions device offline is not retried', async () => {
216+
const commands: string[] = [];
217+
const outputs = [
218+
{ exitCode: 1, stdout: 'partial', stderr: 'adb: device offline' },
219+
{ exitCode: 1, stdout: '', stderr: 'flash: device offline, giving up' },
220+
];
221+
bindAndroidAdbHostStub({
222+
execAdb: async (invocation) => {
223+
commands.push(isWaitForDevice(invocation) ? 'wait-for-device' : 'install');
224+
return outputs[commands.length - 1] ?? ok();
225+
},
226+
});
227+
const adb = createDeviceAdbExecutor(DEVICE);
228+
229+
await adb(['install', 'helper.apk'], { allowFailure: true });
230+
await adb(['install', 'helper.apk'], { allowFailure: true });
231+
expect(commands).toEqual(['install', 'install']);
232+
});
233+
234+
test('a refusal with no budget left for a wait stands', async () => {
235+
const commands: string[] = [];
236+
bindAndroidAdbHostStub({
237+
execAdb: async (invocation) => {
238+
commands.push(isWaitForDevice(invocation) ? 'wait-for-device' : 'install');
239+
return { exitCode: 1, stdout: '', stderr: 'adb: device offline' };
240+
},
241+
});
242+
243+
const result = await createDeviceAdbExecutor(DEVICE)(['install', 'helper.apk'], {
244+
allowFailure: true,
245+
timeoutMs: 1,
246+
});
247+
expect(result.exitCode).toBe(1);
248+
expect(commands).toEqual(['install']);
249+
});
250+
251+
test('the wait asks the same adb server and environment as the refused command', async () => {
252+
const calls: Array<{ wait: boolean; server: unknown; env: unknown }> = [];
253+
bindAndroidAdbHostStub({
254+
execAdb: async (invocation, options) => {
255+
const wait = isWaitForDevice(invocation);
256+
calls.push({ wait, server: invocation.target.server, env: options?.env });
257+
return calls.length === 1 ? { exitCode: 1, stdout: '', stderr: 'adb: device offline' } : ok();
258+
},
259+
});
260+
261+
await createDeviceAdbExecutor(DEVICE)(['install', 'helper.apk'], {
262+
serverPort: 15_037,
263+
env: { ANDROID_SERIAL: 'emulator-5554' },
264+
});
265+
expect(calls.map((call) => call.wait)).toEqual([false, true, false]);
266+
expect(calls[1]?.server).toEqual(calls[0]?.server);
267+
expect(calls[1]?.env).toEqual({ ANDROID_SERIAL: 'emulator-5554' });
268+
});
269+
215270
test('only a device-offline refusal is retried, and a device that stays offline stops waiting', async () => {
216271
const stuck: DeviceInfo = { ...DEVICE, id: 'emulator-5562' };
217272
const commands: string[] = [];
218273
let answers = false;
274+
let timesOut = false;
219275
bindAndroidAdbHostStub({
220276
execAdb: async (invocation) => {
221277
if (isWaitForDevice(invocation)) {
222278
commands.push('wait-for-device');
223279
return ok();
224280
}
225281
commands.push(invocation.command[0] ?? '');
282+
if (timesOut) {
283+
throw new AppError('COMMAND_FAILED', 'adb timed out after 10ms', {
284+
exitCode: -1,
285+
stdout: '',
286+
stderr: '',
287+
timeoutMs: 10,
288+
});
289+
}
226290
if (invocation.command[0] === 'uninstall') {
227291
return { exitCode: 1, stdout: 'Failure [DELETE_FAILED_INTERNAL_ERROR]', stderr: '' };
228292
}
@@ -243,6 +307,13 @@ test('only a device-offline refusal is retried, and a device that stays offline
243307
await adb(['install', 'helper.apk'], { allowFailure: true });
244308
expect(commands).toEqual(['install']);
245309

310+
timesOut = true;
311+
await expect(adb(['install', 'helper.apk'])).rejects.toThrow();
312+
timesOut = false;
313+
commands.length = 0;
314+
await adb(['install', 'helper.apk'], { allowFailure: true });
315+
expect(commands).toEqual(['install']);
316+
246317
answers = true;
247318
await adb(['install', 'helper.apk'], { allowFailure: true });
248319
answers = false;

‎packages/platform-android/src/adb-provider-scope.ts‎

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import {
66
deviceShellExecutableOf,
77
type ShellWord,
88
} from '@agent-device/kernel/device-shell';
9+
import { AppError } from '@agent-device/kernel/errors';
910
import {
1011
androidAdbInvocation,
1112
androidAdbPayloadWithoutSerial,
@@ -35,7 +36,7 @@ import {
3536
type AndroidAdbCommandExecutorOverride,
3637
type AndroidAdbHostTransport,
3738
} from './adb-host.ts';
38-
import { isAndroidAdbDeviceOffline, withAdbFailureHints } from './adb-failure.ts';
39+
import { isAndroidAdbDeviceOfflineRefusal, withAdbFailureHints } from './adb-failure.ts';
3940
import { createExecAndroidPortReverseProvider } from './adb-port-reverse.ts';
4041
import { normalizeAndroidAdbProvider } from './adb-provider-normalization.ts';
4142

@@ -73,14 +74,16 @@ function createSerialAdbExecutor(serial: string, serverPort?: number): AndroidAd
7374
);
7475
};
7576
return await retryOnceAfterDeviceOffline(
76-
serial,
77+
`${options?.serverPort ?? serverPort ?? ''}/${serial}`,
7778
options,
7879
async (attemptOptions) => await exec(args, attemptOptions),
7980
async (timeoutMs) => {
8081
await exec(['wait-for-device'], {
8182
allowFailure: true,
8283
timeoutMs,
8384
signal: options?.signal,
85+
env: options?.env,
86+
serverPort: options?.serverPort,
8487
}).catch(() => undefined);
8588
},
8689
);
@@ -96,60 +99,63 @@ const ANDROID_DEVICE_OFFLINE_WAIT_MS = 15_000;
9699
/** How long a device that stayed offline through a wait has its refusals surface without another. */
97100
const ANDROID_DEVICE_STAYED_OFFLINE_MS = 30_000;
98101

99-
/** Serials that stayed offline through a wait, mapped to when a refusal may wait again. */
102+
/** Devices (keyed by adb server and serial) that stayed offline through a wait, mapped to when a refusal may wait again. */
100103
const devicesStayingOffline = new Map<string, number>();
101104

102105
/**
103-
* Runs `run`, and once more after `waitForDevice` when adb refused it as `device offline`. The
104-
* refusal comes from the host adb before the command reaches the device, so the retry cannot
105-
* repeat an effect. The wait and the retry share the caller's `timeoutMs`, the wait taking at most
106-
* half. A failed wait is not reported: the retry's outcome is the device's state. A device that
107-
* stayed offline through its wait fails fast for a while instead of making every call wait.
106+
* Runs `run`, and once more after `waitForDevice` when the host adb refused it as `device offline`.
107+
* The refusal comes before the command reaches the device, so the retry cannot repeat an effect.
108+
* The wait and the retry stay inside the caller's `timeoutMs`, the wait taking at most half of what
109+
* is left; with no budget left the refusal stands. A failed wait is not reported: the retry's
110+
* outcome is the device's state. A device that stayed offline through its wait fails fast for a
111+
* while instead of making every call wait.
108112
*/
109113
async function retryOnceAfterDeviceOffline(
110-
serial: string,
114+
device: string,
111115
options: AndroidAdbExecutorOptions | undefined,
112116
run: (options: AndroidAdbExecutorOptions | undefined) => Promise<AndroidAdbExecutorResult>,
113117
waitForDevice: (timeoutMs: number) => Promise<void>,
114118
): Promise<AndroidAdbExecutorResult> {
115119
const startedAt = Date.now();
116-
const first = await attemptAdb(serial, async () => await run(options));
117-
if (!first.offline || (devicesStayingOffline.get(serial) ?? 0) > Date.now()) {
120+
const first = await attemptAdb(device, async () => await run(options));
121+
if (!first.offline || (devicesStayingOffline.get(device) ?? 0) > Date.now()) {
118122
return first.outcome();
119123
}
120124
const budgetMs = options?.timeoutMs;
121-
await waitForDevice(
122-
budgetMs === undefined
123-
? ANDROID_DEVICE_OFFLINE_WAIT_MS
124-
: Math.min(ANDROID_DEVICE_OFFLINE_WAIT_MS, Math.floor(budgetMs / 2)),
125-
);
125+
const remainingMs = () =>
126+
budgetMs === undefined ? Infinity : Math.floor(budgetMs - (Date.now() - startedAt));
127+
const waitMs = Math.min(ANDROID_DEVICE_OFFLINE_WAIT_MS, Math.floor(remainingMs() / 2));
128+
if (waitMs < 1) return first.outcome();
129+
await waitForDevice(waitMs);
126130
options?.signal?.throwIfAborted();
127-
const retryOptions =
128-
budgetMs === undefined
129-
? options
130-
: { ...options, timeoutMs: Math.max(1, budgetMs - (Date.now() - startedAt)) };
131-
const retry = await attemptAdb(serial, async () => await run(retryOptions));
132-
if (retry.offline)
133-
devicesStayingOffline.set(serial, Date.now() + ANDROID_DEVICE_STAYED_OFFLINE_MS);
131+
const retryMs = remainingMs();
132+
if (retryMs < 1) return first.outcome();
133+
const retry = await attemptAdb(
134+
device,
135+
async () => await run(budgetMs === undefined ? options : { ...options, timeoutMs: retryMs }),
136+
);
137+
if (retry.offline) {
138+
devicesStayingOffline.set(device, Date.now() + ANDROID_DEVICE_STAYED_OFFLINE_MS);
139+
}
134140
return retry.outcome();
135141
}
136142

137143
/**
138-
* Runs one adb attempt and reports whether adb refused it as `device offline`. Any other outcome
139-
* means the device answered, so it forgets that the device stayed offline.
144+
* Runs one adb attempt and reports whether the host adb refused it as `device offline`. An outcome
145+
* the device answered forgets that the device stayed offline; a timeout or cancellation does not.
140146
*/
141147
async function attemptAdb(
142-
serial: string,
148+
device: string,
143149
run: () => Promise<AndroidAdbExecutorResult>,
144150
): Promise<{ offline: boolean; outcome: () => AndroidAdbExecutorResult }> {
145151
try {
146152
const result = await run();
147-
const offline = result.exitCode !== 0 && isAndroidAdbDeviceOffline(result);
148-
if (!offline) devicesStayingOffline.delete(serial);
153+
const offline = result.exitCode !== 0 && isAndroidAdbDeviceOfflineRefusal(result);
154+
if (!offline) devicesStayingOffline.delete(device);
149155
return { offline, outcome: () => result };
150156
} catch (error) {
151-
const offline = isAndroidAdbDeviceOffline(error);
152-
if (!offline) devicesStayingOffline.delete(serial);
157+
const offline = isAndroidAdbDeviceOfflineRefusal(error);
158+
if (!offline && deviceAnswered(error)) devicesStayingOffline.delete(device);
153159
return {
154160
offline,
155161
outcome: () => {
@@ -159,6 +165,13 @@ async function attemptAdb(
159165
}
160166
}
161167

168+
/** Whether a thrown adb failure is an exit the device reached, not a timeout or cancellation. */
169+
function deviceAnswered(error: unknown): boolean {
170+
if (!(error instanceof AppError) || error.details?.timeoutMs !== undefined) return false;
171+
const exitCode = error.details?.exitCode;
172+
return typeof exitCode === 'number' && exitCode >= 0;
173+
}
174+
162175
function createSerialAdbSpawner(serial: string, serverPort?: number): AndroidAdbSpawner {
163176
return guardDeviceShellSpawn((args, options) => {
164177
const request = deviceAdbRouteRequest(serial, serverPort, args, options);

0 commit comments

Comments
 (0)