From ce8cd055672bd8ca5389c34e99c3094fda1afc2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 4 Dec 2026 17:52:48 +0100 Subject: [PATCH 1/4] fix(android): release sessions after their ADB serial disappears --- .../command-surface/src/management/app.ts | 2 +- .../support/platform-services-fixture.ts | 2 + packages/daemon/src/core/platform-services.ts | 6 +- .../session-close-claim-retry.test.ts | 83 +++++++++++++++++-- .../internal/session-close.ts | 29 ++++++- .../platform-android/src/ime-lifecycle.ts | 27 ++++-- packages/platform-android/src/mechanics.ts | 1 + src/platform-runtime-daemon-services.ts | 5 ++ website/docs/docs/commands.md | 4 +- 9 files changed, 138 insertions(+), 21 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index f990c6872ed..213dd1af927 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. If close cannot confirm its cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', + 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb lists its devices successfully and the session’s serial is absent. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/daemon/src/__tests__/support/platform-services-fixture.ts b/packages/daemon/src/__tests__/support/platform-services-fixture.ts index bdcf8773f27..5750ebe5447 100644 --- a/packages/daemon/src/__tests__/support/platform-services-fixture.ts +++ b/packages/daemon/src/__tests__/support/platform-services-fixture.ts @@ -27,6 +27,7 @@ export function daemonPlatformServicesFixture( deviceBootObservation: Object.freeze({ observeBootTimeMs: observeBootTimeMsFixture, }), + observeLocalAndroidAdbSerials: observeLocalAndroidAdbSerialsFixture, ensureLocalDeviceReady: ensureLocalDeviceReadyFixture, resolveRequestedOpenSurface: resolveRequestedOpenSurfaceFixture, validateOpenRelaunchTarget: validateOpenRelaunchTargetFixture, @@ -37,6 +38,7 @@ export function daemonPlatformServicesFixture( /** The canned runner-session observation: no live runner on any device. */ const observeRunnerSessionFixture = vi.fn(async (_deviceId: string) => undefined); +const observeLocalAndroidAdbSerialsFixture = vi.fn(async () => undefined); /** The canned foreground answer: nothing observable to name a sole foreground app. */ const resolveSoleForegroundAppFixture = vi.fn( async (_params: Readonly<{ simulatorSetPath?: string }>) => undefined, diff --git a/packages/daemon/src/core/platform-services.ts b/packages/daemon/src/core/platform-services.ts index 2d464226098..c482054b693 100644 --- a/packages/daemon/src/core/platform-services.ts +++ b/packages/daemon/src/core/platform-services.ts @@ -11,15 +11,15 @@ export type EnsureLocalDeviceReady = (device: DeviceInfo, signal: AbortSignal) = /** * Root-composed platform services the daemon asks of the host machine for work that binds no - * device runtime, over mechanics the daemon must never name or load itself. The two observation - * members are published contracts types; readiness and open-target classification are signatures - * declared here over neutral types. Device execution is NOT in this port and never + * device runtime, over mechanics the daemon must never name or load itself. + * Device execution is NOT in this port and never * enters it (ADR 0019): it goes through the request-bound runtime binding * (`RequestExecutionScope.bindDevice`), whose owner facts stay the only admission authority. */ export type DaemonPlatformServices = Readonly<{ appleSessionObservation: AppleSessionObservation; deviceBootObservation: DeviceBootObservationService; + observeLocalAndroidAdbSerials(signal?: AbortSignal): Promise; ensureLocalDeviceReady: EnsureLocalDeviceReady; resolveRequestedOpenSurface(params: { device: DeviceInfo; diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts index ea84ddb30ee..d9ebfa83989 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts @@ -59,10 +59,11 @@ afterEach(() => { function claimDevice( sessionStore: ReturnType, session: string, + target: SessionState['device'] = device, ): ReturnType { return acquireDeviceClaim({ env: process.env, - device, + device: target, session, workspace: process.cwd(), stateDir: sessionStore.resolveDaemonStateDir(), @@ -76,13 +77,16 @@ async function openSession( sessionName: string, options: Readonly<{ claim?: false; + device?: SessionState['device']; + sessionStore?: ReturnType; lease?: Readonly<{ registry: LeaseRegistryInstance; retainOnClose?: true }>; scriptPublication?: SessionState['scriptPublication']; }> = {}, ) { - const sessionStore = makeSessionStore(); + const sessionStore = options.sessionStore ?? makeSessionStore(); + const target = options.device ?? device; const acquired = - options.claim === false ? undefined : await claimDevice(sessionStore, sessionName); + options.claim === false ? undefined : await claimDevice(sessionStore, sessionName, target); if (acquired && acquired.status !== 'acquired') { throw new Error('expected the test session to acquire a device claim'); } @@ -90,11 +94,11 @@ async function openSession( tenantId: 'tenant-a', runId: 'run-1', leaseBackend: 'android-instance', - deviceKey: 'android:' + device.id, + deviceKey: 'android:' + target.id, ...(options.lease.retainOnClose ? { retainOnClose: true } : {}), }); sessionStore.publish(sessionName, { - ...makeSession(sessionName, device), + ...makeSession(sessionName, target), appBundleId: 'com.example.app', ...(acquired ? { deviceClaim: acquired.ownership } : {}), ...(options.scriptPublication ? { scriptPublication: options.scriptPublication } : {}), @@ -122,12 +126,17 @@ function close( leaseLifecycleProvider?: LeaseLifecycleProvider; saveScript?: true; app?: string; + observeLocalAndroidAdbSerials?: () => Promise; }> = {}, ) { return handleSessionCommands({ host: createTestHostEnvironment(), createCommandSurface: fakeCreateCommandSurface, - platformServices: daemonPlatformServicesFixture(), + platformServices: daemonPlatformServicesFixture( + options.observeLocalAndroidAdbSerials + ? { observeLocalAndroidAdbSerials: options.observeLocalAndroidAdbSerials } + : {}, + ), lifecycleOperationsLoader: loader, req: { token: 't', @@ -164,6 +173,68 @@ const cleanupIncomplete = { }), }; +const wifiDevice = { ...device, id: '192.0.2.10:5555', kind: 'device' as const }; +const movedDevice = { ...wifiDevice, id: '192.0.2.11:5555' }; +const pidofFailure = new AppError('COMMAND_FAILED', 'Could not read process state', { + reason: 'android-process-probe-unavailable', +}); + +test('plain close retires only the session and claim for a serial that left local adb', async () => { + const sessionName = 'vanished-adb-serial'; + const sessionStore = await openSession(sessionName, { device: wifiDevice }); + await openSession('other-session', { device: movedDevice, sessionStore }); + const { loader, finalizeApplicationClose } = lifecycleOperationsSpy({ + closeApplication: async () => { + throw pidofFailure; + }, + }); + const observeLocalAndroidAdbSerials = vi.fn(async () => [movedDevice.id]); + + await expect( + close(sessionStore, sessionName, loader, { observeLocalAndroidAdbSerials }), + ).resolves.toMatchObject({ ok: true, data: { session: sessionName } }); + + expect(finalizeApplicationClose).toHaveBeenCalledOnce(); + expect(sessionStore.get(sessionName)).toBeUndefined(); + expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)).toEqual([]); + expect(sessionStore.get('other-session')?.device.id).toBe(movedDevice.id); + expect(inspectDeviceClaims({ serial: movedDevice.id }, process.env)[0]?.claim?.session).toBe( + 'other-session', + ); +}); + +test.each([ + { condition: 'still listed', serials: [wifiDevice.id], error: pidofFailure }, + { condition: 'of unknown presence', serials: undefined, error: pidofFailure }, + { + condition: 'absent but the app-stop failure has no typed reason', + serials: [movedDevice.id], + error: new AppError('COMMAND_FAILED', pidofFailure.message), + }, +])( + 'plain close keeps the session and claim when the serial is $condition', + async ({ serials, error }) => { + const sessionName = 'retain-adb-serial'; + const sessionStore = await openSession(sessionName, { device: wifiDevice }); + const { loader } = lifecycleOperationsSpy({ + closeApplication: async () => { + throw error; + }, + }); + + await expect( + close(sessionStore, sessionName, loader, { + observeLocalAndroidAdbSerials: async () => serials, + }), + ).rejects.toBe(error); + + expect(sessionStore.get(sessionName)).toBeDefined(); + expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)[0]?.claim?.session).toBe( + sessionName, + ); + }, +); + test('a retried close reruns the failed cleanup and then releases the device claim', async () => { const sessionName = 'close-retry-releases-claim'; const sessionStore = await openSession(sessionName); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index ebd3ca09ec5..505927c490a 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -2,6 +2,7 @@ import type { EnvMap, HostEnvironment } from '@agent-device/kernel/source-value' import type { DaemonResponse } from '@agent-device/kernel/contracts'; import type { DaemonPlatformServices } from '../../../core/platform-services.ts'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; +import { getRequestSignal } from '@agent-device/host-kit/request'; import { AppError, normalizeError } from '@agent-device/kernel/errors'; import type { LeaseLifecycleProvider, TargetShutdownResult } from '@agent-device/contracts/device'; import type { DaemonRequest } from '../../../core/daemon-request.ts'; @@ -365,6 +366,7 @@ export async function handleSessionCloseCommands( clearRuntimeHints: admission.clearRuntimeHints, repairArmed: repair.repairArmed, platformResourceCleanup, + observeLocalAndroidAdbSerials: params.platformServices.observeLocalAndroidAdbSerials, }), ); if (closed.kind === 'response') return closed.response; @@ -423,6 +425,7 @@ async function runCloseTeardownAndRelease(params: { clearRuntimeHints?: RuntimeHintClearOperation; repairArmed: boolean; platformResourceCleanup: PlatformResourceCleanup; + observeLocalAndroidAdbSerials: DaemonPlatformServices['observeLocalAndroidAdbSerials']; }): Promise { const { req, @@ -437,7 +440,7 @@ async function runCloseTeardownAndRelease(params: { const { address: sessionName } = ref; const cleanupFailures: SessionCleanupFailure[] = []; const { - platformCloseError, + platformCloseError: appStopError, retainExecutionHost, saveScriptOutcome, shutdownPrepared, @@ -457,6 +460,30 @@ async function runCloseTeardownAndRelease(params: { platformResourceCleanup: params.platformResourceCleanup, }); let session = sessionStore.requireCurrent(ref); + let platformCloseError = appStopError; + if ( + cleanupFailures.length === 0 && + lifecycle.owner.kind === 'local-family' && + lifecycle.owner.family === 'android' && + !req.positionals?.length && + !req.flags?.shutdown && + !req.flags?.saveScript && + !req.internal?.killApp && + appStopError instanceof AppError && + appStopError.details?.reason === 'android-process-probe-unavailable' + ) { + const signal = getRequestSignal(req.meta?.requestId); + const serials = await params.observeLocalAndroidAdbSerials(signal).catch(() => undefined); + session = sessionStore.requireCurrent(ref); + if (!signal?.aborted && serials && !serials.includes(session.device.id)) { + emitDiagnostic({ + level: 'warn', + phase: 'android_app_stop_skipped_device_absent', + data: { serial: session.device.id }, + }); + platformCloseError = undefined; + } + } // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint // describe what actually happened to the session. It is built even when a platform-close error // takes precedence, so that error never hides the cleanup failures. diff --git a/packages/platform-android/src/ime-lifecycle.ts b/packages/platform-android/src/ime-lifecycle.ts index 6386c6e8dc9..0a2f1757c5d 100644 --- a/packages/platform-android/src/ime-lifecycle.ts +++ b/packages/platform-android/src/ime-lifecycle.ts @@ -17,19 +17,30 @@ export { // Serials only, with no full-inventory name, boot-state, or target probes. export async function listAndroidAdbSerialsQuick(): Promise { + const devices = await observeAndroidAdbDevices(); + return devices?.filter(({ state }) => state === 'device').map(({ serial }) => serial) ?? []; +} + +/** Includes offline and unauthorized rows. Undefined means adb did not establish its inventory. */ +export async function observeAndroidAdbDevices( + signal?: AbortSignal, +): Promise { requireAndroidAdbHost(); try { const result = await runAndroidHostAdb(parseAndroidAdbArgv(['devices']), { timeoutMs: 5_000, + signal, }); - return result.stdout - .split('\n') - .map((line) => line.trim()) - .filter((line) => line.length > 0 && !line.startsWith('List of devices')) - .map((line) => line.split(/\s+/)) - .filter((parts) => parts[1] === 'device') - .map((parts) => parts[0] as string); + const [header, ...rows] = result.stdout.trim().split(/\r?\n/); + if (header?.trim() !== 'List of devices attached') return undefined; + const devices: { serial: string; state: string }[] = []; + for (const row of rows) { + const [serial, state] = row.trim().split(/\s+/); + if (!serial || !state) return undefined; + devices.push({ serial, state }); + } + return devices; } catch { - return []; + return undefined; } } diff --git a/packages/platform-android/src/mechanics.ts b/packages/platform-android/src/mechanics.ts index a44766bcffa..032181d887f 100644 --- a/packages/platform-android/src/mechanics.ts +++ b/packages/platform-android/src/mechanics.ts @@ -163,6 +163,7 @@ export { export { ANDROID_TEST_IME_SETTINGS_KEYS, listAndroidAdbSerialsQuick, + observeAndroidAdbDevices, readAndroidDefaultInputMethod, restoreAndroidTestIme, restoreOrphanedAndroidTestImeOnDaemonStartup, diff --git a/src/platform-runtime-daemon-services.ts b/src/platform-runtime-daemon-services.ts index 1a1c13ef4ec..3af347b79ad 100644 --- a/src/platform-runtime-daemon-services.ts +++ b/src/platform-runtime-daemon-services.ts @@ -7,6 +7,7 @@ import { validateOpenRelaunchTarget, } from './platform-runtime-open-target.ts'; import type { DaemonPlatformServices } from '@agent-device/daemon'; +import { loadAndroidMechanics } from './platform-runtime-android-mechanics.ts'; /** * Root composition of the daemon's platform-services port (ADR 0019 section 11). Each member is @@ -18,6 +19,10 @@ export function createDaemonPlatformServices(): DaemonPlatformServices { return Object.freeze({ appleSessionObservation, deviceBootObservation, + observeLocalAndroidAdbSerials: async (signal) => { + const { observeAndroidAdbDevices } = await loadAndroidMechanics(); + return (await observeAndroidAdbDevices(signal))?.map(({ serial }) => serial); + }, ensureLocalDeviceReady: ensureLocalPlatformDeviceReady, resolveRequestedOpenSurface, validateOpenRelaunchTarget, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a807a86bbce..abee8e91398 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -240,9 +240,9 @@ Exact behavior: `agent-device help close`. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. - `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. An `open` that passes these flags for another app also removes the earlier hints from the app an earlier `open` applied them to. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity. -- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. +- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` succeeds and omits the session’s serial, plain `close` can still end that local session and release its claim. - On HarmonyOS, `open` reads the foreground app after the launch dispatch, for up to 5 seconds. When the opened app never holds the foreground, the open succeeds and `warnings` name it `open-not-foreground` with the app that holds the foreground, or the fact that no mission is foreground. A lock screen is a typical cause: unlock the device, then run the open again. When no read of the mission list succeeds in that budget, the warning names `open-foreground-probe-unreadable` instead and claims nothing about the app: check the device connection. With `--foreground`, an unconfirmed open fails with `details.reason: open-not-foreground` or `open-foreground-probe-unreadable`, matching the same two cases. -- If `close` cannot confirm its cleanup, it keeps the session and its device claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. +- If `close` cannot confirm its remaining cleanup, it keeps the session and its device claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. iOS Simulator launch prompt: From a5af9f4edd6a12905ea988e1874e418cce946616 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 4 Dec 2026 18:00:06 +0100 Subject: [PATCH 2/4] fix(android): isolate the close serial check --- .../internal/session-close.ts | 68 ++++++++++++------- website/docs/docs/commands.md | 2 +- 2 files changed, 45 insertions(+), 25 deletions(-) diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 505927c490a..9fa0fb38163 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -459,31 +459,10 @@ async function runCloseTeardownAndRelease(params: { finalizeOrdinaryCloseScript, platformResourceCleanup: params.platformResourceCleanup, }); + const mayRetireAfterAppStopError = + cleanupFailures.length === 0 && (await isAndroidCloseSerialAbsent(appStopError, params)); + const platformCloseError = mayRetireAfterAppStopError ? undefined : appStopError; let session = sessionStore.requireCurrent(ref); - let platformCloseError = appStopError; - if ( - cleanupFailures.length === 0 && - lifecycle.owner.kind === 'local-family' && - lifecycle.owner.family === 'android' && - !req.positionals?.length && - !req.flags?.shutdown && - !req.flags?.saveScript && - !req.internal?.killApp && - appStopError instanceof AppError && - appStopError.details?.reason === 'android-process-probe-unavailable' - ) { - const signal = getRequestSignal(req.meta?.requestId); - const serials = await params.observeLocalAndroidAdbSerials(signal).catch(() => undefined); - session = sessionStore.requireCurrent(ref); - if (!signal?.aborted && serials && !serials.includes(session.device.id)) { - emitDiagnostic({ - level: 'warn', - phase: 'android_app_stop_skipped_device_absent', - data: { serial: session.device.id }, - }); - platformCloseError = undefined; - } - } // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint // describe what actually happened to the session. It is built even when a platform-close error // takes precedence, so that error never hides the cleanup failures. @@ -531,6 +510,47 @@ async function runCloseTeardownAndRelease(params: { }; } +async function isAndroidCloseSerialAbsent( + error: unknown, + { + req, + ref, + sessionStore, + lifecycle, + observeLocalAndroidAdbSerials, + }: { + req: DaemonRequest; + ref: SessionRef; + sessionStore: SessionStore; + lifecycle: CloseRuntime | CloseRuntimeWithRuntimeHintClear; + observeLocalAndroidAdbSerials: DaemonPlatformServices['observeLocalAndroidAdbSerials']; + }, +): Promise { + if ( + !(error instanceof AppError) || + error.details?.reason !== 'android-process-probe-unavailable' || + lifecycle.owner.kind !== 'local-family' || + lifecycle.owner.family !== 'android' || + req.positionals?.length || + req.flags?.shutdown || + req.flags?.saveScript || + req.internal?.killApp + ) { + return false; + } + sessionStore.requireCurrent(ref); + const signal = getRequestSignal(req.meta?.requestId); + const serials = await observeLocalAndroidAdbSerials(signal).catch(() => undefined); + const { id: serial } = sessionStore.requireCurrent(ref).device; + if (signal?.aborted || !serials || serials.includes(serial)) return false; + emitDiagnostic({ + level: 'warn', + phase: 'android_app_stop_skipped_device_absent', + data: { serial }, + }); + return true; +} + function buildCloseSuccessResponse(params: { session: SessionState; repair: Extract; diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index abee8e91398..55961e86281 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -242,7 +242,7 @@ Exact behavior: `agent-device help close`. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity. - ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` succeeds and omits the session’s serial, plain `close` can still end that local session and release its claim. - On HarmonyOS, `open` reads the foreground app after the launch dispatch, for up to 5 seconds. When the opened app never holds the foreground, the open succeeds and `warnings` name it `open-not-foreground` with the app that holds the foreground, or the fact that no mission is foreground. A lock screen is a typical cause: unlock the device, then run the open again. When no read of the mission list succeeds in that budget, the warning names `open-foreground-probe-unreadable` instead and claims nothing about the app: check the device connection. With `--foreground`, an unconfirmed open fails with `details.reason: open-not-foreground` or `open-foreground-probe-unreadable`, matching the same two cases. -- If `close` cannot confirm its remaining cleanup, it keeps the session and its device claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. +- If a session holds a device claim and `close` cannot confirm its remaining cleanup, it keeps the session and its claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. iOS Simulator launch prompt: From cd8745488710f19d054a513391858ddb26273907 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Fri, 4 Dec 2026 18:13:23 +0100 Subject: [PATCH 3/4] fix(android): require a usable inventory to release close claims --- .../command-surface/src/management/app.ts | 2 +- .../session-close-claim-retry.test.ts | 21 +++++++++++++++++++ .../internal/session-close.ts | 13 ++++++++---- .../src/ime-lifecycle.test.ts | 18 ++++++++++++++-- .../platform-android/src/ime-lifecycle.ts | 21 +++++++++++++------ website/docs/docs/commands.md | 2 +- 6 files changed, 63 insertions(+), 14 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 213dd1af927..9586c32f66d 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb lists its devices successfully and the session’s serial is absent. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', + 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb successfully lists at least one device and omits the session’s serial. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts index d9ebfa83989..7eb21afdcfe 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts @@ -205,6 +205,7 @@ test('plain close retires only the session and claim for a serial that left loca test.each([ { condition: 'still listed', serials: [wifiDevice.id], error: pidofFailure }, + { condition: 'unconfirmed by an empty inventory', serials: [], error: pidofFailure }, { condition: 'of unknown presence', serials: undefined, error: pidofFailure }, { condition: 'absent but the app-stop failure has no typed reason', @@ -235,6 +236,26 @@ test.each([ }, ); +test('close preserves its app-stop error if the session retires during the inventory read', async () => { + const name = 'retired-during-inventory'; + const sessionStore = await openSession(name, { device: wifiDevice, claim: false }); + const ref = sessionStore.lookup(name)!; + const { loader } = lifecycleOperationsSpy({ + closeApplication: async () => { + throw pidofFailure; + }, + }); + const observeLocalAndroidAdbSerials = vi.fn(async () => { + sessionStore.retire(ref); + return [movedDevice.id]; + }); + + await expect(close(sessionStore, name, loader, { observeLocalAndroidAdbSerials })).rejects.toBe( + pidofFailure, + ); + expect(observeLocalAndroidAdbSerials).toHaveBeenCalledOnce(); +}); + test('a retried close reruns the failed cleanup and then releases the device claim', async () => { const sessionName = 'close-retry-releases-claim'; const sessionStore = await openSession(sessionName); diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 9fa0fb38163..11f0f7915de 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -462,7 +462,9 @@ async function runCloseTeardownAndRelease(params: { const mayRetireAfterAppStopError = cleanupFailures.length === 0 && (await isAndroidCloseSerialAbsent(appStopError, params)); const platformCloseError = mayRetireAfterAppStopError ? undefined : appStopError; - let session = sessionStore.requireCurrent(ref); + let session = sessionStore.resolveCurrent(ref); + if (!session && appStopError) throw appStopError; + session ??= sessionStore.requireCurrent(ref); // Each cleanup report is built where the session's fate is decided, so its diagnostic and hint // describe what actually happened to the session. It is built even when a platform-close error // takes precedence, so that error never hides the cleanup failures. @@ -538,11 +540,10 @@ async function isAndroidCloseSerialAbsent( ) { return false; } - sessionStore.requireCurrent(ref); const signal = getRequestSignal(req.meta?.requestId); const serials = await observeLocalAndroidAdbSerials(signal).catch(() => undefined); - const { id: serial } = sessionStore.requireCurrent(ref).device; - if (signal?.aborted || !serials || serials.includes(serial)) return false; + const serial = sessionStore.resolveCurrent(ref)?.device.id; + if (signal?.aborted || !serial || !adbInventoryOmitsSerial(serials, serial)) return false; emitDiagnostic({ level: 'warn', phase: 'android_app_stop_skipped_device_absent', @@ -551,6 +552,10 @@ async function isAndroidCloseSerialAbsent( return true; } +function adbInventoryOmitsSerial(serials: readonly string[] | undefined, serial: string): boolean { + return Boolean(serials?.length && !serials.includes(serial)); +} + function buildCloseSuccessResponse(params: { session: SessionState; repair: Extract; diff --git a/packages/platform-android/src/ime-lifecycle.test.ts b/packages/platform-android/src/ime-lifecycle.test.ts index b6a20441b70..561b000bfd0 100644 --- a/packages/platform-android/src/ime-lifecycle.test.ts +++ b/packages/platform-android/src/ime-lifecycle.test.ts @@ -2,7 +2,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; import { bindAndroidAdbHostStub } from './adb-host.fixtures.ts'; import { withAndroidHostAdbTransport } from './adb-executor.ts'; -import { listAndroidAdbSerialsQuick } from './ime-lifecycle.ts'; +import { listAndroidAdbSerialsQuick, observeAndroidAdbDevices } from './ime-lifecycle.ts'; test('quick serial listing keeps an unbound adb host port loud', async () => { await assert.rejects( @@ -19,7 +19,7 @@ test('quick serial listing routes its global devices call through the scoped tra async (invocation) => { seenArgs.push(invocation.command); return { - stdout: 'List of devices attached\nemulator-5554\tdevice\n', + stdout: 'List of devices attached\n\nemulator-5554\tdevice\npartial-row\n', stderr: '', exitCode: 0, }; @@ -40,3 +40,17 @@ test('quick serial listing treats a classified transport failure as empty invent assert.deepEqual(serials, []); }); + +test('strict adb inventory refuses a malformed row rather than inferring absence', async () => { + bindAndroidAdbHostStub(); + const devices = await withAndroidHostAdbTransport( + async () => ({ + stdout: 'List of devices attached\nemulator-5554\tdevice\npartial-row\n', + stderr: '', + exitCode: 0, + }), + async () => await observeAndroidAdbDevices(), + ); + + assert.equal(devices, undefined); +}); diff --git a/packages/platform-android/src/ime-lifecycle.ts b/packages/platform-android/src/ime-lifecycle.ts index 0a2f1757c5d..e39822f383f 100644 --- a/packages/platform-android/src/ime-lifecycle.ts +++ b/packages/platform-android/src/ime-lifecycle.ts @@ -17,7 +17,7 @@ export { // Serials only, with no full-inventory name, boot-state, or target probes. export async function listAndroidAdbSerialsQuick(): Promise { - const devices = await observeAndroidAdbDevices(); + const devices = await readAndroidAdbDevices({ allowPartial: true }); return devices?.filter(({ state }) => state === 'device').map(({ serial }) => serial) ?? []; } @@ -25,19 +25,28 @@ export async function listAndroidAdbSerialsQuick(): Promise { export async function observeAndroidAdbDevices( signal?: AbortSignal, ): Promise { + return readAndroidAdbDevices({ signal }); +} + +async function readAndroidAdbDevices(options: { + signal?: AbortSignal; + allowPartial?: boolean; +}): Promise { requireAndroidAdbHost(); try { const result = await runAndroidHostAdb(parseAndroidAdbArgv(['devices']), { timeoutMs: 5_000, - signal, + signal: options.signal, }); - const [header, ...rows] = result.stdout.trim().split(/\r?\n/); - if (header?.trim() !== 'List of devices attached') return undefined; + const lines = result.stdout.trim().split(/\r?\n/); + const rows = options.allowPartial ? lines : lines.slice(1); + if (!options.allowPartial && lines[0]?.trim() !== 'List of devices attached') return undefined; const devices: { serial: string; state: string }[] = []; for (const row of rows) { const [serial, state] = row.trim().split(/\s+/); - if (!serial || !state) return undefined; - devices.push({ serial, state }); + if (!serial) continue; + if (state) devices.push({ serial, state }); + else if (!options.allowPartial) return undefined; } return devices; } catch { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 55961e86281..8e74ad839bc 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -240,7 +240,7 @@ Exact behavior: `agent-device help close`. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. - `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. An `open` that passes these flags for another app also removes the earlier hints from the app an earlier `open` applied them to. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity. -- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` succeeds and omits the session’s serial, plain `close` can still end that local session and release its claim. +- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` lists at least one device and omits the session’s serial, plain `close` can still end that local session and release its claim. - On HarmonyOS, `open` reads the foreground app after the launch dispatch, for up to 5 seconds. When the opened app never holds the foreground, the open succeeds and `warnings` name it `open-not-foreground` with the app that holds the foreground, or the fact that no mission is foreground. A lock screen is a typical cause: unlock the device, then run the open again. When no read of the mission list succeeds in that budget, the warning names `open-foreground-probe-unreadable` instead and claims nothing about the app: check the device connection. With `--foreground`, an unconfirmed open fails with `details.reason: open-not-foreground` or `open-foreground-probe-unreadable`, matching the same two cases. - If a session holds a device claim and `close` cannot confirm its remaining cleanup, it keeps the session and its claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects. From f0e08d050c52c8dd28407abb1331e12292314188 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Sun, 6 Dec 2026 10:29:13 +0100 Subject: [PATCH 4/4] fix(android): release claims after a verified empty inventory --- packages/command-surface/src/management/app.ts | 2 +- .../__tests__/session-close-claim-retry.test.ts | 17 ++++++++++++++++- .../session-lifecycle/internal/session-close.ts | 2 +- website/docs/docs/commands.md | 2 +- 4 files changed, 19 insertions(+), 4 deletions(-) diff --git a/packages/command-surface/src/management/app.ts b/packages/command-surface/src/management/app.ts index 9586c32f66d..f3b8005eded 100644 --- a/packages/command-surface/src/management/app.ts +++ b/packages/command-surface/src/management/app.ts @@ -95,7 +95,7 @@ const openCommandMetadata = defineFieldCommandMetadata( const closeCommandMetadata = defineFieldCommandMetadata( 'close', - 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb successfully lists at least one device and omits the session’s serial. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', + 'Close the named app, or close the active session app when app is omitted. The shutdown option also stops the session simulator or emulator where supported; close alone never stops the device. Android ADB close fails with android-app-close-timeout if the app stays foreground past 2s or a killed process does not exit within 10s; a new process that Android starts afterwards does not fail it. It fails with android-process-probe-unavailable when adb pidof cannot list the app processes; if that happens before the force-stop, the app keeps running. Plain close can still end a local Android session and release its claim if adb returns a valid device list that omits the session’s serial, even if the list is empty. If close cannot confirm its remaining cleanup on a session that holds a device claim, the session and its claim stay. A repeated close retries cleanup with the same options, except that save-script must be omitted after publication.', { app: stringField('Optional app to close.'), shutdown: booleanField('Shutdown the session/device where supported.'), diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts index 7eb21afdcfe..728ad6fab9a 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/__tests__/session-close-claim-retry.test.ts @@ -179,6 +179,22 @@ const pidofFailure = new AppError('COMMAND_FAILED', 'Could not read process stat reason: 'android-process-probe-unavailable', }); +test('plain close releases the last device claim when adb confirms an empty inventory', async () => { + const name = 'last-adb-serial'; + const sessionStore = await openSession(name, { device: wifiDevice }); + const { loader } = lifecycleOperationsSpy({ + closeApplication: async () => { + throw pidofFailure; + }, + }); + + await expect( + close(sessionStore, name, loader, { observeLocalAndroidAdbSerials: async () => [] }), + ).resolves.toMatchObject({ ok: true, data: { session: name } }); + expect(sessionStore.get(name)).toBeUndefined(); + expect(inspectDeviceClaims({ serial: wifiDevice.id }, process.env)).toEqual([]); +}); + test('plain close retires only the session and claim for a serial that left local adb', async () => { const sessionName = 'vanished-adb-serial'; const sessionStore = await openSession(sessionName, { device: wifiDevice }); @@ -205,7 +221,6 @@ test('plain close retires only the session and claim for a serial that left loca test.each([ { condition: 'still listed', serials: [wifiDevice.id], error: pidofFailure }, - { condition: 'unconfirmed by an empty inventory', serials: [], error: pidofFailure }, { condition: 'of unknown presence', serials: undefined, error: pidofFailure }, { condition: 'absent but the app-stop failure has no typed reason', diff --git a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts index 11f0f7915de..ec83878052f 100644 --- a/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts +++ b/packages/daemon/src/sessions/session-lifecycle/internal/session-close.ts @@ -553,7 +553,7 @@ async function isAndroidCloseSerialAbsent( } function adbInventoryOmitsSerial(serials: readonly string[] | undefined, serial: string): boolean { - return Boolean(serials?.length && !serials.includes(serial)); + return serials !== undefined && !serials.includes(serial); } function buildCloseSuccessResponse(params: { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 8e74ad839bc..ef81cd31e5a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -240,7 +240,7 @@ Exact behavior: `agent-device help close`. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. - `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. An `open` that passes these flags for another app also removes the earlier hints from the app an earlier `open` applied them to. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity. -- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` lists at least one device and omits the session’s serial, plain `close` can still end that local session and release its claim. +- ADB-backed Android: `close` fails with `android-app-close-timeout` when the app does not leave the foreground or its processes do not exit in time. It fails with `android-process-probe-unavailable` when it cannot list the app's processes; if that happens before the stop, the app keeps running. If `adb devices` returns a valid list that omits the session’s serial, plain `close` can still end that local session and release its claim. An empty list counts if ADB returned it successfully. - On HarmonyOS, `open` reads the foreground app after the launch dispatch, for up to 5 seconds. When the opened app never holds the foreground, the open succeeds and `warnings` name it `open-not-foreground` with the app that holds the foreground, or the fact that no mission is foreground. A lock screen is a typical cause: unlock the device, then run the open again. When no read of the mission list succeeds in that budget, the warning names `open-foreground-probe-unreadable` instead and claims nothing about the app: check the device connection. With `--foreground`, an unconfirmed open fails with `details.reason: open-not-foreground` or `open-foreground-probe-unreadable`, matching the same two cases. - If a session holds a device claim and `close` cannot confirm its remaining cleanup, it keeps the session and its claim. Run `close` again with the same options to release the device, without `--save-script` if the first attempt saved the script. The same applies when `open --relaunch` cannot confirm its effects.