From 60a998414c96b204ce60f923c22fb371d3b4b81b Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:16:24 +0900 Subject: [PATCH 01/33] fix(android): let press reach a foreign app-error dialog's own buttons When another package (for example System UI) shows "isn't responding", the blocking-dialog guard refused every command, including a press on the dialog's Close app or Wait button, so the dialog could not be dismissed. A single press or click is now admitted when its final tap point lies inside one of the framework app-error dialog buttons (android:id/aerr_*) that are visible and not covered. Every other input is still refused with dispatched: no. After the admitted tap, the guard waits for the dialog focus to clear before its after-command check. Co-Authored-By: Claude Opus 5.5 --- .../src/core/interaction/internal/types.ts | 5 + .../android-system-dialog-readiness.test.ts | 103 +++++++++++++- .../src/execution/android-system-dialog.ts | 133 +++++++++++++++++- .../internal/interaction-runtime.ts | 13 +- ...nteraction-touch-android-readiness.test.ts | 130 ++++++++++++++++- .../interaction-touch-android-readiness.ts | 60 ++++++-- .../internal/interaction-touch-press.ts | 23 +++ .../internal/interaction-touch-runtime.ts | 13 +- 8 files changed, 451 insertions(+), 29 deletions(-) diff --git a/packages/daemon/src/core/interaction/internal/types.ts b/packages/daemon/src/core/interaction/internal/types.ts index 0976cbf806..f34eeb5339 100644 --- a/packages/daemon/src/core/interaction/internal/types.ts +++ b/packages/daemon/src/core/interaction/internal/types.ts @@ -133,6 +133,11 @@ export type InteractionRuntimeInput = { ) => Promise; pairedGestureViewport?: Rect; touchExecutor?: BoundTouchExecutor; + /** + * Runs immediately before a tap is sent, before the ref frame expires: a throw refuses the tap + * with nothing dispatched. `undefined` is a native-ref tap, which has no point to check. + */ + admitTap?: (point: Point | undefined) => void; gestures?: BoundGestureExecutor; /** * The capture every observation on this request reads the screen through: the action binding's diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 932b4f426f..52d368508f 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -15,7 +15,10 @@ import { countDiagnosticEventsByPhase, withDiagnosticsScope, } from '@agent-device/host-kit/diagnostics'; -import { ensureAndroidBlockingSystemDialogReady } from '../android-system-dialog.ts'; +import { + ensureAndroidBlockingSystemDialogReady, + ensureAndroidBlockingSystemDialogReadyForTap, +} from '../android-system-dialog.ts'; // A blocking dialog can surface with no adb traffic at all, so nothing a previous command observed // is evidence about this one. These pin what each readiness phase owes the command it guards. @@ -251,3 +254,101 @@ test('a dump that answered nothing is reported as unobserved, not as a clear scr expect(readiness).toEqual({ status: 'clear' }); expect(unobserved).toBe(1); }); + +/** System UI's ANR dialog as the framework draws it: a title and buttons with `aerr_` ids. */ +function systemUiAnrDialogNodes(): RawSnapshotNode[] { + return [ + { + index: 0, + type: 'android.widget.TextView', + label: "System UI isn't responding", + identifier: 'android:id/alertTitle', + rect: { x: 50, y: 400, width: 500, height: 80 }, + }, + { + index: 1, + type: 'android.widget.Button', + label: 'Close app', + identifier: 'android:id/aerr_close', + rect: CLOSE_APP_RECT, + }, + { + index: 2, + type: 'android.widget.Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + rect: { x: 100, y: 700, width: 220, height: 80 }, + }, + ]; +} + +test("a tap may target a foreign ANR dialog's own buttons, and nothing is tapped for it", async () => { + // The dialog refuses every other input, so its buttons are the only way to close it. + const session = makeAndroidSession('readiness-system-tap'); + screenNodes = systemUiAnrDialogNodes(); + const { observation, calls } = makeObservation(systemDialogFocus); + + const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + observation, + }); + + expect(readiness).toMatchObject({ + status: 'dialog-buttons', + admission: { + focus: systemDialogFocus(), + buttons: [CLOSE_APP_RECT, { x: 100, y: 700, width: 220, height: 80 }], + }, + }); + expect(tapCalls(calls)).toEqual([]); +}); + +test('a tap stays refused when the foreign dialog shows no framework buttons', async () => { + // An app control labelled "Close app" is not the dialog's button: only the framework id counts. + const session = makeAndroidSession('readiness-system-tap-no-ids'); + const { observation } = makeObservation(systemDialogFocus); + + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: expect.stringContaining('Android system dialog is blocking press'), + }); +}); + +test('a tap stays refused when a surface covers the foreign dialog', async () => { + const session = makeAndroidSession('readiness-system-tap-covered'); + screenNodes = [ + ...systemUiAnrDialogNodes(), + { + index: 3, + type: 'com.google.android.material.bottomsheet.BottomSheetDialog', + identifier: 'com.example:id/bottom_sheet', + hittable: true, + rect: { x: 0, y: 0, width: 1080, height: 2400 }, + }, + ]; + const { observation } = makeObservation(systemDialogFocus); + + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED' }); +}); + +test('the session app ANR is still recovered before a tap, not admitted', async () => { + const session = makeAndroidSession('readiness-anr-tap', { appBundleId: APP }); + const { observation, calls } = makeObservation(anrFocus); + + const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + observation, + }); + + expect(readiness).toEqual({ + status: 'recovered', + warning: `Recovered Android app ANR before press: closed and relaunched ${APP}.`, + }); + expect(tapCalls(calls)).toEqual([CLOSE_APP_TAP]); +}); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index d8e335e4ec..813efb094b 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -5,7 +5,13 @@ import type { import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { sleep } from '@agent-device/host-kit/retry'; import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; -import { centerOfRect, type SnapshotNode } from '@agent-device/kernel/snapshot'; +import { containsPoint } from '@agent-device/kernel/rect'; +import { + centerOfRect, + type Point, + type Rect, + type SnapshotNode, +} from '@agent-device/kernel/snapshot'; import { isSnapshotNodeInteractionBlocked } from '@agent-device/capture-kit/snapshot-occlusion'; import { expireRefFrame } from '../core/ref-frame.ts'; @@ -14,10 +20,18 @@ import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; const ANDROID_BLOCKING_MODAL_PATTERN = /\bis(?:n(?:'|'|')?t| not)\s+responding\b/i; const ANDROID_CLOSE_APP_PATTERN = /^close app$/i; +/** + * The framework's app-error dialog buttons (`AppNotRespondingDialog`, `AppErrorDialog`): Close app, + * Wait, Send feedback, Open app again, App info. The resource id does not depend on the device + * language. + */ +const ANDROID_APP_ERROR_DIALOG_BUTTON_ID = /^android:id\/aerr_[a-z_]+$/; const ANDROID_MODAL_POLL_MS = 500; const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = 'Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.'; +const ANDROID_FOREIGN_DIALOG_HINT = + "Press one of the dialog's buttons (Close app or Wait), or run `alert dismiss`, then retry. Every other input is refused while the dialog has focus."; const ANDROID_BLOCKING_DIALOG_INSPECTION_WARNING = 'Android blocking-dialog readiness could not be inspected; the command continued.'; const ANDROID_BLOCKING_DIALOG_WARNING_TEXT_LIMIT = 240; @@ -34,6 +48,21 @@ export type AndroidBlockingDialogReadinessResult = focusedPackage?: string; } | { status: 'recovered'; warning: string }; + +/** + * A foreign blocking dialog that a single tap may still close: the dialog's own buttons as the + * presentation published them, and the refusal for a tap anywhere else. A dialog button is the one + * input that can clear the dialog, so the guard must not refuse it. + */ +export type AndroidBlockingDialogButtonAdmission = Readonly<{ + focus: AndroidBlockingDialogFocus; + buttons: readonly Rect[]; + refusal: () => AppError; +}>; + +export type AndroidBlockingDialogTapReadinessResult = + | AndroidBlockingDialogReadinessResult + | { status: 'dialog-buttons'; admission: AndroidBlockingDialogButtonAdmission }; type AndroidDialogButtonTapResult = | { ok: true; x: number; y: number } | { @@ -175,6 +204,78 @@ export async function ensureAndroidBlockingSystemDialogReady(params: { phase: 'before-command' | 'after-command'; observation?: AndroidObservationAdapter; }): Promise { + const readiness = await readAndroidBlockingSystemDialogReadiness(params); + if (readiness.status === 'foreign-dialog') throw readiness.refusal(); + return readiness; +} + +/** + * The before-command check of a single tap. A foreign app-error dialog ("System UI isn't + * responding") refuses every other input, so its own buttons are the only way to close it from a + * command. The tap proceeds with `dialog-buttons` when the dialog shows touchable buttons; the + * caller must refuse, before any send, a tap point outside them. + */ +export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { + session: SessionState; + command: string; + observation?: AndroidObservationAdapter; +}): Promise { + const readiness = await readAndroidBlockingSystemDialogReadiness({ + ...params, + phase: 'before-command', + }); + if (readiness.status !== 'foreign-dialog') return readiness; + const observation = requireObservation(params.observation); + let buttons: Rect[]; + try { + buttons = findAppErrorDialogButtons( + await readAndroidSnapshotNodes(params.session, observation), + ); + } catch { + throw readiness.refusal(); + } + if (buttons.length === 0) throw readiness.refusal(); + return { + status: 'dialog-buttons', + admission: { focus: readiness.focus, buttons, refusal: readiness.refusal }, + }; +} + +/** True when the tap point falls on one of the dialog's own buttons. */ +export function isAndroidBlockingDialogButtonPoint( + admission: AndroidBlockingDialogButtonAdmission, + point: Point, +): boolean { + return admission.buttons.some((rect) => containsPoint(rect, point.x, point.y)); +} + +/** + * After a tap on a dialog button, Android removes the dialog window asynchronously. Waits a bounded + * time for the focus to leave the dialog, so the after-command check reads the result of the tap + * and not the frame before it. + */ +export async function waitForAndroidBlockingDialogFocusToClear( + session: SessionState, + observation: AndroidObservationAdapter | undefined, +): Promise { + const adapter = requireObservation(observation); + for (let attempt = 0; attempt < ANDROID_MODAL_POLL_ATTEMPTS; attempt += 1) { + const dialog = await adapter.readBlockingDialog(session.device); + if (dialog.status !== 'dialog') return; + await sleep(ANDROID_MODAL_POLL_MS); + } +} + +type AndroidBlockingSystemDialogReadiness = + | AndroidBlockingDialogReadinessResult + | { status: 'foreign-dialog'; focus: AndroidBlockingDialogFocus; refusal: () => AppError }; + +async function readAndroidBlockingSystemDialogReadiness(params: { + session: SessionState; + command: string; + phase: 'before-command' | 'after-command'; + observation?: AndroidObservationAdapter; +}): Promise { const { session, command } = params; if (session.device.platform !== 'android' || isProviderOwnedSession(session)) { return { status: 'clear' }; @@ -227,13 +328,18 @@ export async function ensureAndroidBlockingSystemDialogReady(params: { }); } - throw androidBlockingDialogError({ - session, - command, + return { + status: 'foreign-dialog', focus, - message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, - hint: ANDROID_BLOCKING_DIALOG_HINT, - }); + refusal: () => + androidBlockingDialogError({ + session, + command, + focus, + message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, + hint: ANDROID_FOREIGN_DIALOG_HINT, + }), + }; } async function recoverAppOwnedAndroidBlockingSystemDialogSafely( @@ -461,6 +567,19 @@ function readNodeTextParts(node: { .map((part) => part.trim()); } +/** + * The touchable buttons of a framework app-error dialog, read by resource id. Only a screen that + * also shows the dialog's "isn't responding" title counts, so an app's own control with a + * look-alike id never opens the gate. + */ +function findAppErrorDialogButtons(nodes: SnapshotNode[]): Rect[] { + if (!containsBlockingDialog(nodes)) return []; + return nodes + .filter(isTouchableDialogNode) + .filter((node) => ANDROID_APP_ERROR_DIALOG_BUTTON_ID.test(node.identifier ?? '')) + .flatMap((node) => (node.rect ? [node.rect] : [])); +} + function containsBlockingDialog(nodes: SnapshotNode[]): boolean { return nodes.filter(isTouchableDialogNode).some((node) => { const text = readNodeText(node); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index 17fd0030fa..3227d07ac1 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -44,6 +44,8 @@ export async function createInteractionRuntimeForRoute( pairedGestureViewport?: Rect; touchExecutor?: BoundTouchExecutor; gestures?: BoundGestureExecutor; + /** See `InteractionRuntimeInput.admitTap`. */ + admitTap?: InteractionRuntimeInput['admitTap']; /** * Filled with the LAST capture this request consumed. ADR 0014 ambiguity * issuance is only valid against a tree the session stored under the @@ -106,6 +108,7 @@ export async function createInteractionRuntimeForRoute( probeTargetHittability: readTargetHittabilityProbe(params, session), pairedGestureViewport: params.pairedGestureViewport, touchExecutor: params.touchExecutor, + ...(params.admitTap ? { admitTap: params.admitTap } : {}), gestures: params.gestures, boundCapture: resolveBoundCapture(params), }); @@ -250,6 +253,7 @@ function createInteractionBackend(params: InteractionRuntimeInput): AgentDeviceB ...touchBackendMembers( params.touchExecutor, params.expireRefFrame, + params.admitTap, flags, params.coordinateTapTextInputEvidence, ), @@ -280,6 +284,7 @@ function gestureBackendMembers( function touchBackendMembers( executor: InteractionRuntimeInput['touchExecutor'], expireRefFrame: () => void, + admitTap: InteractionRuntimeInput['admitTap'], flags: InteractionRuntimeInput['flags'], textInputEvidence: InteractionRuntimeInput['coordinateTapTextInputEvidence'], ): Partial { @@ -292,6 +297,7 @@ function touchBackendMembers( return { tap: tapPoint ? (_context, point, options) => { + admitTap?.(point); const evidence = textInputEvidence?.(point, options?.pointObservation); return run(() => tapPoint(point, { @@ -301,7 +307,12 @@ function touchBackendMembers( ); } : undefined, - tapTarget: tapRef ? (_context, target) => run(() => tapRef(target.ref)) : undefined, + tapTarget: tapRef + ? (_context, target) => { + admitTap?.(undefined); + return run(() => tapRef(target.ref)); + } + : undefined, fill: fillPoint ? (_context, point, text, options) => run(() => fillPoint(point, text, options)) : undefined, diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index f614c6c6b4..15a97607f4 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -22,11 +22,15 @@ import { handleInteractionCommands } from '../index.ts'; type EnsureAndroidBlockingSystemDialogReady = typeof import('../../android-system-dialog.ts').ensureAndroidBlockingSystemDialogReady; +type EnsureAndroidBlockingSystemDialogReadyForTap = + typeof import('../../android-system-dialog.ts').ensureAndroidBlockingSystemDialogReadyForTap; const { androidDialogReadiness } = vi.hoisted(() => ({ androidDialogReadiness: { spy: vi.fn(), actual: undefined as unknown as EnsureAndroidBlockingSystemDialogReady, + tapSpy: vi.fn(), + tapActual: undefined as unknown as EnsureAndroidBlockingSystemDialogReadyForTap, }, })); @@ -45,7 +49,12 @@ vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => { vi.mock('../../android-system-dialog.ts', async (importOriginal) => { const actual = await importOriginal(); androidDialogReadiness.actual = actual.ensureAndroidBlockingSystemDialogReady; - return { ...actual, ensureAndroidBlockingSystemDialogReady: androidDialogReadiness.spy }; + androidDialogReadiness.tapActual = actual.ensureAndroidBlockingSystemDialogReadyForTap; + return { + ...actual, + ensureAndroidBlockingSystemDialogReady: androidDialogReadiness.spy, + ensureAndroidBlockingSystemDialogReadyForTap: androidDialogReadiness.tapSpy, + }; }); import { @@ -69,6 +78,10 @@ beforeEach(() => { mockInteractorSnapshot.mockReset(); androidDialogReadiness.spy.mockReset(); androidDialogReadiness.spy.mockImplementation((params) => androidDialogReadiness.actual(params)); + androidDialogReadiness.tapSpy.mockReset(); + androidDialogReadiness.tapSpy.mockImplementation((params) => + androidDialogReadiness.tapActual(params), + ); }); test('press @ref fails when Android tap escapes to launcher', async () => { @@ -312,12 +325,10 @@ test.each(ANDROID_PERMISSION_PROMPT_PACKAGES)( test('a ref action aborts with the shared ref_frame_expired rejection after Android dialog recovery mutates', async () => { // Simulate recovery: the before-command readiness check taps a blocking dialog // (a device mutation) and reports `recovered`, expiring the frame. - androidDialogReadiness.spy.mockImplementation(async (params) => { - if (params.phase === 'before-command') { - expireRefFrame(params.session); - return { status: 'recovered', warning: 'Recovered from a blocking system dialog' }; - } - return { status: 'clear' }; + // A single press reads readiness through the tap variant. + androidDialogReadiness.tapSpy.mockImplementation(async (params) => { + expireRefFrame(params.session); + return { status: 'recovered', warning: 'Recovered from a blocking system dialog' }; }); const sessionStore = makeSessionStore(); const sessionName = 'android-recovery-abort'; @@ -362,3 +373,108 @@ test('a ref action aborts with the shared ref_frame_expired rejection after Andr // The outstanding ref action never dispatched a press against the recovered UI. expect(mockTapPoint).not.toHaveBeenCalled(); }); + +// While System UI's ANR dialog has focus, the guard refuses every input. The dialog's own +// buttons are the one input that can close it, so a single press on one of them goes through, and +// any other tap is still refused before it is sent. +const SYSTEM_UI_ANR = { + status: 'dialog', + focus: { + package: 'com.android.systemui', + focusedWindow: 'Application Not Responding: com.android.systemui', + raw: 'mCurrentFocus=Window{ffeedd u0 Application Not Responding: com.android.systemui}', + }, +} as const; + +function systemUiAnrScreen() { + return attachRefs([ + { + index: 0, + type: 'android.widget.TextView', + label: "System UI isn't responding", + identifier: 'android:id/alertTitle', + rect: { x: 50, y: 400, width: 500, height: 80 }, + }, + { + index: 1, + type: 'android.widget.Button', + label: 'Close app', + identifier: 'android:id/aerr_close', + rect: { x: 100, y: 600, width: 220, height: 80 }, + enabled: true, + hittable: true, + }, + { + index: 2, + type: 'android.widget.Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + rect: { x: 100, y: 700, width: 220, height: 80 }, + enabled: true, + hittable: true, + }, + ]); +} + +async function pressWithSystemUiAnr(positionals: string[], flags: Record = {}) { + const sessionStore = makeSessionStore(); + const sessionName = 'android-system-ui-anr'; + const session = makeAndroidSession(sessionName); + session.appBundleId = 'com.example.app'; + const nodes = systemUiAnrScreen(); + session.snapshot = { nodes, createdAt: Date.now(), backend: 'android' }; + sessionStore.publish(sessionName, session); + + // The dialog holds the focus until a tap reaches the device. + let tapped = false; + mockTapPoint.mockImplementation(async (input) => { + tapped = true; + return { x: input.point.x, y: input.point.y }; + }); + mockGetAndroidBlockingDialogObservation.mockImplementation(async () => + tapped ? { status: 'clear' } : SYSTEM_UI_ANR, + ); + const bindings = getRuntimeBindings(); + return await handleInteractionCommands({ + createCommandSurface: touchCreateCommandSurface, + req: { token: 't', session: sessionName, command: 'press', positionals, flags }, + sessionName, + sessionStore, + contextFromFlags, + ...bindings, + androidObservation: { ...bindings.androidObservation, readSnapshotNodes: async () => nodes }, + }); +} + +test("press on the System UI ANR dialog's Close app goes through the blocking-dialog guard", async () => { + const response = await pressWithSystemUiAnr(['@e2']); + + expect(response).toMatchObject({ ok: true }); + expect(mockTapPoint).toHaveBeenCalledTimes(1); + expect(mockTapPoint.mock.calls[0]?.[0].point).toEqual({ x: 210, y: 640 }); +}); + +test('a press at a point outside the System UI ANR dialog buttons is refused before it is sent', async () => { + const response = await pressWithSystemUiAnr(['540', '1500']); + + expect(response).toMatchObject({ + ok: false, + error: { + code: 'COMMAND_FAILED', + message: expect.stringContaining('Android system dialog is blocking press'), + details: { dispatched: 'no', focusedPackage: 'com.android.systemui' }, + }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); + +test('a repeated press on the System UI ANR dialog stays refused', async () => { + // The later taps of a repeated press would land on whatever the closed dialog uncovers. + const response = await pressWithSystemUiAnr(['@e2'], { count: 2 }); + + expect(response).toMatchObject({ + ok: false, + error: { message: expect.stringContaining('Android system dialog is blocking press') }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index 88dc8d33e5..55179082ca 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -1,7 +1,13 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; +import { discloseDispatch } from '@agent-device/kernel/errors'; +import type { Point } from '@agent-device/kernel/snapshot'; import { ensureAndroidBlockingSystemDialogReady, - type AndroidBlockingDialogReadinessResult, + ensureAndroidBlockingSystemDialogReadyForTap, + isAndroidBlockingDialogButtonPoint, + waitForAndroidBlockingDialogFocusToClear, + type AndroidBlockingDialogButtonAdmission, + type AndroidBlockingDialogTapReadinessResult, } from '../../android-system-dialog.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { readRefMutationFrame } from '../../../core/ref-frame.ts'; @@ -24,27 +30,57 @@ export type ReadinessOutcome = | { aborted: true; response: DaemonResponse } | { aborted: false; - readiness: AndroidBlockingDialogReadinessResult; + readiness: AndroidBlockingDialogTapReadinessResult; runtimeResult: TResult; }; +/** + * The per-request gate of a single tap while a foreign app-error dialog has focus. Readiness opens + * it with the dialog's buttons; the backend calls `admitTap` immediately before it sends the tap + * (and before the ref frame expires). Only one tap, on one of the dialog's buttons, passes. Any + * other tap is refused with the guard's own error and `dispatched: no`. + */ +export type AndroidDialogTapGate = Readonly<{ + open(admission: AndroidBlockingDialogButtonAdmission): void; + admitTap(point: Point | undefined): void; +}>; + +export function createAndroidDialogTapGate(): AndroidDialogTapGate { + let admission: AndroidBlockingDialogButtonAdmission | undefined; + let admittedTaps = 0; + return { + open: (next) => { + admission = next; + }, + admitTap: (point) => { + if (!admission) return; + if (admittedTaps > 0 || !point || !isAndroidBlockingDialogButtonPoint(admission, point)) { + throw discloseDispatch(admission.refusal(), 'no'); + } + admittedTaps += 1; + }, + }; +} + export async function runWithAndroidDialogReadinessCheck( session: SessionState, command: string, - options: { refContext: RefAdmissionContext | undefined }, - run: (readiness: AndroidBlockingDialogReadinessResult) => Promise, + options: { refContext: RefAdmissionContext | undefined; dialogTapGate?: AndroidDialogTapGate }, + run: (readiness: AndroidBlockingDialogTapReadinessResult) => Promise, observation?: AndroidObservationAdapter, ): Promise> { if (session.lease?.leaseProvider) { const readiness = { status: 'clear' } as const; return { aborted: false, readiness, runtimeResult: await run(readiness) }; } - const readiness = await ensureAndroidBlockingSystemDialogReady({ - session, - command, - phase: 'before-command', - observation, - }); + const readiness: AndroidBlockingDialogTapReadinessResult = options.dialogTapGate + ? await ensureAndroidBlockingSystemDialogReadyForTap({ session, command, observation }) + : await ensureAndroidBlockingSystemDialogReady({ + session, + command, + phase: 'before-command', + observation, + }); // ADR 0014: blocking-dialog recovery is itself device-mutating and expires the // frame at its own seam. A ref action admitted against the pre-recovery frame // must NOT continue against the recovered UI — abort it through the SHARED @@ -65,7 +101,11 @@ export async function runWithAndroidDialogReadinessCheck( }); if (abort) return { aborted: true, response: abort }; } + if (readiness.status === 'dialog-buttons') options.dialogTapGate?.open(readiness.admission); const runtimeResult = await run(readiness); + if (readiness.status === 'dialog-buttons') { + await waitForAndroidBlockingDialogFocusToClear(session, observation); + } await ensureAndroidBlockingSystemDialogReady({ session, command, diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index 44875cbfcc..0969bf2937 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -25,6 +25,7 @@ import { type TargetedTouchResult, } from './interaction-touch-response.ts'; import { dispatchRuntimeInteraction } from './interaction-touch-runtime.ts'; +import { createAndroidDialogTapGate } from './interaction-touch-android-readiness.ts'; import { formatTouchTargetLabel } from './interaction-touch-targets.ts'; import { refreshAndroidRefSnapshotIfFreshnessActive } from './interaction-touch-android-freshness.ts'; import { prepareTouchDispatch } from './interaction-touch-prepare.ts'; @@ -107,6 +108,9 @@ function buildTargetedRuntimeOptions( return { androidFreshnessBaseline: admitted.androidFreshnessBaseline, refContext: admitted.refContext, + ...(admitsAndroidDialogButtonTap(session, command, admitted.refs, req.flags) + ? { androidDialogTapGate: createAndroidDialogTapGate() } + : {}), iosTapCorroboration: { target, extra: targetedExtra }, run: async (runtime) => await runTargetedTouchInteraction({ @@ -124,6 +128,9 @@ function buildTargetedRuntimeOptions( }), afterRun: async (result, readiness) => { if (session.lease?.leaseProvider) return undefined; + // The dialog, not the session app, owned the focus before this tap, so the tap cannot have + // escaped the app. + if (readiness.status === 'dialog-buttons') return undefined; return await assertAndroidPressStayedInApp( session, { @@ -159,6 +166,22 @@ function buildTargetedRuntimeOptions( }; } +/** + * Only one plain tap may close a foreign Android app-error dialog: a repeated tap, a double tap, + * or a multi-ref plan would send its later taps to whatever the closed dialog uncovers. + */ +function admitsAndroidDialogButtonTap( + session: AdmittedTargetedTouch['session'], + command: TargetedTouchCommand, + refs: readonly string[] | undefined, + flags: CommandFlags | undefined, +): boolean { + if (session.device.platform !== 'android') return false; + if (command !== 'press' && command !== 'click') return false; + if (refs && refs.length > 1) return false; + return (flags?.count ?? 1) <= 1 && flags?.doubleTap !== true; +} + async function runTargetedTouchInteraction(params: { runtime: Awaited>; command: TargetedTouchCommand; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts index 448c3736a0..063f5e6937 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts @@ -26,9 +26,10 @@ import { isAndroidEscapeError } from './interaction-android-escape.ts'; import { corroborateIosTapFailure, interactionTargetExtra } from './interaction-ios-tap-outcome.ts'; import { runWithAndroidDialogReadinessCheck, + type AndroidDialogTapGate, type RefAdmissionContext, } from './interaction-touch-android-readiness.ts'; -import type { AndroidBlockingDialogReadinessResult } from '../../android-system-dialog.ts'; +import type { AndroidBlockingDialogTapReadinessResult } from '../../android-system-dialog.ts'; import { readSnapshotNodesReferenceFrame } from '@agent-device/capture-kit/touch-reference-frame'; import { buildCorroboratedTapResponseData, @@ -62,6 +63,11 @@ export async function dispatchRuntimeInteraction< * admission rejection built from this context. */ refContext?: RefAdmissionContext; + /** + * Present on a single press or click: while a foreign Android app-error dialog has focus, the + * tap may still go to one of the dialog's own buttons, checked at the tap point before send. + */ + androidDialogTapGate?: AndroidDialogTapGate; /** A failed local iOS tap may be corroborated against one same-scope capture. */ iosTapCorroboration?: { target: InteractionRequestTarget; @@ -74,7 +80,7 @@ export async function dispatchRuntimeInteraction< */ afterRun?( result: TResult, - readiness: AndroidBlockingDialogReadinessResult, + readiness: AndroidBlockingDialogTapReadinessResult, ): Promise; buildPayloads( result: TResult, @@ -90,6 +96,7 @@ export async function dispatchRuntimeInteraction< touchExecutor: options.touchExecutor, settleObservationCapture: options.settleObservationCapture, consumedCapture, + ...(options.androidDialogTapGate ? { admitTap: options.androidDialogTapGate.admitTap } : {}), }); const actionStartedAt = Date.now(); try { @@ -97,7 +104,7 @@ export async function dispatchRuntimeInteraction< const outcome = await runWithAndroidDialogReadinessCheck( session, params.req.command, - { refContext: options.refContext }, + { refContext: options.refContext, dialogTapGate: options.androidDialogTapGate }, async (readiness) => { const result = await options.run(runtime); afterRunWarning = await options.afterRun?.(result, readiness); From 956ac70ca8741fc84879a7a327ee4c9691cabf87 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:27:36 +0900 Subject: [PATCH 02/33] fix(android): confirm the dialog still has focus before a dialog-button tap The dialog-button exception read the button rectangles at the readiness check, before target resolution. If the dialog closed in between, a tap at a stored button point reached whatever the dialog uncovered and was reported as a success. The gate now reads the focus again immediately before the send. When the dialog no longer has focus, the tap is refused with dispatched: no. Co-Authored-By: Claude Opus 5.5 --- .../src/core/interaction/internal/types.ts | 2 +- .../src/execution/android-system-dialog.ts | 44 +++++++++++++++- .../internal/interaction-runtime.ts | 12 ++--- ...nteraction-touch-android-readiness.test.ts | 50 +++++++++++++++++-- .../interaction-touch-android-readiness.ts | 9 ++-- 5 files changed, 99 insertions(+), 18 deletions(-) diff --git a/packages/daemon/src/core/interaction/internal/types.ts b/packages/daemon/src/core/interaction/internal/types.ts index f34eeb5339..784b7f88d6 100644 --- a/packages/daemon/src/core/interaction/internal/types.ts +++ b/packages/daemon/src/core/interaction/internal/types.ts @@ -137,7 +137,7 @@ export type InteractionRuntimeInput = { * Runs immediately before a tap is sent, before the ref frame expires: a throw refuses the tap * with nothing dispatched. `undefined` is a native-ref tap, which has no point to check. */ - admitTap?: (point: Point | undefined) => void; + admitTap?: (point: Point | undefined) => Promise; gestures?: BoundGestureExecutor; /** * The capture every observation on this request reads the screen through: the action binding's diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 813efb094b..a25517d9ce 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -4,7 +4,12 @@ import type { } from '@agent-device/contracts/android-observation'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { sleep } from '@agent-device/host-kit/retry'; -import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; +import { + AppError, + discloseDispatch, + normalizeError, + type NormalizedError, +} from '@agent-device/kernel/errors'; import { containsPoint } from '@agent-device/kernel/rect'; import { centerOfRect, @@ -58,6 +63,12 @@ export type AndroidBlockingDialogButtonAdmission = Readonly<{ focus: AndroidBlockingDialogFocus; buttons: readonly Rect[]; refusal: () => AppError; + /** + * Reads the focus again immediately before the tap is sent. Throws, with nothing sent, when the + * dialog no longer has focus: the buttons were read from an earlier frame, so a tap at their + * points could reach what the dialog uncovered. + */ + confirmFocus: () => Promise; }>; export type AndroidBlockingDialogTapReadinessResult = @@ -235,12 +246,41 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { throw readiness.refusal(); } if (buttons.length === 0) throw readiness.refusal(); + const { session, command } = params; + const { focus, refusal } = readiness; return { status: 'dialog-buttons', - admission: { focus: readiness.focus, buttons, refusal: readiness.refusal }, + admission: { + focus, + buttons, + refusal, + confirmFocus: async () => { + const current = await observation.readBlockingDialog(session.device); + if (current.status !== 'dialog') { + throw discloseDispatch( + androidBlockingDialogError({ + session, + command, + focus, + message: `Android system dialog lost focus before ${command} was sent: ${formatAndroidBlockingDialogFocus(focus)}.`, + hint: 'Nothing was sent. Take a new snapshot, then retry the command.', + }), + 'no', + ); + } + if (!isSameAndroidBlockingDialogFocus(current.focus, focus)) throw refusal(); + }, + }, }; } +function isSameAndroidBlockingDialogFocus( + a: AndroidBlockingDialogFocus, + b: AndroidBlockingDialogFocus, +): boolean { + return a.package === b.package && a.focusedWindow === b.focusedWindow; +} + /** True when the tap point falls on one of the dialog's own buttons. */ export function isAndroidBlockingDialogButtonPoint( admission: AndroidBlockingDialogButtonAdmission, diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index 3227d07ac1..52938bbc83 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -296,10 +296,10 @@ function touchBackendMembers( }; return { tap: tapPoint - ? (_context, point, options) => { - admitTap?.(point); + ? async (_context, point, options) => { + await admitTap?.(point); const evidence = textInputEvidence?.(point, options?.pointObservation); - return run(() => + return await run(() => tapPoint(point, { ...flags, ...(evidence ? { coordinateTapTextInputEvidence: evidence } : {}), @@ -308,9 +308,9 @@ function touchBackendMembers( } : undefined, tapTarget: tapRef - ? (_context, target) => { - admitTap?.(undefined); - return run(() => tapRef(target.ref)); + ? async (_context, target) => { + await admitTap?.(undefined); + return await run(() => tapRef(target.ref)); } : undefined, fill: fillPoint diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 15a97607f4..e0e1a1af09 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -416,7 +416,20 @@ function systemUiAnrScreen() { ]); } -async function pressWithSystemUiAnr(positionals: string[], flags: Record = {}) { +type BlockingDialogObservation = typeof SYSTEM_UI_ANR | { status: 'clear' }; + +async function pressWithSystemUiAnr( + positionals: string[], + flags: Record = {}, + /** + * The focus read number `read` (from 0) returns, before and after the tap. By default the dialog + * holds the focus until a tap reaches the device. + */ + focus: { + beforeTap?: (read: number) => BlockingDialogObservation; + afterTap?: (read: number) => BlockingDialogObservation; + } = {}, +) { const sessionStore = makeSessionStore(); const sessionName = 'android-system-ui-anr'; const session = makeAndroidSession(sessionName); @@ -425,15 +438,20 @@ async function pressWithSystemUiAnr(positionals: string[], flags: Record SYSTEM_UI_ANR); + const afterTap = focus.afterTap ?? (() => ({ status: 'clear' }) as const); let tapped = false; + let reads = 0; mockTapPoint.mockImplementation(async (input) => { tapped = true; + reads = 0; return { x: input.point.x, y: input.point.y }; }); - mockGetAndroidBlockingDialogObservation.mockImplementation(async () => - tapped ? { status: 'clear' } : SYSTEM_UI_ANR, - ); + mockGetAndroidBlockingDialogObservation.mockImplementation(async () => { + const read = reads; + reads += 1; + return tapped ? afterTap(read) : beforeTap(read); + }); const bindings = getRuntimeBindings(); return await handleInteractionCommands({ createCommandSurface: touchCreateCommandSurface, @@ -478,3 +496,25 @@ test('a repeated press on the System UI ANR dialog stays refused', async () => { }); expect(mockTapPoint).not.toHaveBeenCalled(); }); + +test('a press on a System UI ANR dialog button is refused when the dialog loses focus before the send', async () => { + // Readiness reads the dialog; by the read just before the send, Android has removed it, so the + // button points now belong to the screen underneath. + const response = await pressWithSystemUiAnr( + ['@e2'], + {}, + { + beforeTap: (read) => (read === 0 ? SYSTEM_UI_ANR : { status: 'clear' }), + }, + ); + + expect(response).toMatchObject({ + ok: false, + error: { + code: 'COMMAND_FAILED', + message: expect.stringContaining('Android system dialog lost focus before press was sent'), + details: { dispatched: 'no' }, + }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index 55179082ca..50ff4f5dd7 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -37,12 +37,12 @@ export type ReadinessOutcome = /** * The per-request gate of a single tap while a foreign app-error dialog has focus. Readiness opens * it with the dialog's buttons; the backend calls `admitTap` immediately before it sends the tap - * (and before the ref frame expires). Only one tap, on one of the dialog's buttons, passes. Any - * other tap is refused with the guard's own error and `dispatched: no`. + * (and before the ref frame expires). Only one tap, on one of the dialog's buttons, passes, and only + * while the dialog still has focus. Any other tap is refused with `dispatched: no`. */ export type AndroidDialogTapGate = Readonly<{ open(admission: AndroidBlockingDialogButtonAdmission): void; - admitTap(point: Point | undefined): void; + admitTap(point: Point | undefined): Promise; }>; export function createAndroidDialogTapGate(): AndroidDialogTapGate { @@ -52,11 +52,12 @@ export function createAndroidDialogTapGate(): AndroidDialogTapGate { open: (next) => { admission = next; }, - admitTap: (point) => { + admitTap: async (point) => { if (!admission) return; if (admittedTaps > 0 || !point || !isAndroidBlockingDialogButtonPoint(admission, point)) { throw discloseDispatch(admission.refusal(), 'no'); } + await admission.confirmFocus(); admittedTaps += 1; }, }; From 6541ab1d8d0944352f0792df07c984d91c469d60 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:27:42 +0900 Subject: [PATCH 03/33] test(android): cover the wait for the dialog focus to clear after a button tap Android removes the app-error dialog window asynchronously, so the first focus reads after the tap can still show it. No test held the wait that covers this: the press fixture cleared the focus at the tap. Co-Authored-By: Claude Opus 5.5 --- .../interaction-touch-android-readiness.test.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index e0e1a1af09..5a5cfb2706 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -518,3 +518,17 @@ test('a press on a System UI ANR dialog button is refused when the dialog loses }); expect(mockTapPoint).not.toHaveBeenCalled(); }); + +test('a press on a System UI ANR dialog button waits for the dialog focus to clear', async () => { + // Android removes the dialog window asynchronously: the first reads after the tap still show it. + const response = await pressWithSystemUiAnr( + ['@e2'], + {}, + { + afterTap: (read) => (read < 2 ? SYSTEM_UI_ANR : { status: 'clear' }), + }, + ); + + expect(response).toMatchObject({ ok: true }); + expect(mockTapPoint).toHaveBeenCalledTimes(1); +}); From cf6cbbebfacab3f05384bcc5609b11ed668a6bcb Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:28:09 +0900 Subject: [PATCH 04/33] fix(android): find app-error dialog buttons in any device language The dialog-button exception still required the English "isn't responding" title in the snapshot. On a device in another language, the guard detected the ANR window from its fixed window title, but found no buttons, so a press on the dialog's own Close app button stayed refused. The focus read already identifies the ANR window, so the buttons are now found by their framework resource id alone. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-readiness.test.ts | 23 +++++++++++++++++++ .../src/execution/android-system-dialog.ts | 7 +++--- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 52d368508f..0dae8018a7 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -304,6 +304,29 @@ test("a tap may target a foreign ANR dialog's own buttons, and nothing is tapped expect(tapCalls(calls)).toEqual([]); }); +test("a tap may target a localized foreign ANR dialog's own buttons", async () => { + // Android translates the dialog's title and labels; the framework ids stay the same. + const session = makeAndroidSession('readiness-system-tap-localized'); + const [title, closeApp, wait] = systemUiAnrDialogNodes(); + screenNodes = [ + { ...title!, label: 'System UI reagiert nicht' }, + { ...closeApp!, label: 'App schließen' }, + { ...wait!, label: 'Warten' }, + ]; + const { observation } = makeObservation(systemDialogFocus); + + const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + observation, + }); + + expect(readiness).toMatchObject({ + status: 'dialog-buttons', + admission: { buttons: [CLOSE_APP_RECT, { x: 100, y: 700, width: 220, height: 80 }] }, + }); +}); + test('a tap stays refused when the foreign dialog shows no framework buttons', async () => { // An app control labelled "Close app" is not the dialog's button: only the framework id counts. const session = makeAndroidSession('readiness-system-tap-no-ids'); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index a25517d9ce..c2904c5110 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -608,12 +608,11 @@ function readNodeTextParts(node: { } /** - * The touchable buttons of a framework app-error dialog, read by resource id. Only a screen that - * also shows the dialog's "isn't responding" title counts, so an app's own control with a - * look-alike id never opens the gate. + * The touchable buttons of a framework app-error dialog, read by resource id. The caller has + * already read the ANR window's focus, and the dialog's text is in the device language, so only the + * framework id identifies a button: an app cannot declare an id in the `android` package. */ function findAppErrorDialogButtons(nodes: SnapshotNode[]): Rect[] { - if (!containsBlockingDialog(nodes)) return []; return nodes .filter(isTouchableDialogNode) .filter((node) => ANDROID_APP_ERROR_DIALOG_BUTTON_ID.test(node.identifier ?? '')) From dd9d8cee647cd13a472778a782b96b3dbc22668c Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:28:33 +0900 Subject: [PATCH 05/33] fix(android): exclude a dialog button's right and bottom edges from its hit area The dialog-button exception used the shared inclusive containsPoint, so a raw-coordinate press on the pixel just past a button's right or bottom edge was admitted. Android's view hit test excludes those edges, so the tap reached the dialog around the button and closed nothing. Co-Authored-By: Claude Opus 5.5 --- .../daemon/src/execution/android-system-dialog.ts | 15 ++++++++++++--- .../interaction-touch-android-readiness.test.ts | 13 +++++++++++++ 2 files changed, 25 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index c2904c5110..3410c0e1f2 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -10,7 +10,6 @@ import { normalizeError, type NormalizedError, } from '@agent-device/kernel/errors'; -import { containsPoint } from '@agent-device/kernel/rect'; import { centerOfRect, type Point, @@ -281,12 +280,22 @@ function isSameAndroidBlockingDialogFocus( return a.package === b.package && a.focusedWindow === b.focusedWindow; } -/** True when the tap point falls on one of the dialog's own buttons. */ +/** + * True when the tap point falls on one of the dialog's own buttons. Android's view hit test excludes + * the right and bottom edges, so a point on them reaches the dialog around the button, not the + * button. + */ export function isAndroidBlockingDialogButtonPoint( admission: AndroidBlockingDialogButtonAdmission, point: Point, ): boolean { - return admission.buttons.some((rect) => containsPoint(rect, point.x, point.y)); + return admission.buttons.some( + (rect) => + point.x >= rect.x && + point.x < rect.x + rect.width && + point.y >= rect.y && + point.y < rect.y + rect.height, + ); } /** diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 5a5cfb2706..02d687c313 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -486,6 +486,19 @@ test('a press at a point outside the System UI ANR dialog buttons is refused bef expect(mockTapPoint).not.toHaveBeenCalled(); }); +test.each([ + ['the right edge', ['320', '640']], + ['the bottom edge', ['210', '680']], +])( + "a press on %s of a System UI ANR dialog button is refused: Android's hit test excludes it", + async (_edge, positionals) => { + const response = await pressWithSystemUiAnr(positionals); + + expect(response).toMatchObject({ ok: false, error: { details: { dispatched: 'no' } } }); + expect(mockTapPoint).not.toHaveBeenCalled(); + }, +); + test('a repeated press on the System UI ANR dialog stays refused', async () => { // The later taps of a repeated press would land on whatever the closed dialog uncovers. const response = await pressWithSystemUiAnr(['@e2'], { count: 2 }); From c839572d0054ae9f9ef9c2fde10b0834e213e0e1 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:31:07 +0900 Subject: [PATCH 06/33] fix(android): report dispatched: no when a foreign dialog refuses a command ADR 0039 requires dispatched: no for a refusal before any send. The blocking-dialog guard's before-command refusal for a foreign dialog left the field unset, so the request disclosure layer reported dispatched: unknown for a mutating command, while the dialog-button gate's own refusal of the same press already reported no. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/android-system-dialog-readiness.test.ts | 1 + packages/daemon/src/execution/android-system-dialog.ts | 10 +++++++--- .../interaction-touch-android-readiness.test.ts | 5 ++++- .../internal/interaction-touch-android-readiness.ts | 3 +-- 4 files changed, 13 insertions(+), 6 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 0dae8018a7..fd51b64b6b 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -337,6 +337,7 @@ test('a tap stays refused when the foreign dialog shows no framework buttons', a ).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: expect.stringContaining('Android system dialog is blocking press'), + details: { dispatched: 'no' }, }); }); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 3410c0e1f2..4af3f159b1 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -380,14 +380,18 @@ async function readAndroidBlockingSystemDialogReadiness(params: { return { status: 'foreign-dialog', focus, - refusal: () => - androidBlockingDialogError({ + refusal: () => { + const error = androidBlockingDialogError({ session, command, focus, message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, hint: ANDROID_FOREIGN_DIALOG_HINT, - }), + }); + // ADR 0039: before the command, the refusal sends nothing. After it, the command's own + // dispatch ledger discloses what was sent. + return params.phase === 'before-command' ? discloseDispatch(error, 'no') : error; + }, }; } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 02d687c313..0f3633c6f6 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -505,7 +505,10 @@ test('a repeated press on the System UI ANR dialog stays refused', async () => { expect(response).toMatchObject({ ok: false, - error: { message: expect.stringContaining('Android system dialog is blocking press') }, + error: { + message: expect.stringContaining('Android system dialog is blocking press'), + details: { dispatched: 'no' }, + }, }); expect(mockTapPoint).not.toHaveBeenCalled(); }); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index 50ff4f5dd7..1cc4a32361 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -1,5 +1,4 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import { discloseDispatch } from '@agent-device/kernel/errors'; import type { Point } from '@agent-device/kernel/snapshot'; import { ensureAndroidBlockingSystemDialogReady, @@ -55,7 +54,7 @@ export function createAndroidDialogTapGate(): AndroidDialogTapGate { admitTap: async (point) => { if (!admission) return; if (admittedTaps > 0 || !point || !isAndroidBlockingDialogButtonPoint(admission, point)) { - throw discloseDispatch(admission.refusal(), 'no'); + throw admission.refusal(); } await admission.confirmFocus(); admittedTaps += 1; From 329a042b51f38068c31ee93561a066743c07df23 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:43:02 +0900 Subject: [PATCH 07/33] fix(android): refuse a dialog-button tap for a target resolved on an older tree The dialog-button exception checked only the tap point. An app @ref from a snapshot taken before the ANR dialog appeared resolves on that older tree. When its point fell on Close app or Wait, the gate admitted it, the tap closed the dialog, and the response reported a press of the app's own control. The gate now also requires the point to be a dialog button in the tree the target was resolved on. A raw coordinate has no such tree and keeps the point-only check. Co-Authored-By: Claude Opus 5.5 --- .../src/core/interaction/internal/types.ts | 10 +++- .../src/execution/android-system-dialog.ts | 21 ++++++-- .../internal/interaction-runtime.ts | 2 +- ...nteraction-touch-android-readiness.test.ts | 48 +++++++++++++++---- .../interaction-touch-android-readiness.ts | 12 +++-- 5 files changed, 74 insertions(+), 19 deletions(-) diff --git a/packages/daemon/src/core/interaction/internal/types.ts b/packages/daemon/src/core/interaction/internal/types.ts index 784b7f88d6..da1c1ae28a 100644 --- a/packages/daemon/src/core/interaction/internal/types.ts +++ b/packages/daemon/src/core/interaction/internal/types.ts @@ -5,7 +5,12 @@ import type { DaemonPlatformServices } from '../../platform-services.ts'; import type { CommandFlags } from '@agent-device/contracts/command'; import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface'; import type { AndroidObservationAdapter } from '@agent-device/contracts/android-observation'; -import type { Point, Rect, SnapshotPreferredBackend } from '@agent-device/kernel/snapshot'; +import type { + Point, + Rect, + SnapshotNode, + SnapshotPreferredBackend, +} from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import type { RequestCaptureProof } from '../../capture-disclosure.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -136,8 +141,9 @@ export type InteractionRuntimeInput = { /** * Runs immediately before a tap is sent, before the ref frame expires: a throw refuses the tap * with nothing dispatched. `undefined` is a native-ref tap, which has no point to check. + * `resolvedOn` is the tree that measured the point, absent for a raw coordinate. */ - admitTap?: (point: Point | undefined) => Promise; + admitTap?: (point: Point | undefined, resolvedOn?: SnapshotNode[]) => Promise; gestures?: BoundGestureExecutor; /** * The capture every observation on this request reads the screen through: the action binding's diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 4af3f159b1..569b0c4732 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -281,15 +281,28 @@ function isSameAndroidBlockingDialogFocus( } /** - * True when the tap point falls on one of the dialog's own buttons. Android's view hit test excludes - * the right and bottom edges, so a point on them reaches the dialog around the button, not the - * button. + * True when the tap point falls on one of the dialog's own buttons. `resolvedOn` is the tree the + * target was resolved on, when it was resolved on one: the point must be a dialog button there too, + * so an app control from a tree read before the dialog appeared is not retargeted to the dialog + * button that now covers it. */ export function isAndroidBlockingDialogButtonPoint( admission: AndroidBlockingDialogButtonAdmission, point: Point, + resolvedOn?: SnapshotNode[], ): boolean { - return admission.buttons.some( + if (!isPointOnAnyButton(admission.buttons, point)) return false; + return ( + resolvedOn === undefined || isPointOnAnyButton(findAppErrorDialogButtons(resolvedOn), point) + ); +} + +/** + * Android's view hit test excludes the right and bottom edges, so a point on them reaches the + * dialog around the button, not the button. + */ +function isPointOnAnyButton(buttons: readonly Rect[], point: Point): boolean { + return buttons.some( (rect) => point.x >= rect.x && point.x < rect.x + rect.width && diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index 52938bbc83..8967c00877 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -297,7 +297,7 @@ function touchBackendMembers( return { tap: tapPoint ? async (_context, point, options) => { - await admitTap?.(point); + await admitTap?.(point, options?.pointObservation?.nodes); const evidence = textInputEvidence?.(point, options?.pointObservation); return await run(() => tapPoint(point, { diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 0f3633c6f6..910668cd6b 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -421,13 +421,15 @@ type BlockingDialogObservation = typeof SYSTEM_UI_ANR | { status: 'clear' }; async function pressWithSystemUiAnr( positionals: string[], flags: Record = {}, - /** - * The focus read number `read` (from 0) returns, before and after the tap. By default the dialog - * holds the focus until a tap reaches the device. - */ - focus: { + setup: { + /** + * The focus read number `read` (from 0) returns, before and after the tap. By default the + * dialog holds the focus until a tap reaches the device. + */ beforeTap?: (read: number) => BlockingDialogObservation; afterTap?: (read: number) => BlockingDialogObservation; + /** The session's stored snapshot, when it was taken before the dialog appeared. */ + sessionNodes?: ReturnType; } = {}, ) { const sessionStore = makeSessionStore(); @@ -435,11 +437,15 @@ async function pressWithSystemUiAnr( const session = makeAndroidSession(sessionName); session.appBundleId = 'com.example.app'; const nodes = systemUiAnrScreen(); - session.snapshot = { nodes, createdAt: Date.now(), backend: 'android' }; + session.snapshot = { + nodes: setup.sessionNodes ?? nodes, + createdAt: Date.now(), + backend: 'android', + }; sessionStore.publish(sessionName, session); - const beforeTap = focus.beforeTap ?? (() => SYSTEM_UI_ANR); - const afterTap = focus.afterTap ?? (() => ({ status: 'clear' }) as const); + const beforeTap = setup.beforeTap ?? (() => SYSTEM_UI_ANR); + const afterTap = setup.afterTap ?? (() => ({ status: 'clear' }) as const); let tapped = false; let reads = 0; mockTapPoint.mockImplementation(async (input) => { @@ -513,6 +519,32 @@ test('a repeated press on the System UI ANR dialog stays refused', async () => { expect(mockTapPoint).not.toHaveBeenCalled(); }); +test('a ref from a snapshot taken before the ANR dialog is not retargeted to the dialog button over it', async () => { + // The app's own button sits where the dialog's Close app now is: the tap would close System UI + // and report it as a press of the app's button. + const appScreen = attachRefs([ + { + index: 0, + type: 'android.widget.Button', + label: 'Submit order', + identifier: 'com.example.app:id/submit', + rect: { x: 60, y: 590, width: 300, height: 100 }, + enabled: true, + hittable: true, + }, + ]); + const response = await pressWithSystemUiAnr(['@e1'], {}, { sessionNodes: appScreen }); + + expect(response).toMatchObject({ + ok: false, + error: { + message: expect.stringContaining('Android system dialog is blocking press'), + details: { dispatched: 'no' }, + }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); + test('a press on a System UI ANR dialog button is refused when the dialog loses focus before the send', async () => { // Readiness reads the dialog; by the read just before the send, Android has removed it, so the // button points now belong to the screen underneath. diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index 1cc4a32361..e5ed6e74fa 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -1,5 +1,5 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import type { Point } from '@agent-device/kernel/snapshot'; +import type { Point, SnapshotNode } from '@agent-device/kernel/snapshot'; import { ensureAndroidBlockingSystemDialogReady, ensureAndroidBlockingSystemDialogReadyForTap, @@ -41,7 +41,7 @@ export type ReadinessOutcome = */ export type AndroidDialogTapGate = Readonly<{ open(admission: AndroidBlockingDialogButtonAdmission): void; - admitTap(point: Point | undefined): Promise; + admitTap(point: Point | undefined, resolvedOn?: SnapshotNode[]): Promise; }>; export function createAndroidDialogTapGate(): AndroidDialogTapGate { @@ -51,9 +51,13 @@ export function createAndroidDialogTapGate(): AndroidDialogTapGate { open: (next) => { admission = next; }, - admitTap: async (point) => { + admitTap: async (point, resolvedOn) => { if (!admission) return; - if (admittedTaps > 0 || !point || !isAndroidBlockingDialogButtonPoint(admission, point)) { + if ( + admittedTaps > 0 || + !point || + !isAndroidBlockingDialogButtonPoint(admission, point, resolvedOn) + ) { throw admission.refusal(); } await admission.confirmFocus(); From bd290049b59ac7dcb39a58447ee66dc1da112858 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:44:17 +0900 Subject: [PATCH 08/33] fix(android): disclose and name each failed focus check before a dialog-button tap The focus read just before a dialog-button tap reported a probe that answered nothing as "lost focus", although the dialog may still be up. A read that threw (for example, the device went offline) reached the request disclosure layer as dispatched: unknown, although nothing was sent. An unanswered read now says that focus could not be read, and a thrown read is disclosed as dispatched: no. Tests also cover a different dialog taking the focus before the send. Co-Authored-By: Claude Opus 5.5 --- .../src/execution/android-system-dialog.ts | 36 +++++++---- ...nteraction-touch-android-readiness.test.ts | 61 ++++++++++++++++++- 2 files changed, 83 insertions(+), 14 deletions(-) diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 569b0c4732..bd71a93267 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -19,6 +19,7 @@ import { import { isSnapshotNodeInteractionBlocked } from '@agent-device/capture-kit/snapshot-occlusion'; import { expireRefFrame } from '../core/ref-frame.ts'; +import { thrownBeforeDispatch } from './request-dispatch-disclosure.ts'; import type { SessionState } from '../core/session-state.ts'; import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; @@ -254,20 +255,29 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { buttons, refusal, confirmFocus: async () => { - const current = await observation.readBlockingDialog(session.device); - if (current.status !== 'dialog') { - throw discloseDispatch( - androidBlockingDialogError({ - session, - command, - focus, - message: `Android system dialog lost focus before ${command} was sent: ${formatAndroidBlockingDialogFocus(focus)}.`, - hint: 'Nothing was sent. Take a new snapshot, then retry the command.', - }), - 'no', - ); + const current = await observation + .readBlockingDialog(session.device) + .catch((error: unknown) => { + throw thrownBeforeDispatch(error); + }); + if (current.status === 'dialog') { + if (!isSameAndroidBlockingDialogFocus(current.focus, focus)) throw refusal(); + return; } - if (!isSameAndroidBlockingDialogFocus(current.focus, focus)) throw refusal(); + const dialog = formatAndroidBlockingDialogFocus(focus); + throw discloseDispatch( + androidBlockingDialogError({ + session, + command, + focus, + message: + current.status === 'unknown' + ? `Android focus could not be read to confirm that the system dialog still has focus before ${command} was sent: ${dialog}.` + : `Android system dialog lost focus before ${command} was sent: ${dialog}.`, + hint: 'Nothing was sent. Take a new snapshot, then retry the command.', + }), + 'no', + ); }, }, }; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 910668cd6b..cc10f6ee34 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -1,5 +1,6 @@ import { test, expect, vi, beforeEach } from 'vitest'; import { attachRefs } from '@agent-device/kernel/snapshot'; +import { AppError } from '@agent-device/kernel/errors'; import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; import { expireRefFrame } from '../../../core/ref-frame.ts'; import { @@ -416,7 +417,7 @@ function systemUiAnrScreen() { ]); } -type BlockingDialogObservation = typeof SYSTEM_UI_ANR | { status: 'clear' }; +type BlockingDialogObservation = Awaited>; async function pressWithSystemUiAnr( positionals: string[], @@ -567,6 +568,64 @@ test('a press on a System UI ANR dialog button is refused when the dialog loses expect(mockTapPoint).not.toHaveBeenCalled(); }); +test.each([ + [ + 'the focus read answers nothing', + { status: 'unknown' } as const, + 'Android focus could not be read to confirm', + ], + [ + 'another dialog has the focus', + { + status: 'dialog', + focus: { + package: 'com.example.other', + focusedWindow: 'Application Not Responding: com.example.other', + raw: 'mCurrentFocus=Window{aabbcc u0 Application Not Responding: com.example.other}', + }, + } as const, + 'Android system dialog is blocking press', + ], +])( + 'a press on a System UI ANR dialog button is refused when, before the send, %s', + async (_case, beforeSend, message) => { + const response = await pressWithSystemUiAnr( + ['@e2'], + {}, + { + beforeTap: (read) => (read === 0 ? SYSTEM_UI_ANR : beforeSend), + }, + ); + + expect(response).toMatchObject({ + ok: false, + error: { message: expect.stringContaining(message), details: { dispatched: 'no' } }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); + }, +); + +test('a press on a System UI ANR dialog button is refused with nothing sent when the focus read fails', async () => { + let reads = 0; + const response = await pressWithSystemUiAnr( + ['@e2'], + {}, + { + beforeTap: () => { + reads += 1; + if (reads > 1) throw new AppError('COMMAND_FAILED', 'adb: device offline'); + return SYSTEM_UI_ANR; + }, + }, + ); + + expect(response).toMatchObject({ + ok: false, + error: { message: 'adb: device offline', details: { dispatched: 'no' } }, + }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); + test('a press on a System UI ANR dialog button waits for the dialog focus to clear', async () => { // Android removes the dialog window asynchronously: the first reads after the tap still show it. const response = await pressWithSystemUiAnr( From 78e8721df7bff57510a03f6c1f67a0a4e6ebe6ba Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:44:31 +0900 Subject: [PATCH 09/33] fix(android): keep alert dismiss out of the foreign-dialog refusal hint The alert handler recognizes the app-error dialog by its English labels only, so on a device in another language `alert dismiss` finds no alert. A press on one of the dialog's buttons works in every language, so the hint names only that. Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/execution/android-system-dialog.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index bd71a93267..dcaba0a4e3 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -36,7 +36,7 @@ const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = 'Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.'; const ANDROID_FOREIGN_DIALOG_HINT = - "Press one of the dialog's buttons (Close app or Wait), or run `alert dismiss`, then retry. Every other input is refused while the dialog has focus."; + "Press one of the dialog's buttons (Close app or Wait), then retry. Every other input is refused while the dialog has focus."; const ANDROID_BLOCKING_DIALOG_INSPECTION_WARNING = 'Android blocking-dialog readiness could not be inspected; the command continued.'; const ANDROID_BLOCKING_DIALOG_WARNING_TEXT_LIMIT = 240; From c58a596f829a03aa365b417477d70e008bb5ab35 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:45:19 +0900 Subject: [PATCH 10/33] fix(android): record why a dialog-button tap found no buttons to admit When the snapshot read for the dialog's buttons failed, the tap was refused like a dialog without buttons, and the read error was dropped. The refusal stays, and the read failure is now recorded as a diagnostic. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-readiness.test.ts | 19 +++++++++++++++++++ .../src/execution/android-system-dialog.ts | 12 +++++++++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index fd51b64b6b..cec876957c 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -341,6 +341,25 @@ test('a tap stays refused when the foreign dialog shows no framework buttons', a }); }); +test('a tap stays refused when the foreign dialog cannot be read, and the read failure is recorded', async () => { + const session = makeAndroidSession('readiness-system-tap-unread'); + const observation: AndroidObservationAdapter = { + ...makeObservation(systemDialogFocus).observation, + readSnapshotNodes: async () => { + throw new Error('uiautomator dump failed'); + }, + }; + + const unread = await withDiagnosticsScope({}, async () => { + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), + ).rejects.toMatchObject({ details: { dispatched: 'no' } }); + return countDiagnosticEventsByPhase(['android_blocking_dialog_buttons_unread']); + }); + + expect(unread).toBe(1); +}); + test('a tap stays refused when a surface covers the foreign dialog', async () => { const session = makeAndroidSession('readiness-system-tap-covered'); screenNodes = [ diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index dcaba0a4e3..5ac4b3a9d6 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -242,7 +242,17 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { buttons = findAppErrorDialogButtons( await readAndroidSnapshotNodes(params.session, observation), ); - } catch { + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'android_blocking_dialog_buttons_unread', + data: { + session: params.session.name, + deviceId: params.session.device.id, + command: params.command, + error: error instanceof Error ? error.message : String(error), + }, + }); throw readiness.refusal(); } if (buttons.length === 0) throw readiness.refusal(); From 7a64d3d22e08d5149625bb17afc895ee5bad7e3f Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:46:03 +0900 Subject: [PATCH 11/33] test(android): cover each input shape the dialog-button exception admits or refuses Only a repeated press was tested. A double tap and a multi-ref plan are refused for the same reason, and click is admitted like press; a change that dropped any of these checks passed every test. Co-Authored-By: Claude Opus 5.5 --- ...nteraction-touch-android-readiness.test.ts | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index cc10f6ee34..ff004fef61 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -429,6 +429,7 @@ async function pressWithSystemUiAnr( */ beforeTap?: (read: number) => BlockingDialogObservation; afterTap?: (read: number) => BlockingDialogObservation; + command?: 'press' | 'click'; /** The session's stored snapshot, when it was taken before the dialog appeared. */ sessionNodes?: ReturnType; } = {}, @@ -462,7 +463,13 @@ async function pressWithSystemUiAnr( const bindings = getRuntimeBindings(); return await handleInteractionCommands({ createCommandSurface: touchCreateCommandSurface, - req: { token: 't', session: sessionName, command: 'press', positionals, flags }, + req: { + token: 't', + session: sessionName, + command: setup.command ?? 'press', + positionals, + flags, + }, sessionName, sessionStore, contextFromFlags, @@ -479,6 +486,14 @@ test("press on the System UI ANR dialog's Close app goes through the blocking-di expect(mockTapPoint.mock.calls[0]?.[0].point).toEqual({ x: 210, y: 640 }); }); +test("click on the System UI ANR dialog's Wait goes through the blocking-dialog guard", async () => { + const response = await pressWithSystemUiAnr(['@e3'], {}, { command: 'click' }); + + expect(response).toMatchObject({ ok: true }); + expect(mockTapPoint).toHaveBeenCalledTimes(1); + expect(mockTapPoint.mock.calls[0]?.[0].point).toEqual({ x: 210, y: 740 }); +}); + test('a press at a point outside the System UI ANR dialog buttons is refused before it is sent', async () => { const response = await pressWithSystemUiAnr(['540', '1500']); @@ -506,16 +521,17 @@ test.each([ }, ); -test('a repeated press on the System UI ANR dialog stays refused', async () => { - // The later taps of a repeated press would land on whatever the closed dialog uncovers. - const response = await pressWithSystemUiAnr(['@e2'], { count: 2 }); +test.each([ + ['a repeated press', ['@e2'], { count: 2 }], + ['a double tap', ['@e2'], { doubleTap: true }], + ['a multi-ref plan', ['@e2,@e3'], {}], +])('%s on the System UI ANR dialog stays refused', async (_shape, positionals, flags) => { + // Its later taps would land on whatever the closed dialog uncovers. + const response = await pressWithSystemUiAnr(positionals, flags); expect(response).toMatchObject({ ok: false, - error: { - message: expect.stringContaining('Android system dialog is blocking press'), - details: { dispatched: 'no' }, - }, + error: { details: { dispatched: 'no' } }, }); expect(mockTapPoint).not.toHaveBeenCalled(); }); From 1f9bfea68cdce248f8063c8985624754a309598b Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:56:51 +0900 Subject: [PATCH 12/33] fix(android): require the same dialog button at the tap point in both trees The check against the tree a target was resolved on accepted any app-error dialog button at the point. When the dialog's buttons moved after the snapshot, for example after a rotation, a Wait ref whose old point now lies on Close app was admitted, and the tap killed the app that the agent meant to wait for. Each admitted button now keeps its framework resource id, and the button at the point must have the same id in both trees. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-readiness.test.ts | 12 +++++- .../src/execution/android-system-dialog.ts | 38 ++++++++++++------- ...nteraction-touch-android-readiness.test.ts | 14 +++++++ 3 files changed, 49 insertions(+), 15 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index cec876957c..cf1820ee8d 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -298,7 +298,10 @@ test("a tap may target a foreign ANR dialog's own buttons, and nothing is tapped status: 'dialog-buttons', admission: { focus: systemDialogFocus(), - buttons: [CLOSE_APP_RECT, { x: 100, y: 700, width: 220, height: 80 }], + buttons: [ + { identifier: 'android:id/aerr_close', rect: CLOSE_APP_RECT }, + { identifier: 'android:id/aerr_wait', rect: { x: 100, y: 700, width: 220, height: 80 } }, + ], }, }); expect(tapCalls(calls)).toEqual([]); @@ -323,7 +326,12 @@ test("a tap may target a localized foreign ANR dialog's own buttons", async () = expect(readiness).toMatchObject({ status: 'dialog-buttons', - admission: { buttons: [CLOSE_APP_RECT, { x: 100, y: 700, width: 220, height: 80 }] }, + admission: { + buttons: [ + { identifier: 'android:id/aerr_close', rect: CLOSE_APP_RECT }, + { identifier: 'android:id/aerr_wait', rect: { x: 100, y: 700, width: 220, height: 80 } }, + ], + }, }); }); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 5ac4b3a9d6..dd748c5324 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -61,7 +61,7 @@ export type AndroidBlockingDialogReadinessResult = */ export type AndroidBlockingDialogButtonAdmission = Readonly<{ focus: AndroidBlockingDialogFocus; - buttons: readonly Rect[]; + buttons: readonly AndroidAppErrorDialogButton[]; refusal: () => AppError; /** * Reads the focus again immediately before the tap is sent. Throws, with nothing sent, when the @@ -71,6 +71,9 @@ export type AndroidBlockingDialogButtonAdmission = Readonly<{ confirmFocus: () => Promise; }>; +/** One framework app-error dialog button: its resource id (the action it takes) and its frame. */ +export type AndroidAppErrorDialogButton = Readonly<{ identifier: string; rect: Rect }>; + export type AndroidBlockingDialogTapReadinessResult = | AndroidBlockingDialogReadinessResult | { status: 'dialog-buttons'; admission: AndroidBlockingDialogButtonAdmission }; @@ -237,7 +240,7 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { }); if (readiness.status !== 'foreign-dialog') return readiness; const observation = requireObservation(params.observation); - let buttons: Rect[]; + let buttons: AndroidAppErrorDialogButton[]; try { buttons = findAppErrorDialogButtons( await readAndroidSnapshotNodes(params.session, observation), @@ -302,18 +305,21 @@ function isSameAndroidBlockingDialogFocus( /** * True when the tap point falls on one of the dialog's own buttons. `resolvedOn` is the tree the - * target was resolved on, when it was resolved on one: the point must be a dialog button there too, - * so an app control from a tree read before the dialog appeared is not retargeted to the dialog - * button that now covers it. + * target was resolved on, when it was resolved on one: the same button must be at the point there + * too. So an app control from a tree read before the dialog appeared is not retargeted to the + * dialog button that now covers it, and a Wait target is not retargeted to Close app. */ export function isAndroidBlockingDialogButtonPoint( admission: AndroidBlockingDialogButtonAdmission, point: Point, resolvedOn?: SnapshotNode[], ): boolean { - if (!isPointOnAnyButton(admission.buttons, point)) return false; + const button = findButtonAtPoint(admission.buttons, point); + if (!button) return false; + if (resolvedOn === undefined) return true; return ( - resolvedOn === undefined || isPointOnAnyButton(findAppErrorDialogButtons(resolvedOn), point) + findButtonAtPoint(findAppErrorDialogButtons(resolvedOn), point)?.identifier === + button.identifier ); } @@ -321,9 +327,12 @@ export function isAndroidBlockingDialogButtonPoint( * Android's view hit test excludes the right and bottom edges, so a point on them reaches the * dialog around the button, not the button. */ -function isPointOnAnyButton(buttons: readonly Rect[], point: Point): boolean { - return buttons.some( - (rect) => +function findButtonAtPoint( + buttons: readonly AndroidAppErrorDialogButton[], + point: Point, +): AndroidAppErrorDialogButton | undefined { + return buttons.find( + ({ rect }) => point.x >= rect.x && point.x < rect.x + rect.width && point.y >= rect.y && @@ -658,11 +667,14 @@ function readNodeTextParts(node: { * already read the ANR window's focus, and the dialog's text is in the device language, so only the * framework id identifies a button: an app cannot declare an id in the `android` package. */ -function findAppErrorDialogButtons(nodes: SnapshotNode[]): Rect[] { +function findAppErrorDialogButtons(nodes: SnapshotNode[]): AndroidAppErrorDialogButton[] { return nodes .filter(isTouchableDialogNode) - .filter((node) => ANDROID_APP_ERROR_DIALOG_BUTTON_ID.test(node.identifier ?? '')) - .flatMap((node) => (node.rect ? [node.rect] : [])); + .flatMap(({ identifier, rect }) => + identifier && rect && ANDROID_APP_ERROR_DIALOG_BUTTON_ID.test(identifier) + ? [{ identifier, rect }] + : [], + ); } function containsBlockingDialog(nodes: SnapshotNode[]): boolean { diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index ff004fef61..3b4ae4ef60 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -562,6 +562,20 @@ test('a ref from a snapshot taken before the ANR dialog is not retargeted to the expect(mockTapPoint).not.toHaveBeenCalled(); }); +test('a Wait ref is not retargeted to Close app when the dialog buttons moved since the snapshot', async () => { + // The stored snapshot shows Wait where the current dialog shows Close app. + const [title, closeApp, wait] = systemUiAnrScreen(); + const storedScreen = attachRefs([ + { ...title! }, + { ...wait!, rect: closeApp!.rect! }, + { ...closeApp!, rect: wait!.rect! }, + ]); + const response = await pressWithSystemUiAnr(['@e2'], {}, { sessionNodes: storedScreen }); + + expect(response).toMatchObject({ ok: false, error: { details: { dispatched: 'no' } } }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); + test('a press on a System UI ANR dialog button is refused when the dialog loses focus before the send', async () => { // Readiness reads the dialog; by the read just before the send, Android has removed it, so the // button points now belong to the screen underneath. From 09fa660b6116b05e64aeb3f0187f1a3786419291 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:57:21 +0900 Subject: [PATCH 13/33] fix(android): keep the recovery hint when no dialog button can be pressed Every foreign-dialog refusal told the agent to press Close app or Wait. When the guard found no button to admit, every such press is refused the same way: before Android 7.0 the dialog's buttons carry no aerr_ ids (the snapshot helper supports API 23), and a failed snapshot read admits no button. The agent then looped on the same refusal. These two refusals now keep the earlier recovery hint: wait, close the dialog, restart the app, or reboot the emulator. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-readiness.test.ts | 7 +++++-- .../src/execution/android-system-dialog.ts | 19 +++++++++++++------ 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index cf1820ee8d..70fa87f42d 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -345,7 +345,8 @@ test('a tap stays refused when the foreign dialog shows no framework buttons', a ).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: expect.stringContaining('Android system dialog is blocking press'), - details: { dispatched: 'no' }, + // No press can close it, so the hint does not send the agent back to one. + details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, }); }); @@ -361,7 +362,9 @@ test('a tap stays refused when the foreign dialog cannot be read, and the read f const unread = await withDiagnosticsScope({}, async () => { await expect( ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), - ).rejects.toMatchObject({ details: { dispatched: 'no' } }); + ).rejects.toMatchObject({ + details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, + }); return countDiagnosticEventsByPhase(['android_blocking_dialog_buttons_unread']); }); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index dd748c5324..dfa18469eb 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -256,11 +256,13 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { error: error instanceof Error ? error.message : String(error), }, }); - throw readiness.refusal(); + throw readiness.refusal(ANDROID_BLOCKING_DIALOG_HINT); } - if (buttons.length === 0) throw readiness.refusal(); + // Before Android 7.0, the dialog's buttons carry no `aerr_` ids, so no press can close it. + if (buttons.length === 0) throw readiness.refusal(ANDROID_BLOCKING_DIALOG_HINT); const { session, command } = params; - const { focus, refusal } = readiness; + const { focus } = readiness; + const refusal = () => readiness.refusal(); return { status: 'dialog-buttons', admission: { @@ -359,7 +361,12 @@ export async function waitForAndroidBlockingDialogFocusToClear( type AndroidBlockingSystemDialogReadiness = | AndroidBlockingDialogReadinessResult - | { status: 'foreign-dialog'; focus: AndroidBlockingDialogFocus; refusal: () => AppError }; + | { + status: 'foreign-dialog'; + focus: AndroidBlockingDialogFocus; + /** `hint` defaults to the dialog's own buttons; pass another when they cannot be pressed. */ + refusal: (hint?: string) => AppError; + }; async function readAndroidBlockingSystemDialogReadiness(params: { session: SessionState; @@ -422,13 +429,13 @@ async function readAndroidBlockingSystemDialogReadiness(params: { return { status: 'foreign-dialog', focus, - refusal: () => { + refusal: (hint = ANDROID_FOREIGN_DIALOG_HINT) => { const error = androidBlockingDialogError({ session, command, focus, message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, - hint: ANDROID_FOREIGN_DIALOG_HINT, + hint, }); // ADR 0039: before the command, the refusal sends nothing. After it, the command's own // dispatch ledger discloses what was sent. From f399a1d46a0eb6fa8bca7ad40697f9a46a31928c Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:57:42 +0900 Subject: [PATCH 14/33] test(android): stop the dialog-button readiness tests from waiting real time The test for the wait after a dialog-button tap slept through two real 500 ms focus polls. The repository keeps unit tests off real time, so the file now mocks the poll's sleep, as the replay-divergence tests do. Co-Authored-By: Claude Opus 5.5 --- .../internal/interaction-touch-android-readiness.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 3b4ae4ef60..e45bfd4e34 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -47,6 +47,12 @@ vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => { // The blocking-dialog readiness check runs for real (its focus probe is mocked // above); the recovery regression below swaps in a recovering implementation. +// The guard polls the dialog focus between reads; these tests do not wait real time for it. +vi.mock('@agent-device/host-kit/retry', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, sleep: vi.fn(async () => {}) }; +}); + vi.mock('../../android-system-dialog.ts', async (importOriginal) => { const actual = await importOriginal(); androidDialogReadiness.actual = actual.ensureAndroidBlockingSystemDialogReady; From 5914ddc5a035974240a0efdfe1bf03869d1bc2a6 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 10:58:31 +0900 Subject: [PATCH 15/33] docs(android): document the press exception for a foreign ANR dialog A single click or press can now close another app's "isn't responding" dialog, while every other input stays refused. Neither the press and click help nor the command reference said so. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/interaction/metadata.ts | 4 ++-- website/docs/docs/commands.md | 2 ++ 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index a009c86b65..90a6892154 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -62,9 +62,9 @@ const FIND_ACTION_VALUES = [ const interactionCommandDescriptions = { click: - "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix.", + "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix. On Android, while another app's isn't-responding dialog has focus, the only input admitted is one plain tap on one of that dialog's own buttons (Close app or Wait); every other input is refused with dispatched: no.", press: - "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press.", + "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press. On Android, while another app's isn't-responding dialog has focus, the only input admitted is one plain tap on one of that dialog's own buttons (Close app or Wait); every other input is refused with dispatched: no.", fill: 'Replace text in a UI input selected by snapshot ref, selector, or coordinates. An empty text clears the field. Unconfirmed evidence does not establish the resulting value or screen. The recordAs option keeps sensitive text out of a recorded replay while sending it to the live app. To append instead of replacing, use type.', longpress: 'Hold a UI target by snapshot ref, selector, or coordinates to open a context menu or perform another hold gesture. The durationMs input overrides the default hold duration.', diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 75313e2803..02026a673b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1089,6 +1089,8 @@ agent-device diff screenshot --baseline before.png --out diff.png --json On iOS, a press on a control nested inside a larger touch control, such as a swipe action beside its row, refuses with `target_not_hittable` when the platform reports the control as not hittable. Reveal the control, for example by swiping its row, and take a new `snapshot -i`. +On Android, while another app's "isn't responding" dialog has focus, every command refuses with `dispatched: no`, except a single `click` or `press` on one of the dialog's own buttons, such as **Close app** or **Wait**. Take a new `snapshot -i` and press the button's ref. The command then waits for the dialog to close. A repeated press, a double tap, a ref list, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. + A comma-separated ref plan, such as `press @e13,@e14`, presses 2 to 16 refs as one command. Run `snapshot -i` first and copy the refs exactly. A refusal after the first press reports `details.dispatchedSteps`; plan again from a new `snapshot -i`. While script recording is armed, a plan needs `--no-record`. See `agent-device help press`. If rotation stops repeated iOS presses, inspect the screen before you continue with the remaining presses. From 57dc3316ce227cef4e5a4048d830495ded5b0ad1 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 11:11:41 +0900 Subject: [PATCH 16/33] refactor(android): pass the dialog tap gate without a branch The conditional spread that handed admitTap to the interaction runtime raised dispatchRuntimeInteraction's cognitive complexity to 16, over the fallow limit of 15. The runtime already treats an undefined admitTap as absent, so pass the optional value directly. Co-Authored-By: Claude Opus 5.5 --- .../execution/interaction/internal/interaction-touch-runtime.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts index 063f5e6937..1d9ef87002 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts @@ -96,7 +96,7 @@ export async function dispatchRuntimeInteraction< touchExecutor: options.touchExecutor, settleObservationCapture: options.settleObservationCapture, consumedCapture, - ...(options.androidDialogTapGate ? { admitTap: options.androidDialogTapGate.admitTap } : {}), + admitTap: options.androidDialogTapGate?.admitTap, }); const actionStartedAt = Date.now(); try { From 20c4c998dfc2b0cc618c517b4da635b050b32bc2 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 11:17:50 +0900 Subject: [PATCH 17/33] fix(mcp): fit the ANR press note in the always-loaded tool budget The press note added for a foreign ANR dialog raised the always-loaded MCP tools to 23,180 bytes, over the 23,040-byte budget, and repeated a search keyword. Shorten it to one clause without words from the search hints. The refusal hint still tells the agent which buttons it may press. Co-Authored-By: Claude Opus 5.5 --- packages/command-surface/src/interaction/metadata.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index 90a6892154..aebf09dafd 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -62,9 +62,9 @@ const FIND_ACTION_VALUES = [ const interactionCommandDescriptions = { click: - "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix. On Android, while another app's isn't-responding dialog has focus, the only input admitted is one plain tap on one of that dialog's own buttons (Close app or Wait); every other input is refused with dispatched: no.", + "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix. On Android, a foreign ANR dialog admits one tap on Close app or Wait.", press: - "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press. On Android, while another app's isn't-responding dialog has focus, the only input admitted is one plain tap on one of that dialog's own buttons (Close app or Wait); every other input is refused with dispatched: no.", + "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press. On Android, a foreign ANR dialog admits one tap on Close app or Wait.", fill: 'Replace text in a UI input selected by snapshot ref, selector, or coordinates. An empty text clears the field. Unconfirmed evidence does not establish the resulting value or screen. The recordAs option keeps sensitive text out of a recorded replay while sending it to the live app. To append instead of replacing, use type.', longpress: 'Hold a UI target by snapshot ref, selector, or coordinates to open a context menu or perform another hold gesture. The durationMs input overrides the default hold duration.', From 808897e5ca096591bde21a539f8425ababc4487c Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 11:31:36 +0900 Subject: [PATCH 18/33] fix(android): send a refused dialog press to a new snapshot first A press the foreign-dialog guard refused, such as a stale Wait ref after a rotation or an app ref from before the dialog appeared, got the hint "Press one of the dialog's buttons", which the agent believes it just did. Start the hint with a new snapshot so the next press uses a current ref. Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/execution/android-system-dialog.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index dfa18469eb..89a094d489 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -36,7 +36,7 @@ const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = 'Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.'; const ANDROID_FOREIGN_DIALOG_HINT = - "Press one of the dialog's buttons (Close app or Wait), then retry. Every other input is refused while the dialog has focus."; + "Take a new snapshot -i, then press the ref of one of the dialog's buttons (Close app or Wait). Every other input is refused while the dialog has focus."; const ANDROID_BLOCKING_DIALOG_INSPECTION_WARNING = 'Android blocking-dialog readiness could not be inspected; the command continued.'; const ANDROID_BLOCKING_DIALOG_WARNING_TEXT_LIMIT = 240; From db76959cac6c9daf99d376f4d170b7ac1de5310d Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 11:31:36 +0900 Subject: [PATCH 19/33] docs(android): say which commands a foreign ANR dialog refuses The paragraph said every command refuses while the dialog has focus, but snapshot, screenshot, open, and close still run, and the same paragraph tells the reader to take a snapshot. Name the input commands instead. Co-Authored-By: Claude Opus 5.5 --- website/docs/docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 02026a673b..171331edab 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1089,7 +1089,7 @@ agent-device diff screenshot --baseline before.png --out diff.png --json On iOS, a press on a control nested inside a larger touch control, such as a swipe action beside its row, refuses with `target_not_hittable` when the platform reports the control as not hittable. Reveal the control, for example by swiping its row, and take a new `snapshot -i`. -On Android, while another app's "isn't responding" dialog has focus, every command refuses with `dispatched: no`, except a single `click` or `press` on one of the dialog's own buttons, such as **Close app** or **Wait**. Take a new `snapshot -i` and press the button's ref. The command then waits for the dialog to close. A repeated press, a double tap, a ref list, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. +On Android, while another app's "isn't responding" dialog has focus, every input command, such as `fill`, `swipe`, or `back`, refuses with `dispatched: no`, except a single `click` or `press` on one of the dialog's own buttons, such as **Close app** or **Wait**. Take a new `snapshot -i` and press the button's ref. The command then waits for the dialog to close. A repeated press, a double tap, a ref list, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. A comma-separated ref plan, such as `press @e13,@e14`, presses 2 to 16 refs as one command. Run `snapshot -i` first and copy the refs exactly. A refusal after the first press reports `details.dispatchedSteps`; plan again from a new `snapshot -i`. While script recording is armed, a plan needs `--no-record`. See `agent-device help press`. From 45b7fa1b057b517d3f97c9701f36b700eb302601 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:08 +0900 Subject: [PATCH 20/33] refactor(android): check a foreign ANR dialog press once, before dispatch The dialog-button exception checked the tap point inside the backend, through an admitTap seam on InteractionRuntimeInput, compared the point in two trees, and counted taps. Review asked for a smaller shape. The check now runs once in readiness, before dispatch. It admits only the ANR dialog's Close app and Wait buttons (android:id/aerr_close and android:id/aerr_wait) in a fresh capture. A ref must name one of them, and the button with the same id must contain the ref node's center, so a ref read before the dialog appeared, or a Wait ref whose stored position now shows Close app, is refused. A raw point must be inside either button, and a selector is refused. The focus is then confirmed once more before the command runs. The admitTap seam, the dual-tree comparison, and the tap counter are gone: the press shape check already guarantees one tap. Co-Authored-By: Claude Opus 5.5 --- .../src/core/interaction/internal/types.ts | 13 +- .../android-system-dialog-readiness.test.ts | 117 +++++++---- .../src/execution/android-system-dialog.ts | 190 ++++++++---------- .../internal/interaction-runtime.ts | 17 +- ...nteraction-touch-android-readiness.test.ts | 4 +- .../interaction-touch-android-readiness.ts | 58 ++---- .../internal/interaction-touch-press.ts | 23 ++- .../internal/interaction-touch-runtime.ts | 15 +- 8 files changed, 215 insertions(+), 222 deletions(-) diff --git a/packages/daemon/src/core/interaction/internal/types.ts b/packages/daemon/src/core/interaction/internal/types.ts index da1c1ae28a..0976cbf806 100644 --- a/packages/daemon/src/core/interaction/internal/types.ts +++ b/packages/daemon/src/core/interaction/internal/types.ts @@ -5,12 +5,7 @@ import type { DaemonPlatformServices } from '../../platform-services.ts'; import type { CommandFlags } from '@agent-device/contracts/command'; import type { CreateDaemonCommandSurface } from '@agent-device/contracts/daemon-command-surface'; import type { AndroidObservationAdapter } from '@agent-device/contracts/android-observation'; -import type { - Point, - Rect, - SnapshotNode, - SnapshotPreferredBackend, -} from '@agent-device/kernel/snapshot'; +import type { Point, Rect, SnapshotPreferredBackend } from '@agent-device/kernel/snapshot'; import type { SnapshotState } from '@agent-device/contracts/snapshot-model'; import type { RequestCaptureProof } from '../../capture-disclosure.ts'; import type { DeviceInfo } from '@agent-device/kernel/device'; @@ -138,12 +133,6 @@ export type InteractionRuntimeInput = { ) => Promise; pairedGestureViewport?: Rect; touchExecutor?: BoundTouchExecutor; - /** - * Runs immediately before a tap is sent, before the ref frame expires: a throw refuses the tap - * with nothing dispatched. `undefined` is a native-ref tap, which has no point to check. - * `resolvedOn` is the tree that measured the point, absent for a raw coordinate. - */ - admitTap?: (point: Point | undefined, resolvedOn?: SnapshotNode[]) => Promise; gestures?: BoundGestureExecutor; /** * The capture every observation on this request reads the screen through: the action binding's diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 70fa87f42d..23ac67a821 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -255,6 +255,8 @@ test('a dump that answered nothing is reported as unobserved, not as a clear scr expect(unobserved).toBe(1); }); +const WAIT_RECT = { x: 100, y: 700, width: 220, height: 80 }; + /** System UI's ANR dialog as the framework draws it: a title and buttons with `aerr_` ids. */ function systemUiAnrDialogNodes(): RawSnapshotNode[] { return [ @@ -277,37 +279,40 @@ function systemUiAnrDialogNodes(): RawSnapshotNode[] { type: 'android.widget.Button', label: 'Wait', identifier: 'android:id/aerr_wait', - rect: { x: 100, y: 700, width: 220, height: 80 }, + rect: WAIT_RECT, }, ]; } -test("a tap may target a foreign ANR dialog's own buttons, and nothing is tapped for it", async () => { +/** A ref target naming a dialog button as the session snapshot stored it. */ +function refTo(identifier: string, rect = CLOSE_APP_RECT) { + return { kind: 'ref', node: { index: 0, ref: 'e2', identifier, rect } } as const; +} + +test("a tap on a foreign ANR dialog's Close app or Wait proceeds, and nothing is tapped for it", async () => { // The dialog refuses every other input, so its buttons are the only way to close it. const session = makeAndroidSession('readiness-system-tap'); screenNodes = systemUiAnrDialogNodes(); const { observation, calls } = makeObservation(systemDialogFocus); - const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - observation, - }); - - expect(readiness).toMatchObject({ - status: 'dialog-buttons', - admission: { - focus: systemDialogFocus(), - buttons: [ - { identifier: 'android:id/aerr_close', rect: CLOSE_APP_RECT }, - { identifier: 'android:id/aerr_wait', rect: { x: 100, y: 700, width: 220, height: 80 } }, - ], - }, - }); + for (const target of [ + refTo('android:id/aerr_close'), + refTo('android:id/aerr_wait', WAIT_RECT), + { kind: 'point', point: { x: 210, y: 740 } } as const, + ]) { + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target, + observation, + }), + ).resolves.toEqual({ status: 'dialog-button' }); + } expect(tapCalls(calls)).toEqual([]); }); -test("a tap may target a localized foreign ANR dialog's own buttons", async () => { +test("a tap on a localized foreign ANR dialog's Close app proceeds", async () => { // Android translates the dialog's title and labels; the framework ids stay the same. const session = makeAndroidSession('readiness-system-tap-localized'); const [title, closeApp, wait] = systemUiAnrDialogNodes(); @@ -318,30 +323,61 @@ test("a tap may target a localized foreign ANR dialog's own buttons", async () = ]; const { observation } = makeObservation(systemDialogFocus); - const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - observation, - }); + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target: refTo('android:id/aerr_close'), + observation, + }), + ).resolves.toEqual({ status: 'dialog-button' }); +}); + +test.each([ + ['a selector', { kind: 'selector' } as const], + ['a ref to a node the session snapshot does not hold', { kind: 'ref', node: undefined } as const], + ['a ref to an app control', refTo('com.example.app:id/submit')], + ["a ref to the dialog's Send feedback", refTo('android:id/aerr_report')], + ['a Wait ref whose stored position now shows Close app', refTo('android:id/aerr_wait')], + ['a point outside the buttons', { kind: 'point', point: { x: 540, y: 1500 } } as const], +])('a tap on a foreign ANR dialog stays refused for %s', async (_case, target) => { + const session = makeAndroidSession('readiness-system-tap-refused'); + screenNodes = systemUiAnrDialogNodes(); + const { observation, calls } = makeObservation(systemDialogFocus); - expect(readiness).toMatchObject({ - status: 'dialog-buttons', - admission: { - buttons: [ - { identifier: 'android:id/aerr_close', rect: CLOSE_APP_RECT }, - { identifier: 'android:id/aerr_wait', rect: { x: 100, y: 700, width: 220, height: 80 } }, - ], + await expect( + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target, + observation, + }), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: expect.stringContaining('Android system dialog is blocking press'), + details: { + dispatched: 'no', + focusedPackage: 'com.android.systemui', + focusedWindow: 'Application Not Responding: com.android.systemui', + hint: expect.stringContaining('Close app or Wait'), }, }); + expect(tapCalls(calls)).toEqual([]); }); test('a tap stays refused when the foreign dialog shows no framework buttons', async () => { // An app control labelled "Close app" is not the dialog's button: only the framework id counts. const session = makeAndroidSession('readiness-system-tap-no-ids'); + screenNodes = systemUiAnrDialogNodes().map(({ identifier: _id, ...node }) => node); const { observation } = makeObservation(systemDialogFocus); await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target: { kind: 'point', point: { x: 210, y: 640 } }, + observation, + }), ).rejects.toMatchObject({ code: 'COMMAND_FAILED', message: expect.stringContaining('Android system dialog is blocking press'), @@ -361,7 +397,12 @@ test('a tap stays refused when the foreign dialog cannot be read, and the read f const unread = await withDiagnosticsScope({}, async () => { await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target: refTo('android:id/aerr_close'), + observation, + }), ).rejects.toMatchObject({ details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, }); @@ -386,8 +427,13 @@ test('a tap stays refused when a surface covers the foreign dialog', async () => const { observation } = makeObservation(systemDialogFocus); await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', observation }), - ).rejects.toMatchObject({ code: 'COMMAND_FAILED' }); + ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command: 'press', + target: refTo('android:id/aerr_close'), + observation, + }), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { dispatched: 'no' } }); }); test('the session app ANR is still recovered before a tap, not admitted', async () => { @@ -397,6 +443,7 @@ test('the session app ANR is still recovered before a tap, not admitted', async const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ session, command: 'press', + target: refTo('android:id/aerr_close'), observation, }); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 89a094d489..18a8c4018d 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -10,12 +10,7 @@ import { normalizeError, type NormalizedError, } from '@agent-device/kernel/errors'; -import { - centerOfRect, - type Point, - type Rect, - type SnapshotNode, -} from '@agent-device/kernel/snapshot'; +import { centerOfRect, type Point, type SnapshotNode } from '@agent-device/kernel/snapshot'; import { isSnapshotNodeInteractionBlocked } from '@agent-device/capture-kit/snapshot-occlusion'; import { expireRefFrame } from '../core/ref-frame.ts'; @@ -26,11 +21,13 @@ import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; const ANDROID_BLOCKING_MODAL_PATTERN = /\bis(?:n(?:'|'|')?t| not)\s+responding\b/i; const ANDROID_CLOSE_APP_PATTERN = /^close app$/i; /** - * The framework's app-error dialog buttons (`AppNotRespondingDialog`, `AppErrorDialog`): Close app, - * Wait, Send feedback, Open app again, App info. The resource id does not depend on the device - * language. + * The ANR dialog's (`AppNotRespondingDialog`) Close app and Wait buttons. The resource id does not + * depend on the device language, and an app cannot declare an id in the `android` package. */ -const ANDROID_APP_ERROR_DIALOG_BUTTON_ID = /^android:id\/aerr_[a-z_]+$/; +const ANDROID_ANR_DIALOG_BUTTON_IDS: ReadonlySet = new Set([ + 'android:id/aerr_close', + 'android:id/aerr_wait', +]); const ANDROID_MODAL_POLL_MS = 500; const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = @@ -55,28 +52,17 @@ export type AndroidBlockingDialogReadinessResult = | { status: 'recovered'; warning: string }; /** - * A foreign blocking dialog that a single tap may still close: the dialog's own buttons as the - * presentation published them, and the refusal for a tap anywhere else. A dialog button is the one - * input that can clear the dialog, so the guard must not refuse it. + * What a single press or click aims at, read before dispatch: the node a ref names in the session + * snapshot, a raw point, or a selector. */ -export type AndroidBlockingDialogButtonAdmission = Readonly<{ - focus: AndroidBlockingDialogFocus; - buttons: readonly AndroidAppErrorDialogButton[]; - refusal: () => AppError; - /** - * Reads the focus again immediately before the tap is sent. Throws, with nothing sent, when the - * dialog no longer has focus: the buttons were read from an earlier frame, so a tap at their - * points could reach what the dialog uncovered. - */ - confirmFocus: () => Promise; -}>; - -/** One framework app-error dialog button: its resource id (the action it takes) and its frame. */ -export type AndroidAppErrorDialogButton = Readonly<{ identifier: string; rect: Rect }>; +export type AndroidDialogTapTarget = + | { kind: 'ref'; node: SnapshotNode | undefined } + | { kind: 'point'; point: Point } + | { kind: 'selector' }; export type AndroidBlockingDialogTapReadinessResult = | AndroidBlockingDialogReadinessResult - | { status: 'dialog-buttons'; admission: AndroidBlockingDialogButtonAdmission }; + | { status: 'dialog-button' }; type AndroidDialogButtonTapResult = | { ok: true; x: number; y: number } | { @@ -224,14 +210,15 @@ export async function ensureAndroidBlockingSystemDialogReady(params: { } /** - * The before-command check of a single tap. A foreign app-error dialog ("System UI isn't - * responding") refuses every other input, so its own buttons are the only way to close it from a - * command. The tap proceeds with `dialog-buttons` when the dialog shows touchable buttons; the - * caller must refuse, before any send, a tap point outside them. + * The before-command check of a single press or click. A foreign ANR dialog ("System UI isn't + * responding") refuses every other input, so its Close app and Wait buttons are the only way to + * close it from a command. The tap proceeds with `dialog-button` only when it aims at one of them + * in a fresh capture and the dialog still has focus; otherwise it is refused with nothing sent. */ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { session: SessionState; command: string; + target: AndroidDialogTapTarget; observation?: AndroidObservationAdapter; }): Promise { const readiness = await readAndroidBlockingSystemDialogReadiness({ @@ -239,20 +226,19 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { phase: 'before-command', }); if (readiness.status !== 'foreign-dialog') return readiness; + const { session, command } = params; const observation = requireObservation(params.observation); - let buttons: AndroidAppErrorDialogButton[]; + let buttons: SnapshotNode[]; try { - buttons = findAppErrorDialogButtons( - await readAndroidSnapshotNodes(params.session, observation), - ); + buttons = findAnrDialogButtons(await readAndroidSnapshotNodes(session, observation)); } catch (error) { emitDiagnostic({ level: 'warn', phase: 'android_blocking_dialog_buttons_unread', data: { - session: params.session.name, - deviceId: params.session.device.id, - command: params.command, + session: session.name, + deviceId: session.device.id, + command, error: error instanceof Error ? error.message : String(error), }, }); @@ -260,81 +246,71 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { } // Before Android 7.0, the dialog's buttons carry no `aerr_` ids, so no press can close it. if (buttons.length === 0) throw readiness.refusal(ANDROID_BLOCKING_DIALOG_HINT); - const { session, command } = params; - const { focus } = readiness; - const refusal = () => readiness.refusal(); - return { - status: 'dialog-buttons', - admission: { - focus, - buttons, - refusal, - confirmFocus: async () => { - const current = await observation - .readBlockingDialog(session.device) - .catch((error: unknown) => { - throw thrownBeforeDispatch(error); - }); - if (current.status === 'dialog') { - if (!isSameAndroidBlockingDialogFocus(current.focus, focus)) throw refusal(); - return; - } - const dialog = formatAndroidBlockingDialogFocus(focus); - throw discloseDispatch( - androidBlockingDialogError({ - session, - command, - focus, - message: - current.status === 'unknown' - ? `Android focus could not be read to confirm that the system dialog still has focus before ${command} was sent: ${dialog}.` - : `Android system dialog lost focus before ${command} was sent: ${dialog}.`, - hint: 'Nothing was sent. Take a new snapshot, then retry the command.', - }), - 'no', - ); - }, - }, - }; + if (!aimsAtAnrDialogButton(buttons, params.target)) throw readiness.refusal(); + await confirmAndroidBlockingDialogFocus(session, command, readiness.focus, observation); + return { status: 'dialog-button' }; } -function isSameAndroidBlockingDialogFocus( - a: AndroidBlockingDialogFocus, - b: AndroidBlockingDialogFocus, -): boolean { - return a.package === b.package && a.focusedWindow === b.focusedWindow; +/** + * A ref must name a Close app or Wait node, and the button with the same id in the fresh capture + * must contain that node's center: so a ref read before the dialog appeared, or a Wait ref whose + * stored position now shows Close app, is refused. A raw point must be inside either button. + */ +function aimsAtAnrDialogButton(buttons: SnapshotNode[], target: AndroidDialogTapTarget): boolean { + if (target.kind === 'point') return findButtonAtPoint(buttons, target.point) !== undefined; + if (target.kind !== 'ref' || !target.node?.rect) return false; + const button = findButtonAtPoint(buttons, centerOfRect(target.node.rect)); + return button !== undefined && button.identifier === target.node.identifier; } /** - * True when the tap point falls on one of the dialog's own buttons. `resolvedOn` is the tree the - * target was resolved on, when it was resolved on one: the same button must be at the point there - * too. So an app control from a tree read before the dialog appeared is not retargeted to the - * dialog button that now covers it, and a Wait target is not retargeted to Close app. + * Reads the focus again just before the tap is sent. The buttons came from a capture, so if the + * dialog lost focus since then, a tap at their points could reach what the dialog uncovered. */ -export function isAndroidBlockingDialogButtonPoint( - admission: AndroidBlockingDialogButtonAdmission, - point: Point, - resolvedOn?: SnapshotNode[], -): boolean { - const button = findButtonAtPoint(admission.buttons, point); - if (!button) return false; - if (resolvedOn === undefined) return true; - return ( - findButtonAtPoint(findAppErrorDialogButtons(resolvedOn), point)?.identifier === - button.identifier +async function confirmAndroidBlockingDialogFocus( + session: SessionState, + command: string, + focus: AndroidBlockingDialogFocus, + observation: AndroidObservationAdapter, +): Promise { + const current = await observation.readBlockingDialog(session.device).catch((error: unknown) => { + throw thrownBeforeDispatch(error); + }); + if (current.status === 'dialog' && isSameAndroidBlockingDialogFocus(current.focus, focus)) return; + const dialog = formatAndroidBlockingDialogFocus(focus); + const message = + current.status === 'dialog' + ? `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(current.focus)}.` + : current.status === 'unknown' + ? `Android focus could not be read to confirm that the system dialog still has focus before ${command} was sent: ${dialog}.` + : `Android system dialog lost focus before ${command} was sent: ${dialog}.`; + throw discloseDispatch( + androidBlockingDialogError({ + session, + command, + focus: current.status === 'dialog' ? current.focus : focus, + message, + hint: 'Nothing was sent. Take a new snapshot, then retry the command.', + }), + 'no', ); } +function isSameAndroidBlockingDialogFocus( + a: AndroidBlockingDialogFocus, + b: AndroidBlockingDialogFocus, +): boolean { + return a.package === b.package && a.focusedWindow === b.focusedWindow; +} + /** * Android's view hit test excludes the right and bottom edges, so a point on them reaches the * dialog around the button, not the button. */ -function findButtonAtPoint( - buttons: readonly AndroidAppErrorDialogButton[], - point: Point, -): AndroidAppErrorDialogButton | undefined { +function findButtonAtPoint(buttons: SnapshotNode[], point: Point): SnapshotNode | undefined { return buttons.find( ({ rect }) => + rect !== undefined && point.x >= rect.x && point.x < rect.x + rect.width && point.y >= rect.y && @@ -670,17 +646,17 @@ function readNodeTextParts(node: { } /** - * The touchable buttons of a framework app-error dialog, read by resource id. The caller has - * already read the ANR window's focus, and the dialog's text is in the device language, so only the - * framework id identifies a button: an app cannot declare an id in the `android` package. + * The ANR dialog's touchable Close app and Wait buttons, read by resource id: the dialog's text is in + * the device language. */ -function findAppErrorDialogButtons(nodes: SnapshotNode[]): AndroidAppErrorDialogButton[] { +function findAnrDialogButtons(nodes: SnapshotNode[]): SnapshotNode[] { return nodes .filter(isTouchableDialogNode) - .flatMap(({ identifier, rect }) => - identifier && rect && ANDROID_APP_ERROR_DIALOG_BUTTON_ID.test(identifier) - ? [{ identifier, rect }] - : [], + .filter( + (node) => + node.rect !== undefined && + node.identifier !== undefined && + ANDROID_ANR_DIALOG_BUTTON_IDS.has(node.identifier), ); } diff --git a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts index 8967c00877..17fd0030fa 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-runtime.ts @@ -44,8 +44,6 @@ export async function createInteractionRuntimeForRoute( pairedGestureViewport?: Rect; touchExecutor?: BoundTouchExecutor; gestures?: BoundGestureExecutor; - /** See `InteractionRuntimeInput.admitTap`. */ - admitTap?: InteractionRuntimeInput['admitTap']; /** * Filled with the LAST capture this request consumed. ADR 0014 ambiguity * issuance is only valid against a tree the session stored under the @@ -108,7 +106,6 @@ export async function createInteractionRuntimeForRoute( probeTargetHittability: readTargetHittabilityProbe(params, session), pairedGestureViewport: params.pairedGestureViewport, touchExecutor: params.touchExecutor, - ...(params.admitTap ? { admitTap: params.admitTap } : {}), gestures: params.gestures, boundCapture: resolveBoundCapture(params), }); @@ -253,7 +250,6 @@ function createInteractionBackend(params: InteractionRuntimeInput): AgentDeviceB ...touchBackendMembers( params.touchExecutor, params.expireRefFrame, - params.admitTap, flags, params.coordinateTapTextInputEvidence, ), @@ -284,7 +280,6 @@ function gestureBackendMembers( function touchBackendMembers( executor: InteractionRuntimeInput['touchExecutor'], expireRefFrame: () => void, - admitTap: InteractionRuntimeInput['admitTap'], flags: InteractionRuntimeInput['flags'], textInputEvidence: InteractionRuntimeInput['coordinateTapTextInputEvidence'], ): Partial { @@ -296,10 +291,9 @@ function touchBackendMembers( }; return { tap: tapPoint - ? async (_context, point, options) => { - await admitTap?.(point, options?.pointObservation?.nodes); + ? (_context, point, options) => { const evidence = textInputEvidence?.(point, options?.pointObservation); - return await run(() => + return run(() => tapPoint(point, { ...flags, ...(evidence ? { coordinateTapTextInputEvidence: evidence } : {}), @@ -307,12 +301,7 @@ function touchBackendMembers( ); } : undefined, - tapTarget: tapRef - ? async (_context, target) => { - await admitTap?.(undefined); - return await run(() => tapRef(target.ref)); - } - : undefined, + tapTarget: tapRef ? (_context, target) => run(() => tapRef(target.ref)) : undefined, fill: fillPoint ? (_context, point, text, options) => run(() => fillPoint(point, text, options)) : undefined, diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index e45bfd4e34..cd87cb5807 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -531,8 +531,10 @@ test.each([ ['a repeated press', ['@e2'], { count: 2 }], ['a double tap', ['@e2'], { doubleTap: true }], ['a multi-ref plan', ['@e2,@e3'], {}], + ['a selector', ['id="android:id/aerr_close"'], {}], ])('%s on the System UI ANR dialog stays refused', async (_shape, positionals, flags) => { - // Its later taps would land on whatever the closed dialog uncovers. + // Later taps would land on whatever the closed dialog uncovers, and only a ref or a point is + // checked against the dialog. const response = await pressWithSystemUiAnr(positionals, flags); expect(response).toMatchObject({ diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index e5ed6e74fa..b796d1b7ec 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -1,12 +1,10 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; -import type { Point, SnapshotNode } from '@agent-device/kernel/snapshot'; import { ensureAndroidBlockingSystemDialogReady, ensureAndroidBlockingSystemDialogReadyForTap, - isAndroidBlockingDialogButtonPoint, waitForAndroidBlockingDialogFocusToClear, - type AndroidBlockingDialogButtonAdmission, type AndroidBlockingDialogTapReadinessResult, + type AndroidDialogTapTarget, } from '../../android-system-dialog.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { readRefMutationFrame } from '../../../core/ref-frame.ts'; @@ -33,43 +31,17 @@ export type ReadinessOutcome = runtimeResult: TResult; }; -/** - * The per-request gate of a single tap while a foreign app-error dialog has focus. Readiness opens - * it with the dialog's buttons; the backend calls `admitTap` immediately before it sends the tap - * (and before the ref frame expires). Only one tap, on one of the dialog's buttons, passes, and only - * while the dialog still has focus. Any other tap is refused with `dispatched: no`. - */ -export type AndroidDialogTapGate = Readonly<{ - open(admission: AndroidBlockingDialogButtonAdmission): void; - admitTap(point: Point | undefined, resolvedOn?: SnapshotNode[]): Promise; -}>; - -export function createAndroidDialogTapGate(): AndroidDialogTapGate { - let admission: AndroidBlockingDialogButtonAdmission | undefined; - let admittedTaps = 0; - return { - open: (next) => { - admission = next; - }, - admitTap: async (point, resolvedOn) => { - if (!admission) return; - if ( - admittedTaps > 0 || - !point || - !isAndroidBlockingDialogButtonPoint(admission, point, resolvedOn) - ) { - throw admission.refusal(); - } - await admission.confirmFocus(); - admittedTaps += 1; - }, - }; -} - export async function runWithAndroidDialogReadinessCheck( session: SessionState, command: string, - options: { refContext: RefAdmissionContext | undefined; dialogTapGate?: AndroidDialogTapGate }, + options: { + refContext: RefAdmissionContext | undefined; + /** + * Present on a single plain press or click: while a foreign ANR dialog has focus, the tap may + * still go to the dialog's Close app or Wait button. + */ + dialogTapTarget?: AndroidDialogTapTarget; + }, run: (readiness: AndroidBlockingDialogTapReadinessResult) => Promise, observation?: AndroidObservationAdapter, ): Promise> { @@ -77,8 +49,13 @@ export async function runWithAndroidDialogReadinessCheck( const readiness = { status: 'clear' } as const; return { aborted: false, readiness, runtimeResult: await run(readiness) }; } - const readiness: AndroidBlockingDialogTapReadinessResult = options.dialogTapGate - ? await ensureAndroidBlockingSystemDialogReadyForTap({ session, command, observation }) + const readiness: AndroidBlockingDialogTapReadinessResult = options.dialogTapTarget + ? await ensureAndroidBlockingSystemDialogReadyForTap({ + session, + command, + target: options.dialogTapTarget, + observation, + }) : await ensureAndroidBlockingSystemDialogReady({ session, command, @@ -105,9 +82,8 @@ export async function runWithAndroidDialogReadinessCheck( }); if (abort) return { aborted: true, response: abort }; } - if (readiness.status === 'dialog-buttons') options.dialogTapGate?.open(readiness.admission); const runtimeResult = await run(readiness); - if (readiness.status === 'dialog-buttons') { + if (readiness.status === 'dialog-button') { await waitForAndroidBlockingDialogFocusToClear(session, observation); } await ensureAndroidBlockingSystemDialogReady({ diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index 0969bf2937..dc7d22431f 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -25,10 +25,11 @@ import { type TargetedTouchResult, } from './interaction-touch-response.ts'; import { dispatchRuntimeInteraction } from './interaction-touch-runtime.ts'; -import { createAndroidDialogTapGate } from './interaction-touch-android-readiness.ts'; import { formatTouchTargetLabel } from './interaction-touch-targets.ts'; import { refreshAndroidRefSnapshotIfFreshnessActive } from './interaction-touch-android-freshness.ts'; import { prepareTouchDispatch } from './interaction-touch-prepare.ts'; +import { findNodeByRef, normalizeRef } from '@agent-device/kernel/snapshot'; +import type { AndroidDialogTapTarget } from '../../android-system-dialog.ts'; /** * How an admitted targeted `press`/`click`/`longpress`/`hover` executes: the direct-iOS @@ -109,7 +110,7 @@ function buildTargetedRuntimeOptions( androidFreshnessBaseline: admitted.androidFreshnessBaseline, refContext: admitted.refContext, ...(admitsAndroidDialogButtonTap(session, command, admitted.refs, req.flags) - ? { androidDialogTapGate: createAndroidDialogTapGate() } + ? { androidDialogTapTarget: readAndroidDialogTapTarget(session, target) } : {}), iosTapCorroboration: { target, extra: targetedExtra }, run: async (runtime) => @@ -130,7 +131,7 @@ function buildTargetedRuntimeOptions( if (session.lease?.leaseProvider) return undefined; // The dialog, not the session app, owned the focus before this tap, so the tap cannot have // escaped the app. - if (readiness.status === 'dialog-buttons') return undefined; + if (readiness.status === 'dialog-button') return undefined; return await assertAndroidPressStayedInApp( session, { @@ -167,8 +168,8 @@ function buildTargetedRuntimeOptions( } /** - * Only one plain tap may close a foreign Android app-error dialog: a repeated tap, a double tap, - * or a multi-ref plan would send its later taps to whatever the closed dialog uncovers. + * Only one plain tap may close a foreign Android ANR dialog: a repeated tap, a double tap, or a + * multi-ref plan would send its later taps to whatever the closed dialog uncovers. */ function admitsAndroidDialogButtonTap( session: AdmittedTargetedTouch['session'], @@ -182,6 +183,18 @@ function admitsAndroidDialogButtonTap( return (flags?.count ?? 1) <= 1 && flags?.doubleTap !== true; } +/** The ref's node in the session snapshot, or the raw point; a selector is never admitted. */ +function readAndroidDialogTapTarget( + session: AdmittedTargetedTouch['session'], + target: AdmittedTargetedTouch['target'], +): AndroidDialogTapTarget { + if (target.kind === 'point') return { kind: 'point', point: { x: target.x, y: target.y } }; + if (target.kind === 'selector') return { kind: 'selector' }; + const ref = normalizeRef(target.ref); + const node = ref && session.snapshot ? findNodeByRef(session.snapshot.nodes, ref) : null; + return { kind: 'ref', node: node ?? undefined }; +} + async function runTargetedTouchInteraction(params: { runtime: Awaited>; command: TargetedTouchCommand; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts index 1d9ef87002..ae59ce20bc 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts @@ -26,10 +26,12 @@ import { isAndroidEscapeError } from './interaction-android-escape.ts'; import { corroborateIosTapFailure, interactionTargetExtra } from './interaction-ios-tap-outcome.ts'; import { runWithAndroidDialogReadinessCheck, - type AndroidDialogTapGate, type RefAdmissionContext, } from './interaction-touch-android-readiness.ts'; -import type { AndroidBlockingDialogTapReadinessResult } from '../../android-system-dialog.ts'; +import type { + AndroidBlockingDialogTapReadinessResult, + AndroidDialogTapTarget, +} from '../../android-system-dialog.ts'; import { readSnapshotNodesReferenceFrame } from '@agent-device/capture-kit/touch-reference-frame'; import { buildCorroboratedTapResponseData, @@ -64,10 +66,10 @@ export async function dispatchRuntimeInteraction< */ refContext?: RefAdmissionContext; /** - * Present on a single press or click: while a foreign Android app-error dialog has focus, the - * tap may still go to one of the dialog's own buttons, checked at the tap point before send. + * Present on a single plain press or click: while a foreign Android ANR dialog has focus, the + * tap may still go to the dialog's Close app or Wait button, checked before dispatch. */ - androidDialogTapGate?: AndroidDialogTapGate; + androidDialogTapTarget?: AndroidDialogTapTarget; /** A failed local iOS tap may be corroborated against one same-scope capture. */ iosTapCorroboration?: { target: InteractionRequestTarget; @@ -96,7 +98,6 @@ export async function dispatchRuntimeInteraction< touchExecutor: options.touchExecutor, settleObservationCapture: options.settleObservationCapture, consumedCapture, - admitTap: options.androidDialogTapGate?.admitTap, }); const actionStartedAt = Date.now(); try { @@ -104,7 +105,7 @@ export async function dispatchRuntimeInteraction< const outcome = await runWithAndroidDialogReadinessCheck( session, params.req.command, - { refContext: options.refContext, dialogTapGate: options.androidDialogTapGate }, + { refContext: options.refContext, dialogTapTarget: options.androidDialogTapTarget }, async (readiness) => { const result = await options.run(runtime); afterRunWarning = await options.afterRun?.(result, readiness); From 47385f28b0981aa9e9da8ff652156d6423b815fd Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:19 +0900 Subject: [PATCH 21/33] fix(android): refuse a held or jittered press on a foreign ANR dialog The dialog-button exception admitted a press with --hold-ms or --jitter-px. A hold is not the single tap the exception allows, and jitter can move the contact off the checked button. Admit only a press with neither. Co-Authored-By: Claude Opus 5.5 --- .../interaction-touch-android-readiness.test.ts | 6 ++++-- .../interaction/internal/interaction-touch-press.ts | 10 ++++++++-- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index cd87cb5807..d56dcb61dc 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -531,10 +531,12 @@ test.each([ ['a repeated press', ['@e2'], { count: 2 }], ['a double tap', ['@e2'], { doubleTap: true }], ['a multi-ref plan', ['@e2,@e3'], {}], + ['a hold', ['@e2'], { holdMs: 800 }], + ['a jittered press', ['@e2'], { jitterPx: 40 }], ['a selector', ['id="android:id/aerr_close"'], {}], ])('%s on the System UI ANR dialog stays refused', async (_shape, positionals, flags) => { - // Later taps would land on whatever the closed dialog uncovers, and only a ref or a point is - // checked against the dialog. + // Later taps would land on whatever the closed dialog uncovers, a hold is not a tap, jitter can + // move the contact off the button, and only a ref or a point is checked against the dialog. const response = await pressWithSystemUiAnr(positionals, flags); expect(response).toMatchObject({ diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index dc7d22431f..e54693b070 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -169,7 +169,8 @@ function buildTargetedRuntimeOptions( /** * Only one plain tap may close a foreign Android ANR dialog: a repeated tap, a double tap, or a - * multi-ref plan would send its later taps to whatever the closed dialog uncovers. + * multi-ref plan would send its later taps to whatever the closed dialog uncovers, a hold is not a + * tap, and jitter can move the contact off the checked button. */ function admitsAndroidDialogButtonTap( session: AdmittedTargetedTouch['session'], @@ -180,7 +181,12 @@ function admitsAndroidDialogButtonTap( if (session.device.platform !== 'android') return false; if (command !== 'press' && command !== 'click') return false; if (refs && refs.length > 1) return false; - return (flags?.count ?? 1) <= 1 && flags?.doubleTap !== true; + return ( + (flags?.count ?? 1) <= 1 && + flags?.doubleTap !== true && + (flags?.holdMs ?? 0) <= 0 && + (flags?.jitterPx ?? 0) <= 0 + ); } /** The ref's node in the session snapshot, or the raw point; a selector is never admitted. */ From 93bbc98bc5dee87796dcb9678d08aac8763c9f1b Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:29 +0900 Subject: [PATCH 22/33] fix(android): keep the post-press app check after a dialog button A press admitted on a foreign ANR dialog skipped the check that the session app is still in front. Closing the dialog can reveal the launcher or another app, and that check is what reports it. Run the check after a dialog-button press too. Co-Authored-By: Claude Opus 5.5 --- .../interaction-touch-android-readiness.test.ts | 15 +++++++++++++++ .../internal/interaction-touch-press.ts | 3 --- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index d56dcb61dc..24b3b75232 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -679,3 +679,18 @@ test('a press on a System UI ANR dialog button waits for the dialog focus to cle expect(response).toMatchObject({ ok: true }); expect(mockTapPoint).toHaveBeenCalledTimes(1); }); + +test('a press that closes the System UI ANR dialog still reports an app the dialog did not cover', async () => { + // The launcher, not the session app, was under the dialog: the press reports that the session + // app is not in front, as after any other press. + mockGetAndroidAppState.mockResolvedValue({ + package: 'com.google.android.apps.nexuslauncher', + activity: 'Launcher', + }); + + await expect(pressWithSystemUiAnr(['@e2'])).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + message: expect.stringContaining('left com.example.app'), + }); + expect(mockTapPoint).toHaveBeenCalledTimes(1); +}); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index e54693b070..4d7d174283 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -129,9 +129,6 @@ function buildTargetedRuntimeOptions( }), afterRun: async (result, readiness) => { if (session.lease?.leaseProvider) return undefined; - // The dialog, not the session app, owned the focus before this tap, so the tap cannot have - // escaped the app. - if (readiness.status === 'dialog-button') return undefined; return await assertAndroidPressStayedInApp( session, { From 7ac2567a79f285e11aba4ca06d6578422ddce98f Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:38 +0900 Subject: [PATCH 23/33] fix(android): keep the recovery hint for a non-press foreign-dialog refusal The refusal's default hint said to press a dialog button ref. Only a press or click can reach the buttons, so a swipe, fill, or generic command got advice it cannot follow. Keep the recovery steps as the default and pass the dialog-button hint only from the press path. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-readiness.test.ts | 17 +++++++++++++++++ .../src/execution/android-system-dialog.ts | 12 +++++++----- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 23ac67a821..8fbaa5a360 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -436,6 +436,23 @@ test('a tap stays refused when a surface covers the foreign dialog', async () => ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { dispatched: 'no' } }); }); +test('a non-press command refused by a foreign dialog gets the recovery hint', async () => { + // Only a press can reach the dialog's buttons, so other commands are not sent to them. + const session = makeAndroidSession('readiness-system-swipe'); + const { observation } = makeObservation(systemDialogFocus); + + await expect( + ensureAndroidBlockingSystemDialogReady({ + session, + command: 'swipe', + phase: 'before-command', + observation, + }), + ).rejects.toMatchObject({ + details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, + }); +}); + test('the session app ANR is still recovered before a tap, not admitted', async () => { const session = makeAndroidSession('readiness-anr-tap', { appBundleId: APP }); const { observation, calls } = makeObservation(anrFocus); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 18a8c4018d..674e363d5b 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -242,11 +242,13 @@ export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { error: error instanceof Error ? error.message : String(error), }, }); - throw readiness.refusal(ANDROID_BLOCKING_DIALOG_HINT); + throw readiness.refusal(); } // Before Android 7.0, the dialog's buttons carry no `aerr_` ids, so no press can close it. - if (buttons.length === 0) throw readiness.refusal(ANDROID_BLOCKING_DIALOG_HINT); - if (!aimsAtAnrDialogButton(buttons, params.target)) throw readiness.refusal(); + if (buttons.length === 0) throw readiness.refusal(); + if (!aimsAtAnrDialogButton(buttons, params.target)) { + throw readiness.refusal(ANDROID_FOREIGN_DIALOG_HINT); + } await confirmAndroidBlockingDialogFocus(session, command, readiness.focus, observation); return { status: 'dialog-button' }; } @@ -340,7 +342,7 @@ type AndroidBlockingSystemDialogReadiness = | { status: 'foreign-dialog'; focus: AndroidBlockingDialogFocus; - /** `hint` defaults to the dialog's own buttons; pass another when they cannot be pressed. */ + /** `hint` defaults to recovery steps; a press that may target the buttons passes its own. */ refusal: (hint?: string) => AppError; }; @@ -405,7 +407,7 @@ async function readAndroidBlockingSystemDialogReadiness(params: { return { status: 'foreign-dialog', focus, - refusal: (hint = ANDROID_FOREIGN_DIALOG_HINT) => { + refusal: (hint = ANDROID_BLOCKING_DIALOG_HINT) => { const error = androidBlockingDialogError({ session, command, From 75e0e346db338215b941d44b8795510f99706744 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:48 +0900 Subject: [PATCH 24/33] test(android): assert the dialog context in each foreign-dialog refusal The refusal cases checked only dispatched: no and that no tap was sent, so an unrelated refusal could make them pass. Assert the focused package and window as well. Co-Authored-By: Claude Opus 5.5 --- ...nteraction-touch-android-readiness.test.ts | 35 ++++++++++++++----- 1 file changed, 27 insertions(+), 8 deletions(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 24b3b75232..00d05e2ff9 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -393,6 +393,13 @@ const SYSTEM_UI_ANR = { }, } as const; +/** The typed context of a refusal by the System UI ANR dialog's guard. */ +const SYSTEM_UI_ANR_REFUSAL = { + dispatched: 'no', + focusedPackage: SYSTEM_UI_ANR.focus.package, + focusedWindow: SYSTEM_UI_ANR.focus.focusedWindow, +} as const; + function systemUiAnrScreen() { return attachRefs([ { @@ -508,7 +515,7 @@ test('a press at a point outside the System UI ANR dialog buttons is refused bef error: { code: 'COMMAND_FAILED', message: expect.stringContaining('Android system dialog is blocking press'), - details: { dispatched: 'no', focusedPackage: 'com.android.systemui' }, + details: SYSTEM_UI_ANR_REFUSAL, }, }); expect(mockTapPoint).not.toHaveBeenCalled(); @@ -522,7 +529,7 @@ test.each([ async (_edge, positionals) => { const response = await pressWithSystemUiAnr(positionals); - expect(response).toMatchObject({ ok: false, error: { details: { dispatched: 'no' } } }); + expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); expect(mockTapPoint).not.toHaveBeenCalled(); }, ); @@ -541,7 +548,7 @@ test.each([ expect(response).toMatchObject({ ok: false, - error: { details: { dispatched: 'no' } }, + error: { details: SYSTEM_UI_ANR_REFUSAL }, }); expect(mockTapPoint).not.toHaveBeenCalled(); }); @@ -566,7 +573,7 @@ test('a ref from a snapshot taken before the ANR dialog is not retargeted to the ok: false, error: { message: expect.stringContaining('Android system dialog is blocking press'), - details: { dispatched: 'no' }, + details: SYSTEM_UI_ANR_REFUSAL, }, }); expect(mockTapPoint).not.toHaveBeenCalled(); @@ -582,7 +589,7 @@ test('a Wait ref is not retargeted to Close app when the dialog buttons moved si ]); const response = await pressWithSystemUiAnr(['@e2'], {}, { sessionNodes: storedScreen }); - expect(response).toMatchObject({ ok: false, error: { details: { dispatched: 'no' } } }); + expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); expect(mockTapPoint).not.toHaveBeenCalled(); }); @@ -602,7 +609,7 @@ test('a press on a System UI ANR dialog button is refused when the dialog loses error: { code: 'COMMAND_FAILED', message: expect.stringContaining('Android system dialog lost focus before press was sent'), - details: { dispatched: 'no' }, + details: SYSTEM_UI_ANR_REFUSAL, }, }); expect(mockTapPoint).not.toHaveBeenCalled(); @@ -613,6 +620,7 @@ test.each([ 'the focus read answers nothing', { status: 'unknown' } as const, 'Android focus could not be read to confirm', + SYSTEM_UI_ANR.focus, ], [ 'another dialog has the focus', @@ -625,10 +633,14 @@ test.each([ }, } as const, 'Android system dialog is blocking press', + { + package: 'com.example.other', + focusedWindow: 'Application Not Responding: com.example.other', + }, ], ])( 'a press on a System UI ANR dialog button is refused when, before the send, %s', - async (_case, beforeSend, message) => { + async (_case, beforeSend, message, focus) => { const response = await pressWithSystemUiAnr( ['@e2'], {}, @@ -639,7 +651,14 @@ test.each([ expect(response).toMatchObject({ ok: false, - error: { message: expect.stringContaining(message), details: { dispatched: 'no' } }, + error: { + message: expect.stringContaining(message), + details: { + dispatched: 'no', + focusedPackage: focus.package, + focusedWindow: focus.focusedWindow, + }, + }, }); expect(mockTapPoint).not.toHaveBeenCalled(); }, From 3fa8025661bdf6e7460646d911f7f99a8b4448cd Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:00:49 +0900 Subject: [PATCH 25/33] docs(android): name the two buttons a foreign ANR dialog admits The press exception now admits only Close app and Wait, by ref or by coordinates, and refuses a hold, jitter, and a selector. Say so. Co-Authored-By: Claude Opus 5.5 --- website/docs/docs/commands.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 171331edab..641f125e6f 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1089,7 +1089,7 @@ agent-device diff screenshot --baseline before.png --out diff.png --json On iOS, a press on a control nested inside a larger touch control, such as a swipe action beside its row, refuses with `target_not_hittable` when the platform reports the control as not hittable. Reveal the control, for example by swiping its row, and take a new `snapshot -i`. -On Android, while another app's "isn't responding" dialog has focus, every input command, such as `fill`, `swipe`, or `back`, refuses with `dispatched: no`, except a single `click` or `press` on one of the dialog's own buttons, such as **Close app** or **Wait**. Take a new `snapshot -i` and press the button's ref. The command then waits for the dialog to close. A repeated press, a double tap, a ref list, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. +On Android, while another app's "isn't responding" dialog has focus, every input command, such as `fill`, `swipe`, or `back`, refuses with `dispatched: no`, except a single `click` or `press` on the dialog's **Close app** or **Wait** button. Take a new `snapshot -i` and press the button's ref, or its coordinates. The command then waits for the dialog to close. A repeated press, a double tap, a hold, jitter, a ref list, a selector, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. A comma-separated ref plan, such as `press @e13,@e14`, presses 2 to 16 refs as one command. Run `snapshot -i` first and copy the refs exactly. A refusal after the first press reports `details.dispatchedSteps`; plan again from a new `snapshot -i`. While script recording is armed, a plan needs `--no-record`. See `agent-device help press`. From 575cfca43e98dc85fbc5889ce234b216f9da483e Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:09:09 +0900 Subject: [PATCH 26/33] fix(android): check a dialog-button ref in the tree that issued it The foreign ANR dialog check looked the ref up in session.snapshot, but the runtime taps the ref's node in the authorized ref frame (ADR 0014), and a find match taps its own node. A read after the dialog appeared, such as a screenshot, replaces session.snapshot without a new frame. A ref issued on the app screen could then pass the check as Close app and tap the app's button, which nothing checked. Read the node the runtime will tap. Co-Authored-By: Claude Opus 5.5 --- ...nteraction-touch-android-readiness.test.ts | 34 ++++++++++++++++++- .../internal/interaction-touch-press.ts | 20 +++++++++-- 2 files changed, 50 insertions(+), 4 deletions(-) diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index 00d05e2ff9..a357e1d11a 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -2,7 +2,7 @@ import { test, expect, vi, beforeEach } from 'vitest'; import { attachRefs } from '@agent-device/kernel/snapshot'; import { AppError } from '@agent-device/kernel/errors'; import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; -import { expireRefFrame } from '../../../core/ref-frame.ts'; +import { activateCompleteRefFrame, expireRefFrame } from '../../../core/ref-frame.ts'; import { installInteractorSnapshotResolution, mockInteractorSnapshot, @@ -445,6 +445,8 @@ async function pressWithSystemUiAnr( command?: 'press' | 'click'; /** The session's stored snapshot, when it was taken before the dialog appeared. */ sessionNodes?: ReturnType; + /** The tree an earlier `snapshot` issued the refs from, when a later read replaced it. */ + frameNodes?: ReturnType; } = {}, ) { const sessionStore = makeSessionStore(); @@ -452,6 +454,10 @@ async function pressWithSystemUiAnr( const session = makeAndroidSession(sessionName); session.appBundleId = 'com.example.app'; const nodes = systemUiAnrScreen(); + if (setup.frameNodes) { + session.snapshot = { nodes: setup.frameNodes, createdAt: Date.now(), backend: 'android' }; + activateCompleteRefFrame(session); + } session.snapshot = { nodes: setup.sessionNodes ?? nodes, createdAt: Date.now(), @@ -579,6 +585,32 @@ test('a ref from a snapshot taken before the ANR dialog is not retargeted to the expect(mockTapPoint).not.toHaveBeenCalled(); }); +test('a ref is checked in the tree that issued it, not in a later read of the dialog', async () => { + // `snapshot` issued @e2 on the app screen; a screenshot after the dialog appeared replaced the + // session snapshot, where @e2 is Close app. The press would tap the app's button, unchecked. + const appScreen = attachRefs([ + { + index: 0, + type: 'android.widget.TextView', + label: 'Checkout', + rect: { x: 50, y: 100, width: 500, height: 80 }, + }, + { + index: 1, + type: 'android.widget.Button', + label: 'Submit order', + identifier: 'com.example.app:id/submit', + rect: { x: 60, y: 1200, width: 300, height: 100 }, + enabled: true, + hittable: true, + }, + ]); + const response = await pressWithSystemUiAnr(['@e2'], {}, { frameNodes: appScreen }); + + expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); + expect(mockTapPoint).not.toHaveBeenCalled(); +}); + test('a Wait ref is not retargeted to Close app when the dialog buttons moved since the snapshot', async () => { // The stored snapshot shows Wait where the current dialog shows Close app. const [title, closeApp, wait] = systemUiAnrScreen(); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index 4d7d174283..be28be2fe1 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -30,6 +30,7 @@ import { refreshAndroidRefSnapshotIfFreshnessActive } from './interaction-touch- import { prepareTouchDispatch } from './interaction-touch-prepare.ts'; import { findNodeByRef, normalizeRef } from '@agent-device/kernel/snapshot'; import type { AndroidDialogTapTarget } from '../../android-system-dialog.ts'; +import { refFrameTree } from '../../../core/ref-frame.ts'; /** * How an admitted targeted `press`/`click`/`longpress`/`hover` executes: the direct-iOS @@ -110,7 +111,13 @@ function buildTargetedRuntimeOptions( androidFreshnessBaseline: admitted.androidFreshnessBaseline, refContext: admitted.refContext, ...(admitsAndroidDialogButtonTap(session, command, admitted.refs, req.flags) - ? { androidDialogTapTarget: readAndroidDialogTapTarget(session, target) } + ? { + androidDialogTapTarget: readAndroidDialogTapTarget( + session, + target, + req.internal?.findResolvedTarget, + ), + } : {}), iosTapCorroboration: { target, extra: targetedExtra }, run: async (runtime) => @@ -186,15 +193,22 @@ function admitsAndroidDialogButtonTap( ); } -/** The ref's node in the session snapshot, or the raw point; a selector is never admitted. */ +/** + * The node the runtime will tap, or the raw point; a selector is never admitted. A `find` match + * taps its own node. A ref taps its node in the authorized frame (ADR 0014), not in a newer + * observation such as a screenshot's, so the check must read the same tree. + */ function readAndroidDialogTapTarget( session: AdmittedTargetedTouch['session'], target: AdmittedTargetedTouch['target'], + preresolved: PreresolvedInteractionTarget | undefined, ): AndroidDialogTapTarget { if (target.kind === 'point') return { kind: 'point', point: { x: target.x, y: target.y } }; if (target.kind === 'selector') return { kind: 'selector' }; + if (preresolved) return { kind: 'ref', node: preresolved.node }; const ref = normalizeRef(target.ref); - const node = ref && session.snapshot ? findNodeByRef(session.snapshot.nodes, ref) : null; + const tree = refFrameTree(session) ?? session.snapshot; + const node = ref && tree ? findNodeByRef(tree.nodes, ref) : null; return { kind: 'ref', node: node ?? undefined }; } From 2b00c50d8b8fe2a9bf74ec7214c30bb313cea333 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:09:09 +0900 Subject: [PATCH 27/33] docs(android): say where the dialog focus is confirmed The comment said the focus is read again just before the tap is sent. It is read as the last step of readiness, before ref resolution and the send. Co-Authored-By: Claude Opus 5.5 --- packages/daemon/src/execution/android-system-dialog.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 674e363d5b..4f98ca6579 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -266,8 +266,9 @@ function aimsAtAnrDialogButton(buttons: SnapshotNode[], target: AndroidDialogTap } /** - * Reads the focus again just before the tap is sent. The buttons came from a capture, so if the - * dialog lost focus since then, a tap at their points could reach what the dialog uncovered. + * Reads the focus again as the last step of readiness, before ref resolution and the send. The + * buttons came from a capture, so if the dialog lost focus since then, a tap at their points could + * reach what the dialog uncovered. */ async function confirmAndroidBlockingDialogFocus( session: SessionState, From 3d4421536d3beaf4a841e3b32321a2c19bf72215 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:18:42 +0900 Subject: [PATCH 28/33] fix(android): recognize the ANR dialog's aerr buttons as dialog buttons The ANR dialog (AppNotRespondingDialog) names its Close app and Wait buttons android:id/aerr_close and android:id/aerr_wait, not android:id/button1..3. The helper's content classifier and alert detection knew only button1..3, so a capture that held only the ANR dialog was classified as system windows only. Recognize both ids, and model the provider fixture's ANR dialog with them. Co-Authored-By: Claude Opus 5.5 --- .../snapshot-content-recovery.test.ts | 37 +++++++++++++++++++ .../platform-android/src/alert-detection.ts | 3 +- .../android-dialog-fixtures.ts | 4 +- 3 files changed, 41 insertions(+), 3 deletions(-) diff --git a/packages/platform-android/src/__tests__/snapshot-content-recovery.test.ts b/packages/platform-android/src/__tests__/snapshot-content-recovery.test.ts index 9a52b3d5f6..5a00b0ddbd 100644 --- a/packages/platform-android/src/__tests__/snapshot-content-recovery.test.ts +++ b/packages/platform-android/src/__tests__/snapshot-content-recovery.test.ts @@ -236,6 +236,43 @@ test('keeps a recognized system dialog without window metadata', () => { expect(decision).toBeUndefined(); }); +test('keeps an ANR dialog whose buttons carry the framework aerr ids', () => { + // The ANR dialog (`AppNotRespondingDialog`) names its buttons aerr_close and aerr_wait, not + // button1..3, in every device language. + const decision = unusableDecisionFor( + helperXml([ + node({ + text: 'System UI reagiert nicht', + resourceId: 'android:id/alertTitle', + packageName: 'com.android.systemui', + className: 'android.widget.TextView', + }), + node({ + text: 'App schließen', + resourceId: 'android:id/aerr_close', + packageName: 'com.android.systemui', + className: 'android.widget.Button', + }), + node({ + text: 'Warten', + resourceId: 'android:id/aerr_wait', + packageName: 'com.android.systemui', + className: 'android.widget.Button', + }), + ]), + { + backend: 'android-helper', + nodeCount: 3, + rootPresent: true, + windowCount: 1, + captureMode: 'interactive-windows', + }, + { foregroundAppPackage: 'com.pagerviewexample' }, + ); + + expect(decision).toBeUndefined(); +}); + test('rejects system chrome inherited under an empty application window', () => { const decision = unusableDecisionFor( helperXml([ diff --git a/packages/platform-android/src/alert-detection.ts b/packages/platform-android/src/alert-detection.ts index 60af1eebce..ed350e79c2 100644 --- a/packages/platform-android/src/alert-detection.ts +++ b/packages/platform-android/src/alert-detection.ts @@ -52,7 +52,8 @@ export function isAndroidPermissionPackage(packageName: string): boolean { const ANDROID_SYSTEM_DIALOG_PACKAGES = new Set(['android', 'com.android.systemui']); const ANDROID_ALERT_ID_PATTERN = /^android:id\/(?:alertTitle|message|button[123]|parentPanel|buttonPanel|contentPanel)$/i; -const ANDROID_ALERT_BUTTON_ID_PATTERN = /^android:id\/button[123]$/i; +/** AlertDialog's buttons, and the ANR dialog's (`AppNotRespondingDialog`) Close app and Wait. */ +const ANDROID_ALERT_BUTTON_ID_PATTERN = /^android:id\/(?:button[123]|aerr_(?:close|wait))$/i; const ANDROID_PERMISSION_ID_PATTERN = /(?:^|:)id\/permission_/i; const ANDROID_BLOCKING_DIALOG_PATTERN = /\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i; diff --git a/test/integration/provider-scenarios/android-dialog-fixtures.ts b/test/integration/provider-scenarios/android-dialog-fixtures.ts index 42dd71f77c..f7886ef6e1 100644 --- a/test/integration/provider-scenarios/android-dialog-fixtures.ts +++ b/test/integration/provider-scenarios/android-dialog-fixtures.ts @@ -48,8 +48,8 @@ export function androidSystemDialogXml(): string { rootNode(packageName), textNode(1, 'Demo isn't responding', 'android:id/alertTitle', packageName), textNode(2, 'Do you want to close it?', 'android:id/message', packageName), - buttonNode(3, 'Close app', 'android:id/button2', '[52,612][180,664]', packageName), - buttonNode(4, 'Wait', 'android:id/button1', '[210,612][338,664]', packageName), + buttonNode(3, 'Close app', 'android:id/aerr_close', '[52,612][180,664]', packageName), + buttonNode(4, 'Wait', 'android:id/aerr_wait', '[210,612][338,664]', packageName), ' ', ]); } From 0f047ad15d8bf68f014e2884af0b536190783207 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Thu, 26 Nov 2026 13:18:42 +0900 Subject: [PATCH 29/33] fix(android): find the session app ANR's Close app by its framework id App-owned ANR recovery matched the English "Close app" label, so it could not recover on a device in another language. Read the button by android:id/aerr_close through the same reader as the press exception, and delete ANDROID_CLOSE_APP_PATTERN. The unit fixtures now carry the id the real dialog has. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-occlusion.test.ts | 4 +++ .../android-system-dialog-readiness.test.ts | 25 +++++++++++++++++++ .../android-system-dialog-ref-frame.test.ts | 1 + .../src/execution/android-system-dialog.ts | 12 ++++----- .../interaction-dispatch-disclosure.test.ts | 1 + .../internal/interaction-gesture-tap.test.ts | 1 + .../request-router-android-modal.test.ts | 1 + 7 files changed, 38 insertions(+), 7 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts index d6c470ce32..3e6f4af7d0 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts @@ -61,6 +61,7 @@ test('recovery taps the reachable Close app, not a covered one that comes first' index: 0, type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', hittable: true, rect: { x: 40, y: 300, width: 200, height: 80 }, }; @@ -75,6 +76,7 @@ test('recovery taps the reachable Close app, not a covered one that comes first' index: 3, type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', hittable: true, rect: { x: 40, y: 1800, width: 200, height: 80 }, }; @@ -106,6 +108,7 @@ test('a fully covered dialog does not trigger recovery', async () => { index: 1, type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', hittable: true, rect: { x: 40, y: 300, width: 200, height: 80 }, }; @@ -135,6 +138,7 @@ test('collectively covered Close app is neither selected nor tapped', async () = parentIndex: 0, type: 'android.widget.Button', label: 'Close app', + identifier: 'android:id/aerr_close', hittable: true, rect: { x: 40, y: 300, width: 200, height: 80 }, }, diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 8fbaa5a360..2fa5dd1d3f 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -49,6 +49,7 @@ function anrDialogNodes(): RawSnapshotNode[] { index: 1, type: 'android.widget.Button', label: 'Close app', + identifier: 'android:id/aerr_close', rect: CLOSE_APP_RECT, }, ]; @@ -172,6 +173,30 @@ test('an ANR that surfaces between two commands is recovered by the next pre-dis expect(tapCalls(calls)).toEqual([CLOSE_APP_TAP]); }); +test("the session app's ANR is recovered on a device in another language", async () => { + // Recovery finds Close app by its framework id, so a translated label does not hide it. + const session = makeAndroidSession('readiness-anr-localized', { appBundleId: APP }); + const [title, closeApp] = anrDialogNodes(); + screenNodes = [ + { ...title!, label: `${APP} reagiert nicht` }, + { ...closeApp!, label: 'App schließen' }, + ]; + const { observation, calls } = makeObservation(anrFocus); + + const readiness = await ensureAndroidBlockingSystemDialogReady({ + session, + command: 'tap', + phase: 'before-command', + observation, + }); + + expect(readiness).toEqual({ + status: 'recovered', + warning: `Recovered Android app ANR before tap: closed and relaunched ${APP}.`, + }); + expect(tapCalls(calls)).toEqual([CLOSE_APP_TAP]); +}); + test('an ANR whose Close app is covered is not tapped, and recovery reports failure', async () => { // #1832: recovery reads the presentation's occlusion result, so a "Close app" that a foreground // surface covers is unreachable. Tapping it anyway would land the tap on whatever is on top. diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts index 67dab9618d..0ad66ab559 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts @@ -30,6 +30,7 @@ test('android blocking-dialog recovery expires the ref frame before its recovery index: 1, type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', hittable: true, rect: { x: 20, y: 200, width: 120, height: 44 }, }; diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 4f98ca6579..426b76b2f7 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -19,13 +19,13 @@ import type { SessionState } from '../core/session-state.ts'; import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; const ANDROID_BLOCKING_MODAL_PATTERN = /\bis(?:n(?:'|'|')?t| not)\s+responding\b/i; -const ANDROID_CLOSE_APP_PATTERN = /^close app$/i; /** * The ANR dialog's (`AppNotRespondingDialog`) Close app and Wait buttons. The resource id does not * depend on the device language, and an app cannot declare an id in the `android` package. */ +const ANDROID_ANR_CLOSE_BUTTON_ID = 'android:id/aerr_close'; const ANDROID_ANR_DIALOG_BUTTON_IDS: ReadonlySet = new Set([ - 'android:id/aerr_close', + ANDROID_ANR_CLOSE_BUTTON_ID, 'android:id/aerr_wait', ]); const ANDROID_MODAL_POLL_MS = 500; @@ -566,11 +566,9 @@ function findCloseAppButton( if (options.requireDialogSignal !== false && !containsBlockingDialog(nodes)) { return undefined; } - return nodes.filter(isTouchableDialogNode).find((node) => { - return ( - readNodeTextParts(node).some((text) => ANDROID_CLOSE_APP_PATTERN.test(text)) && node.rect - ); - }); + return findAnrDialogButtons(nodes).find( + (node) => node.identifier === ANDROID_ANR_CLOSE_BUTTON_ID, + ); } /** A node the recovery tap can actually reach: present in the tree and not covered by a surface above it. */ diff --git a/packages/daemon/src/execution/interaction/internal/interaction-dispatch-disclosure.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-dispatch-disclosure.test.ts index 5e6df54486..750aed0c69 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-dispatch-disclosure.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-dispatch-disclosure.test.ts @@ -278,6 +278,7 @@ async function refRefusedAfterAndroidRecovery(command: 'press' | 'gesture'): Pro ref: 'e0', type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', rect: { x: 10, y: 20, width: 100, height: 40 }, }, ], diff --git a/packages/daemon/src/execution/interaction/internal/interaction-gesture-tap.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-gesture-tap.test.ts index 8c7037745d..3f3a44ded2 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-gesture-tap.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-gesture-tap.test.ts @@ -284,6 +284,7 @@ for (const canceled of [false, true]) { ref: 'e0', type: 'Button', label: 'Close app', + identifier: 'android:id/aerr_close', rect: { x: 10, y: 20, width: 100, height: 40 }, }, ], diff --git a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts index 77e3fb2200..a85cd49c4c 100644 --- a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts @@ -71,6 +71,7 @@ vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => { index: 1, type: 'android.widget.Button', label: 'Close app', + identifier: 'android:id/aerr_close', rect: { x: 100, y: 600, width: 220, height: 80 }, }, ]); From de93c9762f8d9cdaae32a065037bf56e8fbac3a9 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Fri, 27 Nov 2026 08:32:18 +0900 Subject: [PATCH 30/33] refactor(android): drop the press admission for a foreign ANR dialog The maintainer review asked for the smaller path: `alert` already owns Android system dialogs, and the blocking-dialog guard does not stop it. A second, press-only route to the same Close app button added a hit test, a focus check, and press-pipeline options for something `alert` does already. This removes the pre-dispatch dialog-button check, the tap-shape checks, the dialog hint passed through press and click, and their docs and tests. The app-owned recovery still finds Close app by its framework id. Co-Authored-By: Claude Opus 5.5 --- .../src/interaction/metadata.ts | 4 +- .../android-system-dialog-readiness.test.ts | 221 +--------- .../src/execution/android-system-dialog.ts | 230 +--------- ...nteraction-touch-android-readiness.test.ts | 399 +----------------- .../interaction-touch-android-readiness.ts | 40 +- .../internal/interaction-touch-press.ts | 53 --- .../internal/interaction-touch-runtime.ts | 14 +- website/docs/docs/commands.md | 2 - 8 files changed, 42 insertions(+), 921 deletions(-) diff --git a/packages/command-surface/src/interaction/metadata.ts b/packages/command-surface/src/interaction/metadata.ts index aebf09dafd..a009c86b65 100644 --- a/packages/command-surface/src/interaction/metadata.ts +++ b/packages/command-surface/src/interaction/metadata.ts @@ -62,9 +62,9 @@ const FIND_ACTION_VALUES = [ const interactionCommandDescriptions = { click: - "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix. On Android, a foreign ANR dialog admits one tap on Close app or Wait.", + "Activate a UI target by snapshot ref, selector, or coordinates. This can change app state. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. With settle, continue from the returned diff. Copy refs exactly, including any -sN suffix.", press: - "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press. On Android, a foreign ANR dialog admits one tap on Close app or Wait.", + "Short-press a UI target by snapshot ref, selector, or coordinates. Success reports dispatch only; settle returns the resulting UI diff and verify returns cheap post-action evidence. A ref or selector target is re-checked for motion before dispatch when the session's previous action just animated the screen, and is dispatched at its resting position; one that has not stopped refuses with target_still_moving rather than acting where it was. A comma-separated ref list dispatches 2-16 keys in order as one command, admitted before the first press.", fill: 'Replace text in a UI input selected by snapshot ref, selector, or coordinates. An empty text clears the field. Unconfirmed evidence does not establish the resulting value or screen. The recordAs option keeps sensitive text out of a recorded replay while sending it to the live app. To append instead of replacing, use type.', longpress: 'Hold a UI target by snapshot ref, selector, or coordinates to open a context menu or perform another hold gesture. The durationMs input overrides the default hold duration.', diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 2fa5dd1d3f..31481d107b 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -15,10 +15,7 @@ import { countDiagnosticEventsByPhase, withDiagnosticsScope, } from '@agent-device/host-kit/diagnostics'; -import { - ensureAndroidBlockingSystemDialogReady, - ensureAndroidBlockingSystemDialogReadyForTap, -} from '../android-system-dialog.ts'; +import { ensureAndroidBlockingSystemDialogReady } from '../android-system-dialog.ts'; // A blocking dialog can surface with no adb traffic at all, so nothing a previous command observed // is evidence about this one. These pin what each readiness phase owes the command it guards. @@ -279,219 +276,3 @@ test('a dump that answered nothing is reported as unobserved, not as a clear scr expect(readiness).toEqual({ status: 'clear' }); expect(unobserved).toBe(1); }); - -const WAIT_RECT = { x: 100, y: 700, width: 220, height: 80 }; - -/** System UI's ANR dialog as the framework draws it: a title and buttons with `aerr_` ids. */ -function systemUiAnrDialogNodes(): RawSnapshotNode[] { - return [ - { - index: 0, - type: 'android.widget.TextView', - label: "System UI isn't responding", - identifier: 'android:id/alertTitle', - rect: { x: 50, y: 400, width: 500, height: 80 }, - }, - { - index: 1, - type: 'android.widget.Button', - label: 'Close app', - identifier: 'android:id/aerr_close', - rect: CLOSE_APP_RECT, - }, - { - index: 2, - type: 'android.widget.Button', - label: 'Wait', - identifier: 'android:id/aerr_wait', - rect: WAIT_RECT, - }, - ]; -} - -/** A ref target naming a dialog button as the session snapshot stored it. */ -function refTo(identifier: string, rect = CLOSE_APP_RECT) { - return { kind: 'ref', node: { index: 0, ref: 'e2', identifier, rect } } as const; -} - -test("a tap on a foreign ANR dialog's Close app or Wait proceeds, and nothing is tapped for it", async () => { - // The dialog refuses every other input, so its buttons are the only way to close it. - const session = makeAndroidSession('readiness-system-tap'); - screenNodes = systemUiAnrDialogNodes(); - const { observation, calls } = makeObservation(systemDialogFocus); - - for (const target of [ - refTo('android:id/aerr_close'), - refTo('android:id/aerr_wait', WAIT_RECT), - { kind: 'point', point: { x: 210, y: 740 } } as const, - ]) { - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target, - observation, - }), - ).resolves.toEqual({ status: 'dialog-button' }); - } - expect(tapCalls(calls)).toEqual([]); -}); - -test("a tap on a localized foreign ANR dialog's Close app proceeds", async () => { - // Android translates the dialog's title and labels; the framework ids stay the same. - const session = makeAndroidSession('readiness-system-tap-localized'); - const [title, closeApp, wait] = systemUiAnrDialogNodes(); - screenNodes = [ - { ...title!, label: 'System UI reagiert nicht' }, - { ...closeApp!, label: 'App schließen' }, - { ...wait!, label: 'Warten' }, - ]; - const { observation } = makeObservation(systemDialogFocus); - - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target: refTo('android:id/aerr_close'), - observation, - }), - ).resolves.toEqual({ status: 'dialog-button' }); -}); - -test.each([ - ['a selector', { kind: 'selector' } as const], - ['a ref to a node the session snapshot does not hold', { kind: 'ref', node: undefined } as const], - ['a ref to an app control', refTo('com.example.app:id/submit')], - ["a ref to the dialog's Send feedback", refTo('android:id/aerr_report')], - ['a Wait ref whose stored position now shows Close app', refTo('android:id/aerr_wait')], - ['a point outside the buttons', { kind: 'point', point: { x: 540, y: 1500 } } as const], -])('a tap on a foreign ANR dialog stays refused for %s', async (_case, target) => { - const session = makeAndroidSession('readiness-system-tap-refused'); - screenNodes = systemUiAnrDialogNodes(); - const { observation, calls } = makeObservation(systemDialogFocus); - - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target, - observation, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - message: expect.stringContaining('Android system dialog is blocking press'), - details: { - dispatched: 'no', - focusedPackage: 'com.android.systemui', - focusedWindow: 'Application Not Responding: com.android.systemui', - hint: expect.stringContaining('Close app or Wait'), - }, - }); - expect(tapCalls(calls)).toEqual([]); -}); - -test('a tap stays refused when the foreign dialog shows no framework buttons', async () => { - // An app control labelled "Close app" is not the dialog's button: only the framework id counts. - const session = makeAndroidSession('readiness-system-tap-no-ids'); - screenNodes = systemUiAnrDialogNodes().map(({ identifier: _id, ...node }) => node); - const { observation } = makeObservation(systemDialogFocus); - - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target: { kind: 'point', point: { x: 210, y: 640 } }, - observation, - }), - ).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - message: expect.stringContaining('Android system dialog is blocking press'), - // No press can close it, so the hint does not send the agent back to one. - details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, - }); -}); - -test('a tap stays refused when the foreign dialog cannot be read, and the read failure is recorded', async () => { - const session = makeAndroidSession('readiness-system-tap-unread'); - const observation: AndroidObservationAdapter = { - ...makeObservation(systemDialogFocus).observation, - readSnapshotNodes: async () => { - throw new Error('uiautomator dump failed'); - }, - }; - - const unread = await withDiagnosticsScope({}, async () => { - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target: refTo('android:id/aerr_close'), - observation, - }), - ).rejects.toMatchObject({ - details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, - }); - return countDiagnosticEventsByPhase(['android_blocking_dialog_buttons_unread']); - }); - - expect(unread).toBe(1); -}); - -test('a tap stays refused when a surface covers the foreign dialog', async () => { - const session = makeAndroidSession('readiness-system-tap-covered'); - screenNodes = [ - ...systemUiAnrDialogNodes(), - { - index: 3, - type: 'com.google.android.material.bottomsheet.BottomSheetDialog', - identifier: 'com.example:id/bottom_sheet', - hittable: true, - rect: { x: 0, y: 0, width: 1080, height: 2400 }, - }, - ]; - const { observation } = makeObservation(systemDialogFocus); - - await expect( - ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target: refTo('android:id/aerr_close'), - observation, - }), - ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { dispatched: 'no' } }); -}); - -test('a non-press command refused by a foreign dialog gets the recovery hint', async () => { - // Only a press can reach the dialog's buttons, so other commands are not sent to them. - const session = makeAndroidSession('readiness-system-swipe'); - const { observation } = makeObservation(systemDialogFocus); - - await expect( - ensureAndroidBlockingSystemDialogReady({ - session, - command: 'swipe', - phase: 'before-command', - observation, - }), - ).rejects.toMatchObject({ - details: { dispatched: 'no', hint: expect.stringContaining('reboot the emulator') }, - }); -}); - -test('the session app ANR is still recovered before a tap, not admitted', async () => { - const session = makeAndroidSession('readiness-anr-tap', { appBundleId: APP }); - const { observation, calls } = makeObservation(anrFocus); - - const readiness = await ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command: 'press', - target: refTo('android:id/aerr_close'), - observation, - }); - - expect(readiness).toEqual({ - status: 'recovered', - warning: `Recovered Android app ANR before press: closed and relaunched ${APP}.`, - }); - expect(tapCalls(calls)).toEqual([CLOSE_APP_TAP]); -}); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 426b76b2f7..13b68b8d65 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -4,36 +4,21 @@ import type { } from '@agent-device/contracts/android-observation'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; import { sleep } from '@agent-device/host-kit/retry'; -import { - AppError, - discloseDispatch, - normalizeError, - type NormalizedError, -} from '@agent-device/kernel/errors'; -import { centerOfRect, type Point, type SnapshotNode } from '@agent-device/kernel/snapshot'; +import { AppError, normalizeError, type NormalizedError } from '@agent-device/kernel/errors'; +import { centerOfRect, type SnapshotNode } from '@agent-device/kernel/snapshot'; import { isSnapshotNodeInteractionBlocked } from '@agent-device/capture-kit/snapshot-occlusion'; import { expireRefFrame } from '../core/ref-frame.ts'; -import { thrownBeforeDispatch } from './request-dispatch-disclosure.ts'; import type { SessionState } from '../core/session-state.ts'; import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; const ANDROID_BLOCKING_MODAL_PATTERN = /\bis(?:n(?:'|'|')?t| not)\s+responding\b/i; -/** - * The ANR dialog's (`AppNotRespondingDialog`) Close app and Wait buttons. The resource id does not - * depend on the device language, and an app cannot declare an id in the `android` package. - */ +/** The framework id of the ANR dialog's Close app button. It does not depend on the device language. */ const ANDROID_ANR_CLOSE_BUTTON_ID = 'android:id/aerr_close'; -const ANDROID_ANR_DIALOG_BUTTON_IDS: ReadonlySet = new Set([ - ANDROID_ANR_CLOSE_BUTTON_ID, - 'android:id/aerr_wait', -]); const ANDROID_MODAL_POLL_MS = 500; const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = 'Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.'; -const ANDROID_FOREIGN_DIALOG_HINT = - "Take a new snapshot -i, then press the ref of one of the dialog's buttons (Close app or Wait). Every other input is refused while the dialog has focus."; const ANDROID_BLOCKING_DIALOG_INSPECTION_WARNING = 'Android blocking-dialog readiness could not be inspected; the command continued.'; const ANDROID_BLOCKING_DIALOG_WARNING_TEXT_LIMIT = 240; @@ -50,19 +35,6 @@ export type AndroidBlockingDialogReadinessResult = focusedPackage?: string; } | { status: 'recovered'; warning: string }; - -/** - * What a single press or click aims at, read before dispatch: the node a ref names in the session - * snapshot, a raw point, or a selector. - */ -export type AndroidDialogTapTarget = - | { kind: 'ref'; node: SnapshotNode | undefined } - | { kind: 'point'; point: Point } - | { kind: 'selector' }; - -export type AndroidBlockingDialogTapReadinessResult = - | AndroidBlockingDialogReadinessResult - | { status: 'dialog-button' }; type AndroidDialogButtonTapResult = | { ok: true; x: number; y: number } | { @@ -204,155 +176,6 @@ export async function ensureAndroidBlockingSystemDialogReady(params: { phase: 'before-command' | 'after-command'; observation?: AndroidObservationAdapter; }): Promise { - const readiness = await readAndroidBlockingSystemDialogReadiness(params); - if (readiness.status === 'foreign-dialog') throw readiness.refusal(); - return readiness; -} - -/** - * The before-command check of a single press or click. A foreign ANR dialog ("System UI isn't - * responding") refuses every other input, so its Close app and Wait buttons are the only way to - * close it from a command. The tap proceeds with `dialog-button` only when it aims at one of them - * in a fresh capture and the dialog still has focus; otherwise it is refused with nothing sent. - */ -export async function ensureAndroidBlockingSystemDialogReadyForTap(params: { - session: SessionState; - command: string; - target: AndroidDialogTapTarget; - observation?: AndroidObservationAdapter; -}): Promise { - const readiness = await readAndroidBlockingSystemDialogReadiness({ - ...params, - phase: 'before-command', - }); - if (readiness.status !== 'foreign-dialog') return readiness; - const { session, command } = params; - const observation = requireObservation(params.observation); - let buttons: SnapshotNode[]; - try { - buttons = findAnrDialogButtons(await readAndroidSnapshotNodes(session, observation)); - } catch (error) { - emitDiagnostic({ - level: 'warn', - phase: 'android_blocking_dialog_buttons_unread', - data: { - session: session.name, - deviceId: session.device.id, - command, - error: error instanceof Error ? error.message : String(error), - }, - }); - throw readiness.refusal(); - } - // Before Android 7.0, the dialog's buttons carry no `aerr_` ids, so no press can close it. - if (buttons.length === 0) throw readiness.refusal(); - if (!aimsAtAnrDialogButton(buttons, params.target)) { - throw readiness.refusal(ANDROID_FOREIGN_DIALOG_HINT); - } - await confirmAndroidBlockingDialogFocus(session, command, readiness.focus, observation); - return { status: 'dialog-button' }; -} - -/** - * A ref must name a Close app or Wait node, and the button with the same id in the fresh capture - * must contain that node's center: so a ref read before the dialog appeared, or a Wait ref whose - * stored position now shows Close app, is refused. A raw point must be inside either button. - */ -function aimsAtAnrDialogButton(buttons: SnapshotNode[], target: AndroidDialogTapTarget): boolean { - if (target.kind === 'point') return findButtonAtPoint(buttons, target.point) !== undefined; - if (target.kind !== 'ref' || !target.node?.rect) return false; - const button = findButtonAtPoint(buttons, centerOfRect(target.node.rect)); - return button !== undefined && button.identifier === target.node.identifier; -} - -/** - * Reads the focus again as the last step of readiness, before ref resolution and the send. The - * buttons came from a capture, so if the dialog lost focus since then, a tap at their points could - * reach what the dialog uncovered. - */ -async function confirmAndroidBlockingDialogFocus( - session: SessionState, - command: string, - focus: AndroidBlockingDialogFocus, - observation: AndroidObservationAdapter, -): Promise { - const current = await observation.readBlockingDialog(session.device).catch((error: unknown) => { - throw thrownBeforeDispatch(error); - }); - if (current.status === 'dialog' && isSameAndroidBlockingDialogFocus(current.focus, focus)) return; - const dialog = formatAndroidBlockingDialogFocus(focus); - const message = - current.status === 'dialog' - ? `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(current.focus)}.` - : current.status === 'unknown' - ? `Android focus could not be read to confirm that the system dialog still has focus before ${command} was sent: ${dialog}.` - : `Android system dialog lost focus before ${command} was sent: ${dialog}.`; - throw discloseDispatch( - androidBlockingDialogError({ - session, - command, - focus: current.status === 'dialog' ? current.focus : focus, - message, - hint: 'Nothing was sent. Take a new snapshot, then retry the command.', - }), - 'no', - ); -} - -function isSameAndroidBlockingDialogFocus( - a: AndroidBlockingDialogFocus, - b: AndroidBlockingDialogFocus, -): boolean { - return a.package === b.package && a.focusedWindow === b.focusedWindow; -} - -/** - * Android's view hit test excludes the right and bottom edges, so a point on them reaches the - * dialog around the button, not the button. - */ -function findButtonAtPoint(buttons: SnapshotNode[], point: Point): SnapshotNode | undefined { - return buttons.find( - ({ rect }) => - rect !== undefined && - point.x >= rect.x && - point.x < rect.x + rect.width && - point.y >= rect.y && - point.y < rect.y + rect.height, - ); -} - -/** - * After a tap on a dialog button, Android removes the dialog window asynchronously. Waits a bounded - * time for the focus to leave the dialog, so the after-command check reads the result of the tap - * and not the frame before it. - */ -export async function waitForAndroidBlockingDialogFocusToClear( - session: SessionState, - observation: AndroidObservationAdapter | undefined, -): Promise { - const adapter = requireObservation(observation); - for (let attempt = 0; attempt < ANDROID_MODAL_POLL_ATTEMPTS; attempt += 1) { - const dialog = await adapter.readBlockingDialog(session.device); - if (dialog.status !== 'dialog') return; - await sleep(ANDROID_MODAL_POLL_MS); - } -} - -type AndroidBlockingSystemDialogReadiness = - | AndroidBlockingDialogReadinessResult - | { - status: 'foreign-dialog'; - focus: AndroidBlockingDialogFocus; - /** `hint` defaults to recovery steps; a press that may target the buttons passes its own. */ - refusal: (hint?: string) => AppError; - }; - -async function readAndroidBlockingSystemDialogReadiness(params: { - session: SessionState; - command: string; - phase: 'before-command' | 'after-command'; - observation?: AndroidObservationAdapter; -}): Promise { const { session, command } = params; if (session.device.platform !== 'android' || isProviderOwnedSession(session)) { return { status: 'clear' }; @@ -405,22 +228,13 @@ async function readAndroidBlockingSystemDialogReadiness(params: { }); } - return { - status: 'foreign-dialog', + throw androidBlockingDialogError({ + session, + command, focus, - refusal: (hint = ANDROID_BLOCKING_DIALOG_HINT) => { - const error = androidBlockingDialogError({ - session, - command, - focus, - message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, - hint, - }); - // ADR 0039: before the command, the refusal sends nothing. After it, the command's own - // dispatch ledger discloses what was sent. - return params.phase === 'before-command' ? discloseDispatch(error, 'no') : error; - }, - }; + message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, + hint: ANDROID_BLOCKING_DIALOG_HINT, + }); } async function recoverAppOwnedAndroidBlockingSystemDialogSafely( @@ -566,8 +380,15 @@ function findCloseAppButton( if (options.requireDialogSignal !== false && !containsBlockingDialog(nodes)) { return undefined; } - return findAnrDialogButtons(nodes).find( - (node) => node.identifier === ANDROID_ANR_CLOSE_BUTTON_ID, + return findTouchableDialogButton(nodes, ANDROID_ANR_CLOSE_BUTTON_ID); +} + +function findTouchableDialogButton( + nodes: SnapshotNode[], + identifier: string, +): SnapshotNode | undefined { + return nodes.find( + (node) => node.identifier === identifier && node.rect && isTouchableDialogNode(node), ); } @@ -646,21 +467,6 @@ function readNodeTextParts(node: { .map((part) => part.trim()); } -/** - * The ANR dialog's touchable Close app and Wait buttons, read by resource id: the dialog's text is in - * the device language. - */ -function findAnrDialogButtons(nodes: SnapshotNode[]): SnapshotNode[] { - return nodes - .filter(isTouchableDialogNode) - .filter( - (node) => - node.rect !== undefined && - node.identifier !== undefined && - ANDROID_ANR_DIALOG_BUTTON_IDS.has(node.identifier), - ); -} - function containsBlockingDialog(nodes: SnapshotNode[]): boolean { return nodes.filter(isTouchableDialogNode).some((node) => { const text = readNodeText(node); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts index a357e1d11a..f614c6c6b4 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.test.ts @@ -1,8 +1,7 @@ import { test, expect, vi, beforeEach } from 'vitest'; import { attachRefs } from '@agent-device/kernel/snapshot'; -import { AppError } from '@agent-device/kernel/errors'; import { makeSessionStore } from '../../../__tests__/support/store-factory.ts'; -import { activateCompleteRefFrame, expireRefFrame } from '../../../core/ref-frame.ts'; +import { expireRefFrame } from '../../../core/ref-frame.ts'; import { installInteractorSnapshotResolution, mockInteractorSnapshot, @@ -23,15 +22,11 @@ import { handleInteractionCommands } from '../index.ts'; type EnsureAndroidBlockingSystemDialogReady = typeof import('../../android-system-dialog.ts').ensureAndroidBlockingSystemDialogReady; -type EnsureAndroidBlockingSystemDialogReadyForTap = - typeof import('../../android-system-dialog.ts').ensureAndroidBlockingSystemDialogReadyForTap; const { androidDialogReadiness } = vi.hoisted(() => ({ androidDialogReadiness: { spy: vi.fn(), actual: undefined as unknown as EnsureAndroidBlockingSystemDialogReady, - tapSpy: vi.fn(), - tapActual: undefined as unknown as EnsureAndroidBlockingSystemDialogReadyForTap, }, })); @@ -47,21 +42,10 @@ vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => { // The blocking-dialog readiness check runs for real (its focus probe is mocked // above); the recovery regression below swaps in a recovering implementation. -// The guard polls the dialog focus between reads; these tests do not wait real time for it. -vi.mock('@agent-device/host-kit/retry', async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, sleep: vi.fn(async () => {}) }; -}); - vi.mock('../../android-system-dialog.ts', async (importOriginal) => { const actual = await importOriginal(); androidDialogReadiness.actual = actual.ensureAndroidBlockingSystemDialogReady; - androidDialogReadiness.tapActual = actual.ensureAndroidBlockingSystemDialogReadyForTap; - return { - ...actual, - ensureAndroidBlockingSystemDialogReady: androidDialogReadiness.spy, - ensureAndroidBlockingSystemDialogReadyForTap: androidDialogReadiness.tapSpy, - }; + return { ...actual, ensureAndroidBlockingSystemDialogReady: androidDialogReadiness.spy }; }); import { @@ -85,10 +69,6 @@ beforeEach(() => { mockInteractorSnapshot.mockReset(); androidDialogReadiness.spy.mockReset(); androidDialogReadiness.spy.mockImplementation((params) => androidDialogReadiness.actual(params)); - androidDialogReadiness.tapSpy.mockReset(); - androidDialogReadiness.tapSpy.mockImplementation((params) => - androidDialogReadiness.tapActual(params), - ); }); test('press @ref fails when Android tap escapes to launcher', async () => { @@ -332,10 +312,12 @@ test.each(ANDROID_PERMISSION_PROMPT_PACKAGES)( test('a ref action aborts with the shared ref_frame_expired rejection after Android dialog recovery mutates', async () => { // Simulate recovery: the before-command readiness check taps a blocking dialog // (a device mutation) and reports `recovered`, expiring the frame. - // A single press reads readiness through the tap variant. - androidDialogReadiness.tapSpy.mockImplementation(async (params) => { - expireRefFrame(params.session); - return { status: 'recovered', warning: 'Recovered from a blocking system dialog' }; + androidDialogReadiness.spy.mockImplementation(async (params) => { + if (params.phase === 'before-command') { + expireRefFrame(params.session); + return { status: 'recovered', warning: 'Recovered from a blocking system dialog' }; + } + return { status: 'clear' }; }); const sessionStore = makeSessionStore(); const sessionName = 'android-recovery-abort'; @@ -380,368 +362,3 @@ test('a ref action aborts with the shared ref_frame_expired rejection after Andr // The outstanding ref action never dispatched a press against the recovered UI. expect(mockTapPoint).not.toHaveBeenCalled(); }); - -// While System UI's ANR dialog has focus, the guard refuses every input. The dialog's own -// buttons are the one input that can close it, so a single press on one of them goes through, and -// any other tap is still refused before it is sent. -const SYSTEM_UI_ANR = { - status: 'dialog', - focus: { - package: 'com.android.systemui', - focusedWindow: 'Application Not Responding: com.android.systemui', - raw: 'mCurrentFocus=Window{ffeedd u0 Application Not Responding: com.android.systemui}', - }, -} as const; - -/** The typed context of a refusal by the System UI ANR dialog's guard. */ -const SYSTEM_UI_ANR_REFUSAL = { - dispatched: 'no', - focusedPackage: SYSTEM_UI_ANR.focus.package, - focusedWindow: SYSTEM_UI_ANR.focus.focusedWindow, -} as const; - -function systemUiAnrScreen() { - return attachRefs([ - { - index: 0, - type: 'android.widget.TextView', - label: "System UI isn't responding", - identifier: 'android:id/alertTitle', - rect: { x: 50, y: 400, width: 500, height: 80 }, - }, - { - index: 1, - type: 'android.widget.Button', - label: 'Close app', - identifier: 'android:id/aerr_close', - rect: { x: 100, y: 600, width: 220, height: 80 }, - enabled: true, - hittable: true, - }, - { - index: 2, - type: 'android.widget.Button', - label: 'Wait', - identifier: 'android:id/aerr_wait', - rect: { x: 100, y: 700, width: 220, height: 80 }, - enabled: true, - hittable: true, - }, - ]); -} - -type BlockingDialogObservation = Awaited>; - -async function pressWithSystemUiAnr( - positionals: string[], - flags: Record = {}, - setup: { - /** - * The focus read number `read` (from 0) returns, before and after the tap. By default the - * dialog holds the focus until a tap reaches the device. - */ - beforeTap?: (read: number) => BlockingDialogObservation; - afterTap?: (read: number) => BlockingDialogObservation; - command?: 'press' | 'click'; - /** The session's stored snapshot, when it was taken before the dialog appeared. */ - sessionNodes?: ReturnType; - /** The tree an earlier `snapshot` issued the refs from, when a later read replaced it. */ - frameNodes?: ReturnType; - } = {}, -) { - const sessionStore = makeSessionStore(); - const sessionName = 'android-system-ui-anr'; - const session = makeAndroidSession(sessionName); - session.appBundleId = 'com.example.app'; - const nodes = systemUiAnrScreen(); - if (setup.frameNodes) { - session.snapshot = { nodes: setup.frameNodes, createdAt: Date.now(), backend: 'android' }; - activateCompleteRefFrame(session); - } - session.snapshot = { - nodes: setup.sessionNodes ?? nodes, - createdAt: Date.now(), - backend: 'android', - }; - sessionStore.publish(sessionName, session); - - const beforeTap = setup.beforeTap ?? (() => SYSTEM_UI_ANR); - const afterTap = setup.afterTap ?? (() => ({ status: 'clear' }) as const); - let tapped = false; - let reads = 0; - mockTapPoint.mockImplementation(async (input) => { - tapped = true; - reads = 0; - return { x: input.point.x, y: input.point.y }; - }); - mockGetAndroidBlockingDialogObservation.mockImplementation(async () => { - const read = reads; - reads += 1; - return tapped ? afterTap(read) : beforeTap(read); - }); - const bindings = getRuntimeBindings(); - return await handleInteractionCommands({ - createCommandSurface: touchCreateCommandSurface, - req: { - token: 't', - session: sessionName, - command: setup.command ?? 'press', - positionals, - flags, - }, - sessionName, - sessionStore, - contextFromFlags, - ...bindings, - androidObservation: { ...bindings.androidObservation, readSnapshotNodes: async () => nodes }, - }); -} - -test("press on the System UI ANR dialog's Close app goes through the blocking-dialog guard", async () => { - const response = await pressWithSystemUiAnr(['@e2']); - - expect(response).toMatchObject({ ok: true }); - expect(mockTapPoint).toHaveBeenCalledTimes(1); - expect(mockTapPoint.mock.calls[0]?.[0].point).toEqual({ x: 210, y: 640 }); -}); - -test("click on the System UI ANR dialog's Wait goes through the blocking-dialog guard", async () => { - const response = await pressWithSystemUiAnr(['@e3'], {}, { command: 'click' }); - - expect(response).toMatchObject({ ok: true }); - expect(mockTapPoint).toHaveBeenCalledTimes(1); - expect(mockTapPoint.mock.calls[0]?.[0].point).toEqual({ x: 210, y: 740 }); -}); - -test('a press at a point outside the System UI ANR dialog buttons is refused before it is sent', async () => { - const response = await pressWithSystemUiAnr(['540', '1500']); - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'COMMAND_FAILED', - message: expect.stringContaining('Android system dialog is blocking press'), - details: SYSTEM_UI_ANR_REFUSAL, - }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test.each([ - ['the right edge', ['320', '640']], - ['the bottom edge', ['210', '680']], -])( - "a press on %s of a System UI ANR dialog button is refused: Android's hit test excludes it", - async (_edge, positionals) => { - const response = await pressWithSystemUiAnr(positionals); - - expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); - expect(mockTapPoint).not.toHaveBeenCalled(); - }, -); - -test.each([ - ['a repeated press', ['@e2'], { count: 2 }], - ['a double tap', ['@e2'], { doubleTap: true }], - ['a multi-ref plan', ['@e2,@e3'], {}], - ['a hold', ['@e2'], { holdMs: 800 }], - ['a jittered press', ['@e2'], { jitterPx: 40 }], - ['a selector', ['id="android:id/aerr_close"'], {}], -])('%s on the System UI ANR dialog stays refused', async (_shape, positionals, flags) => { - // Later taps would land on whatever the closed dialog uncovers, a hold is not a tap, jitter can - // move the contact off the button, and only a ref or a point is checked against the dialog. - const response = await pressWithSystemUiAnr(positionals, flags); - - expect(response).toMatchObject({ - ok: false, - error: { details: SYSTEM_UI_ANR_REFUSAL }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test('a ref from a snapshot taken before the ANR dialog is not retargeted to the dialog button over it', async () => { - // The app's own button sits where the dialog's Close app now is: the tap would close System UI - // and report it as a press of the app's button. - const appScreen = attachRefs([ - { - index: 0, - type: 'android.widget.Button', - label: 'Submit order', - identifier: 'com.example.app:id/submit', - rect: { x: 60, y: 590, width: 300, height: 100 }, - enabled: true, - hittable: true, - }, - ]); - const response = await pressWithSystemUiAnr(['@e1'], {}, { sessionNodes: appScreen }); - - expect(response).toMatchObject({ - ok: false, - error: { - message: expect.stringContaining('Android system dialog is blocking press'), - details: SYSTEM_UI_ANR_REFUSAL, - }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test('a ref is checked in the tree that issued it, not in a later read of the dialog', async () => { - // `snapshot` issued @e2 on the app screen; a screenshot after the dialog appeared replaced the - // session snapshot, where @e2 is Close app. The press would tap the app's button, unchecked. - const appScreen = attachRefs([ - { - index: 0, - type: 'android.widget.TextView', - label: 'Checkout', - rect: { x: 50, y: 100, width: 500, height: 80 }, - }, - { - index: 1, - type: 'android.widget.Button', - label: 'Submit order', - identifier: 'com.example.app:id/submit', - rect: { x: 60, y: 1200, width: 300, height: 100 }, - enabled: true, - hittable: true, - }, - ]); - const response = await pressWithSystemUiAnr(['@e2'], {}, { frameNodes: appScreen }); - - expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test('a Wait ref is not retargeted to Close app when the dialog buttons moved since the snapshot', async () => { - // The stored snapshot shows Wait where the current dialog shows Close app. - const [title, closeApp, wait] = systemUiAnrScreen(); - const storedScreen = attachRefs([ - { ...title! }, - { ...wait!, rect: closeApp!.rect! }, - { ...closeApp!, rect: wait!.rect! }, - ]); - const response = await pressWithSystemUiAnr(['@e2'], {}, { sessionNodes: storedScreen }); - - expect(response).toMatchObject({ ok: false, error: { details: SYSTEM_UI_ANR_REFUSAL } }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test('a press on a System UI ANR dialog button is refused when the dialog loses focus before the send', async () => { - // Readiness reads the dialog; by the read just before the send, Android has removed it, so the - // button points now belong to the screen underneath. - const response = await pressWithSystemUiAnr( - ['@e2'], - {}, - { - beforeTap: (read) => (read === 0 ? SYSTEM_UI_ANR : { status: 'clear' }), - }, - ); - - expect(response).toMatchObject({ - ok: false, - error: { - code: 'COMMAND_FAILED', - message: expect.stringContaining('Android system dialog lost focus before press was sent'), - details: SYSTEM_UI_ANR_REFUSAL, - }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test.each([ - [ - 'the focus read answers nothing', - { status: 'unknown' } as const, - 'Android focus could not be read to confirm', - SYSTEM_UI_ANR.focus, - ], - [ - 'another dialog has the focus', - { - status: 'dialog', - focus: { - package: 'com.example.other', - focusedWindow: 'Application Not Responding: com.example.other', - raw: 'mCurrentFocus=Window{aabbcc u0 Application Not Responding: com.example.other}', - }, - } as const, - 'Android system dialog is blocking press', - { - package: 'com.example.other', - focusedWindow: 'Application Not Responding: com.example.other', - }, - ], -])( - 'a press on a System UI ANR dialog button is refused when, before the send, %s', - async (_case, beforeSend, message, focus) => { - const response = await pressWithSystemUiAnr( - ['@e2'], - {}, - { - beforeTap: (read) => (read === 0 ? SYSTEM_UI_ANR : beforeSend), - }, - ); - - expect(response).toMatchObject({ - ok: false, - error: { - message: expect.stringContaining(message), - details: { - dispatched: 'no', - focusedPackage: focus.package, - focusedWindow: focus.focusedWindow, - }, - }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); - }, -); - -test('a press on a System UI ANR dialog button is refused with nothing sent when the focus read fails', async () => { - let reads = 0; - const response = await pressWithSystemUiAnr( - ['@e2'], - {}, - { - beforeTap: () => { - reads += 1; - if (reads > 1) throw new AppError('COMMAND_FAILED', 'adb: device offline'); - return SYSTEM_UI_ANR; - }, - }, - ); - - expect(response).toMatchObject({ - ok: false, - error: { message: 'adb: device offline', details: { dispatched: 'no' } }, - }); - expect(mockTapPoint).not.toHaveBeenCalled(); -}); - -test('a press on a System UI ANR dialog button waits for the dialog focus to clear', async () => { - // Android removes the dialog window asynchronously: the first reads after the tap still show it. - const response = await pressWithSystemUiAnr( - ['@e2'], - {}, - { - afterTap: (read) => (read < 2 ? SYSTEM_UI_ANR : { status: 'clear' }), - }, - ); - - expect(response).toMatchObject({ ok: true }); - expect(mockTapPoint).toHaveBeenCalledTimes(1); -}); - -test('a press that closes the System UI ANR dialog still reports an app the dialog did not cover', async () => { - // The launcher, not the session app, was under the dialog: the press reports that the session - // app is not in front, as after any other press. - mockGetAndroidAppState.mockResolvedValue({ - package: 'com.google.android.apps.nexuslauncher', - activity: 'Launcher', - }); - - await expect(pressWithSystemUiAnr(['@e2'])).rejects.toMatchObject({ - code: 'COMMAND_FAILED', - message: expect.stringContaining('left com.example.app'), - }); - expect(mockTapPoint).toHaveBeenCalledTimes(1); -}); diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts index b796d1b7ec..88dc8d33e5 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-android-readiness.ts @@ -1,10 +1,7 @@ import type { DaemonResponse } from '@agent-device/kernel/contracts'; import { ensureAndroidBlockingSystemDialogReady, - ensureAndroidBlockingSystemDialogReadyForTap, - waitForAndroidBlockingDialogFocusToClear, - type AndroidBlockingDialogTapReadinessResult, - type AndroidDialogTapTarget, + type AndroidBlockingDialogReadinessResult, } from '../../android-system-dialog.ts'; import type { SessionState } from '../../../core/session-state.ts'; import { readRefMutationFrame } from '../../../core/ref-frame.ts'; @@ -27,41 +24,27 @@ export type ReadinessOutcome = | { aborted: true; response: DaemonResponse } | { aborted: false; - readiness: AndroidBlockingDialogTapReadinessResult; + readiness: AndroidBlockingDialogReadinessResult; runtimeResult: TResult; }; export async function runWithAndroidDialogReadinessCheck( session: SessionState, command: string, - options: { - refContext: RefAdmissionContext | undefined; - /** - * Present on a single plain press or click: while a foreign ANR dialog has focus, the tap may - * still go to the dialog's Close app or Wait button. - */ - dialogTapTarget?: AndroidDialogTapTarget; - }, - run: (readiness: AndroidBlockingDialogTapReadinessResult) => Promise, + options: { refContext: RefAdmissionContext | undefined }, + run: (readiness: AndroidBlockingDialogReadinessResult) => Promise, observation?: AndroidObservationAdapter, ): Promise> { if (session.lease?.leaseProvider) { const readiness = { status: 'clear' } as const; return { aborted: false, readiness, runtimeResult: await run(readiness) }; } - const readiness: AndroidBlockingDialogTapReadinessResult = options.dialogTapTarget - ? await ensureAndroidBlockingSystemDialogReadyForTap({ - session, - command, - target: options.dialogTapTarget, - observation, - }) - : await ensureAndroidBlockingSystemDialogReady({ - session, - command, - phase: 'before-command', - observation, - }); + const readiness = await ensureAndroidBlockingSystemDialogReady({ + session, + command, + phase: 'before-command', + observation, + }); // ADR 0014: blocking-dialog recovery is itself device-mutating and expires the // frame at its own seam. A ref action admitted against the pre-recovery frame // must NOT continue against the recovered UI — abort it through the SHARED @@ -83,9 +66,6 @@ export async function runWithAndroidDialogReadinessCheck( if (abort) return { aborted: true, response: abort }; } const runtimeResult = await run(readiness); - if (readiness.status === 'dialog-button') { - await waitForAndroidBlockingDialogFocusToClear(session, observation); - } await ensureAndroidBlockingSystemDialogReady({ session, command, diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts index be28be2fe1..44875cbfcc 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-press.ts @@ -28,9 +28,6 @@ import { dispatchRuntimeInteraction } from './interaction-touch-runtime.ts'; import { formatTouchTargetLabel } from './interaction-touch-targets.ts'; import { refreshAndroidRefSnapshotIfFreshnessActive } from './interaction-touch-android-freshness.ts'; import { prepareTouchDispatch } from './interaction-touch-prepare.ts'; -import { findNodeByRef, normalizeRef } from '@agent-device/kernel/snapshot'; -import type { AndroidDialogTapTarget } from '../../android-system-dialog.ts'; -import { refFrameTree } from '../../../core/ref-frame.ts'; /** * How an admitted targeted `press`/`click`/`longpress`/`hover` executes: the direct-iOS @@ -110,15 +107,6 @@ function buildTargetedRuntimeOptions( return { androidFreshnessBaseline: admitted.androidFreshnessBaseline, refContext: admitted.refContext, - ...(admitsAndroidDialogButtonTap(session, command, admitted.refs, req.flags) - ? { - androidDialogTapTarget: readAndroidDialogTapTarget( - session, - target, - req.internal?.findResolvedTarget, - ), - } - : {}), iosTapCorroboration: { target, extra: targetedExtra }, run: async (runtime) => await runTargetedTouchInteraction({ @@ -171,47 +159,6 @@ function buildTargetedRuntimeOptions( }; } -/** - * Only one plain tap may close a foreign Android ANR dialog: a repeated tap, a double tap, or a - * multi-ref plan would send its later taps to whatever the closed dialog uncovers, a hold is not a - * tap, and jitter can move the contact off the checked button. - */ -function admitsAndroidDialogButtonTap( - session: AdmittedTargetedTouch['session'], - command: TargetedTouchCommand, - refs: readonly string[] | undefined, - flags: CommandFlags | undefined, -): boolean { - if (session.device.platform !== 'android') return false; - if (command !== 'press' && command !== 'click') return false; - if (refs && refs.length > 1) return false; - return ( - (flags?.count ?? 1) <= 1 && - flags?.doubleTap !== true && - (flags?.holdMs ?? 0) <= 0 && - (flags?.jitterPx ?? 0) <= 0 - ); -} - -/** - * The node the runtime will tap, or the raw point; a selector is never admitted. A `find` match - * taps its own node. A ref taps its node in the authorized frame (ADR 0014), not in a newer - * observation such as a screenshot's, so the check must read the same tree. - */ -function readAndroidDialogTapTarget( - session: AdmittedTargetedTouch['session'], - target: AdmittedTargetedTouch['target'], - preresolved: PreresolvedInteractionTarget | undefined, -): AndroidDialogTapTarget { - if (target.kind === 'point') return { kind: 'point', point: { x: target.x, y: target.y } }; - if (target.kind === 'selector') return { kind: 'selector' }; - if (preresolved) return { kind: 'ref', node: preresolved.node }; - const ref = normalizeRef(target.ref); - const tree = refFrameTree(session) ?? session.snapshot; - const node = ref && tree ? findNodeByRef(tree.nodes, ref) : null; - return { kind: 'ref', node: node ?? undefined }; -} - async function runTargetedTouchInteraction(params: { runtime: Awaited>; command: TargetedTouchCommand; diff --git a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts index ae59ce20bc..448c3736a0 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-touch-runtime.ts @@ -28,10 +28,7 @@ import { runWithAndroidDialogReadinessCheck, type RefAdmissionContext, } from './interaction-touch-android-readiness.ts'; -import type { - AndroidBlockingDialogTapReadinessResult, - AndroidDialogTapTarget, -} from '../../android-system-dialog.ts'; +import type { AndroidBlockingDialogReadinessResult } from '../../android-system-dialog.ts'; import { readSnapshotNodesReferenceFrame } from '@agent-device/capture-kit/touch-reference-frame'; import { buildCorroboratedTapResponseData, @@ -65,11 +62,6 @@ export async function dispatchRuntimeInteraction< * admission rejection built from this context. */ refContext?: RefAdmissionContext; - /** - * Present on a single plain press or click: while a foreign Android ANR dialog has focus, the - * tap may still go to the dialog's Close app or Wait button, checked before dispatch. - */ - androidDialogTapTarget?: AndroidDialogTapTarget; /** A failed local iOS tap may be corroborated against one same-scope capture. */ iosTapCorroboration?: { target: InteractionRequestTarget; @@ -82,7 +74,7 @@ export async function dispatchRuntimeInteraction< */ afterRun?( result: TResult, - readiness: AndroidBlockingDialogTapReadinessResult, + readiness: AndroidBlockingDialogReadinessResult, ): Promise; buildPayloads( result: TResult, @@ -105,7 +97,7 @@ export async function dispatchRuntimeInteraction< const outcome = await runWithAndroidDialogReadinessCheck( session, params.req.command, - { refContext: options.refContext, dialogTapTarget: options.androidDialogTapTarget }, + { refContext: options.refContext }, async (readiness) => { const result = await options.run(runtime); afterRunWarning = await options.afterRun?.(result, readiness); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 641f125e6f..75313e2803 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1089,8 +1089,6 @@ agent-device diff screenshot --baseline before.png --out diff.png --json On iOS, a press on a control nested inside a larger touch control, such as a swipe action beside its row, refuses with `target_not_hittable` when the platform reports the control as not hittable. Reveal the control, for example by swiping its row, and take a new `snapshot -i`. -On Android, while another app's "isn't responding" dialog has focus, every input command, such as `fill`, `swipe`, or `back`, refuses with `dispatched: no`, except a single `click` or `press` on the dialog's **Close app** or **Wait** button. Take a new `snapshot -i` and press the button's ref, or its coordinates. The command then waits for the dialog to close. A repeated press, a double tap, a hold, jitter, a ref list, a selector, or a press anywhere else stays refused. When the dialog belongs to the session's own app, agent-device closes it and relaunches the app before the command. - A comma-separated ref plan, such as `press @e13,@e14`, presses 2 to 16 refs as one command. Run `snapshot -i` first and copy the refs exactly. A refusal after the first press reports `details.dispatchedSteps`; plan again from a new `snapshot -i`. While script recording is armed, a plan needs `--no-record`. See `agent-device help press`. If rotation stops repeated iOS presses, inspect the screen before you continue with the remaining presses. From c19df5dcd7b02d50d5d08fc82237b0518e177ec3 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Fri, 27 Nov 2026 08:35:53 +0900 Subject: [PATCH 31/33] refactor(android): find the ANR dialog by its button ids in the daemon The daemon found the ANR dialog by English text ("isn't responding") and Close app by its English label. On a device in another language the recovery found neither. The framework ids do not depend on the language: Close app is `android:id/aerr_close`, and Wait, `android:id/aerr_wait`, is only in the ANR dialog, since the crash dialog also has Close app. Co-Authored-By: Claude Opus 5.5 --- .../android-system-dialog-occlusion.test.ts | 91 ++++++++++++++++++- .../android-system-dialog-ref-frame.test.ts | 10 +- .../src/execution/android-system-dialog.ts | 34 ++----- .../request-router-android-modal.test.ts | 7 ++ 4 files changed, 111 insertions(+), 31 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts index 3e6f4af7d0..81fb1fc9e4 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-occlusion.test.ts @@ -80,9 +80,23 @@ test('recovery taps the reachable Close app, not a covered one that comes first' hittable: true, rect: { x: 40, y: 1800, width: 200, height: 80 }, }; + const visibleWait = { + index: 4, + type: 'Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + hittable: true, + rect: { x: 40, y: 1900, width: 200, height: 80 }, + }; vi.mocked(snapshotAndroid) .mockResolvedValueOnce( - makeAndroidSnapshotCapture([staleCloseApp, sheet, dialog, visibleCloseApp]) as never, + makeAndroidSnapshotCapture([ + staleCloseApp, + sheet, + dialog, + visibleCloseApp, + visibleWait, + ]) as never, ) .mockResolvedValue(makeAndroidSnapshotCapture([]) as never); vi.mocked(runAndroidAdb).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); @@ -112,8 +126,21 @@ test('a fully covered dialog does not trigger recovery', async () => { hittable: true, rect: { x: 40, y: 300, width: 200, height: 80 }, }; + const staleWait = { + index: 2, + type: 'Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + hittable: true, + rect: { x: 40, y: 400, width: 200, height: 80 }, + }; vi.mocked(snapshotAndroid).mockResolvedValue( - makeAndroidSnapshotCapture([staleDialog, staleCloseApp, foregroundSheet(2)]) as never, + makeAndroidSnapshotCapture([ + staleDialog, + staleCloseApp, + staleWait, + foregroundSheet(3), + ]) as never, ); vi.mocked(runAndroidAdb).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); @@ -194,3 +221,63 @@ test('collectively covered Close app is neither selected nor tapped', async () = expect(result.status).toBe('absent'); expect(tappedPoints()).toEqual([]); }); + +test('an ANR dialog in another language is found and closed by its button ids', async () => { + vi.mocked(runAndroidAdb).mockReset(); + vi.mocked(snapshotAndroid) + .mockResolvedValueOnce( + makeAndroidSnapshotCapture([ + { index: 0, type: 'TextView', label: 'Demo reagiert nicht', rect: SCREEN }, + { + index: 1, + type: 'Button', + label: 'App schließen', + identifier: 'android:id/aerr_close', + hittable: true, + rect: { x: 40, y: 1800, width: 200, height: 80 }, + }, + { + index: 2, + type: 'Button', + label: 'Warten', + identifier: 'android:id/aerr_wait', + hittable: true, + rect: { x: 40, y: 1900, width: 200, height: 80 }, + }, + ]) as never, + ) + .mockResolvedValue(makeAndroidSnapshotCapture([]) as never); + vi.mocked(runAndroidAdb).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); + + const result = await recoverAndroidBlockingSystemDialog({ + session: recordingSession('anr-localized'), + }); + + expect(result.status).toBe('recovered'); + expect(tappedPoints()).toEqual([{ x: 140, y: 1840 }]); +}); + +test('a crash dialog, which has Close app but no Wait, is not treated as an ANR', async () => { + vi.mocked(runAndroidAdb).mockReset(); + vi.mocked(snapshotAndroid).mockResolvedValue( + makeAndroidSnapshotCapture([ + { index: 0, type: 'TextView', label: 'Demo keeps stopping', rect: SCREEN }, + { + index: 1, + type: 'Button', + label: 'Close app', + identifier: 'android:id/aerr_close', + hittable: true, + rect: { x: 40, y: 1800, width: 200, height: 80 }, + }, + ]) as never, + ); + vi.mocked(runAndroidAdb).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); + + const result = await recoverAndroidBlockingSystemDialog({ + session: recordingSession('crash-dialog'), + }); + + expect(result.status).toBe('absent'); + expect(tappedPoints()).toEqual([]); +}); diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts index 0ad66ab559..add3c80aff 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-ref-frame.test.ts @@ -34,10 +34,18 @@ test('android blocking-dialog recovery expires the ref frame before its recovery hittable: true, rect: { x: 20, y: 200, width: 120, height: 44 }, }; + const wait = { + index: 2, + type: 'Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + hittable: true, + rect: { x: 20, y: 260, width: 120, height: 44 }, + }; // First read: the blocking dialog is present (drives recovery). Post-tap poll: // the dialog is gone, so recovery completes without sleeping through retries. vi.mocked(snapshotAndroid) - .mockResolvedValueOnce(makeAndroidSnapshotCapture([dialog, closeApp]) as never) + .mockResolvedValueOnce(makeAndroidSnapshotCapture([dialog, closeApp, wait]) as never) .mockResolvedValue(makeAndroidSnapshotCapture([]) as never); vi.mocked(runAndroidAdb).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' } as never); diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index 13b68b8d65..e345d84784 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -12,9 +12,12 @@ import { expireRefFrame } from '../core/ref-frame.ts'; import type { SessionState } from '../core/session-state.ts'; import { isActiveProviderDevice } from '../core/provider-device-admission.ts'; -const ANDROID_BLOCKING_MODAL_PATTERN = /\bis(?:n(?:'|'|')?t| not)\s+responding\b/i; -/** The framework id of the ANR dialog's Close app button. It does not depend on the device language. */ +/** + * The framework ids of the ANR dialog's Close app and Wait buttons. They do not depend on the + * device language, and only the ANR dialog has Wait: the crash dialog also has Close app. + */ const ANDROID_ANR_CLOSE_BUTTON_ID = 'android:id/aerr_close'; +const ANDROID_ANR_WAIT_BUTTON_ID = 'android:id/aerr_wait'; const ANDROID_MODAL_POLL_MS = 500; const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = @@ -445,31 +448,6 @@ function isProviderOwnedSession(session: SessionState): boolean { return Boolean(session.lease?.leaseProvider) || isActiveProviderDevice(session.device); } -function readNodeText(node: { - label?: string; - value?: string | number | boolean | null; - identifier?: string; -}): string { - return readNodeTextParts(node).join(' ').trim(); -} - -function readNodeTextParts(node: { - label?: string; - value?: string | number | boolean | null; - identifier?: string; -}): string[] { - const parts = [node.label, node.identifier]; - if (typeof node.value === 'string' && node.value.trim().length > 0) { - parts.push(node.value); - } - return parts - .filter((part): part is string => typeof part === 'string' && part.trim().length > 0) - .map((part) => part.trim()); -} - function containsBlockingDialog(nodes: SnapshotNode[]): boolean { - return nodes.filter(isTouchableDialogNode).some((node) => { - const text = readNodeText(node); - return text.length > 0 && ANDROID_BLOCKING_MODAL_PATTERN.test(text); - }); + return findTouchableDialogButton(nodes, ANDROID_ANR_WAIT_BUTTON_ID) !== undefined; } diff --git a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts index a85cd49c4c..b88a81544d 100644 --- a/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts +++ b/packages/daemon/src/server/__tests__/request-router-android-modal.test.ts @@ -74,6 +74,13 @@ vi.mock('@agent-device/platform-android/mechanics', async (importOriginal) => { identifier: 'android:id/aerr_close', rect: { x: 100, y: 600, width: 220, height: 80 }, }, + { + index: 2, + type: 'android.widget.Button', + label: 'Wait', + identifier: 'android:id/aerr_wait', + rect: { x: 100, y: 700, width: 220, height: 80 }, + }, ]); } return capture([]); From 63e82ac7f629b1c7df5278fce394364b6d9b2ee9 Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Fri, 27 Nov 2026 08:37:35 +0900 Subject: [PATCH 32/33] fix(android): let alert close or wait on an ANR dialog in any language `alert` found the "isn't responding" dialog by its English text only, and gave Wait no role, so `alert accept` refused it. The dialog's buttons have framework ids that do not depend on the device language: `alert` now finds the dialog by them too, and maps `android:id/aerr_close` to dismiss and `android:id/aerr_wait` to accept. Co-Authored-By: Claude Opus 5.5 --- .../src/__tests__/alert-detection.test.ts | 20 +++++++++++++++++++ .../platform-android/src/alert-detection.ts | 13 +++++++++++- .../provider-scenarios/android-alert.test.ts | 14 +++++++++++++ website/docs/docs/commands.md | 1 + 4 files changed, 47 insertions(+), 1 deletion(-) diff --git a/packages/platform-android/src/__tests__/alert-detection.test.ts b/packages/platform-android/src/__tests__/alert-detection.test.ts index aa29edf488..18ce68cee0 100644 --- a/packages/platform-android/src/__tests__/alert-detection.test.ts +++ b/packages/platform-android/src/__tests__/alert-detection.test.ts @@ -595,3 +595,23 @@ test('shared Apple label additions also name ordinary Android dialog actions', ( ); } }); + +test('an ANR dialog in another language is found, and its buttons are chosen, by their ids', () => { + const system = { bundleId: 'android' }; + const candidate = findAndroidAlertCandidate([ + node(0, 'android.widget.FrameLayout', system), + node(1, 'android.widget.TextView', { + ...system, + label: 'System UI reagiert nicht', + identifier: 'android:id/alertTitle', + }), + { ...button(2, 'App schließen', 'android:id/aerr_close', { x: 70, y: 1210 }), ...system }, + { ...button(3, 'Warten', 'android:id/aerr_wait', { x: 70, y: 1336 }), ...system }, + ]); + + assert.equal(candidate?.alert.source, 'system-dialog'); + assert.equal(candidate?.alert.title, 'System UI reagiert nicht'); + const buttons = candidate?.buttons ?? []; + assert.equal(chooseAndroidAlertButton(buttons, 'dismiss')?.label, 'App schließen'); + assert.equal(chooseAndroidAlertButton(buttons, 'accept')?.label, 'Warten'); +}); diff --git a/packages/platform-android/src/alert-detection.ts b/packages/platform-android/src/alert-detection.ts index ed350e79c2..1bd70cfa53 100644 --- a/packages/platform-android/src/alert-detection.ts +++ b/packages/platform-android/src/alert-detection.ts @@ -57,6 +57,14 @@ const ANDROID_ALERT_BUTTON_ID_PATTERN = /^android:id\/(?:button[123]|aerr_(?:clo const ANDROID_PERMISSION_ID_PATTERN = /(?:^|:)id\/permission_/i; const ANDROID_BLOCKING_DIALOG_PATTERN = /\b(?:is(?:n't| not) responding|keeps stopping|has stopped|close app|app info)\b/i; +/** + * The ANR dialog's buttons by framework id, which does not depend on the device language: dismiss + * presses Close app and accept presses Wait. + */ +const ANDROID_ANR_BUTTON_ROLES: ReadonlyMap = new Map([ + ['android:id/aerr_close', 'dismiss'], + ['android:id/aerr_wait', 'accept'], +]); /** The AlertController panel that holds a dialog's title, message, and buttons, under the platform or an AppCompat package. */ export function isAndroidAlertPanelIdentifier(identifier: string | null): boolean { @@ -296,6 +304,8 @@ function classifyAndroidAlertButtonById( if (/(?:^|:)id\/button1$/i.test(identifier)) return 'accept'; if (/(?:^|:)id\/button2$/i.test(identifier)) return 'dismiss'; if (/(?:^|:)id\/button3$/i.test(identifier)) return 'neutral'; + const anrRole = ANDROID_ANR_BUTTON_ROLES.get(identifier); + if (anrRole) return anrRole; if (ANDROID_GRANT_ID_SHAPE.test(identifier)) return UNDECLARED_GRANT; return null; } @@ -377,7 +387,8 @@ function isAndroidSystemDialogNode(node: RawSnapshotNode): boolean { const packageName = node.bundleId ?? ''; return ( ANDROID_SYSTEM_DIALOG_PACKAGES.has(packageName) && - ANDROID_BLOCKING_DIALOG_PATTERN.test(readNodeText(node)) + (ANDROID_BLOCKING_DIALOG_PATTERN.test(readNodeText(node)) || + ANDROID_ANR_BUTTON_ROLES.has(node.identifier ?? '')) ); } diff --git a/test/integration/provider-scenarios/android-alert.test.ts b/test/integration/provider-scenarios/android-alert.test.ts index cde8b4e2f0..5c8f42ff72 100644 --- a/test/integration/provider-scenarios/android-alert.test.ts +++ b/test/integration/provider-scenarios/android-alert.test.ts @@ -185,3 +185,17 @@ test('Provider-backed integration Android alert ignores app-owned sheets', async }, ); }); + +test('Provider-backed integration Android alert accept waits on an ANR dialog', async () => { + await withProviderScenarioResource( + async () => await createAndroidSettingsWorld(dismissibleDialog(androidSystemDialogXml)), + async (world) => { + const client = world.daemon.client(); + await client.apps.open({ app: 'com.example.demo', ...world.selection }); + + const alertAccept = await client.command.alert({ action: 'accept', ...world.selection }); + assert.equal(alertAccept.button, 'Wait'); + assertCommandCall(world.adbCalls, ['shell', 'input', 'tap', '274', '638']); + }, + ); +}); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 75313e2803..9e53a8e17f 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -955,6 +955,7 @@ agent-device alert dismiss Handle system alerts: - `alert` handles system alerts on iOS, macOS, and Android permission dialogs. On iOS it also covers app-owned modal popups and Safari's page prompts. +- On Android, `alert` also handles the "isn't responding" (ANR) dialog in any device language: `dismiss` presses Close app, and `accept` presses Wait. - Use `alert get` for a quick check, and `alert wait ` only when a prompt may appear after async work. Do not use `settings permission` to answer a dialog already on screen; it is for setup before a flow. - `accept` and `dismiss` are sent once and never replayed, even if the response is lost. A closed alert does not prove that a permission was granted, so verify the app outcome. - `accept` picks the lasting grant, such as `Allow While Using App` over `Allow Once`, or "Allow all" on Android's partial-media sheet. On iOS, `dismiss` presses only a recognized decline button, such as `Cancel` or `Don't Allow`. iOS simulators also recognize these labels in the device's preferred languages; on physical iOS devices, tvOS, and visionOS the runner cannot read the OS strings, so it recognizes the system prompts' Simplified Chinese wording from a built-in table, at the rank of the English label each entry translates; wording the table does not cover stays unknown. From 6b57b4245784cff89692bc9cc9f2656ce04bc1be Mon Sep 17 00:00:00 2001 From: DongYun Kang Date: Fri, 27 Nov 2026 08:40:02 +0900 Subject: [PATCH 33/33] fix(android): name alert in the refusal hint for another app's ANR While another app's "isn't responding" dialog has focus, the guard refuses every command that acts on the screen, and its hint said only to wait, restart the app, or reboot. In a reported case none of these cleared it. `alert` is not stopped by the guard and presses the dialog's buttons, so the hint now names `alert dismiss` and `alert accept`. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/android-system-dialog-readiness.test.ts | 7 ++++++- packages/daemon/src/execution/android-system-dialog.ts | 5 ++++- website/docs/docs/commands.md | 2 +- 3 files changed, 11 insertions(+), 3 deletions(-) diff --git a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts index 31481d107b..1b11f3cfec 100644 --- a/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts +++ b/packages/daemon/src/execution/__tests__/android-system-dialog-readiness.test.ts @@ -234,7 +234,12 @@ test('a system dialog that surfaces between two commands blocks the next command phase: 'before-command', observation, }), - ).rejects.toMatchObject({ code: 'COMMAND_FAILED' }); + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { + hint: 'Run alert dismiss to close the app that is not responding, or alert accept to wait for it, then retry.', + }, + }); }); test('an ANR the command itself provoked still fails that command', async () => { diff --git a/packages/daemon/src/execution/android-system-dialog.ts b/packages/daemon/src/execution/android-system-dialog.ts index e345d84784..303d66daa6 100644 --- a/packages/daemon/src/execution/android-system-dialog.ts +++ b/packages/daemon/src/execution/android-system-dialog.ts @@ -22,6 +22,9 @@ const ANDROID_MODAL_POLL_MS = 500; const ANDROID_MODAL_POLL_ATTEMPTS = 12; const ANDROID_BLOCKING_DIALOG_HINT = 'Wait for Android to recover, close the dialog, restart the app, or reboot the emulator, then retry.'; +/** `alert` is not stopped by this guard, and it presses the ANR dialog's buttons by their ids. */ +const ANDROID_FOREIGN_ANR_HINT = + 'Run alert dismiss to close the app that is not responding, or alert accept to wait for it, then retry.'; const ANDROID_BLOCKING_DIALOG_INSPECTION_WARNING = 'Android blocking-dialog readiness could not be inspected; the command continued.'; const ANDROID_BLOCKING_DIALOG_WARNING_TEXT_LIMIT = 240; @@ -236,7 +239,7 @@ export async function ensureAndroidBlockingSystemDialogReady(params: { command, focus, message: `Android system dialog is blocking ${command}: ${formatAndroidBlockingDialogFocus(focus)}.`, - hint: ANDROID_BLOCKING_DIALOG_HINT, + hint: ANDROID_FOREIGN_ANR_HINT, }); } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 9e53a8e17f..9794ad5e3e 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -955,7 +955,7 @@ agent-device alert dismiss Handle system alerts: - `alert` handles system alerts on iOS, macOS, and Android permission dialogs. On iOS it also covers app-owned modal popups and Safari's page prompts. -- On Android, `alert` also handles the "isn't responding" (ANR) dialog in any device language: `dismiss` presses Close app, and `accept` presses Wait. +- On Android, `alert` also handles the "isn't responding" (ANR) dialog in any device language: `dismiss` presses Close app, and `accept` presses Wait. While another app's ANR dialog has focus, commands that act on the screen are refused and their hint names `alert`. - Use `alert get` for a quick check, and `alert wait ` only when a prompt may appear after async work. Do not use `settings permission` to answer a dialog already on screen; it is for setup before a flow. - `accept` and `dismiss` are sent once and never replayed, even if the response is lost. A closed alert does not prove that a permission was granted, so verify the app outcome. - `accept` picks the lasting grant, such as `Allow While Using App` over `Allow Once`, or "Allow all" on Android's partial-media sheet. On iOS, `dismiss` presses only a recognized decline button, such as `Cancel` or `Don't Allow`. iOS simulators also recognize these labels in the device's preferred languages; on physical iOS devices, tvOS, and visionOS the runner cannot read the OS strings, so it recognizes the system prompts' Simplified Chinese wording from a built-in table, at the rank of the English label each entry translates; wording the table does not cover stays unknown.