Repository navigation
Expand file tree
/
Copy pathadb-failure.ts
More file actions
333 lines (310 loc) · 13 KB
/
Copy pathadb-failure.ts
File metadata and controls
333 lines (310 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
type AndroidAdbFailureReason =
| 'timeout'
| 'device_offline'
| 'device_unauthorized'
| 'device_not_found'
| 'multiple_devices'
| 'no_devices'
| 'connection_dropped'
| 'server_version_mismatch'
| 'install_insufficient_storage'
| 'install_update_incompatible'
| 'install_version_downgrade'
| 'install_failed';
export type AndroidAdbFailureClassification = Readonly<{
reason: AndroidAdbFailureReason;
hint: string;
retriable?: boolean;
/** The host adb refused the command before it reached the device, so it had no effect there. */
hostRefusal?: true;
}>;
type AndroidAdbFailureMatcher = readonly [
pattern: RegExp,
failure: AndroidAdbFailureClassification,
matchStdout?: true,
];
const ANDROID_ADB_DEVICE_OFFLINE_FAILURE = {
reason: 'device_offline',
hint: 'The device is connected but offline — wait for it to finish booting or run adb reconnect, then retry.',
retriable: true,
} as const satisfies AndroidAdbFailureClassification;
const ANDROID_ADB_FAILURE_MATCHERS = [
[
/device unauthorized|device still authorizing/,
{
reason: 'device_unauthorized',
hint: 'USB debugging is not authorized — accept the authorization prompt on the device screen (re-plug the cable if none appears), then retry.',
},
],
[/device offline/, ANDROID_ADB_DEVICE_OFFLINE_FAILURE],
[
/more than one (?:device\/emulator|device and emulator)/,
{
reason: 'multiple_devices',
hint: 'Multiple Android devices are connected — pass --serial <serial> (see adb devices) to select one.',
},
],
[
/no devices\/emulators found|no devices found/,
{
reason: 'no_devices',
hint: 'No Android devices detected — boot an emulator or connect a device and verify it appears in adb devices.',
},
],
[
/device (?:'[^']*' )?not found/,
{
reason: 'device_not_found',
hint: 'The device disconnected or is restarting — verify it is listed in adb devices, then retry.',
retriable: true,
},
],
[
/adb server version \(\d+\) doesn't match this client/,
{
reason: 'server_version_mismatch',
hint: 'Multiple adb installs conflict — adb restarts its server automatically, so retry; align PATH to a single adb to stop recurrences.',
retriable: true,
},
],
[
/transport error|connection reset|broken pipe|protocol fault/,
{
reason: 'connection_dropped',
hint: 'The adb connection dropped — retry; if it persists, run adb kill-server and reconnect the device.',
retriable: true,
},
],
[
/install_failed_insufficient_storage/,
{
reason: 'install_insufficient_storage',
hint: 'The device is out of storage — free up space or uninstall unused apps, then retry the install.',
},
true,
],
[
/install_failed_update_incompatible/,
{
reason: 'install_update_incompatible',
hint: 'The installed app has an incompatible signature — uninstall the existing app first, then retry the install.',
},
true,
],
[
/install_failed_version_downgrade/,
{
reason: 'install_version_downgrade',
hint: 'The APK is older than the installed app — uninstall the app first (or install with downgrade allowed), then retry.',
},
true,
],
[
/install_failed_\w+|install_parse_failed_\w+/,
{
reason: 'install_failed',
hint: 'The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.',
},
true,
],
] as const satisfies readonly AndroidAdbFailureMatcher[];
const ANDROID_ADB_TIMEOUT_FAILURE: AndroidAdbFailureClassification = Object.freeze({
reason: 'timeout',
hint: 'adb timed out — the adb server may be wedged. Run adb kill-server && adb start-server, check adb devices, then retry.',
});
const ANDROID_HELPER_INSTALL_TIMEOUT_HINT =
'The helper install timed out — some OEM builds (ColorOS is one) hold the first install of each package behind a system install-confirmation dialog and adb waits for it. Check the device screen, confirm any pending install prompt, then retry; if none is showing, run adb kill-server && adb start-server and retry.';
type HostRefusalShape = readonly [head: RegExp, reason: AndroidAdbFailureReason];
const HOST_REFUSAL_PREFIX = String.raw`(?:adb|error): `;
/** First stderr line, lowercased, of each refusal the host adb issues before the command leaves the host. */
const HOST_REFUSAL_SHAPES: readonly HostRefusalShape[] = [
[
new RegExp(`^${HOST_REFUSAL_PREFIX}device (?:unauthorized|still authorizing)\\.?$`),
'device_unauthorized',
],
[new RegExp(`^${HOST_REFUSAL_PREFIX}device (?:'[^']*' )?offline$`), 'device_offline'],
[
new RegExp(`^${HOST_REFUSAL_PREFIX}more than one (?:device/emulator|device and emulator)$`),
'multiple_devices',
],
[new RegExp(`^${HOST_REFUSAL_PREFIX}no devices(?:/emulators)? found$`), 'no_devices'],
[new RegExp(`^${HOST_REFUSAL_PREFIX}device (?:'[^']*' )?not found$`), 'device_not_found'],
];
/** The fixed trailer lines adb appends to a device_unauthorized refusal. */
const HOST_REFUSAL_TRAILER =
/^(?:this adb server's \$adb_vendor_keys is not set|try 'adb kill-server' if that seems wrong\.|(?:otherwise|please) check (?:for|the) (?:a )?confirmation dialog on your device\.)$/;
const ANDROID_ADB_FAILURES_BY_REASON = new Map<
AndroidAdbFailureReason,
AndroidAdbFailureClassification
>(ANDROID_ADB_FAILURE_MATCHERS.map(([, failure]) => [failure.reason, failure]));
function classifyHostRefusal(
stderrText: string,
stdoutText: string,
): AndroidAdbFailureClassification | undefined {
if (stdoutText !== '') return undefined;
const [head, ...trailer] = stderrText
.split('\n')
.map((line) => line.trim())
.filter((line) => line !== '');
if (head === undefined || !trailer.every((line) => HOST_REFUSAL_TRAILER.test(line))) {
return undefined;
}
const reason = HOST_REFUSAL_SHAPES.find(([shape]) => shape.test(head))?.[1];
const failure = reason && ANDROID_ADB_FAILURES_BY_REASON.get(reason);
return failure && { ...failure, hostRefusal: true };
}
export function classifyAndroidAdbFailure(
stderr: string,
stdout = '',
): AndroidAdbFailureClassification | undefined {
const stderrText = stderr.toLowerCase();
const stdoutText = stdout.toLowerCase();
const refusal = classifyHostRefusal(stderrText, stdoutText);
if (refusal) return refusal;
for (const [pattern, classification, matchStdout] of ANDROID_ADB_FAILURE_MATCHERS) {
if (pattern.test(stderrText) || (matchStdout && pattern.test(stdoutText))) {
return classification;
}
}
return undefined;
}
import { AppError, discloseDispatch } from '@agent-device/kernel/errors';
import { isCommandTimeoutError } from '@agent-device/host-kit/command';
import type { HostCommandResult } from '@agent-device/contracts/platform-runtime-host';
import type { AndroidAdbExecutorResult } from './adb-transport.ts';
/**
* Enriches a failed adb command error in place with the classified hint,
* `retriable` flag, machine-readable `adbFailure` family, and `adbHostRefusal` when the host adb
* refused the command before it reached the device, so every adb call
* site surfaces guidance without per-site classification. Exec-layer timeouts
* classify as `timeout` even though they leave no stderr. No-op for errors that
* are not adb command failures or that carry no recognized failure signal; an
* existing hint or retriable verdict is never overwritten.
*/
export function attachAdbFailureHint<T>(error: T): T {
if (!(error instanceof AppError) || error.code !== 'COMMAND_FAILED') return error;
const classification = classifyAdbCommandError(error);
if (!classification) return error;
error.details = {
...error.details,
adbFailure: classification.reason,
...(classification.hostRefusal ? { adbHostRefusal: true } : {}),
...(typeof error.details?.hint === 'string' ? {} : { hint: classification.hint }),
...(classification.retriable !== undefined && error.details?.retriable === undefined
? { retriable: classification.retriable }
: {}),
};
return error;
}
/**
* Rewrites the hint on a helper-APK install timeout to name the likelier cause. Some OEM builds
* (ColorOS is one) hold the package installer open on a system install-confirmation dialog for
* the first install of a package; the command yields no stderr, so the generic timeout hint reads
* as a wedged adb server and points away from the only fix. Reach it only through
* `installAndroidHelperPackage`, the Android helper install seam: every other adb timeout keeps
* the generic advice. Only that generic advice is replaced — a hint curated nearer the failure
* (a provider's own advice, or a request cancellation) survives, as elsewhere in this module.
*/
export function attachAndroidHelperInstallTimeoutHint<T>(error: T): T {
if (!isCommandTimeoutError(error)) return error;
const curatedHint = error.details?.hint;
if (typeof curatedHint === 'string' && curatedHint !== ANDROID_ADB_TIMEOUT_FAILURE.hint) {
return error;
}
const classified = attachAdbFailureHint(error);
classified.details = { ...classified.details, hint: ANDROID_HELPER_INSTALL_TIMEOUT_HINT };
return classified;
}
// Timeout wins over text matchers: the exec layer deliberately builds timeout
// errors around "timed out after Nms" because partial output from the killed
// process is untrustworthy — classifying that partial stderr (e.g. flagging a
// half-written transport line retriable) would point away from the real fix.
function classifyAdbCommandError(error: AppError): AndroidAdbFailureClassification | undefined {
if (typeof error.details?.timeoutMs === 'number') return ANDROID_ADB_TIMEOUT_FAILURE;
const stderr = typeof error.details?.stderr === 'string' ? error.details.stderr : '';
const stdout = typeof error.details?.stdout === 'string' ? error.details.stdout : '';
return classifyAndroidAdbFailure(stderr, stdout);
}
/**
* Builds the COMMAND_FAILED AppError for a failed `allowFailure` adb result and
* runs it through the failure classifier. This is the shared construction point
* for call sites that tolerate a failure to inspect it and then throw — those
* errors never cross the executor throw path, so they classify here instead.
* Site-provided `details` win on key collisions, and a site `hint` is preserved
* over the classified one.
*
* Nonzero exits set processExitError so normalizeError appends the first stderr
* line to the curated message — the classified hint and stderr-excerpt
* enrichment compose instead of competing. Semantic failures thrown at exit 0
* (e.g. an `am start` error printed on a successful exit) stay unflagged so a
* stray stderr line never decorates a message the process exit does not back up.
*/
export function androidAdbResultError(
message: string,
result: Pick<AndroidAdbExecutorResult, 'exitCode' | 'stdout' | 'stderr'>,
details?: Record<string, unknown>,
): AppError {
const failureDetails =
result.exitCode === 0
? { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, ...details }
: {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
processExitError: true,
...details,
};
return attachAdbFailureHint(new AppError('COMMAND_FAILED', message, failureDetails));
}
export function withAdbFailureHints<Args extends unknown[], Result>(
call: (...args: Args) => Promise<Result>,
): (...args: Args) => Promise<Result> {
return async (...args) => {
try {
return await call(...args);
} catch (error) {
throw attachAdbFailureHint(error);
}
};
}
export function androidDiscoveryCommandError(
message: string,
result: HostCommandResult,
fallbackHint: string,
): AppError {
const failure = classifyAndroidAdbFailure(result.stderr, result.stdout);
return new AppError('COMMAND_FAILED', message, {
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
processExitError: true,
hint: failure?.hint ?? fallbackHint,
...(failure ? { adbFailure: failure.reason } : {}),
...(failure?.retriable === undefined ? {} : { retriable: failure.retriable }),
});
}
export function attachAndroidDiscoveryTimeout<T>(error: T): T {
if (!isCommandTimeoutError(error)) return error;
error.details = {
...error.details,
adbFailure: ANDROID_ADB_TIMEOUT_FAILURE.reason,
...(typeof error.details?.hint === 'string'
? {}
: {
hint: ANDROID_ADB_TIMEOUT_FAILURE.hint,
}),
};
return error;
}
/** One adb input send's failure: adb that never started or a host adb refusal delivered nothing; otherwise it may have. */
export function discloseAdbInputDispatch(error: unknown): unknown {
if (!(error instanceof AppError)) return error;
return discloseDispatch(
error,
error.code === 'TOOL_MISSING' || isAdbHostRefusal(error) ? 'no' : 'unknown',
);
}
/** Whether the host adb refused the command before it reached the device, so it had no effect there. */
export function isAdbHostRefusal(error: AppError): boolean {
return error.details?.adbHostRefusal === true;
}