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
6 changes: 5 additions & 1 deletion packages/contracts/src/android-observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,11 @@ export type AndroidBlockingDialogFocus = Readonly<{
/** One observation of Android's focused system-window state. */
export type AndroidBlockingDialogObservation =
| Readonly<{ status: 'dialog'; focus: AndroidBlockingDialogFocus }>
| Readonly<{ status: 'clear' }>
| Readonly<{
status: 'clear';
/** The app package that owns the focused window, when the read named one. */
focusedPackage?: string;
}>
| Readonly<{ status: 'unknown' }>;

/** The minimal result needed by daemon-owned recovery to classify an adb tap. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ function buildAndroidEscapeHint(permissionDialog: boolean): string {
return 'Use screenshot as visual truth, then take a fresh snapshot -i before retrying.';
}

function looksLikeAndroidEscapeSurface(packageName: string): boolean {
export function looksLikeAndroidEscapeSurface(packageName: string): boolean {
return (
packageName === 'com.android.settings' ||
packageName === 'com.android.systemui' ||
Expand Down
9 changes: 7 additions & 2 deletions packages/daemon/src/execution/android-system-dialog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,11 @@ export type AndroidBlockingDialogRecoveryResult =
| { status: 'failed'; reason: 'tap-failed' | 'dismiss-failed' | 'relaunch-failed' | 'error' }
| { status: 'unknown'; reason: 'inspection-failed'; warning: string };
export type AndroidBlockingDialogReadinessResult =
| { status: 'clear' }
| {
status: 'clear';
/** The app package that owned the focused window, when the readiness read named one. */
focusedPackage?: string;
}
| { status: 'recovered'; warning: string };
type AndroidDialogButtonTapResult =
| { ok: true; x: number; y: number }
Expand Down Expand Up @@ -193,8 +197,9 @@ export async function ensureAndroidBlockingSystemDialogReady(params: {
commandPhase: params.phase,
},
});
return { status: 'clear' };
}
return { status: 'clear' };
return dialogObservation;
}
const focus = dialogObservation.focus;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,11 @@ async function pressThatLeftTheApp(): Promise<unknown> {
{ token: 't', session: session.name, command: 'press', positionals: ['@e1'] },
createRequestDispatchLedger(),
async () => {
await assertAndroidPressStayedInApp(session, '@e1', observation);
await assertAndroidPressStayedInApp(
session,
{ command: 'press', targetLabel: '@e1' },
observation,
);
return null;
},
);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,29 +1,44 @@
import type { AndroidObservationAdapter } from '@agent-device/contracts/android-observation';
import { AppError } from '@agent-device/kernel/errors';
import { detectAndroidEscapeSurface } from '../../android-foreground-surface.ts';
import {
detectAndroidEscapeSurface,
looksLikeAndroidEscapeSurface,
} from '../../android-foreground-surface.ts';
import type { SessionState } from '../../../core/session-state.ts';

/**
* Post-press escape guard. Throws when the tap left the app for a genuine
* escape surface (settings/systemui/launcher). 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-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.
*/
export async function assertAndroidPressStayedInApp(
session: SessionState,
targetLabel: string,
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.
const { focusedPackageBefore } = touch;
if (
focusedPackageBefore !== undefined &&
focusedPackageBefore !== session.appBundleId &&
looksLikeAndroidEscapeSurface(focusedPackageBefore)
) {
return undefined;
}
const surface = await detectAndroidEscapeSurface(session, observation);
if (!surface) return undefined;

if (surface.permissionDialog) {
return `press ${targetLabel} opened an Android permission dialog (${surface.foregroundPackage}) over ${surface.expectedPackage}. ${surface.hint}`;
return `${touch.command} ${touch.targetLabel} opened an Android permission dialog (${surface.foregroundPackage}) over ${surface.expectedPackage}. ${surface.hint}`;
}

throw new AppError(
'COMMAND_FAILED',
`press ${targetLabel} left ${session.appBundleId} and foregrounded ${surface.foregroundPackage}. The tap likely escaped the app.`,
`${touch.command} ${touch.targetLabel} left ${session.appBundleId} and foregrounded ${surface.foregroundPackage}. The tap likely escaped the app.`,
surface,
);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
import { touchCreateCommandSurface } from '../../../__tests__/support/touch-command-surface-fake.ts';
import {
getRuntimeBindings,
mockLongPressPoint,
mockTapPoint,
resetGetRuntimeFixture,
} from '../../__tests__/interaction-get-runtime-fixture.ts';
Expand Down Expand Up @@ -166,6 +167,83 @@ test('press @ref fails when Android tap escapes to Settings', async () => {
});
});

const LAUNCHER_PACKAGE = 'com.google.android.apps.nexuslauncher';

