Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion packages/contracts/src/android-observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<string | undefined> {
// 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 &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
33 changes: 33 additions & 0 deletions packages/platform-android/src/__tests__/app-parsers.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import {
parseAndroidComponent,
parseAndroidLaunchablePackages,
parseAndroidResumedActivity,
readAndroidBlockingDialogFocus,
Expand Down Expand Up @@ -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(
Expand Down
33 changes: 21 additions & 12 deletions packages/platform-android/src/app-parsers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { AndroidBlockingDialogObservation } from '@agent-device/contracts/android-observation';

export type AndroidBlockingDialogFocus = {
package?: string;
focusedWindow: string;
Expand Down Expand Up @@ -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<string>();
Expand Down Expand Up @@ -83,18 +97,17 @@ 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);
});
return { focusObserved, focus, ...(focusedPackage ? { focusedPackage } : {}) };
}

/** 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<AndroidBlockingDialogObservation, { status: 'clear' }> {
return focusedPackage ? { status: 'clear', focusedPackage } : { status: 'clear' };
}

Expand Down Expand Up @@ -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;
Expand Down
9 changes: 2 additions & 7 deletions packages/platform-android/src/app-state.ts
Original file line number Diff line number Diff line change
@@ -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'],
Expand Down Expand Up @@ -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);
}
9 changes: 4 additions & 5 deletions packages/platform-android/src/observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
ANDROID_FOCUS_MARKERS,
ANDROID_FOCUSED_WINDOW_MARKER,
clearAndroidBlockingDialogObservation,
parseAndroidComponent,
readAndroidBlockingDialogFocus,
} from './app-parsers.ts';

Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -182,10 +183,8 @@ function preservePositiveMemo(memo: Map<string, boolean>, 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;
}
Expand Down
24 changes: 6 additions & 18 deletions packages/platform-android/src/window-state.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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
Expand Down Expand Up @@ -110,16 +113,6 @@ const androidWindowDumpEverAnswered = new Map<string, Map<string, boolean>>();
*/
export type AndroidWindowDumpReader = (args: readonly string[]) => Promise<string>;

/**
* 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<string, Promise<string>>();
return (args) => {
Expand Down Expand Up @@ -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;
}
Loading