Skip to content

Commit fae04c3

Browse files
authored
fix(errors): typed reasons for the session-app and session-or-selector refusals (#3194)
* feat(kernel): publish typed reasons for session-app and session-or-selector refusals Both refusals answer before anything reaches a device, so a driver must branch on details.reason plus dispatched:no rather than matching the message. Declares the two reason values once at the owning kernel type, with the construction helpers and their normalize/wire coverage. Refs #3181 * fix(apple,android): attach the session-app reason to per-app setting refusals Both owners already refused an appless `settings permission` and an appless iOS `settings location`; each site now states the shared reason instead of leaving prose as the only signal. Both platforms use one reason because the recovery is the same whichever setting asked. The Apple and Android error assertions gained reason and dispatched so the behavior is keyed on details, not on the message. Refs #3181 * fix(daemon): state the session-or-selector reason on the refused route response The daemon refuses a device-bound command before it resolves a target, which is exactly the case where dispatched:no makes a retry safe. The refusal now carries the published reason through errorResponse, and the request-router test proves the reason survives finalizeDaemonResponse to the caller on the returned-error path rather than only at its construction site. Refs #3181 * fix(test): key the e2e appless-cleanup skip on the reason instead of its message The mic-permission cleanup skip matched an exact error string, so a reworded refusal would silently resume retrying a command that can never succeed. It now keys on details.reason, and the suite asserts a byte-identical message with no reason still exhausts its retries — the prose alone must never activate the guard. Documents both published reasons with their recovery in the user docs. Refs #3181 * style: repository-wide format * refactor(apple,android): drop the unused assertThrowsAppError and split the details check The affected audit surfaced both test helpers as dead exports and flagged the cyclomatic growth from the new reason/dispatched branches. Removing the sync assertion, which no test imported, and moving the machine-readable checks into their own function keeps each assertion at the complexity it had before. Refs #3181 * fix(settings): complete the session-app reason across the whole refusal family Every per-app settings refusal must be identifiable by reason, not only the ones first converted: the daemon's clear-app-state pre-check and the Apple, Android, and HarmonyOS owner throws now answer with session_app_required and dispatched:no as well. The clear-app-state doc bullet states the refusal. Docs corrections: session_app_required is raised by the settings handlers after device routing, so the dispatched vocabulary entry describes only the session-or-selector refusal as pre-routing; and the permission bullet no longer claims Android on/off location or macOS system-level permissions need a session app, which they do not. The e2e skip's success case now pairs the reason with different message wording, so a guard that also required the legacy string would fail: only the reason triggers the skip. * docs(settings): name the app-id alternative for recovering from session_app_required A setting that takes an app id, like clear-app-state, recovers by naming the app on the request itself; scripts need not open the app just to satisfy that refusal. * refactor(kernel): scope the refusal-reason map to what it declares PRE_DISPATCH_REFUSAL_REASONS states the kernel-owned subset whose refusals always disclose dispatched:no, instead of a name that implies it holds every published reason (the WebDriver and other producer reasons live beside their own disclosures). The map's own doc names the versioned docs as the wire vocabulary and the disclosure table as the producer registry. The session-or-selector refusal gains its daemon.route row in contracts/fixtures/dispatch-disclosure.json, driven through the real router with an unopened session. That command declares no recording effect, so the dispatched:no the row asserts can only come from the producer rather than the read-only seam. The e2e cleanup fixture builds its refusal from sessionAppRequiredDetails() instead of re-typing the details shape, and the permission bullet stops implying a request can name an app for settings permission while #3179 is open.
1 parent 294dc7d commit fae04c3

22 files changed

Lines changed: 380 additions & 39 deletions

File tree

‎contracts/fixtures/dispatch-disclosure.json‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,12 @@
8989
"trigger": "get through the request router: the router, not only the interaction route, discloses no for a command the registry declares observes-app",
9090
"dispatched": "no"
9191
},
92+
{
93+
"id": "daemon.route.session-or-selector-refusal",
94+
"producer": "daemon",
95+
"trigger": "a device-bound command with no active session and no device selector: requireSessionOrExplicitSelector refuses before any target resolves, carrying details.reason session_or_device_selector_required",
96+
"dispatched": "no"
97+
},
9298
{
9399
"id": "daemon.route.find-type-refused-after-focus",
94100
"producer": "daemon",

‎packages/kernel/src/errors.test.ts‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,76 @@ import assert from 'node:assert/strict';
22
import { test } from 'vitest';
33
import {
44
AppError,
5+
defaultHintForCode,
56
discloseDispatch,
67
discloseDispatchAfterSteps,
78
normalizeError,
9+
PRE_DISPATCH_REFUSAL_REASONS,
10+
sessionAppRequiredDetails,
11+
sessionOrDeviceSelectorRequiredDetails,
812
throwDaemonError,
913
readElementMatchCandidateRefs,
1014
readErrorCandidateViews,
1115
summarizeCommandAttemptFailures,
1216
} from './errors.ts';
1317

18+
test('the pre-dispatch refusal reasons are the values consumers branch on', () => {
19+
assert.deepEqual(PRE_DISPATCH_REFUSAL_REASONS, {
20+
sessionAppRequired: 'session_app_required',
21+
sessionOrDeviceSelectorRequired: 'session_or_device_selector_required',
22+
});
23+
});
24+
25+
for (const [label, details, code, message] of [
26+
[
27+
'sessionAppRequired',
28+
sessionAppRequiredDetails(),
29+
'INVALID_ARGS',
30+
'permission setting requires an active app in session',
31+
],
32+
[
33+
'sessionOrDeviceSelectorRequired',
34+
sessionOrDeviceSelectorRequiredDetails(),
35+
'INVALID_ARGS',
36+
'clipboard requires an active session or an explicit device selector (e.g. --platform ios).',
37+
],
38+
] as const) {
39+
test(`${label} refusal carries its reason and dispatched:no through normalize and the wire`, () => {
40+
const normalized = normalizeError(new AppError(code, message, details));
41+
assert.equal(normalized.message, message);
42+
assert.equal(normalized.details?.reason, details.reason);
43+
assert.equal(normalized.details?.dispatched, 'no');
44+
assert.throws(
45+
() => throwDaemonError(normalized),
46+
(error: unknown) =>
47+
error instanceof AppError &&
48+
error.details?.reason === details.reason &&
49+
error.details?.dispatched === 'no',
50+
);
51+
});
52+
53+
test(`${label} reason survives a second normalization of the wire shape`, () => {
54+
const once = normalizeError(new AppError(code, message, details));
55+
const twice = normalizeError(new AppError(once.code, once.message, once.details));
56+
assert.deepEqual(twice.details, once.details);
57+
});
58+
}
59+
60+
test('a published refusal keeps the INVALID_ARGS default hint — the reason carries the extra fact', () => {
61+
for (const details of [sessionAppRequiredDetails(), sessionOrDeviceSelectorRequiredDetails()]) {
62+
const normalized = normalizeError(new AppError('INVALID_ARGS', 'refused', details));
63+
assert.equal(normalized.hint, defaultHintForCode('INVALID_ARGS'));
64+
}
65+
});
66+
67+
test('a sibling INVALID_ARGS refusal without a reason cannot activate a reason-driven consumer', () => {
68+
const unrelated = normalizeError(
69+
new AppError('INVALID_ARGS', 'clipboard requires a subcommand: read or write'),
70+
);
71+
assert.equal(unrelated.details?.reason, undefined);
72+
assert.equal('dispatched' in (unrelated.details ?? {}), false);
73+
});
74+
1475
test('normalizeError retains redacted nested command errors through repeated normalization', () => {
1576
const stderr = `Launch request denied\n${'Context line\n'.repeat(50)}Underlying reason: token=private-value device locked`;
1677
const expected = stderr.replace('private-value', '[REDACTED]');

‎packages/kernel/src/errors.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,61 @@ export function throwDaemonError(error: DaemonError): never {
251251
);
252252
}
253253

254+
/**
255+
* The `details.reason` values a pre-dispatch refusal answers with when the caller must know *why* a
256+
* request was stopped rather than read the prose: what a caller does to recover is the reason's
257+
* meaning, and the reason strings are wire vocabulary (documented in
258+
* `website/docs/docs/commands.md`). This map is the kernel-owned subset whose refusals always
259+
* state `dispatched: 'no'` too — a refusal that provably reached no device is exactly what makes a
260+
* retry safe. Other producers own their own reason strings beside their own disclosures.
261+
*/
262+
export const PRE_DISPATCH_REFUSAL_REASONS = {
263+
/**
264+
* A per-app setting was asked for while the request carries no app — the session binds none and,
265+
* for a setting that takes an app id, none was named for this request. Recovery: `open` the app
266+
* (or name the app id on the request), then retry. The daemon's `clear-app-state` pre-check and
267+
* the Apple, Android, and HarmonyOS owners all answer with this one reason for every per-app
268+
* setting, because the recovery is the same whichever setting asked.
269+
*/
270+
sessionAppRequired: 'session_app_required',
271+
/**
272+
* A device-bound command was asked for with neither an active session nor an explicit device
273+
* selector, so there was no target to route to. Recovery: `open` a session or pass `--platform`
274+
* or another device selector, then retry. One reason covers every command that asks the daemon to
275+
* find a device for it; the command it asks for stays in the message.
276+
*/
277+
sessionOrDeviceSelectorRequired: 'session_or_device_selector_required',
278+
} as const;
279+
280+
export type PreDispatchRefusalReason =
281+
(typeof PRE_DISPATCH_REFUSAL_REASONS)[keyof typeof PRE_DISPATCH_REFUSAL_REASONS];
282+
283+
/** The details of a refusal that stopped a request before anything could reach a device. */
284+
export type RefusalDetails<TReason extends PreDispatchRefusalReason> = AppErrorDetails & {
285+
reason: TReason;
286+
dispatched: 'no';
287+
};
288+
289+
/** The details of a per-app setting refused for want of an app. */
290+
export function sessionAppRequiredDetails(): RefusalDetails<
291+
(typeof PRE_DISPATCH_REFUSAL_REASONS)['sessionAppRequired']
292+
> {
293+
return {
294+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
295+
dispatched: 'no',
296+
};
297+
}
298+
299+
/** The details of a command refused for want of a target to route to. */
300+
export function sessionOrDeviceSelectorRequiredDetails(): RefusalDetails<
301+
(typeof PRE_DISPATCH_REFUSAL_REASONS)['sessionOrDeviceSelectorRequired']
302+
> {
303+
return {
304+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionOrDeviceSelectorRequired,
305+
dispatched: 'no',
306+
};
307+
}
308+
254309
/**
255310
* `details.reason` of a request its requester abandoned — an explicit cancel or
256311
* a client disconnect. One definition, so every layer that must let a

‎packages/platform-android/src/__tests__/settings-permission.test.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { androidRevokedPermissionWarning } from '../settings-permission.ts';
55
import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts';
66
import { assertRejectsAppError } from './test-utils/app-error.ts';
77
import { withFakeAdb } from './test-utils/fake-adb.ts';
8+
import { PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
89

910
// #1796. Two invariants decide every case here:
1011
// * `pm` defaults grant/revoke and the permission-flag operations to UserHandle.USER_SYSTEM,
@@ -314,13 +315,18 @@ test.each([
314315
);
315316
});
316317

317-
test('setAndroidSetting permission requires an app in session', async () => {
318+
test('setAndroidSetting permission requires an app in session with the published reason', async () => {
318319
await assertRejectsAppError(
319320
() =>
320321
setAndroidSetting(ANDROID_EMULATOR, 'permission', 'deny', undefined, {
321322
permissionTarget: 'camera',
322323
}),
323-
{ code: 'INVALID_ARGS', message: /requires an active app in session/ },
324+
{
325+
code: 'INVALID_ARGS',
326+
message: /requires an active app in session/,
327+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
328+
dispatched: 'no',
329+
},
324330
);
325331
});
326332

‎packages/platform-android/src/__tests__/settings.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { test } from 'vitest';
22
import assert from 'node:assert/strict';
33
import { TEXT_SIZE_CATEGORIES } from '@agent-device/contracts/settings';
4+
import { PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
45
import { readAndroidSetting, setAndroidSetting } from '../settings.ts';
56
import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts';
67
import { assertRejectsAppError } from './test-utils/app-error.ts';
@@ -63,6 +64,19 @@ test('setAndroidSetting clear-app-state force stops and clears package data', as
6364
);
6465
});
6566

67+
test('setAndroidSetting clear-app-state refuses an appless session with the published reason', async () => {
68+
await withFakeAdb(
69+
(args) => ({ stderr: `unexpected args: ${args.join(' ')}`, exitCode: 1 }),
70+
async ({ device }) => {
71+
await assertRejectsAppError(() => setAndroidSetting(device, 'clear-app-state', 'clear'), {
72+
code: 'INVALID_ARGS',
73+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
74+
dispatched: 'no',
75+
});
76+
},
77+
);
78+
});
79+
6680
test('setAndroidSetting fingerprint retries emulator command when shell cmd fingerprint fails', async () => {
6781
await withFakeAdb(
6882
(args) => {

‎packages/platform-android/src/__tests__/test-utils/app-error.ts‎

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,29 @@
11
import assert from 'node:assert/strict';
22
import { AppError, normalizeError } from '@agent-device/kernel/errors';
33

4-
type ExpectedAppError = { code: string; message?: RegExp; hint?: string | RegExp };
4+
type ExpectedAppError = {
5+
code: string;
6+
message?: RegExp;
7+
hint?: string | RegExp;
8+
/** The machine-readable `details.reason` the refusal must carry; key behavior on this, not on `message`. */
9+
reason?: string;
10+
/** The `details.dispatched` disclosure the producer must have proven. */
11+
dispatched?: 'no' | 'unknown';
12+
};
13+
14+
/** Keys the assertion on the machine-readable refusal facts rather than on `message` prose. */
15+
function assertExpectedErrorDetails(error: AppError, expected: ExpectedAppError): void {
16+
if (expected.reason !== undefined) {
17+
assert.equal(
18+
error.details?.reason,
19+
expected.reason,
20+
`expected details.reason ${expected.reason}, got ${JSON.stringify(error.details)}`,
21+
);
22+
}
23+
if (expected.dispatched !== undefined) {
24+
assert.equal(error.details?.dispatched, expected.dispatched);
25+
}
26+
}
527

628
function assertAppError(error: unknown, expected: ExpectedAppError): true {
729
assert.ok(
@@ -10,6 +32,7 @@ function assertAppError(error: unknown, expected: ExpectedAppError): true {
1032
);
1133
assert.equal(error.code, expected.code);
1234
if (expected.message) assert.match(error.message, expected.message);
35+
assertExpectedErrorDetails(error, expected);
1336
if (expected.hint !== undefined) {
1437
const { hint } = normalizeError(error);
1538
assert.ok(typeof hint === 'string', `expected a hint on ${error.code}, got ${String(hint)}`);
@@ -25,7 +48,3 @@ export async function assertRejectsAppError(
2548
): Promise<void> {
2649
await assert.rejects(run, (error: unknown) => assertAppError(error, expected));
2750
}
28-
29-
export function assertThrowsAppError(fn: () => unknown, expected: ExpectedAppError): void {
30-
assert.throws(fn, (error: unknown) => assertAppError(error, expected));
31-
}

‎packages/platform-android/src/settings.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
AppError,
3+
sessionAppRequiredDetails,
34
summarizeCommandAttemptFailures,
45
type CommandAttemptFailure,
56
} from '@agent-device/kernel/errors';
@@ -124,6 +125,7 @@ export async function setAndroidSetting(
124125
throw new AppError(
125126
'INVALID_ARGS',
126127
'settings clear-app-state requires an app id or an active app session.',
128+
sessionAppRequiredDetails(),
127129
);
128130
}
129131
const resolved = await resolveAndroidApp(device, appPackage);
@@ -162,7 +164,11 @@ export async function setAndroidSetting(
162164
}
163165
case 'permission': {
164166
if (!appPackage) {
165-
throw new AppError('INVALID_ARGS', 'permission setting requires an active app in session');
167+
throw new AppError(
168+
'INVALID_ARGS',
169+
'permission setting requires an active app in session',
170+
sessionAppRequiredDetails(),
171+
);
166172
}
167173
return await setAndroidPermission(device, appPackage, state, options);
168174
}

‎packages/platform-apple/src/__tests__/app-error.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,34 @@ type ExpectedAppError = {
88
normalizedMessage?: RegExp;
99
/** `null` asserts the failure attached no hint of its own, so normalization falls back to the code default. */
1010
hint?: string | RegExp | null;
11+
/** The machine-readable `details.reason` the refusal must carry; key behavior on this, not on `message`. */
12+
reason?: string;
13+
/** The `details.dispatched` disclosure the producer must have proven. */
14+
dispatched?: 'no' | 'unknown';
1115
};
1216

17+
/** Keys the assertion on the machine-readable refusal facts rather than on `message` prose. */
18+
function assertExpectedErrorDetails(error: AppError, expected: ExpectedAppError): void {
19+
if (expected.reason !== undefined) {
20+
assert.equal(
21+
error.details?.reason,
22+
expected.reason,
23+
`expected details.reason ${expected.reason}, got ${JSON.stringify(error.details)}`,
24+
);
25+
}
26+
if (expected.dispatched !== undefined) {
27+
assert.equal(error.details?.dispatched, expected.dispatched);
28+
}
29+
}
30+
1331
function assertAppError(error: unknown, expected: ExpectedAppError): true {
1432
assert.ok(
1533
error instanceof AppError,
1634
`expected AppError, got ${error?.constructor?.name ?? typeof error}: ${String(error)}`,
1735
);
1836
assert.equal(error.code, expected.code);
1937
if (expected.message) assert.match(error.message, expected.message);
38+
assertExpectedErrorDetails(error, expected);
2039
if (expected.normalizedMessage) {
2140
assert.match(normalizeError(error).message, expected.normalizedMessage);
2241
}
@@ -37,7 +56,3 @@ export async function assertRejectsAppError(
3756
): Promise<void> {
3857
await assert.rejects(run, (error: unknown) => assertAppError(error, expected));
3958
}
40-
41-
export function assertThrowsAppError(fn: () => unknown, expected: ExpectedAppError): void {
42-
assert.throws(fn, (error: unknown) => assertAppError(error, expected));
43-
}

‎packages/platform-apple/src/core/__tests__/app-settings.test.ts‎

Lines changed: 56 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ const simulatorActual = await vi.importActual<typeof import('../simulator.ts')>(
2828
import { setIosSetting } from '../app-settings.ts';
2929
import { withMockedMacOsHelper } from './macos-helper-test-utils.ts';
3030
import { ensureBootedSimulator } from '../simulator.ts';
31-
import { AppError } from '@agent-device/kernel/errors';
31+
import { AppError, PRE_DISPATCH_REFUSAL_REASONS } from '@agent-device/kernel/errors';
3232
import { runCmd } from '@agent-device/host-kit/command';
3333
import { retryWithPolicy } from '@agent-device/host-kit/retry';
3434
import { assertRejectsAppError } from '../../__tests__/app-error.ts';
@@ -315,6 +315,61 @@ test('setIosSetting location set sends simulator latitude and longitude', async
315315
);
316316
});
317317

318+
test('setIosSetting permission requires an app in session with the published reason', async () => {
319+
await withFakeAppleTool(
320+
(args) => {
321+
if (isSimctlListDevices(args)) return BOOTED_SIM_LIST_JSON;
322+
return unexpectedArgs(args);
323+
},
324+
async () => {
325+
await assertRejectsAppError(
326+
() =>
327+
setIosSetting(IOS_TEST_SIMULATOR, 'permission', 'grant', undefined, {
328+
permissionTarget: 'camera',
329+
}),
330+
{
331+
code: 'INVALID_ARGS',
332+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
333+
dispatched: 'no',
334+
},
335+
);
336+
},
337+
);
338+
});
339+
340+
test('setIosSetting location refuses an appless session with the published reason', async () => {
341+
mockEnsureBootedSimulator.mockResolvedValue(undefined);
342+
343+
await withFakeAppleTool(
344+
(args) => unexpectedArgs(args),
345+
async () => {
346+
await assertRejectsAppError(() => setIosSetting(IOS_TEST_SIMULATOR, 'location', 'on'), {
347+
code: 'INVALID_ARGS',
348+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
349+
dispatched: 'no',
350+
});
351+
},
352+
);
353+
});
354+
355+
test('setIosSetting clear-app-state refuses an appless session with the published reason', async () => {
356+
mockEnsureBootedSimulator.mockResolvedValue(undefined);
357+
358+
await withFakeAppleTool(
359+
(args) => unexpectedArgs(args),
360+
async () => {
361+
await assertRejectsAppError(
362+
() => setIosSetting(IOS_TEST_SIMULATOR, 'clear-app-state', 'clear'),
363+
{
364+
code: 'INVALID_ARGS',
365+
reason: PRE_DISPATCH_REFUSAL_REASONS.sessionAppRequired,
366+
dispatched: 'no',
367+
},
368+
);
369+
},
370+
);
371+
});
372+
318373
test('setIosSetting appearance toggle flips current simulator appearance', async () => {
319374
await withFakeAppleTool(
320375
(args) => {

0 commit comments

Comments
 (0)