async function longPressAtPointWithFocusBefore(
focusedPackageBefore: string,
foregroundPackageAfter: string = LAUNCHER_PACKAGE,
) {
const sessionStore = makeSessionStore();
const sessionName = 'android-longpress-focus-before';
const session = makeAndroidSession(sessionName);
session.appBundleId = 'com.example.app';
sessionStore.publish(sessionName, session);
// The before-command readiness read names the focused package; the after-command read is clear.
mockGetAndroidBlockingDialogObservation.mockResolvedValueOnce({
status: 'clear',
focusedPackage: focusedPackageBefore,
});
mockGetAndroidAppState.mockResolvedValue({ package: foregroundPackageAfter, activity: 'Main' });
return await handleInteractionCommands({
createCommandSurface: touchCreateCommandSurface,
req: {
token: 't',
session: sessionName,
command: 'longpress',
positionals: ['540', '1300', '1000'],
flags: {},
},
sessionName,
sessionStore,
contextFromFlags,
...getRuntimeBindings(),
});
}

test('longpress at a point fails, naming longpress, when the app owned the focus before and the launcher after', async () => {
await expect(longPressAtPointWithFocusBefore('com.example.app')).rejects.toMatchObject({
code: 'COMMAND_FAILED',
message: expect.stringMatching(
/^longpress .+ left com\.example\.app and foregrounded com\.google\.android\.apps\.nexuslauncher\./,
),
});
expect(mockLongPressPoint).toHaveBeenCalledTimes(1);
});

test('longpress at a point succeeds when the launcher owned the focus before and after the dispatch', async () => {
const response = await longPressAtPointWithFocusBefore(LAUNCHER_PACKAGE);
expect(response).toMatchObject({ ok: true });
expect(mockLongPressPoint).toHaveBeenCalledTimes(1);
});

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',
async (_flow, focusedPackageBefore, foregroundPackageAfter) => {
await expect(
longPressAtPointWithFocusBefore(focusedPackageBefore, foregroundPackageAfter),
).rejects.toMatchObject({
code: 'COMMAND_FAILED',
message: expect.stringContaining(
`left com.example.app and foregrounded ${foregroundPackageAfter}.`,
),
});
},
);

test('longpress at a point warns about a second permission prompt that follows a first one', async () => {
const response = await longPressAtPointWithFocusBefore(
'com.google.android.permissioncontroller',
'com.google.android.permissioncontroller',
);
expect(response).toMatchObject({
ok: true,
data: { warning: expect.stringMatching(/^longpress .+ opened an Android permission dialog/) },
});
});

