From 547901a767633d7616bb9ffef43258923e83b863 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 08:22:59 +0100 Subject: [PATCH 01/12] fix(android): give a helper the system refused to start one more start, and scope the session fake's stall to its helper A one-shot helper run whose typed exit result reports INSTRUMENTATION_FAILED ran nothing on the device. Right after a boot or a /data restore the system refuses a current helper about once in ten and starts it on the next run, so the capture resets the helper runtime and starts it exactly once more. Any other failure, or a second refusal, surfaces as before. The session fake counted its stalled snapshots across helper processes, so a capture cancelled before its helper was ready left the stall to the next helper. The stall now belongs to the first helper, and the cancel tests abort at explicit points instead of on a 10 ms timer. Fixes #4030 Fixes #4109 Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-session.fixtures.ts | 13 +- .../__tests__/snapshot-helper-session.test.ts | 72 ++++---- .../snapshot-helper-start-retry.test.ts | 157 ++++++++++++++++++ .../src/snapshot-helper-capture.ts | 13 ++ packages/platform-android/src/snapshot.ts | 44 +++-- 5 files changed, 257 insertions(+), 42 deletions(-) create mode 100644 packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts index 7a317a3bd2..a44f78613d 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -186,9 +186,15 @@ export type SessionProviderOptions = { stalledCleanup?: boolean; /** How many `forward --remove` calls hang until their cleanup budget aborts them. */ stalledForwardRemovals?: number; + /** + * How many snapshot requests the first helper process leaves unanswered. A stall belongs to the + * helper that hung, so a helper started after it answers. + */ stalledSnapshots?: number; - /** How many snapshot requests each helper process answers before `stalledSnapshots` applies. */ + /** How many snapshot requests the first helper answers before `stalledSnapshots` applies. */ answeredSnapshotsBeforeStall?: number; + /** Called when the helper receives a request it leaves unanswered. */ + onStalledSnapshot?: () => void; /** Whether `adb features` advertises the shell protocol that forwards device exit status. */ shellProtocolV2?: boolean; /** Make the `adb features` probe fail the way an adb too old to know the command does. */ @@ -211,7 +217,7 @@ export type FakeAndroidHelperRuntimeRelease = export function createSessionProvider(options: SessionProviderOptions): AndroidAdbProvider { bindAndroidAdbTestHost(); - let stalledSnapshots = options.stalledSnapshots ?? 0; + let spawnedHelpers = 0; return { exec: createSessionExec(options), spawn: (args) => { @@ -219,6 +225,8 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA const port = readSessionPort(args); const process = new FakeAndroidProcess(); options.processes?.push(process); + spawnedHelpers += 1; + let stalledSnapshots = spawnedHelpers === 1 ? (options.stalledSnapshots ?? 0) : 0; let snapshotCount = 0; const sockets = new Set(); const server = net.createServer((socket) => { @@ -263,6 +271,7 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA snapshotCount += 1; if (snapshotCount > (options.answeredSnapshotsBeforeStall ?? 0) && stalledSnapshots > 0) { stalledSnapshots -= 1; + options.onStalledSnapshot?.(); return; } const body = ``; diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts index 38cfa9a472..e835a98e9b 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.test.ts @@ -99,53 +99,69 @@ test('retires a persistent session that exceeds the helper command budget', asyn ); }); -test('cancels a stalled snapshot, retires its helper, and starts the next capture cleanly', async () => { - const calls: (readonly string[])[] = []; - const processes: FakeAndroidProcess[] = []; - const provider = createSessionProvider({ calls, processes, stalledSnapshots: 1 }); - const controller = new AbortController(); - const capture = captureAndroidSnapshotWithHelperSession({ - adb: provider.exec, - adbProvider: provider, - deviceKey: 'android:emulator-5554', - signal: controller.signal, - }); - setTimeout(() => controller.abort(new Error('wait deadline exceeded')), 10); +// A cancellation lands wherever the caller's deadline falls (#4030): before the helper reports +// ready, or while the helper holds the snapshot request it never answers. +for (const cancelPoint of ['before the helper is ready', 'while the helper stalls'] as const) { + test(`cancels a capture ${cancelPoint}, retires its helper, and starts the next capture cleanly`, async () => { + const calls: (readonly string[])[] = []; + const processes: FakeAndroidProcess[] = []; + const controller = new AbortController(); + const cancel = () => controller.abort(new Error('wait deadline exceeded')); + const provider = createSessionProvider({ + calls, + processes, + stalledSnapshots: 1, + ...(cancelPoint === 'while the helper stalls' ? { onStalledSnapshot: cancel } : {}), + }); + const capture = captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: { + ...provider, + spawn: (args, options) => { + const process = provider.spawn!(args, options); + if (cancelPoint === 'before the helper is ready') cancel(); + return process; + }, + }, + deviceKey: 'android:emulator-5554', + signal: controller.signal, + }); - await assert.rejects(capture, /wait deadline exceeded/); - assert.equal(processes[0]?.killed, true); - assert.equal( - calls.some((args) => args[0] === 'forward' && args[1] === '--remove'), - true, - ); + await assert.rejects(capture, /wait deadline exceeded/); + assert.equal(processes[0]?.killed, true); + assert.equal( + calls.some((args) => args[0] === 'forward' && args[1] === '--remove'), + true, + ); - const next = await captureAndroidSnapshotWithHelperSession({ - adb: provider.exec, - adbProvider: provider, - deviceKey: 'android:emulator-5554', + const next = await captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey: 'android:emulator-5554', + }); + assert.match(next?.xml ?? '', /snapshot 1/); + assert.equal(next?.metadata.sessionReused, false); + assert.equal(processes.length, 2); }); - assert.match(next?.xml ?? '', /snapshot 1/); - assert.equal(next?.metadata.sessionReused, false); - assert.equal(processes.length, 2); -}); +} test('canceled capture joins canceled external cleanup before returning', async () => { const calls: (readonly string[])[] = []; const cleanupAborts: (readonly string[])[] = []; + const controller = new AbortController(); const provider = createSessionProvider({ calls, cleanupAborts, stalledSnapshots: 1, stalledCleanup: true, + onStalledSnapshot: () => controller.abort(new Error('wait deadline exceeded')), }); - const controller = new AbortController(); const capture = captureAndroidSnapshotWithHelperSession({ adb: provider.exec, adbProvider: provider, deviceKey: 'android:emulator-5554', signal: controller.signal, }); - setTimeout(() => controller.abort(new Error('wait deadline exceeded')), 10); const outcome = await Promise.race([ capture.then( diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts new file mode 100644 index 0000000000..4992af5e55 --- /dev/null +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -0,0 +1,157 @@ +import assert from 'node:assert/strict'; +import { afterEach, beforeEach, test, vi } from 'vitest'; + +vi.mock('../adb.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, sleep: vi.fn(async () => {}) }; +}); + +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { normalizeError } from '@agent-device/kernel/errors'; +import type { AndroidAdbExecutorResult, AndroidAdbProvider } from '../adb-executor.ts'; +import { snapshotAndroid } from '../snapshot.ts'; +import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; +import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; +import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; +import { + ANDROID_HELPER_INSTALLED_VERSION_PROBE, + androidHelperInstrumentationOutput, + androidHelperRuntimeProbeResult, + FakeAndroidProcess, + isAndroidHelperRuntimeForceStop, + isAndroidHelperRuntimeProbe, +} from './snapshot-helper-session.fixtures.ts'; +import { bindAndroidAdbTestHost } from './test-utils/android-host-test-setup.ts'; + +const device: DeviceInfo = { + platform: 'android', + id: 'emulator-5556', + name: 'Pixel', + kind: 'emulator', + booted: true, +}; + +const HELPER_RUNNER = `${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName}/.SnapshotInstrumentation`; + +// What `am instrument` prints when the system could not start the instrumentation at all. +const INSTRUMENTATION_FAILED_RUN: AndroidAdbExecutorResult = { + exitCode: 1, + stdout: '', + stderr: `android.util.AndroidException: INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, +}; + +const CAPTURED_RUN: AndroidAdbExecutorResult = { + exitCode: 0, + stdout: androidHelperInstrumentationOutput( + '', + ), + stderr: '', +}; + +beforeEach(async () => { + await resetAndroidSnapshotHelperSessions(); + resetAndroidSnapshotHelperInstallCache(); +}); + +afterEach(async () => { + await resetAndroidSnapshotHelperSessions(); +}); + +/** + * A device right after boot (#4109): the helper is installed and current, the persistent session + * exits before it is ready, and each one-shot run answers with the next of `oneShotRuns`. + */ +function freshlyBootedHelper(oneShotRuns: AndroidAdbExecutorResult[]): { + provider: AndroidAdbProvider; + calls: (readonly string[])[]; +} { + bindAndroidAdbTestHost(); + const calls: (readonly string[])[] = []; + const runs = [...oneShotRuns]; + return { + calls, + provider: { + exec: async (args) => { + calls.push(args); + if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; + if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); + if (args.includes('instrument')) return runs.shift() ?? CAPTURED_RUN; + return { exitCode: 0, stdout: '', stderr: '' }; + }, + spawn: () => { + const process = new FakeAndroidProcess(); + setImmediate(() => { + process.stderr.write(INSTRUMENTATION_FAILED_RUN.stderr); + process.emitExit(1, null); + }); + return process; + }, + }, + }; +} + +const isOneShotRun = (args: readonly string[]) => args.includes('instrument'); + +async function snapshotRejection(provider: AndroidAdbProvider) { + try { + await snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + }); + } catch (error) { + return normalizeError(error); + } + assert.fail('expected the snapshot to fail'); +} + +test('a helper the system failed to start gets one more start after a runtime reset', async () => { + const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); + + const snapshot = await snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + }); + + assert.ok(snapshot.nodes.some((node) => node.label === 'after retry')); + const oneShotRuns = calls.flatMap((args, index) => (isOneShotRun(args) ? [index] : [])); + assert.equal(oneShotRuns.length, 2); + assert.ok( + calls.slice(oneShotRuns[0], oneShotRuns[1]).some(isAndroidHelperRuntimeForceStop), + 'the helper runtime is reset before the second start', + ); +}); + +test('a helper the system fails to start twice reports the start failure', async () => { + const { provider, calls } = freshlyBootedHelper([ + INSTRUMENTATION_FAILED_RUN, + INSTRUMENTATION_FAILED_RUN, + ]); + + const error = await snapshotRejection(provider); + + assert.equal(calls.filter(isOneShotRun).length, 2); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.deepEqual(error.details?.instrumentation, { exitCode: 1, failed: HELPER_RUNNER }); +}); + +test('a helper that started and then exited early is not started again', async () => { + const earlyExits: AndroidAdbExecutorResult[] = [ + { exitCode: 1, stdout: 'INSTRUMENTATION_ABORTED: System has crashed.\n', stderr: '' }, + // The same words without the startup-failure envelope are a message, not a failed start. + { + exitCode: 1, + stdout: `INSTRUMENTATION_RESULT: shortMsg=INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, + stderr: '', + }, + ]; + for (const run of earlyExits) { + await resetAndroidSnapshotHelperSessions(); + resetAndroidSnapshotHelperInstallCache(); + const { provider, calls } = freshlyBootedHelper([run]); + + const error = await snapshotRejection(provider); + + assert.equal(calls.filter(isOneShotRun).length, 1, run.stdout); + assert.equal(error.code, 'COMMAND_FAILED'); + } +}); diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index c1402b0186..d5995a0d18 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -12,6 +12,7 @@ import { readInstrumentationResultIntegerList, readInstrumentationResultNumber, readInstrumentationExitResult, + type AndroidInstrumentationExitResult, } from './instrumentation-helper.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, @@ -121,6 +122,18 @@ export async function captureAndroidSnapshotWithHelper( return output; } +/** + * The one-shot run failed because the system never started the helper: `am instrument` reported + * `INSTRUMENTATION_FAILED`, so the helper did not run and printed nothing. + */ +export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean { + if (!(error instanceof AppError)) return false; + const instrumentation = error.details?.instrumentation as + | AndroidInstrumentationExitResult + | undefined; + return instrumentation?.failed !== undefined; +} + /** * An executor failure (a deadline, a spawn error) carries the helper's raw stdout, which can hold the * snapshot it was printing. It is replaced by the parsed instrumentation result; `stderr` and the diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index baa411529e..608e58541f 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -30,7 +30,10 @@ import { import { buildAndroidSnapshotClickabilityEvidence } from './snapshot-clickability.ts'; import { resolveAndroidAdbProvider, type AndroidAdbProvider } from './adb-executor.ts'; import { sleep } from './adb.ts'; -import { buildAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts'; +import { + buildAndroidSnapshotHelperCaptureOptions, + isAndroidSnapshotHelperStartFailure, +} from './snapshot-helper-capture.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, @@ -503,17 +506,34 @@ async function captureAndroidUiHierarchyFromHelper(params: { }); await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); } - return await withDiagnosticTimer( - ANDROID_SNAPSHOT_HELPER_CAPTURE_PHASE, - async () => await captureAndroidSnapshotWithHelper(captureOptions), - { - packageName: artifact.manifest.packageName, - version: artifact.manifest.version, - timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, - commandTimeoutMs: ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, - transport: 'instrumentation' satisfies AndroidSnapshotHelperTransport, - }, - ); + const captureOneShot = async () => + await withDiagnosticTimer( + ANDROID_SNAPSHOT_HELPER_CAPTURE_PHASE, + async () => await captureAndroidSnapshotWithHelper(captureOptions), + { + packageName: artifact.manifest.packageName, + version: artifact.manifest.version, + timeoutMs: ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, + commandTimeoutMs: ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, + transport: 'instrumentation' satisfies AndroidSnapshotHelperTransport, + }, + ); + try { + return await captureOneShot(); + } catch (error) { + signal?.throwIfAborted(); + // Right after a boot or a `/data` restore, the system can refuse to start a current helper + // once and start it on the next run (#4109). A refused start ran nothing on the device, so it + // gets exactly one more start after a runtime reset; any other failure is the answer. + if (!isAndroidSnapshotHelperStartFailure(error)) throw error; + emitDiagnostic({ + level: 'warn', + phase: 'android_snapshot_helper_start_retry', + data: { instrumentation: normalizeError(error).details?.instrumentation }, + }); + await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); + return await captureOneShot(); + } } function formatAndroidHelperCaptureResult( From 0ab7c3a39d5b126dbceb40943d649f90f9866d35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 08:25:25 +0100 Subject: [PATCH 02/12] docs(android): say what a refused helper start ran Co-Authored-By: Claude Opus 5.5 --- packages/platform-android/src/snapshot-helper-capture.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index d5995a0d18..83fee89428 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -124,7 +124,7 @@ export async function captureAndroidSnapshotWithHelper( /** * The one-shot run failed because the system never started the helper: `am instrument` reported - * `INSTRUMENTATION_FAILED`, so the helper did not run and printed nothing. + * `INSTRUMENTATION_FAILED`, so no helper code ran on the device. */ export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean { if (!(error instanceof AppError)) return false; From b96d4735bd8bfdec7d1b0069ee49166f80abfcdc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 08:40:50 +0100 Subject: [PATCH 03/12] fix(android): do not start the helper again for a capture cancelled during the reset Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 23 +++++++++++++++++++ packages/platform-android/src/snapshot.ts | 1 + 2 files changed, 24 insertions(+) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 4992af5e55..7500281995 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -155,3 +155,26 @@ test('a helper that started and then exited early is not started again', async ( assert.equal(error.code, 'COMMAND_FAILED'); } }); + +test('a capture cancelled during the reset before the second start does not start the helper again', async () => { + const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); + const controller = new AbortController(); + const exec = provider.exec; + provider.exec = async (args, options) => { + // The runtime reset that follows the refused one-shot start, not the session's own cleanup. + if (isAndroidHelperRuntimeForceStop(args) && calls.some(isOneShotRun)) { + controller.abort(new Error('wait deadline exceeded')); + } + return await exec(args, options); + }; + + await assert.rejects( + snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + signal: controller.signal, + }), + /wait deadline exceeded/, + ); + assert.equal(calls.filter(isOneShotRun).length, 1); +}); diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index 608e58541f..6ffc3965f1 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -532,6 +532,7 @@ async function captureAndroidUiHierarchyFromHelper(params: { data: { instrumentation: normalizeError(error).details?.instrumentation }, }); await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); + signal?.throwIfAborted(); return await captureOneShot(); } } From e0379797112521c561419cad363ed8d45dca5c17 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 08:42:39 +0100 Subject: [PATCH 04/12] fix(android): let a cancellation end the reset before a second helper start The reset before the second start now forwards the request signal to its force-stop and settle delay, so a cancelled or expired request rejects promptly instead of finishing the reset first. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 73 +++++++++++++------ .../src/snapshot-helper-runtime.ts | 6 +- packages/platform-android/src/snapshot.ts | 2 +- 3 files changed, 55 insertions(+), 26 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 7500281995..977644fc19 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -1,9 +1,20 @@ import assert from 'node:assert/strict'; import { afterEach, beforeEach, test, vi } from 'vitest'; +// Time does not pass on its own: a wait without a signal ends at once, and a cancellable wait ends +// only when its signal aborts, so a wait that ignores the caller's cancellation is observable. vi.mock('../adb.ts', async (importOriginal) => { const actual = await importOriginal(); - return { ...actual, sleep: vi.fn(async () => {}) }; + return { + ...actual, + sleep: vi.fn( + async (_ms: number, signal?: AbortSignal) => + await new Promise((resolve) => { + if (!signal || signal.aborted) return resolve(); + signal.addEventListener('abort', () => resolve(), { once: true }); + }), + ), + }; }); import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -156,25 +167,41 @@ test('a helper that started and then exited early is not started again', async ( } }); -test('a capture cancelled during the reset before the second start does not start the helper again', async () => { - const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); - const controller = new AbortController(); - const exec = provider.exec; - provider.exec = async (args, options) => { - // The runtime reset that follows the refused one-shot start, not the session's own cleanup. - if (isAndroidHelperRuntimeForceStop(args) && calls.some(isOneShotRun)) { - controller.abort(new Error('wait deadline exceeded')); - } - return await exec(args, options); - }; - - await assert.rejects( - snapshotAndroid(device, { - helperAdb: provider, - helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - signal: controller.signal, - }), - /wait deadline exceeded/, - ); - assert.equal(calls.filter(isOneShotRun).length, 1); -}); +// The reset before the second start is a force-stop and then a settle delay; a cancellation in either +// ends the capture there. +for (const cancelPoint of ['force-stop', 'settle delay'] as const) { + test(`a capture cancelled during the reset's ${cancelPoint} rejects without starting the helper again`, async () => { + const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); + const controller = new AbortController(); + const cancel = () => controller.abort(new Error('wait deadline exceeded')); + const exec = provider.exec; + provider.exec = async (args, options) => { + // The reset that follows the refused one-shot start, not the session's own cleanup. + if (!isAndroidHelperRuntimeForceStop(args) || !calls.some(isOneShotRun)) { + return await exec(args, options); + } + calls.push(args); + if (cancelPoint === 'settle delay') { + setImmediate(cancel); + return { exitCode: 0, stdout: '', stderr: '' }; + } + // A force-stop that hangs ends only through the signal it was given. + cancel(); + return await new Promise((_resolve, reject) => { + const signal = options?.signal; + if (signal?.aborted) reject(signal.reason); + signal?.addEventListener('abort', () => reject(signal.reason), { once: true }); + }); + }; + + await assert.rejects( + snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + signal: controller.signal, + }), + /wait deadline exceeded/, + ); + assert.equal(calls.filter(isOneShotRun).length, 1); + }); +} diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index f8615a5821..282c6251f0 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -28,12 +28,14 @@ export async function retireAndroidSnapshotHelperAfterContentFailure(params: { } } +/** A cancelled `signal` ends the reset early; the caller decides what a cancellation answers. */ export async function resetAndroidSnapshotHelperRuntime( adb: AndroidAdbExecutor, packageName: string, + signal?: AbortSignal, ): Promise { - await stopAndroidSnapshotHelperRuntime({ adb, packageName }); - await sleep(HELPER_RUNTIME_RESET_DELAY_MS); + await stopAndroidSnapshotHelperRuntime({ adb, packageName, ...(signal ? { signal } : {}) }); + await sleep(HELPER_RUNTIME_RESET_DELAY_MS, signal); emitDiagnostic({ level: 'debug', phase: 'android_snapshot_helper_runtime_reset', diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index 6ffc3965f1..a594173e56 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -531,7 +531,7 @@ async function captureAndroidUiHierarchyFromHelper(params: { phase: 'android_snapshot_helper_start_retry', data: { instrumentation: normalizeError(error).details?.instrumentation }, }); - await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); + await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName, signal); signal?.throwIfAborted(); return await captureOneShot(); } From 4da1b468bf85673a9f5a05ee9f3f0e1d91c9daac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 08:56:35 +0100 Subject: [PATCH 05/12] fix(android): retry only a start am instrument refused, and keep the reset log honest A one-shot failure is a refused start only when the run exited with INSTRUMENTATION_FAILED and carries nothing a started instrumentation prints or a signal ends; a run that started and printed is not retried. A cancelled reset no longer reports a completed runtime reset. The force-stop cancel test now aborts once the force-stop is in flight and listening. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 12 +++++++++--- .../src/instrumentation-helper.ts | 17 +++++++++++++++++ .../src/snapshot-helper-capture.ts | 17 +++++++++-------- .../src/snapshot-helper-runtime.ts | 2 ++ 4 files changed, 37 insertions(+), 11 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 977644fc19..7c9a073006 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -154,6 +154,12 @@ test('a helper that started and then exited early is not started again', async ( stdout: `INSTRUMENTATION_RESULT: shortMsg=INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, stderr: '', }, + // A run that started and printed is not a refused start, whatever line its stderr also holds. + { + exitCode: 1, + stdout: 'INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n', + stderr: INSTRUMENTATION_FAILED_RUN.stderr, + }, ]; for (const run of earlyExits) { await resetAndroidSnapshotHelperSessions(); @@ -185,12 +191,12 @@ for (const cancelPoint of ['force-stop', 'settle delay'] as const) { setImmediate(cancel); return { exitCode: 0, stdout: '', stderr: '' }; } - // A force-stop that hangs ends only through the signal it was given. - cancel(); + // A force-stop that hangs ends only through the signal it was given; the cancellation lands + // once it is in flight and listening. return await new Promise((_resolve, reject) => { const signal = options?.signal; - if (signal?.aborted) reject(signal.reason); signal?.addEventListener('abort', () => reject(signal.reason), { once: true }); + setImmediate(cancel); }); }; diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index 33c59867f2..6bb70f7e80 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -313,6 +313,23 @@ function appendLine(value: string | undefined, line: string): string | undefined return next.length > MESSAGE_FIELD_MAX_CHARS ? value : next; } +/** + * A run `am instrument` refused to start: it exited, reported `INSTRUMENTATION_FAILED`, and carries + * nothing a started instrumentation prints (a status or result code, an abort) or a signal ends. + */ +export function isRefusedInstrumentationStart(result: unknown): boolean { + if (typeof result !== 'object' || result === null) return false; + const run: Partial> = result; + return ( + typeof run.failed === 'string' && + typeof run.exitCode === 'number' && + run.signal === undefined && + run.statusCode === undefined && + run.resultCode === undefined && + run.aborted === undefined + ); +} + export function readInstrumentationExitResult(run: { stdout: string; stderr: string; diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index 83fee89428..03c89f7ffb 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -12,7 +12,7 @@ import { readInstrumentationResultIntegerList, readInstrumentationResultNumber, readInstrumentationExitResult, - type AndroidInstrumentationExitResult, + isRefusedInstrumentationStart, } from './instrumentation-helper.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, @@ -123,15 +123,16 @@ export async function captureAndroidSnapshotWithHelper( } /** - * The one-shot run failed because the system never started the helper: `am instrument` reported - * `INSTRUMENTATION_FAILED`, so no helper code ran on the device. + * The one-shot run failed because the system never started the helper: `am instrument` refused the + * start, so no helper code ran on the device and the helper reported nothing. */ export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean { - if (!(error instanceof AppError)) return false; - const instrumentation = error.details?.instrumentation as - | AndroidInstrumentationExitResult - | undefined; - return instrumentation?.failed !== undefined; + return ( + error instanceof AppError && + error.code === 'COMMAND_FAILED' && + error.details?.helper === undefined && + isRefusedInstrumentationStart(error.details?.instrumentation) + ); } /** diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index 282c6251f0..d91b94cd4f 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -36,6 +36,8 @@ export async function resetAndroidSnapshotHelperRuntime( ): Promise { await stopAndroidSnapshotHelperRuntime({ adb, packageName, ...(signal ? { signal } : {}) }); await sleep(HELPER_RUNTIME_RESET_DELAY_MS, signal); + // A cancelled reset may have cut the force-stop or the settle short, so it does not report one. + if (signal?.aborted) return; emitDiagnostic({ level: 'debug', phase: 'android_snapshot_helper_runtime_reset', From 0abf74d24a76bbcb0a52e2a81062fb3cb796ce52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 09:12:52 +0100 Subject: [PATCH 06/12] fix(android): define a refused helper start by what the system reports A one-shot failure is retried only when all of these hold: the run came back from adb on its own with a non-zero exit and no signal; it reported INSTRUMENTATION_FAILED; its only status is the system's refusal report (status -1 from ActivityManagerService, as captured on an Android 15 emulator); it has no result code, abort, result message or stack; no field was withheld; and no helper session was ready for the capture. Each condition has a row in one table-driven test. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 202 +++++++++++++----- .../src/instrumentation-helper.ts | 34 ++- .../src/snapshot-helper-capture.ts | 16 +- .../src/snapshot-helper-runtime.ts | 2 +- .../src/snapshot-helper-session.ts | 28 +-- packages/platform-android/src/snapshot.ts | 24 ++- 6 files changed, 203 insertions(+), 103 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 7c9a073006..45f6c178fd 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -18,7 +18,7 @@ vi.mock('../adb.ts', async (importOriginal) => { }); import type { DeviceInfo } from '@agent-device/kernel/device'; -import { normalizeError } from '@agent-device/kernel/errors'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { AndroidAdbExecutorResult, AndroidAdbProvider } from '../adb-executor.ts'; import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; @@ -26,6 +26,7 @@ import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-l import { ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT } from './test-utils/android-snapshot-helper.ts'; import { ANDROID_HELPER_INSTALLED_VERSION_PROBE, + createSessionProvider, androidHelperInstrumentationOutput, androidHelperRuntimeProbeResult, FakeAndroidProcess, @@ -44,11 +45,25 @@ const device: DeviceInfo = { const HELPER_RUNNER = `${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName}/.SnapshotInstrumentation`; -// What `am instrument` prints when the system could not start the instrumentation at all. +// What `am instrument -w` prints when the system refuses to start the instrumentation, as captured +// from an Android 15 emulator: ActivityManagerService reports the refusal as status -1, and then +// `am` throws INSTRUMENTATION_FAILED. +const REFUSED_STDOUT = [ + `INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, + 'INSTRUMENTATION_STATUS: id=ActivityManagerService', + 'INSTRUMENTATION_STATUS_CODE: -1', + '', +].join('\n'); +const REFUSED_STDERR = [ + `android.util.AndroidException: INSTRUMENTATION_FAILED: ${HELPER_RUNNER}`, + '\tat com.android.commands.am.Instrument.run(Instrument.java:543)', + '\tat com.android.commands.am.Am.runInstrument(Am.java:213)', + '', +].join('\n'); const INSTRUMENTATION_FAILED_RUN: AndroidAdbExecutorResult = { exitCode: 1, - stdout: '', - stderr: `android.util.AndroidException: INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, + stdout: REFUSED_STDOUT, + stderr: REFUSED_STDERR, }; const CAPTURED_RUN: AndroidAdbExecutorResult = { @@ -68,17 +83,21 @@ afterEach(async () => { await resetAndroidSnapshotHelperSessions(); }); +type OneShotRun = AndroidAdbExecutorResult | AppError; + /** - * A device right after boot (#4109): the helper is installed and current, the persistent session - * exits before it is ready, and each one-shot run answers with the next of `oneShotRuns`. + * A device whose helper is installed and current. Its persistent session either exits before it is + * ready, refused like the one-shot run (#4109), or becomes ready and then fails its capture. Each + * one-shot run answers with the next of `oneShotRuns`; an `AppError` is thrown as the executor does. */ -function freshlyBootedHelper(oneShotRuns: AndroidAdbExecutorResult[]): { - provider: AndroidAdbProvider; - calls: (readonly string[])[]; -} { +function freshlyBootedHelper( + oneShotRuns: OneShotRun[], + session: 'exits-before-ready' | 'ready-then-fails' = 'exits-before-ready', +): { provider: AndroidAdbProvider; calls: (readonly string[])[] } { bindAndroidAdbTestHost(); const calls: (readonly string[])[] = []; const runs = [...oneShotRuns]; + const failingSession = createSessionProvider({ calls: [], responseMode: 'malformed' }); return { calls, provider: { @@ -86,13 +105,17 @@ function freshlyBootedHelper(oneShotRuns: AndroidAdbExecutorResult[]): { calls.push(args); if (args.includes('--show-versioncode')) return ANDROID_HELPER_INSTALLED_VERSION_PROBE; if (isAndroidHelperRuntimeProbe(args)) return androidHelperRuntimeProbeResult(); - if (args.includes('instrument')) return runs.shift() ?? CAPTURED_RUN; - return { exitCode: 0, stdout: '', stderr: '' }; + if (!isOneShotRun(args)) return { exitCode: 0, stdout: '', stderr: '' }; + const run = runs.shift() ?? CAPTURED_RUN; + if (run instanceof AppError) throw run; + return run; }, - spawn: () => { + spawn: (args, options) => { + if (session === 'ready-then-fails') return failingSession.spawn!(args, options); const process = new FakeAndroidProcess(); setImmediate(() => { - process.stderr.write(INSTRUMENTATION_FAILED_RUN.stderr); + process.stdout.write(REFUSED_STDOUT); + process.stderr.write(REFUSED_STDERR); process.emitExit(1, null); }); return process; @@ -115,24 +138,109 @@ async function snapshotRejection(provider: AndroidAdbProvider) { assert.fail('expected the snapshot to fail'); } -test('a helper the system failed to start gets one more start after a runtime reset', async () => { - const { provider, calls } = freshlyBootedHelper([INSTRUMENTATION_FAILED_RUN]); +// Only a start the system refused, before any session was ready, gets a second start. Every other +// row differs from that refusal in one respect and fails on its first run. +const startFailures: { + name: string; + run: OneShotRun; + session?: 'ready-then-fails'; + retried: boolean; +}[] = [ + { name: 'a start the system refused', run: INSTRUMENTATION_FAILED_RUN, retried: true }, + { + name: 'a refused start after a session was ready', + run: INSTRUMENTATION_FAILED_RUN, + session: 'ready-then-fails', + retried: false, + }, + { + name: 'a run that exited 0', + run: { ...INSTRUMENTATION_FAILED_RUN, exitCode: 0 }, + retried: false, + }, + { + name: 'a run a signal ended', + run: { ...INSTRUMENTATION_FAILED_RUN, signal: 'SIGKILL' }, + retried: false, + }, + { + name: 'a run the command budget ended', + run: new AppError('COMMAND_FAILED', 'adb command timed out', { + timeoutMs: 30_000, + exitCode: 1, + stdout: REFUSED_STDOUT, + stderr: REFUSED_STDERR, + }), + retried: false, + }, + { + name: 'a run that aborted', + run: { + ...INSTRUMENTATION_FAILED_RUN, + stdout: `${REFUSED_STDOUT}INSTRUMENTATION_ABORTED: System has crashed.\n`, + }, + retried: false, + }, + { + name: 'a run whose abort message was withheld', + run: { + ...INSTRUMENTATION_FAILED_RUN, + stdout: `${REFUSED_STDOUT}INSTRUMENTATION_ABORTED: \n`, + }, + retried: false, + }, + { + name: 'a run that started and printed', + run: { + ...INSTRUMENTATION_FAILED_RUN, + stdout: 'INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n', + }, + retried: false, + }, + { + name: 'a run with a result message', + run: { + ...INSTRUMENTATION_FAILED_RUN, + stdout: `${REFUSED_STDOUT}INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n`, + }, + retried: false, + }, + { + name: 'the refusal words outside the startup-failure envelope', + run: { + exitCode: 1, + stdout: `INSTRUMENTATION_RESULT: shortMsg=INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, + stderr: '', + }, + retried: false, + }, +]; - const snapshot = await snapshotAndroid(device, { - helperAdb: provider, - helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, - }); +for (const row of startFailures) { + test(`${row.name} ${row.retried ? 'gets one more start after a runtime reset' : 'is not started again'}`, async () => { + const { provider, calls } = freshlyBootedHelper([row.run], row.session); - assert.ok(snapshot.nodes.some((node) => node.label === 'after retry')); - const oneShotRuns = calls.flatMap((args, index) => (isOneShotRun(args) ? [index] : [])); - assert.equal(oneShotRuns.length, 2); - assert.ok( - calls.slice(oneShotRuns[0], oneShotRuns[1]).some(isAndroidHelperRuntimeForceStop), - 'the helper runtime is reset before the second start', - ); -}); + if (!row.retried) { + const error = await snapshotRejection(provider); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(calls.filter(isOneShotRun).length, 1); + return; + } + const snapshot = await snapshotAndroid(device, { + helperAdb: provider, + helperArtifact: ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT, + }); + assert.ok(snapshot.nodes.some((node) => node.label === 'after retry')); + const oneShotRuns = calls.flatMap((args, index) => (isOneShotRun(args) ? [index] : [])); + assert.equal(oneShotRuns.length, 2); + assert.ok( + calls.slice(oneShotRuns[0], oneShotRuns[1]).some(isAndroidHelperRuntimeForceStop), + 'the helper runtime is reset before the second start', + ); + }); +} -test('a helper the system fails to start twice reports the start failure', async () => { +test('a helper the system refuses to start twice reports the refusal', async () => { const { provider, calls } = freshlyBootedHelper([ INSTRUMENTATION_FAILED_RUN, INSTRUMENTATION_FAILED_RUN, @@ -142,35 +250,13 @@ test('a helper the system fails to start twice reports the start failure', async assert.equal(calls.filter(isOneShotRun).length, 2); assert.equal(error.code, 'COMMAND_FAILED'); - assert.deepEqual(error.details?.instrumentation, { exitCode: 1, failed: HELPER_RUNNER }); -}); - -test('a helper that started and then exited early is not started again', async () => { - const earlyExits: AndroidAdbExecutorResult[] = [ - { exitCode: 1, stdout: 'INSTRUMENTATION_ABORTED: System has crashed.\n', stderr: '' }, - // The same words without the startup-failure envelope are a message, not a failed start. - { - exitCode: 1, - stdout: `INSTRUMENTATION_RESULT: shortMsg=INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, - stderr: '', - }, - // A run that started and printed is not a refused start, whatever line its stderr also holds. - { - exitCode: 1, - stdout: 'INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n', - stderr: INSTRUMENTATION_FAILED_RUN.stderr, - }, - ]; - for (const run of earlyExits) { - await resetAndroidSnapshotHelperSessions(); - resetAndroidSnapshotHelperInstallCache(); - const { provider, calls } = freshlyBootedHelper([run]); - - const error = await snapshotRejection(provider); - - assert.equal(calls.filter(isOneShotRun).length, 1, run.stdout); - assert.equal(error.code, 'COMMAND_FAILED'); - } + assert.equal(error.details?.androidSnapshotHelperStartRefused, true); + assert.deepEqual(error.details?.instrumentation, { + exitCode: 1, + statusCode: -1, + failed: HELPER_RUNNER, + error: `Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, + }); }); // The reset before the second start is a force-stop and then a settle delay; a cancellation in either diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index 6bb70f7e80..1442f3641a 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -313,20 +313,32 @@ function appendLine(value: string | undefined, line: string): string | undefined return next.length > MESSAGE_FIELD_MAX_CHARS ? value : next; } +// The status code `ActivityManagerService` reports for an instrumentation it refused to start. +// The snapshot helper itself only reports 1 (a chunk) and 2 (session ready). +const SYSTEM_REFUSED_START_STATUS_CODE = -1; + /** - * A run `am instrument` refused to start: it exited, reported `INSTRUMENTATION_FAILED`, and carries - * nothing a started instrumentation prints (a status or result code, an abort) or a signal ends. + * Whether a run is a start the system refused, and nothing else. All of these hold: + * - `am instrument` reported `INSTRUMENTATION_FAILED`; + * - the process exited with a non-zero code, and no signal ended it; + * - its only status is the system's refusal report: status code -1 with an `Error` message; + * - it has no result code, abort, `shortMsg`, `longMsg` or stack, which only a started + * instrumentation prints; + * - no field was withheld. */ -export function isRefusedInstrumentationStart(result: unknown): boolean { - if (typeof result !== 'object' || result === null) return false; - const run: Partial> = result; +export function isRefusedInstrumentationStart(result: AndroidInstrumentationExitResult): boolean { return ( - typeof run.failed === 'string' && - typeof run.exitCode === 'number' && - run.signal === undefined && - run.statusCode === undefined && - run.resultCode === undefined && - run.aborted === undefined + result.failed !== undefined && + result.exitCode !== null && + result.exitCode !== 0 && + result.signal === undefined && + result.statusCode === SYSTEM_REFUSED_START_STATUS_CODE && + result.resultCode === undefined && + result.aborted === undefined && + result.shortMsg === undefined && + result.longMsg === undefined && + result.stack === undefined && + result.withheldFields === undefined ); } diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index 03c89f7ffb..8bb7da0469 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -123,16 +123,11 @@ export async function captureAndroidSnapshotWithHelper( } /** - * The one-shot run failed because the system never started the helper: `am instrument` refused the - * start, so no helper code ran on the device and the helper reported nothing. + * The one-shot run exited on its own after the system refused to start the helper (see + * `isRefusedInstrumentationStart`), so no helper code ran on the device. */ export function isAndroidSnapshotHelperStartFailure(error: unknown): boolean { - return ( - error instanceof AppError && - error.code === 'COMMAND_FAILED' && - error.details?.helper === undefined && - isRefusedInstrumentationStart(error.details?.instrumentation) - ); + return error instanceof AppError && error.details?.androidSnapshotHelperStartRefused === true; } /** @@ -282,6 +277,11 @@ function readAndroidSnapshotHelperOutput( stderr: result.stderr, exitCode: result.exitCode, instrumentation, + // Read only here, where adb returned the run's own exit: a deadline or a host failure throws + // before this point, so it can never read as a refused start. + ...(isRefusedInstrumentationStart(instrumentation) + ? { androidSnapshotHelperStartRefused: true } + : {}), ...androidCaptureFailureReasonDetail( androidCaptureFailureReasonFromExitCode(result.exitCode), ), diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index d91b94cd4f..e56e7d3815 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -34,7 +34,7 @@ export async function resetAndroidSnapshotHelperRuntime( packageName: string, signal?: AbortSignal, ): Promise { - await stopAndroidSnapshotHelperRuntime({ adb, packageName, ...(signal ? { signal } : {}) }); + await stopAndroidSnapshotHelperRuntime({ adb, packageName, signal }); await sleep(HELPER_RUNTIME_RESET_DELAY_MS, signal); // A cancelled reset may have cut the force-stop or the settle short, so it does not report one. if (signal?.aborted) return; diff --git a/packages/platform-android/src/snapshot-helper-session.ts b/packages/platform-android/src/snapshot-helper-session.ts index 59f9b64ae7..5da974adbd 100644 --- a/packages/platform-android/src/snapshot-helper-session.ts +++ b/packages/platform-android/src/snapshot-helper-session.ts @@ -10,10 +10,7 @@ import type { AndroidSnapshotHelperCaptureOptions, AndroidSnapshotHelperOutput, } from './snapshot-helper-types.ts'; -import { - resolveAndroidSnapshotHelperCaptureOptions, - type AndroidSnapshotHelperResolvedCaptureOptions, -} from './snapshot-helper-capture.ts'; +import { resolveAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts'; import { isAndroidSnapshotHelperSessionRequestTimeout, parseAndroidSnapshotHelperSessionTouchResponse, @@ -25,7 +22,7 @@ import { getLiveAndroidSnapshotHelperSession, retireFailedAndroidSnapshotHelperSession, stopAndroidSnapshotHelperSession, - type AndroidSnapshotHelperSession, + type AndroidSnapshotHelperSessionAcquisition, type AndroidSnapshotHelperSessionHelperIdentity, } from './snapshot-helper-session-lifecycle.ts'; @@ -33,22 +30,15 @@ export async function captureAndroidSnapshotWithHelperSession( options: AndroidSnapshotHelperCaptureOptions, ): Promise { const acquired = await acquireAndroidSnapshotHelperSession(options); - if (!acquired) return undefined; - return await captureFromAndroidSnapshotHelperSession({ - session: acquired.session, - deviceKey: acquired.deviceKey, - options, - resolved: acquired.resolved, - }); + return acquired ? await captureFromAndroidSnapshotHelperSession(acquired, options) : undefined; } -async function captureFromAndroidSnapshotHelperSession(params: { - session: AndroidSnapshotHelperSession; - deviceKey: string; - options: AndroidSnapshotHelperCaptureOptions; - resolved: AndroidSnapshotHelperResolvedCaptureOptions; -}): Promise { - const { session, deviceKey, options, resolved } = params; +/** Captures over a session that is ready; `undefined` means the session failed and was retired. */ +export async function captureFromAndroidSnapshotHelperSession( + acquired: AndroidSnapshotHelperSessionAcquisition, + options: AndroidSnapshotHelperCaptureOptions, +): Promise { + const { session, deviceKey, resolved } = acquired; const requestedAtMs = Date.now(); const reused = session.capturedCount > 0; try { diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index a594173e56..5edd41ac66 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -43,7 +43,6 @@ import { } from './snapshot-helper-types.ts'; import { captureAndroidSnapshotWithHelper, - captureAndroidSnapshotWithHelperSession, ensureAndroidSnapshotHelper, forgetAndroidSnapshotHelperInstall, stopAndroidSnapshotHelperSession, @@ -53,7 +52,11 @@ import { type AndroidSnapshotHelperInstallResult, type AndroidSnapshotHelperOutput, } from './snapshot-helper.ts'; -import { getLiveAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; +import { + acquireAndroidSnapshotHelperSession, + getLiveAndroidSnapshotHelperSession, +} from './snapshot-helper-session-lifecycle.ts'; +import { captureFromAndroidSnapshotHelperSession } from './snapshot-helper-session.ts'; import { isAndroidSnapshotHelperNotCurrentError } from './snapshot-helper-install.ts'; import { getAndroidSnapshotHelperSessionDeviceKey, @@ -481,10 +484,18 @@ async function captureAndroidUiHierarchyFromHelper(params: { }); captureOptions.idleWait = params.idleWait; let sessionCapture: AndroidSnapshotHelperOutput | undefined; + // A helper that reached a ready session was started, so a refused start after it is not #4109. + let sessionReady = false; try { await withDiagnosticTimer( ANDROID_SNAPSHOT_HELPER_SESSION_CAPTURE_PHASE, - async () => (sessionCapture = await captureAndroidSnapshotWithHelperSession(captureOptions)), + async () => { + const acquired = await acquireAndroidSnapshotHelperSession(captureOptions); + sessionReady = acquired !== undefined; + if (acquired) { + sessionCapture = await captureFromAndroidSnapshotHelperSession(acquired, captureOptions); + } + }, () => ({ packageName: artifact.manifest.packageName, version: artifact.manifest.version, @@ -523,9 +534,10 @@ async function captureAndroidUiHierarchyFromHelper(params: { } catch (error) { signal?.throwIfAborted(); // Right after a boot or a `/data` restore, the system can refuse to start a current helper - // once and start it on the next run (#4109). A refused start ran nothing on the device, so it - // gets exactly one more start after a runtime reset; any other failure is the answer. - if (!isAndroidSnapshotHelperStartFailure(error)) throw error; + // once and start it on the next run (#4109). When no session was ready and the system refused + // the one-shot start, nothing ran on the device, so the helper gets exactly one more start + // after a runtime reset. Any other failure is the answer. + if (sessionReady || !isAndroidSnapshotHelperStartFailure(error)) throw error; emitDiagnostic({ level: 'warn', phase: 'android_snapshot_helper_start_retry', From 4416dd4c6957012b047b3815d76692a6b5a32f4d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 09:19:42 +0100 Subject: [PATCH 07/12] fix(android): require the system's refusal report for a refused helper start The exit-result parser now records whether the run's only report was the system refusing to start it: one status holding just Error and id=ActivityManagerService, ended by status code -1, with no result record. The refused-start predicate requires it, so INSTRUMENTATION_FAILED without that record, or the record after another status, is not retried. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 14 +++++ .../src/instrumentation-helper.ts | 52 ++++++++++++++++--- 2 files changed, 58 insertions(+), 8 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 45f6c178fd..0dc911a369 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -205,6 +205,19 @@ const startFailures: { }, retried: false, }, + { + name: 'a failed start without the system refusal record', + run: { ...INSTRUMENTATION_FAILED_RUN, stdout: 'INSTRUMENTATION_STATUS_CODE: -1\n' }, + retried: false, + }, + { + name: 'a refusal record after another status report', + run: { + ...INSTRUMENTATION_FAILED_RUN, + stdout: `INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n${REFUSED_STDOUT}`, + }, + retried: false, + }, { name: 'the refusal words outside the startup-failure envelope', run: { @@ -256,6 +269,7 @@ test('a helper the system refuses to start twice reports the refusal', async () statusCode: -1, failed: HELPER_RUNNER, error: `Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, + systemRefusal: true, }); }); diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index 1442f3641a..951ed4094f 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -144,6 +144,11 @@ export type AndroidInstrumentationExitResult = { * attribute-like assignment, a payload record) or because a line of it was cut at the line limit. */ withheldFields?: Array; + /** + * The run's only report was the system refusing to start it: one status holding just an `Error` + * and `id=ActivityManagerService`, ended by status code -1, and no result record. + */ + systemRefusal?: true; }; const LINE_MAX_CHARS = 4_096; @@ -174,6 +179,10 @@ const ABORTED_RE = /^INSTRUMENTATION_ABORTED:[ \t]?(.*)$/; const PROTOCOL_RECORD_RE = /^INSTRUMENTATION_(?:STATUS|STATUS_CODE|RESULT|CODE|ABORTED|FAILED):/; const VALUE_RECORD_RE = /^INSTRUMENTATION_(?:STATUS|RESULT): ([^=]*)=(.*)$/; const CODE_RE = /^INSTRUMENTATION_(STATUS_CODE|CODE): (-?\d+)\s*$/; +// How `ActivityManagerService` reports an instrumentation it refused to start, before `am` prints +// INSTRUMENTATION_FAILED. The snapshot helper itself only reports status 1 (a chunk) and 2 (ready). +const SYSTEM_REFUSAL_REPORTER = 'ActivityManagerService'; +const SYSTEM_REFUSAL_STATUS_CODE = -1; // The protocol keys whose values are text, by the field they fill. const MESSAGE_FIELDS = { shortMsg: 'shortMsg', longMsg: 'longMsg', Error: 'error', stack: 'stack' }; type MessageField = 'shortMsg' | 'longMsg' | 'error' | 'stack'; @@ -219,6 +228,23 @@ function createInstrumentationOutput() { > = {}; let open: MessageField | undefined; const withheld = new Set(); + // The status being read, by its keys, and what the run reported so far, for `systemRefusal`. + let statusKeys = new Set(); + let reportedBySystem = false; + let statusReports = 0; + let systemRefusal = false; + let resultRecords = false; + const readStatusEnd = (code: number) => { + statusReports += 1; + systemRefusal = + statusReports === 1 && + code === SYSTEM_REFUSAL_STATUS_CODE && + reportedBySystem && + statusKeys.size === 2 && + statusKeys.has('Error'); + statusKeys = new Set(); + reportedBySystem = false; + }; /** A line the limit cut cannot be proven clean, so its field is withheld like a marked one. */ const checked = (field: MessageField | 'aborted', text: string, cut: boolean) => { if (cut || holdsSnapshotMarker(text)) withheld.add(field); @@ -250,8 +276,13 @@ function createInstrumentationOutput() { if (code) { const value = Number(code[2]); if (!Number.isSafeInteger(value)) return undefined; - if (code[1] === 'CODE') fields.resultCode ??= value; - else fields.statusCode = value; + if (code[1] === 'CODE') { + resultRecords = true; + fields.resultCode ??= value; + } else { + readStatusEnd(value); + fields.statusCode = value; + } return undefined; } const aborted = ABORTED_RE.exec(line); @@ -262,6 +293,12 @@ function createInstrumentationOutput() { return undefined; } const record = VALUE_RECORD_RE.exec(line); + if (record && line.startsWith('INSTRUMENTATION_STATUS:')) { + statusKeys.add(record[1]!); + if (record[1] === 'id') reportedBySystem = record[2] === SYSTEM_REFUSAL_REPORTER; + } else if (record) { + resultRecords = true; + } const field = record ? messageFieldOf(record[1]!) : undefined; if (!field || fields[field] !== undefined) return undefined; fields[field] = checked(field, record![2] ?? '', cut).slice(0, MESSAGE_FIELD_MAX_CHARS); @@ -297,6 +334,9 @@ function createInstrumentationOutput() { ...(error !== undefined ? { error: error.trimEnd() } : {}), ...(stack !== undefined ? { stack: stack.trimEnd() } : {}), ...(withheld.size > 0 ? { withheldFields: [...withheld].sort() } : {}), + ...(systemRefusal && statusReports === 1 && !resultRecords + ? { systemRefusal: true as const } + : {}), }; }, }; @@ -313,15 +353,11 @@ function appendLine(value: string | undefined, line: string): string | undefined return next.length > MESSAGE_FIELD_MAX_CHARS ? value : next; } -// The status code `ActivityManagerService` reports for an instrumentation it refused to start. -// The snapshot helper itself only reports 1 (a chunk) and 2 (session ready). -const SYSTEM_REFUSED_START_STATUS_CODE = -1; - /** * Whether a run is a start the system refused, and nothing else. All of these hold: * - `am instrument` reported `INSTRUMENTATION_FAILED`; * - the process exited with a non-zero code, and no signal ended it; - * - its only status is the system's refusal report: status code -1 with an `Error` message; + * - its only report is the system's refusal (`systemRefusal`); * - it has no result code, abort, `shortMsg`, `longMsg` or stack, which only a started * instrumentation prints; * - no field was withheld. @@ -332,7 +368,7 @@ export function isRefusedInstrumentationStart(result: AndroidInstrumentationExit result.exitCode !== null && result.exitCode !== 0 && result.signal === undefined && - result.statusCode === SYSTEM_REFUSED_START_STATUS_CODE && + result.systemRefusal === true && result.resultCode === undefined && result.aborted === undefined && result.shortMsg === undefined && From ce58be2e047cd257dec2597a028681fbbaeb71d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 09:26:02 +0100 Subject: [PATCH 08/12] refactor(android): give the helper runtime reset one call shape and the fallback reset the request signal The reset takes a params object like its module siblings. The session-fallback reset now ends early on a cancelled request too. The refused-start retry moves beside the reset it uses, which keeps snapshot.ts under its line cap. Co-Authored-By: Claude Opus 5.5 --- .../src/snapshot-helper-runtime.ts | 51 +++++++++++++++---- packages/platform-android/src/snapshot.ts | 43 +++++++--------- 2 files changed, 60 insertions(+), 34 deletions(-) diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index e56e7d3815..b21e46bb8f 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -1,7 +1,9 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { normalizeError } from '@agent-device/kernel/errors'; import { sleep } from './adb.ts'; import type { AndroidAdbExecutor } from './adb-executor.ts'; import { stopAndroidSnapshotHelperRuntime } from './snapshot-helper-retirement.ts'; +import { isAndroidSnapshotHelperStartFailure } from './snapshot-helper-capture.ts'; import { stopAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; const HELPER_RUNTIME_RESET_DELAY_MS = 150; @@ -24,23 +26,52 @@ export async function retireAndroidSnapshotHelperAfterContentFailure(params: { params.signal?.throwIfAborted(); if (!retiredPersistentSession) { // The suspect helper ran one-shot, so no session stop reset the runtime for us. - await resetAndroidSnapshotHelperRuntime(params.adb, params.packageName); + await resetAndroidSnapshotHelperRuntime({ adb: params.adb, packageName: params.packageName }); } } /** A cancelled `signal` ends the reset early; the caller decides what a cancellation answers. */ -export async function resetAndroidSnapshotHelperRuntime( - adb: AndroidAdbExecutor, - packageName: string, - signal?: AbortSignal, -): Promise { - await stopAndroidSnapshotHelperRuntime({ adb, packageName, signal }); - await sleep(HELPER_RUNTIME_RESET_DELAY_MS, signal); +export async function resetAndroidSnapshotHelperRuntime(params: { + adb: AndroidAdbExecutor; + packageName: string; + signal?: AbortSignal; +}): Promise { + await stopAndroidSnapshotHelperRuntime(params); + await sleep(HELPER_RUNTIME_RESET_DELAY_MS, params.signal); // A cancelled reset may have cut the force-stop or the settle short, so it does not report one. - if (signal?.aborted) return; + if (params.signal?.aborted) return; emitDiagnostic({ level: 'debug', phase: 'android_snapshot_helper_runtime_reset', - data: { packageName }, + data: { packageName: params.packageName }, }); } + +/** + * Runs a one-shot helper capture. Right after a boot or a `/data` restore, the system can refuse to + * start a current helper once and start it on the next run (#4109). When no session was ready for + * this capture and the system refused the start, nothing ran on the device, so the helper gets + * exactly one more start after a runtime reset. Any other failure is the answer. + */ +export async function captureRetryingRefusedAndroidSnapshotHelperStart(params: { + capture: () => Promise; + sessionReady: boolean; + adb: AndroidAdbExecutor; + packageName: string; + signal?: AbortSignal; +}): Promise { + try { + return await params.capture(); + } catch (error) { + params.signal?.throwIfAborted(); + if (params.sessionReady || !isAndroidSnapshotHelperStartFailure(error)) throw error; + emitDiagnostic({ + level: 'warn', + phase: 'android_snapshot_helper_start_retry', + data: { instrumentation: normalizeError(error).details?.instrumentation }, + }); + await resetAndroidSnapshotHelperRuntime(params); + params.signal?.throwIfAborted(); + return await params.capture(); + } +} diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index 5edd41ac66..84bf8bec47 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -30,10 +30,7 @@ import { import { buildAndroidSnapshotClickabilityEvidence } from './snapshot-clickability.ts'; import { resolveAndroidAdbProvider, type AndroidAdbProvider } from './adb-executor.ts'; import { sleep } from './adb.ts'; -import { - buildAndroidSnapshotHelperCaptureOptions, - isAndroidSnapshotHelperStartFailure, -} from './snapshot-helper-capture.ts'; +import { buildAndroidSnapshotHelperCaptureOptions } from './snapshot-helper-capture.ts'; import { ANDROID_SNAPSHOT_HELPER_CAPTURE_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_COMMAND_TIMEOUT_MS, @@ -78,6 +75,7 @@ import { readAndroidCaptureFailureReason, } from '@agent-device/contracts/android-snapshot-quality'; import { + captureRetryingRefusedAndroidSnapshotHelperStart, resetAndroidSnapshotHelperRuntime, retireAndroidSnapshotHelperAfterContentFailure, } from './snapshot-helper-runtime.ts'; @@ -515,7 +513,12 @@ async function captureAndroidUiHierarchyFromHelper(params: { phase: 'android_snapshot_helper_session_fallback', data: { reason: normalizeError(error).message }, }); - await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName); + await resetAndroidSnapshotHelperRuntime({ + adb, + packageName: artifact.manifest.packageName, + signal, + }); + signal?.throwIfAborted(); } const captureOneShot = async () => await withDiagnosticTimer( @@ -529,24 +532,13 @@ async function captureAndroidUiHierarchyFromHelper(params: { transport: 'instrumentation' satisfies AndroidSnapshotHelperTransport, }, ); - try { - return await captureOneShot(); - } catch (error) { - signal?.throwIfAborted(); - // Right after a boot or a `/data` restore, the system can refuse to start a current helper - // once and start it on the next run (#4109). When no session was ready and the system refused - // the one-shot start, nothing ran on the device, so the helper gets exactly one more start - // after a runtime reset. Any other failure is the answer. - if (sessionReady || !isAndroidSnapshotHelperStartFailure(error)) throw error; - emitDiagnostic({ - level: 'warn', - phase: 'android_snapshot_helper_start_retry', - data: { instrumentation: normalizeError(error).details?.instrumentation }, - }); - await resetAndroidSnapshotHelperRuntime(adb, artifact.manifest.packageName, signal); - signal?.throwIfAborted(); - return await captureOneShot(); - } + return await captureRetryingRefusedAndroidSnapshotHelperStart({ + capture: captureOneShot, + sessionReady, + adb, + packageName: artifact.manifest.packageName, + signal, + }); } function formatAndroidHelperCaptureResult( @@ -727,7 +719,10 @@ async function rejectAndroidHelperCaptureFailure(params: { }, }); await stopAndroidSnapshotHelperSession(params.helperDeviceKey); - await resetAndroidSnapshotHelperRuntime(params.adb, params.artifact.manifest.packageName); + await resetAndroidSnapshotHelperRuntime({ + adb: params.adb, + packageName: params.artifact.manifest.packageName, + }); forgetAndroidSnapshotHelperInstall({ deviceKey: params.helperDeviceKey, packageName: params.artifact.manifest.packageName, From 3e59eaeb55486b47716b88f1d647dc1a3f26af13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 09:41:50 +0100 Subject: [PATCH 09/12] refactor(android): read each instrumentation record kind in its own helper Keeps readProtocolRecord under the complexity threshold after the system-refusal tracking; behavior is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/instrumentation-helper.ts | 56 ++++++++++++------- 1 file changed, 35 insertions(+), 21 deletions(-) diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index 951ed4094f..d11a4a08aa 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -270,39 +270,53 @@ function createInstrumentationOutput() { fields[open] = appendLine(fields[open], checked(open, line, cut)); } }; + const readCodeRecord = (kind: string, value: number) => { + if (kind === 'CODE') { + resultRecords = true; + fields.resultCode ??= value; + return; + } + readStatusEnd(value); + fields.statusCode = value; + }; + const readAbortedRecord = (message: string, cut: boolean) => { + if (fields.aborted !== undefined) return; + // The abort message is one line; whatever follows it is not part of it. + fields.aborted = checked('aborted', message, cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + }; + /** Notes which report a value record belongs to, for `systemRefusal`. */ + const noteValueRecord = (line: string, key: string, value: string) => { + if (!line.startsWith('INSTRUMENTATION_STATUS:')) { + resultRecords = true; + return; + } + statusKeys.add(key); + if (key === 'id') reportedBySystem = value === SYSTEM_REFUSAL_REPORTER; + }; + /** Answers the message field a value record opens, if any. */ + const readMessageRecord = (key: string, value: string, cut: boolean) => { + const field = messageFieldOf(key); + if (!field || fields[field] !== undefined) return undefined; + fields[field] = checked(field, value, cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + return field; + }; /** Reads one protocol record; answers the message field whose value it opens, if any. */ const readProtocolRecord = (line: string, cut: boolean): MessageField | undefined => { const code = CODE_RE.exec(line); if (code) { const value = Number(code[2]); - if (!Number.isSafeInteger(value)) return undefined; - if (code[1] === 'CODE') { - resultRecords = true; - fields.resultCode ??= value; - } else { - readStatusEnd(value); - fields.statusCode = value; - } + if (Number.isSafeInteger(value)) readCodeRecord(code[1]!, value); return undefined; } const aborted = ABORTED_RE.exec(line); if (aborted) { - if (fields.aborted !== undefined) return undefined; - // The abort message is one line; whatever follows it is not part of it. - fields.aborted = checked('aborted', aborted[1] ?? '', cut).slice(0, MESSAGE_FIELD_MAX_CHARS); + readAbortedRecord(aborted[1] ?? '', cut); return undefined; } const record = VALUE_RECORD_RE.exec(line); - if (record && line.startsWith('INSTRUMENTATION_STATUS:')) { - statusKeys.add(record[1]!); - if (record[1] === 'id') reportedBySystem = record[2] === SYSTEM_REFUSAL_REPORTER; - } else if (record) { - resultRecords = true; - } - const field = record ? messageFieldOf(record[1]!) : undefined; - if (!field || fields[field] !== undefined) return undefined; - fields[field] = checked(field, record![2] ?? '', cut).slice(0, MESSAGE_FIELD_MAX_CHARS); - return field; + if (!record) return undefined; + noteValueRecord(line, record[1]!, record[2] ?? ''); + return readMessageRecord(record[1]!, record[2] ?? '', cut); }; const stdout = createLineAssembler(readStdoutLine); const stderr = createLineAssembler(readFailed); From 1dacf44c88e99057cb8415237c3c9b8c7dd31789 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 10:05:32 +0100 Subject: [PATCH 10/12] fix(android): match a refused helper start by the exact shape of the system's report The parser now records every non-blank stdout line by record kind and key, never by value, and marks systemRefusal only when stdout is exactly the system's refusal: a status holding just Error and id=ActivityManagerService, then status code -1, and no other line. Trailing helper status, a malformed trailing record or plain output no longer qualify. The predicate keeps only conditions that can each fail alone, and the test table has one row per condition, each verified by deleting that condition. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 140 +++++++++--------- .../src/instrumentation-helper.ts | 82 +++++----- 2 files changed, 106 insertions(+), 116 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 0dc911a369..f70614b4c1 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -20,6 +20,10 @@ vi.mock('../adb.ts', async (importOriginal) => { import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { AndroidAdbExecutorResult, AndroidAdbProvider } from '../adb-executor.ts'; +import { + isRefusedInstrumentationStart, + readInstrumentationExitResult, +} from '../instrumentation-helper.ts'; import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; @@ -138,98 +142,98 @@ async function snapshotRejection(provider: AndroidAdbProvider) { assert.fail('expected the snapshot to fail'); } -// Only a start the system refused, before any session was ready, gets a second start. Every other -// row differs from that refusal in one respect and fails on its first run. -const startFailures: { - name: string; - run: OneShotRun; - session?: 'ready-then-fails'; - retried: boolean; +// One row per condition of a refused start: each row is the captured refusal with exactly that +// condition broken, so dropping the condition from the predicate flips its rows and no others. +const refusal = { exitCode: 1, stdout: REFUSED_STDOUT, stderr: REFUSED_STDERR }; +const refusalRows: { + breaks: string; + run: { exitCode: number | null; stdout: string; stderr: string; signal?: string }; }[] = [ - { name: 'a start the system refused', run: INSTRUMENTATION_FAILED_RUN, retried: true }, - { - name: 'a refused start after a session was ready', - run: INSTRUMENTATION_FAILED_RUN, - session: 'ready-then-fails', - retried: false, - }, + { breaks: 'nothing', run: refusal }, { - name: 'a run that exited 0', - run: { ...INSTRUMENTATION_FAILED_RUN, exitCode: 0 }, - retried: false, - }, - { - name: 'a run a signal ended', - run: { ...INSTRUMENTATION_FAILED_RUN, signal: 'SIGKILL' }, - retried: false, - }, - { - name: 'a run the command budget ended', - run: new AppError('COMMAND_FAILED', 'adb command timed out', { - timeoutMs: 30_000, - exitCode: 1, - stdout: REFUSED_STDOUT, - stderr: REFUSED_STDERR, - }), - retried: false, - }, - { - name: 'a run that aborted', - run: { - ...INSTRUMENTATION_FAILED_RUN, - stdout: `${REFUSED_STDOUT}INSTRUMENTATION_ABORTED: System has crashed.\n`, - }, - retried: false, + breaks: 'the INSTRUMENTATION_FAILED envelope', + run: { ...refusal, stderr: REFUSED_STDERR.split('\n').slice(1).join('\n') }, }, + { breaks: 'an exit status', run: { ...refusal, exitCode: null } }, + { breaks: 'a non-zero exit', run: { ...refusal, exitCode: 0 } }, + { breaks: 'no signal', run: { ...refusal, signal: 'SIGKILL' } }, { - name: 'a run whose abort message was withheld', - run: { - ...INSTRUMENTATION_FAILED_RUN, - stdout: `${REFUSED_STDOUT}INSTRUMENTATION_ABORTED: \n`, - }, - retried: false, + breaks: 'the system reporter', + run: { ...refusal, stdout: REFUSED_STDOUT.replace('id=ActivityManagerService', 'id=Other') }, }, { - name: 'a run that started and printed', + breaks: 'the refusal status code', run: { - ...INSTRUMENTATION_FAILED_RUN, - stdout: 'INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n', + ...refusal, + stdout: REFUSED_STDOUT.replace('STATUS_CODE: -1', 'STATUS_CODE: -2'), }, - retried: false, }, + ...[ + [ + 'a trailing helper status', + 'INSTRUMENTATION_STATUS: agentDeviceProtocol=1\nINSTRUMENTATION_STATUS: payloadBase64=PHg+\n', + ], + ['a malformed trailing result', 'INSTRUMENTATION_RESULT: invalid\n'], + ['a trailing result message', 'INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n'], + ['a trailing abort', 'INSTRUMENTATION_ABORTED: System has crashed.\n'], + ['a trailing withheld abort', 'INSTRUMENTATION_ABORTED: \n'], + ['a trailing plain line', 'plain output\n'], + ].map(([what, trailer]) => ({ + breaks: `the refusal-only stdout (${what})`, + run: { ...refusal, stdout: `${REFUSED_STDOUT}${trailer}` }, + })), { - name: 'a run with a result message', + breaks: 'the refusal-only stdout (an earlier helper status)', run: { - ...INSTRUMENTATION_FAILED_RUN, - stdout: `${REFUSED_STDOUT}INSTRUMENTATION_RESULT: shortMsg=Process crashed.\n`, + ...refusal, + stdout: `INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n${REFUSED_STDOUT}`, }, - retried: false, }, { - name: 'a failed start without the system refusal record', - run: { ...INSTRUMENTATION_FAILED_RUN, stdout: 'INSTRUMENTATION_STATUS_CODE: -1\n' }, - retried: false, + breaks: 'the refusal-only stdout (no Error record)', + run: { ...refusal, stdout: REFUSED_STDOUT.split('\n').slice(1).join('\n') }, }, +]; + +test('a refused start is told apart from every run that breaks one of its conditions', () => { + const misclassified = refusalRows + .filter( + (row) => + isRefusedInstrumentationStart(readInstrumentationExitResult(row.run)) !== + (row.breaks === 'nothing'), + ) + .map((row) => row.breaks); + assert.deepEqual(misclassified, []); +}); + +// The two conditions that live outside the run's parsed result: the run came back from adb on its +// own, and no session was ready for the capture. +const captureRows: { + name: string; + run: OneShotRun; + session?: 'ready-then-fails'; + retried: boolean; +}[] = [ + { name: 'a start the system refused', run: INSTRUMENTATION_FAILED_RUN, retried: true }, { - name: 'a refusal record after another status report', - run: { - ...INSTRUMENTATION_FAILED_RUN, - stdout: `INSTRUMENTATION_STATUS: numtests=1\nINSTRUMENTATION_STATUS_CODE: 1\n${REFUSED_STDOUT}`, - }, + name: 'a refused start after a session was ready', + run: INSTRUMENTATION_FAILED_RUN, + session: 'ready-then-fails', retried: false, }, { - name: 'the refusal words outside the startup-failure envelope', - run: { + name: 'a run the command budget ended', + run: new AppError('COMMAND_FAILED', 'adb command timed out', { + timeoutMs: 30_000, exitCode: 1, - stdout: `INSTRUMENTATION_RESULT: shortMsg=INSTRUMENTATION_FAILED: ${HELPER_RUNNER}\n`, - stderr: '', - }, + stdout: REFUSED_STDOUT, + stderr: REFUSED_STDERR, + }), retried: false, }, ]; -for (const row of startFailures) { +for (const row of captureRows) { test(`${row.name} ${row.retried ? 'gets one more start after a runtime reset' : 'is not started again'}`, async () => { const { provider, calls } = freshlyBootedHelper([row.run], row.session); diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index d11a4a08aa..e886bc27d3 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -145,8 +145,8 @@ export type AndroidInstrumentationExitResult = { */ withheldFields?: Array; /** - * The run's only report was the system refusing to start it: one status holding just an `Error` - * and `id=ActivityManagerService`, ended by status code -1, and no result record. + * Stdout held the system's refusal to start the run and nothing else: a status holding just an + * `Error` and `id=ActivityManagerService`, then status code -1, and no other line. */ systemRefusal?: true; }; @@ -183,6 +183,11 @@ const CODE_RE = /^INSTRUMENTATION_(STATUS_CODE|CODE): (-?\d+)\s*$/; // INSTRUMENTATION_FAILED. The snapshot helper itself only reports status 1 (a chunk) and 2 (ready). const SYSTEM_REFUSAL_REPORTER = 'ActivityManagerService'; const SYSTEM_REFUSAL_STATUS_CODE = -1; +// The refusal's stdout lines by record kind and key; Bundle order decides which key comes first. +const SYSTEM_REFUSAL_SHAPES = new Set([ + 'STATUS Error,STATUS id,STATUS_CODE', + 'STATUS id,STATUS Error,STATUS_CODE', +]); // The protocol keys whose values are text, by the field they fill. const MESSAGE_FIELDS = { shortMsg: 'shortMsg', longMsg: 'longMsg', Error: 'error', stack: 'stack' }; type MessageField = 'shortMsg' | 'longMsg' | 'error' | 'stack'; @@ -228,23 +233,9 @@ function createInstrumentationOutput() { > = {}; let open: MessageField | undefined; const withheld = new Set(); - // The status being read, by its keys, and what the run reported so far, for `systemRefusal`. - let statusKeys = new Set(); + // Every non-blank stdout line by kind and key, never by value, for `systemRefusal`. + const stdoutShape: string[] = []; let reportedBySystem = false; - let statusReports = 0; - let systemRefusal = false; - let resultRecords = false; - const readStatusEnd = (code: number) => { - statusReports += 1; - systemRefusal = - statusReports === 1 && - code === SYSTEM_REFUSAL_STATUS_CODE && - reportedBySystem && - statusKeys.size === 2 && - statusKeys.has('Error'); - statusKeys = new Set(); - reportedBySystem = false; - }; /** A line the limit cut cannot be proven clean, so its field is withheld like a marked one. */ const checked = (field: MessageField | 'aborted', text: string, cut: boolean) => { if (cut || holdsSnapshotMarker(text)) withheld.add(field); @@ -262,6 +253,7 @@ function createInstrumentationOutput() { return false; }; const readStdoutLine = (line: string, cut: boolean) => { + if (line.trim() !== '') stdoutShape.push(stdoutLineShape(line, cut)); if (readFailed(line, cut)) { open = undefined; } else if (PROTOCOL_RECORD_RE.test(line)) { @@ -271,28 +263,14 @@ function createInstrumentationOutput() { } }; const readCodeRecord = (kind: string, value: number) => { - if (kind === 'CODE') { - resultRecords = true; - fields.resultCode ??= value; - return; - } - readStatusEnd(value); - fields.statusCode = value; + if (kind === 'CODE') fields.resultCode ??= value; + else fields.statusCode = value; }; const readAbortedRecord = (message: string, cut: boolean) => { if (fields.aborted !== undefined) return; // The abort message is one line; whatever follows it is not part of it. fields.aborted = checked('aborted', message, cut).slice(0, MESSAGE_FIELD_MAX_CHARS); }; - /** Notes which report a value record belongs to, for `systemRefusal`. */ - const noteValueRecord = (line: string, key: string, value: string) => { - if (!line.startsWith('INSTRUMENTATION_STATUS:')) { - resultRecords = true; - return; - } - statusKeys.add(key); - if (key === 'id') reportedBySystem = value === SYSTEM_REFUSAL_REPORTER; - }; /** Answers the message field a value record opens, if any. */ const readMessageRecord = (key: string, value: string, cut: boolean) => { const field = messageFieldOf(key); @@ -315,7 +293,9 @@ function createInstrumentationOutput() { } const record = VALUE_RECORD_RE.exec(line); if (!record) return undefined; - noteValueRecord(line, record[1]!, record[2] ?? ''); + if (record[1] === 'id' && line.startsWith('INSTRUMENTATION_STATUS:')) { + reportedBySystem = record[2] === SYSTEM_REFUSAL_REPORTER; + } return readMessageRecord(record[1]!, record[2] ?? '', cut); }; const stdout = createLineAssembler(readStdoutLine); @@ -348,7 +328,9 @@ function createInstrumentationOutput() { ...(error !== undefined ? { error: error.trimEnd() } : {}), ...(stack !== undefined ? { stack: stack.trimEnd() } : {}), ...(withheld.size > 0 ? { withheldFields: [...withheld].sort() } : {}), - ...(systemRefusal && statusReports === 1 && !resultRecords + ...(SYSTEM_REFUSAL_SHAPES.has(stdoutShape.join(',')) && + reportedBySystem && + fields.statusCode === SYSTEM_REFUSAL_STATUS_CODE ? { systemRefusal: true as const } : {}), }; @@ -356,6 +338,18 @@ function createInstrumentationOutput() { }; } +/** A stdout line by record kind and key only; anything else is told apart only as protocol or text. */ +function stdoutLineShape(line: string, cut: boolean): string { + if (cut) return 'cut'; + const code = CODE_RE.exec(line); + if (code) return code[1]!; + const record = VALUE_RECORD_RE.exec(line); + if (record) { + return `${line.startsWith('INSTRUMENTATION_STATUS:') ? 'STATUS' : 'RESULT'} ${record[1]}`; + } + return PROTOCOL_RECORD_RE.test(line) ? 'protocol' : 'text'; +} + function messageFieldOf(key: string): MessageField | undefined { return Object.hasOwn(MESSAGE_FIELDS, key) ? (MESSAGE_FIELDS[key as keyof typeof MESSAGE_FIELDS] as MessageField) @@ -370,11 +364,9 @@ function appendLine(value: string | undefined, line: string): string | undefined /** * Whether a run is a start the system refused, and nothing else. All of these hold: * - `am instrument` reported `INSTRUMENTATION_FAILED`; - * - the process exited with a non-zero code, and no signal ended it; - * - its only report is the system's refusal (`systemRefusal`); - * - it has no result code, abort, `shortMsg`, `longMsg` or stack, which only a started - * instrumentation prints; - * - no field was withheld. + * - the process exited with a non-zero code; + * - no signal ended it; + * - its stdout is the system's refusal report and nothing else (`systemRefusal`). */ export function isRefusedInstrumentationStart(result: AndroidInstrumentationExitResult): boolean { return ( @@ -382,13 +374,7 @@ export function isRefusedInstrumentationStart(result: AndroidInstrumentationExit result.exitCode !== null && result.exitCode !== 0 && result.signal === undefined && - result.systemRefusal === true && - result.resultCode === undefined && - result.aborted === undefined && - result.shortMsg === undefined && - result.longMsg === undefined && - result.stack === undefined && - result.withheldFields === undefined + result.systemRefusal === true ); } From 27e8d699aa9ce6b188a4e817cf680a751914d53a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:01:31 +0100 Subject: [PATCH 11/12] refactor(android): keep one refused-start fact on the error, and keep the fallback reset as on main The system-refusal shape no longer appears on the instrumentation result: isRefusedInstrumentationStart reads the finished run itself, and the error carries only androidSnapshotHelperStartRefused. The session-fallback reset returns to main's uncancellable form, which is outside #4109, and the retry wrapper is no longer generic. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-helper-start-retry.test.ts | 12 +---- .../src/instrumentation-helper.ts | 44 +++++++++++-------- .../src/snapshot-helper-capture.ts | 2 +- .../src/snapshot-helper-runtime.ts | 7 +-- packages/platform-android/src/snapshot.ts | 7 +-- 5 files changed, 34 insertions(+), 38 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index f70614b4c1..6c65d9c364 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -20,10 +20,7 @@ vi.mock('../adb.ts', async (importOriginal) => { import type { DeviceInfo } from '@agent-device/kernel/device'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { AndroidAdbExecutorResult, AndroidAdbProvider } from '../adb-executor.ts'; -import { - isRefusedInstrumentationStart, - readInstrumentationExitResult, -} from '../instrumentation-helper.ts'; +import { isRefusedInstrumentationStart } from '../instrumentation-helper.ts'; import { snapshotAndroid } from '../snapshot.ts'; import { resetAndroidSnapshotHelperInstallCache } from '../snapshot-helper-install.ts'; import { resetAndroidSnapshotHelperSessions } from '../snapshot-helper-session-lifecycle.ts'; @@ -197,11 +194,7 @@ const refusalRows: { test('a refused start is told apart from every run that breaks one of its conditions', () => { const misclassified = refusalRows - .filter( - (row) => - isRefusedInstrumentationStart(readInstrumentationExitResult(row.run)) !== - (row.breaks === 'nothing'), - ) + .filter((row) => isRefusedInstrumentationStart(row.run) !== (row.breaks === 'nothing')) .map((row) => row.breaks); assert.deepEqual(misclassified, []); }); @@ -273,7 +266,6 @@ test('a helper the system refuses to start twice reports the refusal', async () statusCode: -1, failed: HELPER_RUNNER, error: `Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, - systemRefusal: true, }); }); diff --git a/packages/platform-android/src/instrumentation-helper.ts b/packages/platform-android/src/instrumentation-helper.ts index e886bc27d3..c197dc4ed6 100644 --- a/packages/platform-android/src/instrumentation-helper.ts +++ b/packages/platform-android/src/instrumentation-helper.ts @@ -144,11 +144,6 @@ export type AndroidInstrumentationExitResult = { * attribute-like assignment, a payload record) or because a line of it was cut at the line limit. */ withheldFields?: Array; - /** - * Stdout held the system's refusal to start the run and nothing else: a status holding just an - * `Error` and `id=ActivityManagerService`, then status code -1, and no other line. - */ - systemRefusal?: true; }; const LINE_MAX_CHARS = 4_096; @@ -233,7 +228,7 @@ function createInstrumentationOutput() { > = {}; let open: MessageField | undefined; const withheld = new Set(); - // Every non-blank stdout line by kind and key, never by value, for `systemRefusal`. + // Every non-blank stdout line by kind and key, never by value, for `isSystemRefusal`. const stdoutShape: string[] = []; let reportedBySystem = false; /** A line the limit cut cannot be proven clean, so its field is withheld like a marked one. */ @@ -328,13 +323,16 @@ function createInstrumentationOutput() { ...(error !== undefined ? { error: error.trimEnd() } : {}), ...(stack !== undefined ? { stack: stack.trimEnd() } : {}), ...(withheld.size > 0 ? { withheldFields: [...withheld].sort() } : {}), - ...(SYSTEM_REFUSAL_SHAPES.has(stdoutShape.join(',')) && - reportedBySystem && - fields.statusCode === SYSTEM_REFUSAL_STATUS_CODE - ? { systemRefusal: true as const } - : {}), }; }, + /** + * Stdout held the system's refusal to start the run and nothing else: a status holding just an + * `Error` and `id=ActivityManagerService`, then status code -1, and no other line. + */ + isSystemRefusal: () => + SYSTEM_REFUSAL_SHAPES.has(stdoutShape.join(',')) && + reportedBySystem && + fields.statusCode === SYSTEM_REFUSAL_STATUS_CODE, }; } @@ -362,32 +360,42 @@ function appendLine(value: string | undefined, line: string): string | undefined } /** - * Whether a run is a start the system refused, and nothing else. All of these hold: + * Whether a finished run is a start the system refused, and nothing else. All of these hold: * - `am instrument` reported `INSTRUMENTATION_FAILED`; * - the process exited with a non-zero code; * - no signal ended it; - * - its stdout is the system's refusal report and nothing else (`systemRefusal`). + * - its stdout is the system's refusal report and nothing else. */ -export function isRefusedInstrumentationStart(result: AndroidInstrumentationExitResult): boolean { +export function isRefusedInstrumentationStart(run: InstrumentationRun): boolean { + const output = readInstrumentationOutput(run); + const result = output.result(run.exitCode, run.signal, true); return ( result.failed !== undefined && result.exitCode !== null && result.exitCode !== 0 && result.signal === undefined && - result.systemRefusal === true + output.isSystemRefusal() ); } -export function readInstrumentationExitResult(run: { +type InstrumentationRun = { stdout: string; stderr: string; exitCode: number | null | undefined; signal?: string | null; -}): AndroidInstrumentationExitResult { +}; + +function readInstrumentationOutput(run: InstrumentationRun) { const output = createInstrumentationOutput(); output.writeStdout(run.stdout); output.writeStderr(run.stderr); - return output.result(run.exitCode, run.signal, true); + return output; +} + +export function readInstrumentationExitResult( + run: InstrumentationRun, +): AndroidInstrumentationExitResult { + return readInstrumentationOutput(run).result(run.exitCode, run.signal, true); } /** The exit of a spawned helper process and what it printed. */ diff --git a/packages/platform-android/src/snapshot-helper-capture.ts b/packages/platform-android/src/snapshot-helper-capture.ts index 8bb7da0469..e089068187 100644 --- a/packages/platform-android/src/snapshot-helper-capture.ts +++ b/packages/platform-android/src/snapshot-helper-capture.ts @@ -279,7 +279,7 @@ function readAndroidSnapshotHelperOutput( instrumentation, // Read only here, where adb returned the run's own exit: a deadline or a host failure throws // before this point, so it can never read as a refused start. - ...(isRefusedInstrumentationStart(instrumentation) + ...(isRefusedInstrumentationStart(result) ? { androidSnapshotHelperStartRefused: true } : {}), ...androidCaptureFailureReasonDetail( diff --git a/packages/platform-android/src/snapshot-helper-runtime.ts b/packages/platform-android/src/snapshot-helper-runtime.ts index b21e46bb8f..1ff826a334 100644 --- a/packages/platform-android/src/snapshot-helper-runtime.ts +++ b/packages/platform-android/src/snapshot-helper-runtime.ts @@ -2,6 +2,7 @@ import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { normalizeError } from '@agent-device/kernel/errors'; import { sleep } from './adb.ts'; import type { AndroidAdbExecutor } from './adb-executor.ts'; +import type { AndroidSnapshotHelperOutput } from './snapshot-helper-types.ts'; import { stopAndroidSnapshotHelperRuntime } from './snapshot-helper-retirement.ts'; import { isAndroidSnapshotHelperStartFailure } from './snapshot-helper-capture.ts'; import { stopAndroidSnapshotHelperSession } from './snapshot-helper-session-lifecycle.ts'; @@ -53,13 +54,13 @@ export async function resetAndroidSnapshotHelperRuntime(params: { * this capture and the system refused the start, nothing ran on the device, so the helper gets * exactly one more start after a runtime reset. Any other failure is the answer. */ -export async function captureRetryingRefusedAndroidSnapshotHelperStart(params: { - capture: () => Promise; +export async function captureRetryingRefusedAndroidSnapshotHelperStart(params: { + capture: () => Promise; sessionReady: boolean; adb: AndroidAdbExecutor; packageName: string; signal?: AbortSignal; -}): Promise { +}): Promise { try { return await params.capture(); } catch (error) { diff --git a/packages/platform-android/src/snapshot.ts b/packages/platform-android/src/snapshot.ts index 84bf8bec47..f71b0237af 100644 --- a/packages/platform-android/src/snapshot.ts +++ b/packages/platform-android/src/snapshot.ts @@ -513,12 +513,7 @@ async function captureAndroidUiHierarchyFromHelper(params: { phase: 'android_snapshot_helper_session_fallback', data: { reason: normalizeError(error).message }, }); - await resetAndroidSnapshotHelperRuntime({ - adb, - packageName: artifact.manifest.packageName, - signal, - }); - signal?.throwIfAborted(); + await resetAndroidSnapshotHelperRuntime({ adb, packageName: artifact.manifest.packageName }); } const captureOneShot = async () => await withDiagnosticTimer( From d293daf99b9708f71530f1f275858f63f60accee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Mon, 2 Nov 2026 19:13:43 +0100 Subject: [PATCH 12/12] test(android): pin the refused-start fixture to the verbatim live capture Co-Authored-By: Claude Opus 5.5 --- .../src/__tests__/snapshot-helper-start-retry.test.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts index 6c65d9c364..a1643e25d8 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-start-retry.test.ts @@ -44,11 +44,13 @@ const device: DeviceInfo = { booted: true, }; -const HELPER_RUNNER = `${ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName}/.SnapshotInstrumentation`; +const HELPER_PACKAGE = ANDROID_SNAPSHOT_HELPER_FIXTURE_ARTIFACT.manifest.packageName; +// The component as `am` names it in its refusal: fully qualified, not the `/.Class` short form. +const HELPER_RUNNER = `${HELPER_PACKAGE}/${HELPER_PACKAGE}.SnapshotInstrumentation`; -// What `am instrument -w` prints when the system refuses to start the instrumentation, as captured -// from an Android 15 emulator: ActivityManagerService reports the refusal as status -1, and then -// `am` throws INSTRUMENTATION_FAILED. +// What `am instrument -w` printed, verbatim, when the system refused to start the uninstalled helper +// on an Android 15 (API 35) emulator: ActivityManagerService reports the refusal as status -1, and +// then `am` throws INSTRUMENTATION_FAILED. The live retry run on the same device printed the same. const REFUSED_STDOUT = [ `INSTRUMENTATION_STATUS: Error=Unable to find instrumentation info for: ComponentInfo{${HELPER_RUNNER}}`, 'INSTRUMENTATION_STATUS: id=ActivityManagerService',