Skip to content

Commit dba7393

Browse files
committed
fix(android): cover install rejections and preserve diagnostic identity (#1285 review)
P1: the device-side install marker now covers the whole install phase. ensureAndroidSnapshotHelper previously tagged only a resolved nonzero install result; an AndroidAdbProvider.install rejection (enriched INSTALL_FAILED_* AppError from the provider funnel) bypassed the marker and fell back to the generic retry/doctor hint. Both paths now flow through markAndroidSnapshotHelperInstallFailure, which mutates details in place so the original code, message, hint, details, and cause all survive. Regression covers the public daemon snapshot route with a real request handler and an injected provider whose install rejects. P2: androidSnapshotHelperCaptureError rewrapped through normalizeError, which lifts diagnosticId/logPath out of details — the rewrap dropped them (ADR 0010 violation). They are now reinstated into the rewrapped error's details. Hint selection moved to a helper to keep the function under the complexity gate.
1 parent 661d276 commit dba7393

5 files changed

Lines changed: 227 additions & 29 deletions

File tree

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import { beforeEach, expect, test } from 'vitest';
2+
import { createRequestHandler } from '../request-router.ts';
3+
import { LeaseRegistry } from '../lease-registry.ts';
4+
import { SessionStore } from '../session-store.ts';
5+
import { AppError } from '../../kernel/errors.ts';
6+
import { resetAndroidSnapshotHelperInstallCache } from '../../platforms/android/snapshot-helper-install.ts';
7+
import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from '../../__tests__/test-utils/index.ts';
8+
import type { AndroidAdbProvider } from '../../platforms/android/adb-executor.ts';
9+
10+
function makeAndroidSessionStore(name: string): SessionStore {
11+
const sessionStore = new SessionStore(`/tmp/${name}`);
12+
sessionStore.set('default', {
13+
name: 'default',
14+
createdAt: Date.now(),
15+
device: {
16+
platform: 'android',
17+
id: 'remote-android-1',
18+
name: 'Remote Android',
19+
kind: 'device',
20+
booted: true,
21+
},
22+
appBundleId: 'com.example.app',
23+
actions: [],
24+
});
25+
return sessionStore;
26+
}
27+
28+
function makeHandler(sessionStore: SessionStore, androidAdbProvider: () => AndroidAdbProvider) {
29+
return createRequestHandler({
30+
logPath: '/tmp/daemon.log',
31+
token: 'token',
32+
sessionStore,
33+
leaseRegistry: new LeaseRegistry(),
34+
androidAdbProvider,
35+
trackDownloadableArtifact: () => 'artifact-id',
36+
});
37+
}
38+
39+
beforeEach(() => {
40+
resetAndroidSnapshotHelperInstallCache();
41+
});
42+
43+
// Regression for #1284/#1285 P1: a provider whose `install` REJECTS with an
44+
// enriched INSTALL_FAILED_* error (instead of resolving with a nonzero result)
45+
// must still surface the device-side install classification on the public
46+
// daemon snapshot error, not the generic retry/doctor hint.
47+
test('snapshot reports a device-side install failure when the provider install rejects', async () => {
48+
const sessionStore = makeAndroidSessionStore(
49+
'agent-device-request-router-snapshot-helper-install-reject-test',
50+
);
51+
const provider: AndroidAdbProvider = {
52+
// Version probe reports no installed helper; every other device query is inert.
53+
exec: async () => ({ exitCode: 0, stdout: '', stderr: '' }),
54+
install: async () => {
55+
throw new AppError('COMMAND_FAILED', 'Failed to install Android snapshot helper', {
56+
stderr: 'adb: failed to install helper.apk: Failure [INSTALL_FAILED_TEST_ONLY]',
57+
stdout: '',
58+
exitCode: 1,
59+
processExitError: true,
60+
});
61+
},
62+
snapshotHelperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT,
63+
};
64+
const handler = makeHandler(sessionStore, () => provider);
65+
66+
const response = await handler({
67+
token: 'token',
68+
session: 'default',
69+
command: 'snapshot',
70+
positionals: [],
71+
flags: {},
72+
});
73+
74+
expect(response.ok).toBe(false);
75+
if (response.ok) throw new Error('Expected snapshot to fail');
76+
expect(response.error.message).toMatch(/Android snapshot helper failed/);
77+
expect(response.error.message).toMatch(/INSTALL_FAILED_TEST_ONLY/);
78+
// The provider funnel's classified adb hint is preserved, with the
79+
// device-side framing appended rather than replacing it.
80+
expect(response.error.hint).toMatch(/package installer rejected the APK/);
81+
expect(response.error.hint).toMatch(/device-side install failure/);
82+
expect(response.error.hint).not.toMatch(/pnpm build:android/);
83+
expect(response.error.details?.androidSnapshotHelperInstallFailure).toBe(true);
84+
});

‎src/platforms/android/__tests__/snapshot-helper.test.ts‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import {
1313
forgetAndroidSnapshotHelperInstall,
1414
resetAndroidSnapshotHelperInstallCache,
1515
} from '../snapshot-helper-install.ts';
16+
import { AppError } from '../../../kernel/errors.ts';
1617
import { parseAndroidSnapshotHelperManifest } from '../snapshot-helper-artifact.ts';
1718
import { verifyAndroidHelperApkChecksum } from '../helper-package-install.ts';
1819
import type {
@@ -236,6 +237,48 @@ test('ensureAndroidSnapshotHelper tags a device-side install rejection distinctl
236237
);
237238
});
238239