const ANDROID_PERMISSION_PROMPT_PACKAGES = [
'com.android.permissioncontroller',
'com.google.android.permissioncontroller',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,12 @@ export async function runWithAndroidDialogReadinessCheck<TResult>(
session: SessionState,
command: string,
options: { refContext: RefAdmissionContext | undefined },
run: () => Promise<TResult>,
run: (readiness: AndroidBlockingDialogReadinessResult) => Promise<TResult>,
observation?: AndroidObservationAdapter,
): Promise<ReadinessOutcome<TResult>> {
if (session.lease?.leaseProvider) {
return { aborted: false, readiness: { status: 'clear' }, runtimeResult: await run() };
const readiness = { status: 'clear' } as const;
return { aborted: false, readiness, runtimeResult: await run(readiness) };
}
const readiness = await ensureAndroidBlockingSystemDialogReady({
session,
Expand Down Expand Up @@ -64,7 +65,7 @@ export async function runWithAndroidDialogReadinessCheck<TResult>(
});
if (abort) return { aborted: true, response: abort };
}
const runtimeResult = await run();
const runtimeResult = await run(readiness);
await ensureAndroidBlockingSystemDialogReady({
session,
command,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,15 @@ function buildTargetedRuntimeOptions(
expectedResolvedTarget: req.internal?.replayTargetGuard,
preresolvedTarget: req.internal?.findResolvedTarget,
}),
afterRun: async (result) => {
afterRun: async (result, readiness) => {
if (session.lease?.leaseProvider) return undefined;
return await assertAndroidPressStayedInApp(
session,
formatTouchTargetLabel(target, result),
{
command,
targetLabel: formatTouchTargetLabel(target, result),
focusedPackageBefore: readiness.status === 'clear' ? readiness.focusedPackage : undefined,
},
params.androidObservation,
);
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import {
runWithAndroidDialogReadinessCheck,
type RefAdmissionContext,
} from './interaction-touch-android-readiness.ts';
import type { AndroidBlockingDialogReadinessResult } from '../../android-system-dialog.ts';
import { readSnapshotNodesReferenceFrame } from '@agent-device/capture-kit/touch-reference-frame';
import {
buildCorroboratedTapResponseData,
Expand Down Expand Up @@ -67,8 +68,14 @@ export async function dispatchRuntimeInteraction<
extra: Record<string, unknown>;
};
run(runtime: Awaited<ReturnType<typeof createInteractionRuntimeForRoute>>): Promise<TResult>;
/** May return a warning to append to the successful response (e.g. a pending Android permission dialog). */
afterRun?(result: TResult): Promise<string | undefined>;
/**
* May return a warning to append to the successful response (e.g. a pending Android permission
* dialog). `readiness` is the Android readiness read taken before the dispatch.
*/
afterRun?(
result: TResult,
readiness: AndroidBlockingDialogReadinessResult,
): Promise<string | undefined>;
buildPayloads(
result: TResult,
): InteractionResponsePayloads | Promise<InteractionResponsePayloads>;
Expand All @@ -91,9 +98,9 @@ export async function dispatchRuntimeInteraction<
session,
params.req.command,
{ refContext: options.refContext },
async () => {
async (readiness) => {
const result = await options.run(runtime);
afterRunWarning = await options.afterRun?.(result);
afterRunWarning = await options.afterRun?.(result, readiness);
return result;
},
params.androidObservation,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ test('readAndroidBlockingDialogFocus preserves responding window text without re
focusedWindow: '123 u0 com.example.app/com.example.MainActivity Demo is not responding',
raw: 'mCurrentFocus=Window{123 u0 com.example.app/com.example.MainActivity Demo is not responding}',
},
focusedPackage: 'com.example.app',
},
);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -820,7 +820,10 @@ test('fresh helper focus answers app guards while system windows retain ANR diag
packageName: manifest.packageName,
instrumentationRunner: manifest.instrumentationRunner,
});
assert.deepEqual(await observer.readBlockingDialog(device), { status: 'clear' });
assert.deepEqual(await observer.readBlockingDialog(device), {
status: 'clear',
focusedPackage: 'com.example.app',
});
assert.equal(
await observer.readAppFocus(device, 'com.example.app', { requireNoBlockingDialog: true }),
true,
Expand Down
22 changes: 20 additions & 2 deletions packages/platform-android/src/app-parsers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ 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_.$]+/;

export function parseAndroidLaunchablePackages(stdout: string): string[] {
const packages = new Set<string>();
Expand Down Expand Up @@ -65,19 +66,36 @@ export function parseAndroidUserInstalledPackages(stdout: string): string[] {
* title. The other markers are still parsed — the marker order is unchanged (#592) — but a dump
* that names just the focused app token has NOT answered this question and must not suppress the
* variant that can.
*
* `focusedPackage` is the package of the `package/Activity` component the first focused-window
* line names. A window without a component (a popup, the keyboard, the notification shade) names
* no package.
*/
export type AndroidBlockingDialogRead = {
focusObserved: boolean;
focus: AndroidBlockingDialogFocus | null;
focusedPackage?: string;
};

export function readAndroidBlockingDialogFocus(text: string): AndroidBlockingDialogRead {
let focusObserved = false;
let focusedPackage: string | undefined;
const focus = parseAndroidFocusSegment(text, (segment, raw, marker) => {
if (marker === ANDROID_FOCUSED_WINDOW_MARKER) focusObserved = true;
if (marker === ANDROID_FOCUSED_WINDOW_MARKER && !focusObserved) {
focusObserved = true;
focusedPackage = ANDROID_COMPONENT_PATTERN.exec(segment.split('}')[0] ?? '')?.[1];
}
return parseAndroidBlockingDialogFromSegment(segment, raw);
});
return { focusObserved, focus };
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;
} {
return focusedPackage ? { status: 'clear', focusedPackage } : { status: 'clear' };
}

export function parseAndroidFocusSegment<T>(
Expand Down
16 changes: 16 additions & 0 deletions packages/platform-android/src/observation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,22 @@ test('classifies an app-owned ANR without exposing dump mechanics to the daemon'
});
});

test('a clear blocking-dialog read names the package of the focused component only', async () => {
const read = async (focusLine: string) =>
await createAndroidObservationAdapter(
hostFor(new Map([['shell dumpsys window windows', focusLine]])),
).readBlockingDialog(device);

await expect(
read(
'mCurrentFocus=Window{1 u0 com.google.android.apps.nexuslauncher/com.android.launcher3.uioverrides.QuickstepLauncher}',
),
).resolves.toEqual({ status: 'clear', focusedPackage: 'com.google.android.apps.nexuslauncher' });
await expect(read('mCurrentFocus=Window{3 u0 Splash Screen com.example.app}')).resolves.toEqual({
status: 'clear',
});
});

test('owns touch rounding and screen-size parsing behind raw host commands', async () => {
const host = hostFor(new Map([['shell wm size', 'Physical size: 1080x2400']]));
const observer = createAndroidObservationAdapter(host);
Expand Down
5 changes: 3 additions & 2 deletions packages/platform-android/src/observation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AppError } from '@agent-device/kernel/errors';
import {
ANDROID_FOCUS_MARKERS,
ANDROID_FOCUSED_WINDOW_MARKER,
clearAndroidBlockingDialogObservation,
readAndroidBlockingDialogFocus,
} from './app-parsers.ts';

Expand Down Expand Up @@ -139,12 +140,12 @@ 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' };
return { status: 'clear', focusedPackage: focus.focusedPackage };
}
for (const args of orderedDumps(device, 'blockingDialog')) {
const parsed = readAndroidBlockingDialogFocus(await read(args));
if (parsed.focus) return { status: 'dialog', focus: parsed.focus };
if (parsed.focusObserved) return { status: 'clear' };
if (parsed.focusObserved) return clearAndroidBlockingDialogObservation(parsed.focusedPackage);
}
return { status: 'unknown' };
}
Expand Down
Loading
Loading