From 8953c0a0824d38984865688342553edc3454484f Mon Sep 17 00:00:00 2001 From: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Date: Wed, 28 Oct 2026 11:16:17 -0700 Subject: [PATCH 1/3] fix(platform-android): disable persistent Android snapshots after an unhealthy helper retirement When a failed capture's forced retirement cannot prove the helper was released, or its cleanup times out, set that helper build's failedSessions entry to an infinite retryAt so the existing backoff gate keeps the device on one-shot snapshots until resetAndroidSnapshotHelperSessions clears it. Emit android_snapshot_helper_persistent_session_disabled with release and externalCleanupTimedOut so the disable reason is visible. The retirement API now returns release and cleanup status so the caller can decide. Forward removal reports a rejection as a timed-out cleanup instead of rejecting the teardown, so a stalled removal no longer makes the retirement throw before it is classified. Tests move the clock past the retry ceiling before the second capture, cover the cleanup timeout reached through a stalled forward removal, and only consume a configured stall when the call has a cleanup signal. Fixes #3929 --- .../snapshot-helper-session-lifecycle.test.ts | 96 ++++++++++++++++++- .../snapshot-helper-session.fixtures.ts | 12 ++- .../src/snapshot-helper-retirement.ts | 49 ++++++---- .../src/snapshot-helper-session-lifecycle.ts | 30 +++++- 4 files changed, 160 insertions(+), 27 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts index a543483be6..161dd12842 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts @@ -1,5 +1,5 @@ import assert from 'node:assert/strict'; -import { afterEach, beforeEach, test } from 'vitest'; +import { afterEach, beforeEach, test, vi } from 'vitest'; import { captureAndroidSnapshotWithHelperSession } from '../snapshot-helper-session.ts'; import { resetAndroidSnapshotHelperSessions, @@ -11,10 +11,15 @@ import { recoverAndroidSnapshotHelperRetirement } from '../snapshot-helper-retir import { createSessionProvider, FakeAndroidProcess, + isAndroidHelperForwardRemoval, isAndroidHelperRuntimeForceStop, type SessionProviderOptions, } from './snapshot-helper-session.fixtures.ts'; import type { AndroidAdbExecutor, AndroidAdbProvider } from '../adb-executor.ts'; +import path from 'node:path'; +import { promises as fs } from 'node:fs'; +import { mkdtempForTest } from './test-utils/tmp-dir.ts'; +import { withDiagnosticsScope } from '@agent-device/host-kit/diagnostics'; beforeEach(async () => { delete process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION; @@ -22,6 +27,7 @@ beforeEach(async () => { }); afterEach(async () => { + vi.restoreAllMocks(); delete process.env.AGENT_DEVICE_ANDROID_SNAPSHOT_HELPER_SESSION; await resetAndroidSnapshotHelperSessions(); }); @@ -226,6 +232,94 @@ test('a session whose capture timed out is not restarted by the next command', a ); }); +test('a retirement that cannot prove release keeps the helper build one-shot until reset', async () => { + const spawnArgs: (readonly string[])[] = []; + // The stalled capture is retired, and the device cannot be read back afterwards: the frozen-helper + // shape of #3929, where nothing proves the helper let go of UiAutomation. + const provider = createSessionProvider({ + calls: [], + spawnArgs, + stalledSnapshots: 1, + runtimeRelease: 'unreadable', + }); + const capture = (deviceKey: string) => + captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey, + commandTimeoutMs: 400, + }); + const logPath = path.join( + await mkdtempForTest('agent-device-android-session-disable-diag-'), + 'diag.ndjson', + ); + + await withDiagnosticsScope({ debug: true, logPath }, async () => { + assert.equal(await capture('android:coloros-16'), undefined); + skewClockPastSessionBackoff(); + assert.equal( + await capture('android:coloros-16'), + undefined, + 'the next command answers one-shot after any ordinary backoff has run out', + ); + assert.equal(spawnArgs.length, 1, 'the unhealthy helper is not spawned again'); + const otherDevice = await capture('android:other-device'); + assert.equal(otherDevice?.metadata.transport, 'persistent-session'); + }); + + const log = await fs.readFile(logPath, 'utf8'); + assert.match(log, /android_snapshot_helper_persistent_session_disabled/); + assert.match(log, /"release":"unknown"/); + + await resetAndroidSnapshotHelperSessions(); + const fresh = await capture('android:coloros-16'); + assert.equal(spawnArgs.length, 3, 'reset allows a fresh persistent attempt'); + assert.equal(fresh?.metadata.transport, 'persistent-session'); +}); + +test('a retirement whose forward removal stalls keeps the helper build one-shot', async () => { + const calls: (readonly string[])[] = []; + const spawnArgs: (readonly string[])[] = []; + const cleanupAborts: (readonly string[])[] = []; + // The device proves release, but the forward removal hangs until the retirement budget aborts it. + const provider = createSessionProvider({ + calls, + spawnArgs, + cleanupAborts, + stalledSnapshots: 1, + stalledForwardRemovals: 1, + }); + const capture = () => + captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey: 'android:coloros-16', + commandTimeoutMs: 400, + }); + const logPath = path.join( + await mkdtempForTest('agent-device-android-session-cleanup-timeout-diag-'), + 'diag.ndjson', + ); + + await withDiagnosticsScope({ debug: true, logPath }, async () => { + assert.equal(await capture(), undefined, 'the stalled cleanup still falls back to one-shot'); + skewClockPastSessionBackoff(); + assert.equal(await capture(), undefined); + }); + + assert.equal(cleanupAborts.filter(isAndroidHelperForwardRemoval).length, 1); + assert.equal(spawnArgs.length, 1, 'the helper whose cleanup timed out is not spawned again'); + const log = await fs.readFile(logPath, 'utf8'); + assert.match(log, /android_snapshot_helper_persistent_session_disabled/); + assert.match(log, /"externalCleanupTimedOut":true/); +}); + +/** Moves the module clock past the longest backoff a failed capture can earn on its own. */ +function skewClockPastSessionBackoff(): void { + const realNow = Date.now.bind(Date); + vi.spyOn(Date, 'now').mockImplementation(() => realNow() + 10 * 60_000); +} + test('starts and reuses a persistent Android snapshot helper session', async () => { const calls: (readonly string[])[] = []; const spawnArgs: (readonly string[])[] = []; 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 6086c3ef7a..35c14a9887 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -184,6 +184,8 @@ export type SessionProviderOptions = { forceStopDelayMs?: number; recoveryFailure?: boolean; stalledCleanup?: boolean; + /** How many `forward --remove` calls hang until their cleanup budget aborts them. */ + stalledForwardRemovals?: number; stalledSnapshots?: number; /** Whether `adb features` advertises the shell protocol that forwards device exit status. */ shellProtocolV2?: boolean; @@ -370,8 +372,14 @@ async function stallSessionCleanupIfConfigured( signal: AbortSignal | undefined, forceStopsRuntime: boolean, ): Promise { - const removesForward = args[0] === 'forward' && args[1] === '--remove'; - if (!options.stalledCleanup || !signal || (!removesForward && !forceStopsRuntime)) return; + const removesForward = isAndroidHelperForwardRemoval(args); + const stalledForwardRemovals = options.stalledForwardRemovals ?? 0; + const stallsForwardRemoval = removesForward && stalledForwardRemovals > 0; + // Only a call with a cleanup signal can actually hang, so only it consumes a stall. + if (stallsForwardRemoval && signal) options.stalledForwardRemovals = stalledForwardRemovals - 1; + const stalls = + stallsForwardRemoval || (options.stalledCleanup && (removesForward || forceStopsRuntime)); + if (!stalls || !signal) return; await new Promise((_resolve, reject) => { const onAbort = () => { options.cleanupAborts?.push(args); diff --git a/packages/platform-android/src/snapshot-helper-retirement.ts b/packages/platform-android/src/snapshot-helper-retirement.ts index 9336a07cdd..24e351ca60 100644 --- a/packages/platform-android/src/snapshot-helper-retirement.ts +++ b/packages/platform-android/src/snapshot-helper-retirement.ts @@ -227,20 +227,22 @@ export async function settleAndroidSnapshotHelperSessionCleanup(params: { forceStopRuntime: boolean; }): Promise<{ timedOut: boolean }> { const signal = AbortSignal.timeout(params.timeoutMs); - await Promise.all([ - ...(params.forceStopRuntime - ? [ - stopAndroidSnapshotHelperRuntime({ - adb: params.adb, - packageName: params.packageName, - timeoutMs: params.timeoutMs, - signal, - }), - ] - : []), - removeAndroidSnapshotHelperSessionForward({ ...params, signal }), - ]); - return { timedOut: signal.aborted }; + const forwardRemoved = ( + await Promise.all([ + ...(params.forceStopRuntime + ? [ + stopAndroidSnapshotHelperRuntime({ + adb: params.adb, + packageName: params.packageName, + timeoutMs: params.timeoutMs, + signal, + }), + ] + : []), + removeAndroidSnapshotHelperSessionForward({ ...params, signal }), + ]) + ).at(-1); + return { timedOut: signal.aborted || forwardRemoved !== true }; } /** @@ -367,13 +369,20 @@ async function removeAndroidSnapshotHelperSessionForward(params: { port: number; timeoutMs: number; signal: AbortSignal; -}): Promise { +}): Promise { params.process.stdin?.end(); params.process.stdout?.destroy(); params.process.stderr?.destroy(); - await params.adb(['forward', '--remove', `tcp:${params.port}`], { - allowFailure: true, - timeoutMs: params.timeoutMs, - signal: params.signal, - }); + // `allowFailure` already absorbs an adb error, so a rejection is a removal that ran out of budget + // or was aborted: report it as a timed-out cleanup rather than failing the teardown. + return await params + .adb(['forward', '--remove', `tcp:${params.port}`], { + allowFailure: true, + timeoutMs: params.timeoutMs, + signal: params.signal, + }) + .then( + () => true, + () => false, + ); } diff --git a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts index 72be1819e7..32b562d01c 100644 --- a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts +++ b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts @@ -33,6 +33,7 @@ import { } from './snapshot-helper-session-protocol.ts'; import { type AndroidSnapshotHelperProcessExit, + type AndroidSnapshotHelperRuntimeRelease, ANDROID_SNAPSHOT_HELPER_DEVICE_RETIREMENT_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_HOST_PROCESS_EXIT_GRACE_MS, getAndroidSnapshotHelperSessionDeviceKey, @@ -255,12 +256,27 @@ export async function retireFailedAndroidSnapshotHelperSession(params: { signal?: AbortSignal; cause: unknown; }): Promise { - await stopAndroidSnapshotHelperSession(params.deviceKey, { + const retirement = await stopAndroidSnapshotHelperSession(params.deviceKey, { force: true, signal: params.signal, cause: params.cause, }); if (params.signal?.aborted) return; + // CONSERVATIVE: a frozen helper can stall adb on its next start (#3929), so a retirement that did + // not prove release keeps this build one-shot until reset. `unknown` may be one slow `pidof` read. + if (retirement && (retirement.release !== 'released' || retirement.cleanupTimedOut)) { + failedSessions().set(params.identity, Number.POSITIVE_INFINITY); + emitDiagnostic({ + level: 'warn', + phase: 'android_snapshot_helper_persistent_session_disabled', + data: { + deviceKey: params.deviceKey, + release: retirement.release, + externalCleanupTimedOut: retirement.cleanupTimedOut, + }, + }); + return; + } failedSessions().set( params.identity, Date.now() + @@ -459,9 +475,15 @@ export async function stopAndroidSnapshotHelperSession( signal?: AbortSignal; cause?: unknown; } = {}, -): Promise { +): Promise< + | { + release: AndroidSnapshotHelperRuntimeRelease; + cleanupTimedOut: boolean; + } + | undefined +> { const session = sessions().get(deviceKey); - if (!session) return false; + if (!session) return undefined; sessions().delete(deviceKey); const processExit = observeAndroidSnapshotHelperProcessExit(session.process); const force = options.force === true || options.signal?.aborted === true; @@ -530,7 +552,7 @@ export async function stopAndroidSnapshotHelperSession( externalCleanupTimedOut: cleanup.timedOut, }, }); - return true; + return { release, cleanupTimedOut: cleanup.timedOut }; } async function requestGracefulSessionExit( From ad940b187a0d4cad8b4c114bc38a2b1ff1ebcd33 Mon Sep 17 00:00:00 2001 From: Matt Van Horn Date: Thu, 29 Oct 2026 06:28:31 -0700 Subject: [PATCH 2/3] fix(platform-android): key the persistent-snapshot disable on a reused session timing out A live run on an emulator, freezing the idle helper with `am freeze --sticky ` after the first persistent snapshot, showed that force-stop kills the frozen helper cleanly: the retirement reports release=released and no cleanup timeout, so the previous trigger never fired and the helper would restart after the backoff. Disable the persistent path for a helper build when a session that has already answered a capture then times out on the next one. The session request timeout now carries a typed reason, the capture passes reusedSessionTimedOut to the retirement, and stopAndroidSnapshotHelperSession goes back to returning a boolean. A timed-out first capture on a fresh session still earns only the ordinary backoff. Tests cover the reused-session disable (with release=released), the fresh-session timeout, and a stalled forward removal that still falls back. Refs #3929 --- .../snapshot-helper-session-lifecycle.test.ts | 67 +++++++++++++------ .../snapshot-helper-session.fixtures.ts | 4 +- .../src/snapshot-helper-session-lifecycle.ts | 30 +++------ .../src/snapshot-helper-session-protocol.ts | 8 +++ .../src/snapshot-helper-session.ts | 4 +- 5 files changed, 71 insertions(+), 42 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts index 161dd12842..a082f7a19a 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session-lifecycle.test.ts @@ -232,15 +232,15 @@ test('a session whose capture timed out is not restarted by the next command', a ); }); -test('a retirement that cannot prove release keeps the helper build one-shot until reset', async () => { +test('a reused session whose capture times out keeps the helper build one-shot until reset', async () => { const spawnArgs: (readonly string[])[] = []; - // The stalled capture is retired, and the device cannot be read back afterwards: the frozen-helper - // shape of #3929, where nothing proves the helper let go of UiAutomation. + // The helper answers once and then goes silent: the idle freeze of #3929. Force-stop kills the + // frozen process cleanly, so the retirement proves release and only the timeout tells. const provider = createSessionProvider({ calls: [], spawnArgs, + answeredSnapshotsBeforeStall: 1, stalledSnapshots: 1, - runtimeRelease: 'unreadable', }); const capture = (deviceKey: string) => captureAndroidSnapshotWithHelperSession({ @@ -255,21 +255,22 @@ test('a retirement that cannot prove release keeps the helper build one-shot unt ); await withDiagnosticsScope({ debug: true, logPath }, async () => { - assert.equal(await capture('android:coloros-16'), undefined); + assert.equal((await capture('android:coloros-16'))?.metadata.transport, 'persistent-session'); + assert.equal(await capture('android:coloros-16'), undefined, 'the frozen session falls back'); skewClockPastSessionBackoff(); assert.equal( await capture('android:coloros-16'), undefined, 'the next command answers one-shot after any ordinary backoff has run out', ); - assert.equal(spawnArgs.length, 1, 'the unhealthy helper is not spawned again'); + assert.equal(spawnArgs.length, 1, 'the frozen helper build is not spawned again'); const otherDevice = await capture('android:other-device'); assert.equal(otherDevice?.metadata.transport, 'persistent-session'); }); const log = await fs.readFile(logPath, 'utf8'); + assert.match(log, /"phase":"android_snapshot_helper_session_stop"[^\n]*"release":"released"/); assert.match(log, /android_snapshot_helper_persistent_session_disabled/); - assert.match(log, /"release":"unknown"/); await resetAndroidSnapshotHelperSessions(); const fresh = await capture('android:coloros-16'); @@ -277,11 +278,37 @@ test('a retirement that cannot prove release keeps the helper build one-shot unt assert.equal(fresh?.metadata.transport, 'persistent-session'); }); -test('a retirement whose forward removal stalls keeps the helper build one-shot', async () => { +test('a first capture that times out on a fresh session only earns the ordinary backoff', async () => { + const spawnArgs: (readonly string[])[] = []; + const provider = createSessionProvider({ calls: [], spawnArgs, stalledSnapshots: 1 }); + const capture = () => + captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey: 'android:emulator-5554', + commandTimeoutMs: 400, + }); + const logPath = path.join( + await mkdtempForTest('agent-device-android-session-first-timeout-diag-'), + 'diag.ndjson', + ); + + await withDiagnosticsScope({ debug: true, logPath }, async () => { + assert.equal(await capture(), undefined); + skewClockPastSessionBackoff(); + assert.equal((await capture())?.metadata.transport, 'persistent-session'); + }); + + assert.equal(spawnArgs.length, 2, 'the backoff ran out and a new helper was started'); + const log = await fs.readFile(logPath, 'utf8'); + assert.doesNotMatch(log, /android_snapshot_helper_persistent_session_disabled/); +}); + +test('a retirement whose forward removal stalls still falls back to one-shot', async () => { const calls: (readonly string[])[] = []; const spawnArgs: (readonly string[])[] = []; const cleanupAborts: (readonly string[])[] = []; - // The device proves release, but the forward removal hangs until the retirement budget aborts it. + // The forward removal hangs until the retirement budget aborts it. const provider = createSessionProvider({ calls, spawnArgs, @@ -289,28 +316,26 @@ test('a retirement whose forward removal stalls keeps the helper build one-shot' stalledSnapshots: 1, stalledForwardRemovals: 1, }); - const capture = () => - captureAndroidSnapshotWithHelperSession({ - adb: provider.exec, - adbProvider: provider, - deviceKey: 'android:coloros-16', - commandTimeoutMs: 400, - }); const logPath = path.join( await mkdtempForTest('agent-device-android-session-cleanup-timeout-diag-'), 'diag.ndjson', ); await withDiagnosticsScope({ debug: true, logPath }, async () => { - assert.equal(await capture(), undefined, 'the stalled cleanup still falls back to one-shot'); - skewClockPastSessionBackoff(); - assert.equal(await capture(), undefined); + assert.equal( + await captureAndroidSnapshotWithHelperSession({ + adb: provider.exec, + adbProvider: provider, + deviceKey: 'android:emulator-5554', + commandTimeoutMs: 400, + }), + undefined, + 'the stalled cleanup still falls back to one-shot', + ); }); assert.equal(cleanupAborts.filter(isAndroidHelperForwardRemoval).length, 1); - assert.equal(spawnArgs.length, 1, 'the helper whose cleanup timed out is not spawned again'); const log = await fs.readFile(logPath, 'utf8'); - assert.match(log, /android_snapshot_helper_persistent_session_disabled/); assert.match(log, /"externalCleanupTimedOut":true/); }); 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 35c14a9887..7a317a3bd2 100644 --- a/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts +++ b/packages/platform-android/src/__tests__/snapshot-helper-session.fixtures.ts @@ -187,6 +187,8 @@ export type SessionProviderOptions = { /** How many `forward --remove` calls hang until their cleanup budget aborts them. */ stalledForwardRemovals?: number; stalledSnapshots?: number; + /** How many snapshot requests each helper process answers before `stalledSnapshots` applies. */ + answeredSnapshotsBeforeStall?: number; /** 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. */ @@ -259,7 +261,7 @@ export function createSessionProvider(options: SessionProviderOptions): AndroidA return; } snapshotCount += 1; - if (stalledSnapshots > 0) { + if (snapshotCount > (options.answeredSnapshotsBeforeStall ?? 0) && stalledSnapshots > 0) { stalledSnapshots -= 1; return; } diff --git a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts index 32b562d01c..3c418464cf 100644 --- a/packages/platform-android/src/snapshot-helper-session-lifecycle.ts +++ b/packages/platform-android/src/snapshot-helper-session-lifecycle.ts @@ -33,7 +33,6 @@ import { } from './snapshot-helper-session-protocol.ts'; import { type AndroidSnapshotHelperProcessExit, - type AndroidSnapshotHelperRuntimeRelease, ANDROID_SNAPSHOT_HELPER_DEVICE_RETIREMENT_TIMEOUT_MS, ANDROID_SNAPSHOT_HELPER_HOST_PROCESS_EXIT_GRACE_MS, getAndroidSnapshotHelperSessionDeviceKey, @@ -253,27 +252,26 @@ export async function retireFailedAndroidSnapshotHelperSession(params: { failedAfterMs: number; /** Budget of the one-shot capture that answers in place of the failed session. */ fallbackBudgetMs: number; + /** The session had already answered a capture, and this one got no answer before its deadline. */ + reusedSessionTimedOut: boolean; signal?: AbortSignal; cause: unknown; }): Promise { - const retirement = await stopAndroidSnapshotHelperSession(params.deviceKey, { + await stopAndroidSnapshotHelperSession(params.deviceKey, { force: true, signal: params.signal, cause: params.cause, }); if (params.signal?.aborted) return; - // CONSERVATIVE: a frozen helper can stall adb on its next start (#3929), so a retirement that did - // not prove release keeps this build one-shot until reset. `unknown` may be one slow `pidof` read. - if (retirement && (retirement.release !== 'released' || retirement.cleanupTimedOut)) { + // A helper that answered and then went silent was frozen while idle (#3929: ColorOS freezes the + // idle helper, force-stop kills it cleanly, and every restarted helper is frozen again), so this + // build stays one-shot until reset. + if (params.reusedSessionTimedOut) { failedSessions().set(params.identity, Number.POSITIVE_INFINITY); emitDiagnostic({ level: 'warn', phase: 'android_snapshot_helper_persistent_session_disabled', - data: { - deviceKey: params.deviceKey, - release: retirement.release, - externalCleanupTimedOut: retirement.cleanupTimedOut, - }, + data: { deviceKey: params.deviceKey, failedAfterMs: params.failedAfterMs }, }); return; } @@ -475,15 +473,9 @@ export async function stopAndroidSnapshotHelperSession( signal?: AbortSignal; cause?: unknown; } = {}, -): Promise< - | { - release: AndroidSnapshotHelperRuntimeRelease; - cleanupTimedOut: boolean; - } - | undefined -> { +): Promise { const session = sessions().get(deviceKey); - if (!session) return undefined; + if (!session) return false; sessions().delete(deviceKey); const processExit = observeAndroidSnapshotHelperProcessExit(session.process); const force = options.force === true || options.signal?.aborted === true; @@ -552,7 +544,7 @@ export async function stopAndroidSnapshotHelperSession( externalCleanupTimedOut: cleanup.timedOut, }, }); - return { release, cleanupTimedOut: cleanup.timedOut }; + return true; } async function requestGracefulSessionExit( diff --git a/packages/platform-android/src/snapshot-helper-session-protocol.ts b/packages/platform-android/src/snapshot-helper-session-protocol.ts index b9d031d476..865bc1cd58 100644 --- a/packages/platform-android/src/snapshot-helper-session-protocol.ts +++ b/packages/platform-android/src/snapshot-helper-session-protocol.ts @@ -35,6 +35,13 @@ export function allocateAndroidSnapshotHelperSessionPort(): Promise { }); } +const SESSION_REQUEST_TIMEOUT_REASON = 'android_snapshot_helper_session_request_timeout'; + +/** The helper accepted the session request but sent no answer before the command deadline. */ +export function isAndroidSnapshotHelperSessionRequestTimeout(error: unknown): boolean { + return error instanceof AppError && error.details?.reason === SESSION_REQUEST_TIMEOUT_REASON; +} + export function sendAndroidSnapshotHelperSessionCommand( port: number, command: string, @@ -52,6 +59,7 @@ export function sendAndroidSnapshotHelperSessionCommand( command: command.split(' ', 1)[0], timeoutMs, port, + reason: SESSION_REQUEST_TIMEOUT_REASON, }), ); }, timeoutMs); diff --git a/packages/platform-android/src/snapshot-helper-session.ts b/packages/platform-android/src/snapshot-helper-session.ts index 3ab0bdd6f2..4c68c26d68 100644 --- a/packages/platform-android/src/snapshot-helper-session.ts +++ b/packages/platform-android/src/snapshot-helper-session.ts @@ -15,6 +15,7 @@ import { type AndroidSnapshotHelperResolvedCaptureOptions, } from './snapshot-helper-capture.ts'; import { + isAndroidSnapshotHelperSessionRequestTimeout, parseAndroidSnapshotHelperSessionTouchResponse, requestAndroidSnapshotHelperSessionSnapshot, sendAndroidSnapshotHelperSessionCommand, @@ -49,8 +50,8 @@ async function captureFromAndroidSnapshotHelperSession(params: { }): Promise { const { session, deviceKey, options, resolved } = params; const requestedAtMs = Date.now(); + const reused = session.capturedCount > 0; try { - const reused = session.capturedCount > 0; const output = await requestAndroidSnapshotHelperSessionSnapshot({ port: session.port, commandTimeoutMs: resolved.commandTimeoutMs, @@ -73,6 +74,7 @@ async function captureFromAndroidSnapshotHelperSession(params: { identity: session.identity, failedAfterMs: Date.now() - requestedAtMs, fallbackBudgetMs: resolveAndroidSnapshotHelperCaptureOptions(options).commandTimeoutMs, + reusedSessionTimedOut: reused && isAndroidSnapshotHelperSessionRequestTimeout(error), signal: options.signal, cause: error, }); From 5825ab9b4576fa04b651f9b203f409960930a8dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 30 Oct 2026 10:08:56 +0100 Subject: [PATCH 3/3] refactor(android): simplify helper cleanup result handling --- .../src/snapshot-helper-retirement.ts | 28 ++++++++----------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/packages/platform-android/src/snapshot-helper-retirement.ts b/packages/platform-android/src/snapshot-helper-retirement.ts index 24e351ca60..2a12f81f85 100644 --- a/packages/platform-android/src/snapshot-helper-retirement.ts +++ b/packages/platform-android/src/snapshot-helper-retirement.ts @@ -227,22 +227,18 @@ export async function settleAndroidSnapshotHelperSessionCleanup(params: { forceStopRuntime: boolean; }): Promise<{ timedOut: boolean }> { const signal = AbortSignal.timeout(params.timeoutMs); - const forwardRemoved = ( - await Promise.all([ - ...(params.forceStopRuntime - ? [ - stopAndroidSnapshotHelperRuntime({ - adb: params.adb, - packageName: params.packageName, - timeoutMs: params.timeoutMs, - signal, - }), - ] - : []), - removeAndroidSnapshotHelperSessionForward({ ...params, signal }), - ]) - ).at(-1); - return { timedOut: signal.aborted || forwardRemoved !== true }; + const [, forwardRemoved] = await Promise.all([ + params.forceStopRuntime + ? stopAndroidSnapshotHelperRuntime({ + adb: params.adb, + packageName: params.packageName, + timeoutMs: params.timeoutMs, + signal, + }) + : undefined, + removeAndroidSnapshotHelperSessionForward({ ...params, signal }), + ]); + return { timedOut: signal.aborted || !forwardRemoved }; } /**