240+
test('ensureAndroidSnapshotHelper tags a rejected provider install without losing the enriched error', async () => {
241+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'snapshot-helper-install-throw-'));
242+
const apkPath = path.join(tmpDir, 'helper.apk');
243+
await fs.writeFile(apkPath, 'helper-apk');
244+
const installError = new AppError('COMMAND_FAILED', 'Failed to install Android snapshot helper', {
245+
stderr: 'adb: failed to install helper.apk: Failure [INSTALL_FAILED_TEST_ONLY]',
246+
stdout: '',
247+
exitCode: 1,
248+
processExitError: true,
249+
hint: 'The Android package installer rejected the APK — see the INSTALL_FAILED code in the error output for the exact cause.',
250+
});
251+
const adb: AndroidAdbExecutor = async (args) => {
252+
if (args.includes('--show-versioncode')) {
253+
return { exitCode: 1, stdout: '', stderr: 'not found' };
254+
}
255+
throw new Error(`unexpected adb call: ${args.join(' ')}`);
256+
};
257+
const adbProvider: AndroidAdbProvider = {
258+
exec: adb,
259+
install: async () => {
260+
throw installError;
261+
},
262+
};
263+
264+
await assert.rejects(
265+
() =>
266+
ensureAndroidSnapshotHelper({
267+
adb,
268+
adbProvider,
269+
artifact: { apkPath, manifest: { ...manifest, sha256: sha256Text('helper-apk') } },
270+
}),
271+
(error) => {
272+
assert.equal(error, installError);
273+
const details = (error as AppError).details;
274+
assert.equal(details?.androidSnapshotHelperInstallFailure, true);
275+
assert.match(String(details?.stderr), /INSTALL_FAILED_TEST_ONLY/);
276+
assert.match(String(details?.hint), /package installer rejected the APK/);
277+
return true;
278+
},
279+
);
280+
});
281+
239282
test('ensureAndroidSnapshotHelper replaces same-version helper when APK bytes differ', async () => {
240283
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'snapshot-helper-identity-'));
241284
const apkPath = path.join(tmpDir, 'helper.apk');

‎src/platforms/android/__tests__/snapshot.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,6 +943,28 @@ test('snapshotAndroid distinguishes a device-side install rejection from a missi
943943
);
944944
});
945945

