diff --git a/packages/contracts/src/android-observation.ts b/packages/contracts/src/android-observation.ts index d9e441b67c..9268503c8d 100644 --- a/packages/contracts/src/android-observation.ts +++ b/packages/contracts/src/android-observation.ts @@ -9,7 +9,10 @@ export type AndroidBlockingDialogFocus = Readonly<{ raw: string; }>; -/** One observation of Android's focused system-window state. */ +/** + * One observation of Android's focused system-window state. `unknown` is the case the daemon must + * not confuse with `clear`: no read named the focused window, so it is evidence about nothing. + */ export type AndroidBlockingDialogObservation = | Readonly<{ status: 'dialog'; focus: AndroidBlockingDialogFocus }> | Readonly<{ diff --git a/packages/daemon/src/execution/interaction/internal/interaction-android-escape.ts b/packages/daemon/src/execution/interaction/internal/interaction-android-escape.ts index 7565948f54..245e9593b6 100644 --- a/packages/daemon/src/execution/interaction/internal/interaction-android-escape.ts +++ b/packages/daemon/src/execution/interaction/internal/interaction-android-escape.ts @@ -7,20 +7,18 @@ import { import type { SessionState } from '../../../core/session-state.ts'; /** - * Post-press escape guard. Throws when a touch dispatched while the session app owned the focus - * left the app for a genuine escape surface (settings/systemui/launcher). A touch dispatched while an - * escape surface already owned the focus (the launcher after `home`) acted on that surface, so it - * cannot escape the app. Other packages that own the focus inside an app flow (a permission prompt, - * a custom tab, a sign-in activity) do not skip the guard. A foregrounded permission prompt is NOT an escape — the press succeeded and - * raised a system dialog the agent consumes via `alert` — so it returns a response warning instead. + * Post-touch escape guard. Throws when a touch left the session app for an escape surface + * (settings/systemui/launcher), unless an escape surface other than the session app already owned + * the focus before the dispatch. + * A raised permission prompt is not an escape: it returns a response warning for `alert` instead. */ export async function assertAndroidPressStayedInApp( session: SessionState, touch: { command: string; targetLabel: string; focusedPackageBefore?: string }, observation?: AndroidObservationAdapter, ): Promise { - // CONSERVATIVE: an unread pre-dispatch focus still runs the guard, because it is no evidence that - // the app was in the background. Revisit if every readiness read names the focused package. + // CONSERVATIVE: an unread pre-dispatch focus runs the guard; it is no evidence that an escape + // surface owned the focus. Revisit if every readiness read names the focused package. const { focusedPackageBefore } = touch; if ( focusedPackageBefore !== 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 2777239efc..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 @@ -216,11 +216,12 @@ test('longpress at a point succeeds when the launcher owned the focus before and expect(mockLongPressPoint).toHaveBeenCalledTimes(1); }); +// Only an escape surface owning the focus skips the guard, not any package other than the app. test.each([ ['a permission prompt', 'com.google.android.permissioncontroller', 'com.android.settings'], ['a Trusted Web Activity', 'com.android.chrome', LAUNCHER_PACKAGE], ])( - 'longpress at a point still fails when %s in the app flow owned the focus before an escape', + 'longpress at a point keeps failing an escape when %s in the app flow owned the focus before', async (_flow, focusedPackageBefore, foregroundPackageAfter) => { await expect( longPressAtPointWithFocusBefore(focusedPackageBefore, foregroundPackageAfter), diff --git a/packages/platform-android/src/__tests__/app-parsers.test.ts b/packages/platform-android/src/__tests__/app-parsers.test.ts index eb2fe88e4c..c18a9059d3 100644 --- a/packages/platform-android/src/__tests__/app-parsers.test.ts +++ b/packages/platform-android/src/__tests__/app-parsers.test.ts @@ -1,6 +1,7 @@ import { test } from 'vitest'; import assert from 'node:assert/strict'; import { + parseAndroidComponent, parseAndroidLaunchablePackages, parseAndroidResumedActivity, readAndroidBlockingDialogFocus, @@ -38,6 +39,38 @@ test('readAndroidBlockingDialogFocus preserves responding window text without re ); }); +// Every reader (resumed activity, focused window, foreground) passes its segment here. +test.each([ + [' ActivityRecord{99 u0 com.example.app/.MainActivity t7}', 'com.example.app', '.MainActivity'], + [ + 'Window{84ec7b8 u0 com.android.settings/com.android.settings.Settings$AppNotificationSettingsActivity', + 'com.android.settings', + 'com.android.settings.Settings$AppNotificationSettingsActivity', + ], + [ + ' u0 com.example_app2.beta/com.example_app2.Main}', + 'com.example_app2.beta', + 'com.example_app2.Main', + ], + [ + ' ActivityRecord{1 u0 com.first.app/.One t1} ActivityRecord{2 u0 com.second.app/.Two t2}', + 'com.first.app', + '.One', + ], +])('parseAndroidComponent reads the first package/Activity in %j', (segment, pkg, activity) => { + assert.deepEqual(parseAndroidComponent(segment), { package: pkg, activity }); +}); + +test.each([ + '', + 'Window{5a1b2c3 u0 NotificationShade}', + 'Window{5a1b2c3 u0 Application Not Responding: com.example.app}', + ' u0 android/com.android.internal.app.ResolverActivity}', + ' u0 com.example.app}', +])('parseAndroidComponent names no component in %j', (segment) => { + assert.equal(parseAndroidComponent(segment), null); +}); + test('parseAndroidResumedActivity reads every resumed-marker shape', () => { assert.deepEqual( parseAndroidResumedActivity( diff --git a/packages/platform-android/src/app-parsers.ts b/packages/platform-android/src/app-parsers.ts index 17e0777494..c693fcadae 100644 --- a/packages/platform-android/src/app-parsers.ts +++ b/packages/platform-android/src/app-parsers.ts @@ -1,3 +1,5 @@ +import type { AndroidBlockingDialogObservation } from '@agent-device/contracts/android-observation'; + export type AndroidBlockingDialogFocus = { package?: string; focusedWindow: string; @@ -28,7 +30,19 @@ export const ANDROID_FOCUS_MARKERS = [ ] as const; const ANDROID_ANR_TITLE_PATTERN = /\bApplication Not Responding:\s*([A-Za-z0-9_.]+)/i; const ANDROID_PACKAGE_PATTERN = /\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\b/; -const ANDROID_COMPONENT_PATTERN = /\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/[A-Za-z0-9_.$]+/; +const ANDROID_COMPONENT_PATTERN = + /\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/; + +/** + * The first `package/Activity` component in a dump segment. Callers choose the segment (a marker's + * line remainder, or the window text up to `}`) and the marker order. + */ +export function parseAndroidComponent( + segment: string, +): { package: string; activity: string } | null { + const match = ANDROID_COMPONENT_PATTERN.exec(segment); + return match?.[1] && match[2] ? { package: match[1], activity: match[2] } : null; +} export function parseAndroidLaunchablePackages(stdout: string): string[] { const packages = new Set(); @@ -83,7 +97,7 @@ export function readAndroidBlockingDialogFocus(text: string): AndroidBlockingDia const focus = parseAndroidFocusSegment(text, (segment, raw, marker) => { if (marker === ANDROID_FOCUSED_WINDOW_MARKER && !focusObserved) { focusObserved = true; - focusedPackage = ANDROID_COMPONENT_PATTERN.exec(segment.split('}')[0] ?? '')?.[1]; + focusedPackage = parseAndroidComponent(segment.split('}')[0] ?? '')?.package; } return parseAndroidBlockingDialogFromSegment(segment, raw); }); @@ -91,10 +105,9 @@ export function readAndroidBlockingDialogFocus(text: string): AndroidBlockingDia } /** A clear blocking-dialog observation that names the focused package when the read did. */ -export function clearAndroidBlockingDialogObservation(focusedPackage: string | undefined): { - status: 'clear'; - focusedPackage?: string; -} { +export function clearAndroidBlockingDialogObservation( + focusedPackage: string | undefined, +): Extract { return focusedPackage ? { status: 'clear', focusedPackage } : { status: 'clear' }; } @@ -130,12 +143,8 @@ export function parseAndroidResumedActivity( // marker only counts at the start of a field, i.e. at line start or after whitespace. if (markerIndex === -1 || (markerIndex > 0 && /\S/.test(line[markerIndex - 1] ?? ''))) continue; - const component = line - .slice(markerIndex + marker.length) - .match(/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/); - if (component?.[1] && component[2]) { - return { package: component[1], activity: component[2] }; - } + const component = parseAndroidComponent(line.slice(markerIndex + marker.length)); + if (component) return component; } } return null; diff --git a/packages/platform-android/src/app-state.ts b/packages/platform-android/src/app-state.ts index 2d416f6433..3e521faec5 100644 --- a/packages/platform-android/src/app-state.ts +++ b/packages/platform-android/src/app-state.ts @@ -1,6 +1,6 @@ import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; import { deviceShellArgv, type ShellWord } from '@agent-device/kernel/device-shell'; -import { parseAndroidFocusSegment } from './app-parsers.ts'; +import { parseAndroidComponent, parseAndroidFocusSegment } from './app-parsers.ts'; const FOCUS_COMMANDS = [ ['dumpsys', 'window', 'windows'], @@ -43,10 +43,5 @@ async function readAndroidFocusWithExecutor( } export function parseAndroidForegroundApp(text: string): AppStateRuntimeResult | null { - return parseAndroidFocusSegment(text, (segment) => parseAndroidComponentFromSegment(segment)); -} - -function parseAndroidComponentFromSegment(segment: string): AppStateRuntimeResult | null { - const match = segment.match(/\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/); - return match?.[1] && match[2] ? { package: match[1], activity: match[2] } : null; + return parseAndroidFocusSegment(text, parseAndroidComponent); } diff --git a/packages/platform-android/src/observation.ts b/packages/platform-android/src/observation.ts index 3f05a89f8f..1a5ec91663 100644 --- a/packages/platform-android/src/observation.ts +++ b/packages/platform-android/src/observation.ts @@ -13,6 +13,7 @@ import { ANDROID_FOCUS_MARKERS, ANDROID_FOCUSED_WINDOW_MARKER, clearAndroidBlockingDialogObservation, + parseAndroidComponent, readAndroidBlockingDialogFocus, } from './app-parsers.ts'; @@ -140,7 +141,7 @@ async function readBlockingDialog( const { runAndroidAutomationHelper } = await import('./automation-helper.ts'); const focus = await runAndroidAutomationHelper(device, { action: 'focus' }); if (focus?.windowType === '1' && focus.focusedPackage && focus.focusedPackage !== 'android') { - return { status: 'clear', focusedPackage: focus.focusedPackage }; + return clearAndroidBlockingDialogObservation(focus.focusedPackage); } for (const args of orderedDumps(device, 'blockingDialog')) { const parsed = readAndroidBlockingDialogFocus(await read(args)); @@ -182,10 +183,8 @@ function preservePositiveMemo(memo: Map, key: string, answered: function parseForeground(text: string): AppStateRuntimeResult | null { for (const match of text.matchAll(FOCUS_LINE)) { - const component = match[1]?.match( - /\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/, - ); - if (component?.[1] && component[2]) return { package: component[1], activity: component[2] }; + const component = parseAndroidComponent(match[1] ?? ''); + if (component) return component; } return null; } diff --git a/packages/platform-android/src/window-state.ts b/packages/platform-android/src/window-state.ts index 3928fb4e94..7882e96ef7 100644 --- a/packages/platform-android/src/window-state.ts +++ b/packages/platform-android/src/window-state.ts @@ -1,3 +1,4 @@ +import type { AndroidBlockingDialogObservation } from '@agent-device/contracts/android-observation'; import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime'; import type { DeviceInfo } from '@agent-device/kernel/device'; import { runAndroidShell } from './adb.ts'; @@ -6,11 +7,13 @@ import { ANDROID_FOCUS_MARKERS, ANDROID_RESUMED_ACTIVITY_MARKERS, clearAndroidBlockingDialogObservation, + parseAndroidComponent, parseAndroidResumedActivity, readAndroidBlockingDialogFocus, - type AndroidBlockingDialogFocus, } from './app-parsers.ts'; +export type { AndroidBlockingDialogObservation }; + /** * What is on the Android screen right now: which app owns the foreground, which activity AMS * reports resumed, and whether a blocking system dialog owns the focus. Every answer comes out @@ -110,16 +113,6 @@ const androidWindowDumpEverAnswered = new Map>(); */ export type AndroidWindowDumpReader = (args: readonly string[]) => Promise; -/** - * What one look at the device says about a blocking system dialog. `unknown` is the case the - * daemon must not confuse with `clear`: no variant printed the focused window, so this look is - * evidence about nothing. - */ -export type AndroidBlockingDialogObservation = - | { status: 'dialog'; focus: AndroidBlockingDialogFocus } - | { status: 'clear'; focusedPackage?: string } - | { status: 'unknown' }; - export function createAndroidWindowDumpReader(device: DeviceInfo): AndroidWindowDumpReader { const dumps = new Map>(); return (args) => { @@ -252,13 +245,8 @@ function escapeRegExp(value: string): string { function parseLegacyAndroidForegroundApp(text: string): AppStateRuntimeResult | null { for (const match of text.matchAll(ANDROID_FOCUS_LINE)) { - const segment = match[1]; - const component = segment?.match( - /\b([A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)+)\/([A-Za-z0-9_.$]+)/, - ); - if (component?.[1] && component[2]) { - return { package: component[1], activity: component[2] }; - } + const component = parseAndroidComponent(match[1] ?? ''); + if (component) return component; } return null; }