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
4 changes: 1 addition & 3 deletions packages/contracts/src/facades/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,7 @@ export type { CommandFlags, MaestroRuntimeFlags } from '../command-flags.ts';
export type { DaemonWireRequest, DaemonWireRequestMeta } from '../daemon-wire-request.ts';
export type { DispatchedCommand } from '../dispatched-command.ts';
export {
ANDROID_IME_HELPER_DISPATCH_REJECTED_REASON,
ANDROID_IME_HELPER_NO_ACK_REASON,
ANDROID_SHELL_TEXT_UNSUPPORTED_REASON,
ANDROID_TEXT_CHANNEL_REASONS,
normalizeBatchCommandName,
readOptionalInteger,
readOptionalNumber,
Expand Down
36 changes: 19 additions & 17 deletions packages/contracts/src/input-validation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';

export function readOptionalInteger(
record: Record<string, unknown>,
Expand Down Expand Up @@ -40,23 +40,25 @@ export function readOptionalNumber(
}

/**
* The typed reason the Android adb-shell text channel reports when it cannot carry the
* requested text. Recovery routing keys on this constant, never on the message: the message
* states the channel limit; the reason names which recovery surfaces apply. It lives here
* because every producer and consumer of the reason already evaluates this module.
* Why an Android text channel refused to carry the text it was handed. Recovery routing keys on the
* reason, never on the message: the message states the channel limit, the reason names which
* recovery surfaces apply. The table lives here because every producer of these failures and the
* replay boundary that rewrites their hint already evaluate this module.
*/
export const ANDROID_SHELL_TEXT_UNSUPPORTED_REASON = 'android_shell_text_unsupported' as const;

/**
* Typed reasons for the Android test-IME broadcast channel's truthful-outcome failures (#4520).
* The channel's acknowledgement proves attempted dispatch only; these reasons distinguish "no
* acknowledgement evidence at all" (result=0 / unparseable — a pre-ack helper or no receiver, which
* are indistinguishable and therefore both refused) from a receiver-reported rejection. Result data
* carries codes and lengths only, never user text.
*/
export const ANDROID_IME_HELPER_NO_ACK_REASON = 'android_ime_helper_no_ack' as const;
export const ANDROID_IME_HELPER_DISPATCH_REJECTED_REASON =
'android_ime_helper_dispatch_rejected' as const;
export const ANDROID_TEXT_CHANNEL_REASONS = {
// The adb-shell fallback carries ASCII text only; a helper or provider channel is needed.
shellTextUnsupported: {
reason: 'android_shell_text_unsupported',
commands: ['fill', 'type'],
},
// The test IME helper gave no evidence it attempted the dispatch, so nothing is proven typed.
imeHelperNoAck: { reason: 'android_ime_helper_no_ack', commands: ['fill', 'type'] },
// The test IME helper answered that it rejected the dispatch, so nothing was typed.
imeHelperDispatchRejected: {
reason: 'android_ime_helper_dispatch_rejected',
commands: ['fill', 'type'],
},
} as const satisfies ReasonTable<'android text channel'>;

/** Resolves a batch step command with the same whitespace and case rules on both peers. */
export function normalizeBatchCommandName(command: unknown): string {
Expand Down
6 changes: 0 additions & 6 deletions packages/contracts/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -160,12 +160,6 @@ export function settingsAppNotConsumedRefusal(
const SETTINGS_APP_NOT_INSTALLED_HINT =
'Run apps --all for the exact bundle id or package name, or install the app, then retry with that id in --app.';

/**
* The reason an Android app-scoped mutation refuses an app that resolves to an intent rather than a
* package: a permission or app-data change needs a package, so the recovery is naming one.
*/
export const SETTINGS_APP_NOT_PACKAGE_REASON = 'setting_app_not_package';

/**
* Resolves the app an app-scoped mutation lands on through the owner's own app resolution, ahead of
* anything that reaches the device. A failed resolution therefore dispatched nothing, and an app that
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import {
readAndroidClipboardWithAdb,
writeAndroidClipboardWithAdb,
} from '../device-input-state.ts';
import { ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_REASON } from '../clipboard-shell-response.ts';
import {
flushDiagnosticsToSessionFile,
withDiagnosticsScope,
Expand Down Expand Up @@ -399,7 +398,7 @@ test('readAndroidClipboardWithAdb refuses the exit-0 no-implementation answer in
assert.equal(error.code, 'UNSUPPORTED_OPERATION');
assert.equal(
(error.details as { reason?: unknown }).reason,
ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_REASON,
'android_clipboard_shell_command_unavailable',
);
});

Expand All @@ -418,7 +417,7 @@ test('writeAndroidClipboardWithAdb refuses the exit-0 no-implementation answer i
assert.equal(error.code, 'UNSUPPORTED_OPERATION');
assert.equal(
(error.details as { reason?: unknown }).reason,
ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_REASON,
'android_clipboard_shell_command_unavailable',
);
});

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { expect, test } from 'vitest';
import assert from 'node:assert/strict';
import { setAndroidGlobalToggle, type AndroidGlobalToggle } from '../settings-global-toggle.ts';
import {
ANDROID_GLOBAL_TOGGLE_REASONS,
setAndroidGlobalToggle,
type AndroidGlobalToggle,
} from '../settings-global-toggle.ts';
import { withFakeAdb } from './test-utils/fake-adb.ts';
import { underFakeTimers } from './test-utils/fake-timers.ts';

Expand All @@ -13,8 +17,8 @@ const TOGGLE: AndroidGlobalToggle<'example'> = {
stateKey: 'example',
parseRow: (storedValue) =>
storedValue === '1' ? 'enabled' : storedValue === '0' ? 'disabled' : undefined,
notAppliedReason: 'example-not-applied',
unreadableReason: 'example-unreadable',
notAppliedReason: ANDROID_GLOBAL_TOGGLE_REASONS.mobileDataNotApplied.reason,
unreadableReason: ANDROID_GLOBAL_TOGGLE_REASONS.mobileDataUnreadable.reason,
sampleIntervalMs: 300,
hint: 'Read example_on.',
};
Expand All @@ -32,7 +36,7 @@ test('the sample taken after the settle window runs out still answers with the t
).rejects.toMatchObject({
code: 'COMMAND_FAILED',
details: {
reason: 'example-not-applied',
reason: ANDROID_GLOBAL_TOGGLE_REASONS.mobileDataNotApplied.reason,
example: 'disabled',
storedValue: '0',
dispatched: 'unknown',
Expand Down
3 changes: 1 addition & 2 deletions packages/platform-android/src/__tests__/settings.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { test, vi } from 'vitest';
import assert from 'node:assert/strict';
import { SETTINGS_APP_NOT_PACKAGE_REASON } from '@agent-device/contracts/settings';
import { TEXT_SIZE_CATEGORIES } from '@agent-device/contracts/settings-catalog';
import { AppError, PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
import { readAndroidSetting, setAndroidSetting } from '../settings.ts';
Expand Down Expand Up @@ -227,7 +226,7 @@ test('setAndroidSetting permission refuses an app alias that resolves to an inte
setAndroidSetting(device, 'permission', 'grant', 'settings', {
permissionTarget: 'camera',
}),
{ code: 'INVALID_ARGS', reason: SETTINGS_APP_NOT_PACKAGE_REASON, dispatched: 'no' },
{ code: 'INVALID_ARGS', reason: 'setting_app_not_package', dispatched: 'no' },
);
assert.deepEqual(calls, [CURRENT_USER]);
});
Expand Down
3 changes: 1 addition & 2 deletions packages/platform-android/src/__tests__/text-input.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { test } from 'vitest';
import assert from 'node:assert/strict';
import { ANDROID_SHELL_TEXT_UNSUPPORTED_REASON } from '@agent-device/contracts/input-validation';
import { ANDROID_TEST_IME_OPEN_HINT, fillAndroid, typeAndroid } from '../text-input.ts';
import { assertRejectsAppError } from './test-utils/app-error.ts';
import {
Expand Down Expand Up @@ -320,7 +319,7 @@ test('typeAndroid reports clear error when unicode input is unsupported', async
await assertRejectsAppError(() => typeAndroid(device, '很'), {
code: 'COMMAND_FAILED',
message: /provider-native text injection/i,
reason: ANDROID_SHELL_TEXT_UNSUPPORTED_REASON,
reason: 'android_shell_text_unsupported',
hint: ANDROID_TEST_IME_OPEN_HINT,
});
},
Expand Down
11 changes: 7 additions & 4 deletions packages/platform-android/src/adb-port-reverse.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import { withKeyedLock } from '@agent-device/kernel/keyed-lock';
import { androidAdbResultError } from './adb-failure.ts';
import { normalizeAndroidAdbProvider } from './adb-provider-normalization.ts';
Expand All @@ -25,8 +25,11 @@ export type AndroidExecPortReverseOptions = Readonly<{
noRebind?: boolean;
}>;

const ANDROID_PORT_REVERSE_REBIND_REFUSED_REASON = 'android_port_reverse_rebind_refused';

/** Why an owner-tracked port reverse refuses to touch the device's mapping table. */
const PORT_REVERSE_REASONS = {
// The endpoint already has a device mapping, which a `--no-rebind` reverse never replaces.
rebindRefused: { reason: 'android_port_reverse_rebind_refused', commands: ['open'] },
} as const satisfies ReasonTable<'android adb port reverse'>;
const managedAndroidPortReverseProviders = new WeakSet<AndroidPortReverseProvider>();

export function createAndroidPortReverseManager(
Expand Down Expand Up @@ -169,7 +172,7 @@ function rebindRefusedError(
'COMMAND_FAILED',
`Android port reverse ${requested.local} is already mapped on the device`,
{
reason: ANDROID_PORT_REVERSE_REBIND_REFUSED_REASON,
reason: PORT_REVERSE_REASONS.rebindRefused.reason,
requested,
existing,
hint: `agent-device does not replace an existing reverse mapping on a shared device. Remove the mapping that holds device ${requested.local}, or use another device port.`,
Expand Down
10 changes: 8 additions & 2 deletions packages/platform-android/src/adb-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
relayDeviceShellArgvWithOptions,
relayDeviceShellArgvWithoutOptions,
} from '@agent-device/kernel/device-shell';
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { Readable, Stream, Writable } from 'node:stream';
import type { Rect } from '@agent-device/kernel/snapshot';
import type {
Expand Down Expand Up @@ -596,6 +596,12 @@ export function requireManagedAndroidAdbCommand(command: readonly string[]): voi
if (isAndroidAdbManagedForbiddenCommand(head)) throw transportMismatch('target');
}

/** Why a managed adb transport refuses a call at all. */
const MANAGED_TRANSPORT_REASONS = {
// The call aimed a managed adb transport at another device, target, or server.
transportMismatch: { reason: 'managed-device-transport-mismatch' },
} as const satisfies ReasonTable<'android adb transport'>;

/** What a managed transport refuses to be pointed at: another device, target, or adb server. */
const TRANSPORT_MISMATCH_MESSAGES = {
device: 'Managed ADB transport cannot address another device.',
Expand All @@ -605,7 +611,7 @@ const TRANSPORT_MISMATCH_MESSAGES = {

function transportMismatch(scope: keyof typeof TRANSPORT_MISMATCH_MESSAGES): never {
throw new AppError('COMMAND_FAILED', TRANSPORT_MISMATCH_MESSAGES[scope], {
reason: 'managed-device-transport-mismatch',
reason: MANAGED_TRANSPORT_REASONS.transportMismatch.reason,
});
}

Expand Down
50 changes: 42 additions & 8 deletions packages/platform-android/src/app-lifecycle.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { AppStateRuntimeResult } from '@agent-device/contracts/app-state-runtime';
import { Deadline, sleep } from '@agent-device/host-kit/retry';
import { isCommandTimeoutError } from '@agent-device/host-kit/command';
Expand Down Expand Up @@ -27,6 +27,40 @@ import {
import { androidLaunchCategory, androidLauncherCategories } from './launcher-categories.ts';
import { getAndroidAppState, getAndroidResumedActivity } from './window-state.ts';

/** The `open` refusals this module states in `error.details.reason`. */
const ANDROID_APP_OPEN_REASONS = {
// The `--activity` value is not an Android component name.
invalidActivityComponent: { reason: 'invalid-android-activity-component' },
// The app the helper launched never reached the foreground before the launch budget ran out.
launchNotForeground: { reason: 'android-launch-not-foreground' },
} as const satisfies ReasonTable<'open'>;

/**
* The `close` refusals this module states in `error.details.reason`. `open --relaunch` stops the app
* through the same fences, so the timeout and the probe refusal name `open` too. A Maestro flow's
* `killApp` step guards its kill with the probe refusal too, so `replay` and `test` name it.
*/
const ANDROID_APP_CLOSE_REASONS = {
// A stop fence ended before the app left the foreground or its killed processes exited.
appCloseTimeout: { reason: 'android-app-close-timeout', commands: ['open'] },
// `adb pidof` or the resumed-activity read did not answer, so process state is unknown.
processProbeUnavailable: {
reason: 'android-process-probe-unavailable',
commands: ['open', 'replay', 'test'],
},
} as const satisfies ReasonTable<'close'>;

/** The refusals only a Maestro flow's `killApp` step raises, through `killAndroidPackage`. */
const ANDROID_APP_KILL_REASONS = {
// `am kill` returned and the process is still running; force-stop it instead.
killProcessSurvived: { reason: 'android-kill-process-survived', commands: ['test'] },
// `am kill` only reaps background processes, so it refuses the foreground app.
killRequiresBackgroundApp: {
reason: 'android-kill-requires-background-app',
commands: ['test'],
},
} as const satisfies ReasonTable<'replay'>;

const ANDROID_DEFAULT_CATEGORY = 'android.intent.category.DEFAULT';
const ANDROID_LOCALHOST_HOSTNAMES = new Set(['localhost', '127.0.0.1', '::1', '[::1]']);
/** Owns localhost URL reverses, so a teardown that removes only owned mappings removes them too. */
Expand Down Expand Up @@ -169,7 +203,7 @@ const ANDROID_ACTIVITY_COMPONENT = new RegExp(
function requireAndroidActivityComponent(activity: string): void {
if (ANDROID_ACTIVITY_COMPONENT.test(activity)) return;
throw new AppError('INVALID_ARGS', `Invalid Android activity component: ${activity}`, {
reason: 'invalid-android-activity-component',
reason: ANDROID_APP_OPEN_REASONS.invalidActivityComponent.reason,
activity,
hint: 'Pass --activity as <package>/<Class>, .<Class>, or <Class>, using letters, digits, `_`, `.`, and `$`.',
});
Expand Down Expand Up @@ -273,7 +307,7 @@ async function tryAndroidHelperLaunch(
'COMMAND_FAILED',
'Android helper launch timed out before the application reached the foreground',
{
reason: 'android-launch-not-foreground',
reason: ANDROID_APP_OPEN_REASONS.launchNotForeground.reason,
packageName,
stdout,
timeoutMs: ANDROID_HELPER_OPEN_TIMEOUT_MS,
Expand Down Expand Up @@ -659,7 +693,7 @@ async function killAndroidPackage(device: DeviceInfo, packageName: string): Prom
const resumed = await getAndroidResumedActivity(device);
if (resumed.status === 'resumed' && resumed.package === packageName) {
throw new AppError('COMMAND_FAILED', `Cannot kill foreground app ${packageName}`, {
reason: 'android-kill-requires-background-app',
reason: ANDROID_APP_KILL_REASONS.killRequiresBackgroundApp.reason,
hint: 'Background the app before killApp (for example pressKey: Home): am kill only reaps background processes.',
});
}
Expand All @@ -668,7 +702,7 @@ async function killAndroidPackage(device: DeviceInfo, packageName: string): Prom
'COMMAND_FAILED',
`Could not read resumed activity state before killing ${packageName}`,
{
reason: 'android-process-probe-unavailable',
reason: ANDROID_APP_CLOSE_REASONS.processProbeUnavailable.reason,
hint: 'adb dumpsys did not answer; retry once the device is reachable.',
},
);
Expand All @@ -681,7 +715,7 @@ async function killAndroidPackage(device: DeviceInfo, packageName: string): Prom
const process = await readAndroidPackageProcessState(device, packageName);
if (process === 'running') {
throw new AppError('COMMAND_FAILED', `am kill did not stop ${packageName}`, {
reason: 'android-kill-process-survived',
reason: ANDROID_APP_KILL_REASONS.killProcessSurvived.reason,
hint: 'The process survived am kill (for example a foreground service keeps it alive): use stopApp (am force-stop) to terminate it.',
});
}
Expand All @@ -692,7 +726,7 @@ async function killAndroidPackage(device: DeviceInfo, packageName: string): Prom

function androidPidofUnavailableError(packageName: string): AppError {
return new AppError('COMMAND_FAILED', `Could not read process state for ${packageName}`, {
reason: 'android-process-probe-unavailable',
reason: ANDROID_APP_CLOSE_REASONS.processProbeUnavailable.reason,
hint: 'adb pidof did not answer; retry once the device is reachable.',
});
}
Expand Down Expand Up @@ -734,7 +768,7 @@ const ANDROID_CLOSE_TIMEOUTS: Record<
function androidCloseTimeoutError(packageName: string, phase: AndroidStopFencePhase): AppError {
const { message, timeoutMs } = ANDROID_CLOSE_TIMEOUTS[phase];
return new AppError('COMMAND_FAILED', `Android app ${packageName} ${message}`, {
reason: 'android-app-close-timeout',
reason: ANDROID_APP_CLOSE_REASONS.appCloseTimeout.reason,
phase,
packageName,
timeoutMs,
Expand Down
9 changes: 7 additions & 2 deletions packages/platform-android/src/automation-helper.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { AppError } from '@agent-device/kernel/errors';
import { AppError, type ReasonTable } from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import {
getLiveAndroidSnapshotHelperSession,
Expand Down Expand Up @@ -145,6 +145,11 @@ function decodeHelperIndex(value: string | undefined): number | undefined {
return value !== undefined && /^\d+$/.test(value) ? Number(value) : undefined;
}

const ANDROID_HELPER_INPUT_REASONS = {
// The request had no room left for one helper input attempt, so nothing was sent.
budgetExhausted: { reason: 'android-input-budget-exhausted' },
} as const satisfies ReasonTable<'android input'>;

/**
* The host waits for input up to its cap, or until the request's own deadline when that is sooner.
* A request with no room for one attempt is refused before anything is sent. The refusal is thrown
Expand All @@ -163,7 +168,7 @@ function admitInputTimeoutMs(): number {
'COMMAND_FAILED',
'Android input was not sent: the request has too little time left for one attempt',
{
reason: 'android-input-budget-exhausted',
reason: ANDROID_HELPER_INPUT_REASONS.budgetExhausted.reason,
remainingMs: timeoutMs,
minimumMs: MIN_INPUT_ATTEMPT_MS,
dispatched: 'no',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { normalizeError } from '@agent-device/kernel/errors';
import {
androidClipboardShellCommandUnavailableError,
androidClipboardShellSupportForVerdict,
ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_REASON,
classifyAndroidClipboardShellResponse,
} from './clipboard-shell-response.ts';

Expand Down Expand Up @@ -107,7 +106,7 @@ test('clipboard shell refusal is dispatchable and names the substitute', () => {
assert.equal(error.code, 'UNSUPPORTED_OPERATION');
assert.equal(
(error.details as { reason?: unknown }).reason,
ANDROID_CLIPBOARD_SHELL_COMMAND_UNAVAILABLE_REASON,
'android_clipboard_shell_command_unavailable',
);
assert.match(String(normalizeError(error).hint), /pasting into a focused field/);
});
Loading
Loading