946+
test('snapshotAndroid preserves upstream diagnosticId and logPath through the capture rewrap', async () => {
947+
const helperAdb = createHelperAdb({
948+
instrument: async () => {
949+
throw new AppError('COMMAND_FAILED', 'helper capture exploded', {
950+
diagnosticId: 'diag-upstream',
951+
logPath: '/tmp/upstream.ndjson',
952+
});
953+
},
954+
});
955+
956+
await assert.rejects(
957+
() => snapshotAndroidWithHelper(helperAdb),
958+
(error) => {
959+
assert.match((error as Error).message, /Android snapshot helper failed/);
960+
const details = (error as { details?: Record<string, unknown> }).details;
961+
assert.equal(details?.diagnosticId, 'diag-upstream');
962+
assert.equal(details?.logPath, '/tmp/upstream.ndjson');
963+
return true;
964+
},
965+
);
966+
});
967+
946968
test('snapshotAndroid emits timeout diagnostics when helper capture times out', async () => {
947969
const helperAdb = createHelperAdb({
948970
instrument: async () => {

‎src/platforms/android/snapshot-helper-install.ts‎

Lines changed: 40 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { asAppError, type AppError } from '../../kernel/errors.ts';
12
import { readAndroidSnapshotHelperInstallOptions } from './snapshot-helper-artifact.ts';
23
import {
34
inspectInstalledAndroidHelper,
@@ -136,25 +137,30 @@ export async function ensureAndroidSnapshotHelper(options: {
136137
};
137138
}
138139

139-
const result = await installAndroidSnapshotHelper(
140-
adb,
141-
options.adbProvider ?? adb,
142-
artifact.apkPath,
143-
readAndroidSnapshotHelperInstallOptions(artifact.manifest),
144-
{
145-
packageName,
146-
timeoutMs: options.timeoutMs,
147-
},
148-
);
140+
let result: Awaited<ReturnType<AndroidAdbExecutor>>;
141+
try {
142+
result = await installAndroidSnapshotHelper(
143+
adb,
144+
options.adbProvider ?? adb,
145+
artifact.apkPath,
146+
readAndroidSnapshotHelperInstallOptions(artifact.manifest),
147+
{
148+
packageName,
149+
timeoutMs: options.timeoutMs,
150+
},
151+
);
152+
} catch (error) {
153+
forgetInstalledSnapshotHelper(installCacheKey);
154+
throw markAndroidSnapshotHelperInstallFailure(error, { packageName, versionCode });
155+
}
149156
if (result.exitCode !== 0) {
150157
forgetInstalledSnapshotHelper(installCacheKey);
151-
throw androidAdbResultError('Failed to install Android snapshot helper', result, {
152-
packageName,
153-
versionCode,
154-
// Distinguishes a device-side install rejection (adb/OEM policy) from an
155-
// artifact-resolution failure so the capture-layer error can hint accordingly.
156-
androidSnapshotHelperInstallFailure: true,
157-
});
158+
throw markAndroidSnapshotHelperInstallFailure(
159+
androidAdbResultError('Failed to install Android snapshot helper', result, {
160+
packageName,
161+
versionCode,
162+
}),
163+
);
158164
}
159165

160166
rememberInstalledSnapshotHelper(installCacheKey, versionCode);
@@ -168,6 +174,23 @@ export async function ensureAndroidSnapshotHelper(options: {
168174
};
169175
}
170176

177+
// Tags every failure of the helper install phase — nonzero results and provider
178+
// rejections alike — so the capture layer can distinguish a device-side install
179+
// rejection (adb/OEM policy) from a missing build artifact. Mutates details in
180+
// place, preserving the original code, message, hint, and cause.
181+
function markAndroidSnapshotHelperInstallFailure(
182+
error: unknown,
183+
context?: { packageName: string; versionCode: number },
184+
): AppError {
185+
const appError = asAppError(error, 'COMMAND_FAILED');
186+
appError.details = {
187+
...context,
188+
...appError.details,
189+
androidSnapshotHelperInstallFailure: true,
190+
};
191+
return appError;
192+
}
193+
171194
function normalizeAdbProvider(
172195
provider: AndroidAdbProvider | AndroidAdbExecutor | undefined,
173196
adb: AndroidAdbExecutor,

‎src/platforms/android/snapshot.ts‎

Lines changed: 38 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
import fs from 'node:fs/promises';
22
import path from 'node:path';
3-
import { AppError, normalizeError, toAppErrorCode } from '../../kernel/errors.ts';
3+
import {
4+
AppError,
5+
normalizeError,
6+
toAppErrorCode,
7+
type NormalizedError,
8+
} from '../../kernel/errors.ts';
49
import { emitDiagnostic, withDiagnosticTimer } from '../../utils/diagnostics.ts';
510
import type { DeviceInfo } from '../../kernel/device.ts';
611
import { findProjectRoot, readVersion } from '../../utils/version.ts';
@@ -464,28 +469,49 @@ function formatAndroidSnapshotHelperFailureReason(error: unknown): string {
464469

465470
function androidSnapshotHelperCaptureError(error: unknown, reason: string): AppError {
466471
const normalized = normalizeError(error);
467-
const busy =
468-
isStructuredHelperTimeout(normalized.details?.helper, normalized.message) ||
469-
isKilledHelperInstrumentationFailure(normalized);
470-
const installFailure = normalized.details?.androidSnapshotHelperInstallFailure === true;
471-
const hint = busy
472-
? 'Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists.'
473-
: installFailure
474-
? `${normalized.hint ? `${normalized.hint} ` : ''}This is a device-side install failure (adb rejection or OEM policy) — the helper artifact itself is present, this is not a missing/unbuilt build.`
475-
: (normalized.hint ??
476-
'Retry once. If the helper still fails, run agent-device doctor and report the diagnostic log; agent-device does not substitute a second snapshot engine.');
477472
return new AppError(
478473
toAppErrorCode(normalized.code),
479474
`Android snapshot helper failed: ${reason}`,
480475
{
481476
...normalized.details,
477+
...liftedDiagnosticIdentity(normalized),
482478
androidSnapshotHelperFailureReason: reason,
483-
hint,
479+
hint: androidSnapshotHelperCaptureHint(normalized),
484480
},
485481
error,
486482
);
487483
}
488484

485+
function androidSnapshotHelperCaptureHint(normalized: NormalizedError): string {
486+
const busy =
487+
isStructuredHelperTimeout(normalized.details?.helper, normalized.message) ||
488+
isKilledHelperInstrumentationFailure(normalized);
489+
if (busy) {
490+
return 'Android accessibility snapshots can be blocked by busy or continuously changing app UI. Use screenshot as visual truth after this timeout and report the busy UI if it persists.';
491+
}
492+
if (normalized.details?.androidSnapshotHelperInstallFailure === true) {
493+
return [
494+
normalized.hint,
495+
'This is a device-side install failure (adb rejection or OEM policy) — the helper artifact itself is present, this is not a missing/unbuilt build.',
496+
]
497+
.filter(Boolean)
498+
.join(' ');
499+
}
500+
return (
501+
normalized.hint ??
502+
'Retry once. If the helper still fails, run agent-device doctor and report the diagnostic log; agent-device does not substitute a second snapshot engine.'
503+
);
504+
}
505+
506+
// normalizeError lifts these out of details (ADR 0010); a rewrap must put them
507+
// back so the upstream diagnostic identity survives.
508+
function liftedDiagnosticIdentity(normalized: NormalizedError): Record<string, string> {
509+
const identity: Record<string, string> = {};
510+
if (normalized.diagnosticId !== undefined) identity.diagnosticId = normalized.diagnosticId;
511+
if (normalized.logPath !== undefined) identity.logPath = normalized.logPath;
512+
return identity;
513+
}
514+
489515
function isKilledHelperInstrumentationFailure(error: {
490516
message: string;
491517
details?: Record<string, unknown>;

0 commit comments

Comments
 (0)