Repository navigation
Expand file tree
/
Copy pathsettings.ts
More file actions
416 lines (378 loc) · 19 KB
/
Copy pathsettings.ts
File metadata and controls
416 lines (378 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
import { AppError } from '@agent-device/kernel/errors';
/**
* The `settings permission` vocabulary, declared once. These collections are what the parsers
* below, the public client permission types, the CLI's membership sets, and the permission-name
* fragments of `settings` help and its invalid-args message are built from, and their order is
* the order `settings` help lists the names in.
*
* Acceptance is not support: each backend keeps its own target mapping and its own support check,
* so a name accepted here never promises that the selected platform serves it.
*/
export const PERMISSION_ACTIONS = ['grant', 'deny', 'reset'] as const;
export const PERMISSION_MODES = ['full', 'limited'] as const;
/** The app-scoped targets, the only ones `parsePermissionTarget` accepts. */
export const MOBILE_PERMISSION_TARGETS = [
'all',
'camera',
'microphone',
'photos',
'contacts',
'contacts-limited',
'notifications',
'calendar',
'location',
'location-always',
'media-library',
'motion',
'reminders',
'siri',
] as const;
/** The desktop targets the CLI and the public client accept; `parsePermissionTarget` refuses them. */
export const MACOS_PERMISSION_TARGETS = [
'accessibility',
'screen-recording',
'input-monitoring',
] as const;
export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
export type PermissionMode = (typeof PERMISSION_MODES)[number];
export type MobilePermissionTarget = (typeof MOBILE_PERMISSION_TARGETS)[number];
/**
* The app-scoped vocabulary `parsePermissionTarget` returns. The public client's `PermissionTarget`
* in `client-settings.ts` is wider: it also names the macOS targets.
*/
export type PermissionTarget = MobilePermissionTarget;
/**
* The preferred-text-size ladder `settings text-size` accepts, in the order `settings` help lists
* it. Apple serves it natively — `simctl ui <device> content_size` reads and writes exactly these
* names — and Android serves it through its `system font_scale` multiplier, so this ladder is the
* cross-platform vocabulary and each owner maps it in its own native terms. Acceptance is not
* support: an owner that cannot serve the ladder refuses at admission, on its own fact.
*/
export const TEXT_SIZE_CATEGORIES = [
'extra-small',
'small',
'medium',
'large',
'extra-large',
'extra-extra-large',
'extra-extra-extra-large',
'accessibility-medium',
'accessibility-large',
'accessibility-extra-large',
'accessibility-extra-extra-large',
'accessibility-extra-extra-extra-large',
] as const;
export type TextSizeCategory = (typeof TEXT_SIZE_CATEGORIES)[number];
/**
* The appearances `settings appearance` accepts, in the order `settings` help lists them. Apple
* applies them natively; Android maps them onto `ui_night_mode`. Acceptance is not support.
*/
export const APPEARANCE_ACTIONS = ['light', 'dark', 'toggle'] as const;
export type AppearanceAction = (typeof APPEARANCE_ACTIONS)[number];
/**
* The state spellings `settings <setting> <state>` accepts. Unlike the appearance and permission
* vocabularies these are aliases onto a boolean rather than a name the device echoes back, so
* membership — not {@link findVocabularyName} — decides, and padding stays rejected: an
* `adb shell settings put` argument with a stray space in it is a caller bug, not a spelling.
*/
const SETTING_STATE_ON = ['on', 'true', '1'];
const SETTING_STATE_OFF = ['off', 'false', '0'];
/**
* The settings that answer a bare `settings <setting>` with the value the target holds. This is the
* vocabulary every settings type and every settings owner reads it from; the matching value is
* `READABLE_SETTINGS` in `platform-runtime-operations.ts`, where the CLI hub can evaluate it, and
* that module pins the two equal in both directions at compile time.
*/
export type ReadableSetting = 'text-size';
/**
* What `text-size` answers with. The ladder is shared across platforms, so a read names the
* category the ladder calls the device's value *and* the value the platform itself reported: an
* Apple content-size name, or an Android `font_scale` multiplier. The ladder is coarser than any
* one platform's own scale, and `platformValue` is what keeps a normalized answer auditable.
*/
export type TextSizeSettingPayload = Readonly<{
setting: 'text-size';
category: TextSizeCategory;
platformValue: string;
}>;
/**
* The payload a readable setting answers with, keyed by the setting that answered. Each readable
* setting has its own shape — a category and a multiplier are not the same observation — so the
* discriminant is what lets a response be composed, recorded, and printed from one place without
* assuming every setting is a ladder rung. A second readable setting joins this union and supplies
* its own sentence in `describeSettingRead`, which is where the compiler then asks for it.
*/
export type ReadSettingResult = TextSizeSettingPayload;
/** Builds the ladder's read payload, so no owner renames its keys or drops the platform value. */
export function textSizeSettingPayload(
category: TextSizeCategory,
platformValue: string,
): TextSizeSettingPayload {
return Object.freeze({ setting: 'text-size', category, platformValue });
}
/** The one sentence a settings read answers with, per payload shape rather than per call site. */
export function describeSettingRead(result: ReadSettingResult): string {
return `Text size is ${result.category}`;
}
/**
* The sentence a settings mutation answers with. It belongs to the vocabulary rather than the daemon
* because it is a claim about the setting: `clear-app-state` names the app it cleared and `text-size`
* names the rung it applied, and both are the same words whoever performs the write.
*/
export function describeSettingWrite(
setting: string,
state: string,
appBundleId: string | undefined,
): string {
if (setting === 'clear-app-state') return `Cleared user data for ${appBundleId}`;
if (setting === 'text-size') return `Text size set to ${state}`;
return `Updated setting: ${setting}`;
}
export type SettingOptions = {
permissionTarget?: string;
permissionMode?: string;
latitude?: number;
longitude?: number;
};
/**
* Whether naming an app for one mutation can mean anything on one target.
*
* `app-scoped` is the shape the public `app` field exists for: the change lands on that bundle id
* or package (`simctl privacy`, Android's `pm`). `device-level` is a mutation the same command
* serves for the whole device: Android's on/off `location` writes the global `location_mode`, and
* the macOS host's permissions are TCC grants to the host process, so neither can consume an app.
* `unknown` covers every combination this table does not settle — a setting with no app shape and no
* device-wide write of its own (`wifi` on the macOS host) among them — and is deliberately not a
* verdict: support belongs to the owner's runtime fact, which answers a setting it does not serve
* (`permission` on HarmonyOS) with its own refusal rather than with a complaint about an argument it
* never read.
*/
export type SettingsAppScope = 'app-scoped' | 'device-level' | 'unknown';
/**
* What kind of target a `settings` mutation runs on, as far as consuming an app is concerned:
* the Apple family, the macOS host, or the non-Apple targets that share the mobile app shape
* (Android, HarmonyOS, Vega, Linux, web). The daemon derives it from a device with the kernel's
* own predicates; being app-scoped here is a claim about the shape of the change, never about
* support — an owner that serves no such setting answers with its own refusal.
*/
export type SettingsTargetFamily = 'apple' | 'mobile' | 'macos-host';
/**
* The one table deciding whether an app named on a `settings` request is consumed. It is keyed on
* the target family, a fact the daemon derives from the device before binding a runtime, and it
* stays honest by settling only the combinations whose owner behavior is already fixed elsewhere:
* `clear-app-state` is app-scoped wherever it is served (`isMacOsSettingSupported` keeps macOS out
* of that claim), `permission` is app-scoped on every non-Apple mobile target and on Apple and
* host-level on macOS, and on/off `location` is app-scoped only on Apple, where it maps to a
* privacy grant — while `location set` moves the device's own location for everyone.
*/
export function settingsAppScope(
family: SettingsTargetFamily,
setting: string,
state: string | undefined,
): SettingsAppScope {
const normalizedSetting = setting.trim().toLowerCase();
if (normalizedSetting === 'clear-app-state') {
return family === 'macos-host' ? 'unknown' : 'app-scoped';
}
if (normalizedSetting === 'permission') {
return family === 'macos-host' ? 'device-level' : 'app-scoped';
}
if (normalizedSetting === 'location') return locationAppScope(family, state);
return 'unknown';
}
/**
* One on/off `location` is a privacy grant only on Apple, where it maps to `simctl privacy`; on
* the other mobile targets it writes the global `location_mode`, and `set` moves the device's own
* location for everyone. A state this ladder does not name settles nothing, and the macOS host,
* whose location surface `isMacOsSettingSupported` keeps out of the settings vocabulary, is no
* verdict either.
*/
function locationAppScope(
family: SettingsTargetFamily,
state: string | undefined,
): SettingsAppScope {
const normalizedState = state?.trim().toLowerCase();
if (normalizedState === 'set') return 'device-level';
if (normalizedState === undefined || (normalizedState !== 'on' && normalizedState !== 'off')) {
return 'unknown';
}
if (family === 'apple') return 'app-scoped';
if (family === 'mobile') return 'device-level';
return 'unknown';
}
/**
* The reason a request is told its app names nothing: what a caller does about it — drop the app or
* move to a target whose mutation is app-scoped — is the reason's meaning, so a driver can branch
* on `error.details.reason` instead of the prose. Paired with `dispatched: no`, because the
* refusal runs before a device is touched.
*/
export const SETTINGS_APP_NOT_CONSUMED_REASON = 'setting_app_not_consumed';
/**
* The refusal a mutation answers with when its target consumes no app: the code, sentence, typed
* details, and hint as data, so the daemon can answer with it through its own response builder
* rather than by unwrapping an error the CLI would then re-normalize. The `app` that named nothing
* stays in `details` — the caller asked about that bundle id and the answer should quote it back.
*/
export function settingsAppNotConsumedRefusal(
setting: string,
state: string | undefined,
app: string,
): {
code: 'INVALID_ARGS';
message: string;
details: Record<string, unknown>;
hint: string;
} {
const described = state === undefined ? setting : `${setting} ${state}`;
return {
code: 'INVALID_ARGS',
message: `settings ${described} applies to the target itself, not to an app: ${app} names nothing it can grant or revoke.`,
details: {
reason: SETTINGS_APP_NOT_CONSUMED_REASON,
dispatched: 'no',
setting: described,
app,
},
hint: `Drop the --app option and run \`settings ${described}\`, or aim the app at an app-scoped setting such as \`settings permission grant location --app ${app}\`.`,
};
}
const SETTINGS_WIFI_USAGE = '<wifi|airplane|location> <on|off>';
const SETTINGS_LOCATION_SET_USAGE = 'location set <lat> <lon>';
const SETTINGS_ANIMATIONS_USAGE = 'animations <on|off>';
const SETTINGS_APPEARANCE_USAGE = `appearance <${APPEARANCE_ACTIONS.join('|')}>`;
const SETTINGS_FACEID_USAGE = 'faceid <match|nonmatch|enroll|unenroll>';
const SETTINGS_TOUCHID_USAGE = 'touchid <match|nonmatch|enroll|unenroll>';
const SETTINGS_FINGERPRINT_USAGE = 'fingerprint <match|nonmatch>';
const SETTINGS_CLEAR_APP_STATE_USAGE = 'clear-app-state [app-id]';
const SETTINGS_RESET_KEYCHAIN_USAGE = 'reset-keychain clear';
/**
* The bracket is what makes `settings text-size` a read: the ladder is the write form, and the bare
* setting asks the owner for the category it currently holds.
*/
const SETTINGS_TEXT_SIZE_USAGE = `text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`;
const SETTINGS_PERMISSION_USAGE = `permission <${PERMISSION_ACTIONS.join('|')}> <${MOBILE_PERMISSION_TARGETS.join('|')}> [${PERMISSION_MODES.join('|')}]`;
/**
* The macOS permission form. Its action list is the subset the macOS owner serves (`deny` is
* refused there), so it stays a literal while the accepted names come from the vocabulary.
*/
export const SETTINGS_MACOS_PERMISSION_USAGE = `permission <grant|reset> <${MACOS_PERMISSION_TARGETS.join('|')}>`;
const SETTINGS_MACOS_SUPPORTED_MESSAGE = `macOS supports only settings ${SETTINGS_APPEARANCE_USAGE} and settings ${SETTINGS_MACOS_PERMISSION_USAGE}. wifi|airplane|location|animations|text-size remain unsupported on macOS.`;
export const SETTINGS_USAGE_OVERRIDE = [
`settings ${SETTINGS_WIFI_USAGE}`,
`settings ${SETTINGS_LOCATION_SET_USAGE}`,
`settings ${SETTINGS_ANIMATIONS_USAGE}`,
`settings ${SETTINGS_APPEARANCE_USAGE}`,
`settings ${SETTINGS_TEXT_SIZE_USAGE}`,
`settings ${SETTINGS_FACEID_USAGE}`,
`settings ${SETTINGS_TOUCHID_USAGE}`,
`settings ${SETTINGS_FINGERPRINT_USAGE}`,
`settings ${SETTINGS_CLEAR_APP_STATE_USAGE}`,
`settings ${SETTINGS_RESET_KEYCHAIN_USAGE}`,
`settings ${SETTINGS_PERMISSION_USAGE}`,
`settings ${SETTINGS_MACOS_PERMISSION_USAGE}`,
].join(' | ');
export const SETTINGS_INVALID_ARGS_MESSAGE = `settings requires ${SETTINGS_WIFI_USAGE}, ${SETTINGS_LOCATION_SET_USAGE}, ${SETTINGS_ANIMATIONS_USAGE}, ${SETTINGS_APPEARANCE_USAGE}, ${SETTINGS_TEXT_SIZE_USAGE}, ${SETTINGS_FACEID_USAGE}, ${SETTINGS_TOUCHID_USAGE}, ${SETTINGS_FINGERPRINT_USAGE}, ${SETTINGS_CLEAR_APP_STATE_USAGE}, ${SETTINGS_RESET_KEYCHAIN_USAGE}, ${SETTINGS_PERMISSION_USAGE}, or ${SETTINGS_MACOS_PERMISSION_USAGE}`;
export function isMacOsSettingSupported(setting: string): boolean {
const normalized = setting.trim().toLowerCase();
return normalized === 'appearance' || normalized === 'permission';
}
export function getUnsupportedMacOsSettingMessage(setting: string): string {
return `Unsupported macOS setting: ${setting}. ${SETTINGS_MACOS_SUPPORTED_MESSAGE}`;
}
/**
* The category a caller asked for. `simctl` exits 0 with `Invalid argument` for a category it does
* not know, so a write must never delegate validation to the tool: every surface parses here
* first, and the refusal names the whole ladder.
*/
export function parseTextSizeCategory(value: string | undefined): TextSizeCategory {
const parsed = readTextSizeCategory(value);
if (parsed !== undefined) return parsed;
throw new AppError('INVALID_ARGS', invalidTextSizeMessage(value));
}
/** The refusal every surface that rejects an off-ladder category answers with. */
export function invalidTextSizeMessage(value: string | undefined): string {
return `Invalid text size: ${value ?? ''}. Use ${TEXT_SIZE_CATEGORIES.join('|')}.`;
}
/** The category an owner reads back, or `undefined` for a value the ladder does not name. */
export function readTextSizeCategory(value: string | undefined): TextSizeCategory | undefined {
return findVocabularyName(TEXT_SIZE_CATEGORIES, value);
}
/**
* What a setting declares to refuse a leaf it was never verified on: the sentence, the next command
* to run, and the reason both legs of that setting answer with. The shape is declared here so every
* setting's refusal is checked against it at its declaration, and the Apple leaf guard can name it
* without inventing a second vocabulary.
*/
export type AppleSettingLeafRefusal = Readonly<{
message: string;
hint: string;
reason: 'setting-unsupported-on-leaf';
}>;
/**
* The one refusal an Apple target gives for a text-size request its leaf does not serve, shared by
* the three surfaces that can answer it: the daemon (before it binds, so a request that never touched
* a device also never expires the session ref frame), the Apple runtime's read fact, and the Apple
* owner's own guard. The Apple write fact is one claim for the whole simulator family and
* `simctl ui <device> content_size` is narrower than that, which is why a per-setting refusal has to
* exist at all; a per-setting runtime fact is where it belongs once the fact model carries one, and
* until then this is the single declaration rather than three copies of the prose.
*/
export const APPLE_TEXT_SIZE_LEAF_REFUSAL = Object.freeze({
message: 'Reading or setting a text size is supported on iOS and iPadOS simulators.',
hint: 'Run `xcrun simctl ui <device> content_size` on a booted iPhone or iPad simulator.',
reason: 'setting-unsupported-on-leaf',
} as const) satisfies AppleSettingLeafRefusal;
/**
* Simulator biometrics are driven through BiometricKit_Sim notifications, which only the iPhone and
* iPad simulator runtimes observe; a post on an Apple TV or Vision Pro simulator exits 0 and changes
* nothing, so the leaf is refused before anything is posted.
*/
export const APPLE_BIOMETRIC_LEAF_REFUSAL = Object.freeze({
message: 'Face ID and Touch ID simulation is supported on iOS and iPadOS simulators.',
hint: 'Select a booted iPhone or iPad simulator, then run `settings faceid <state>` or `settings touchid <state>`.',
reason: 'setting-unsupported-on-leaf',
} as const) satisfies AppleSettingLeafRefusal;
/** The one membership rule every settings-vocabulary parser shares: a name matches itself, any casing. */
function findVocabularyName<const TNames extends readonly string[]>(
names: TNames,
value: string | undefined,
): TNames[number] | undefined {
const normalized = value?.trim().toLowerCase();
return normalized === undefined ? undefined : names.find((name) => name === normalized);
}
export function parsePermissionAction(action: string): PermissionAction {
const parsed = findVocabularyName(PERMISSION_ACTIONS, action);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`Invalid permission action: ${action}. Use ${PERMISSION_ACTIONS.join('|')}.`,
);
}
export function parsePermissionTarget(value: string | undefined): PermissionTarget {
const parsed = findVocabularyName(MOBILE_PERMISSION_TARGETS, value);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`permission setting requires a target: ${MOBILE_PERMISSION_TARGETS.join('|')}`,
);
}
/**
* The appearance a caller asked for. Every surface that sets one parses here first: `simctl` and
* `adb` both answer a bad token with a tool-specific error or a silent no-op, so the refusal has to
* name the accepted set before a device is touched.
*/
export function parseAppearanceAction(state: string): AppearanceAction {
const parsed = findVocabularyName(APPEARANCE_ACTIONS, state);
if (parsed !== undefined) return parsed;
throw new AppError(
'INVALID_ARGS',
`Invalid appearance state: ${state}. Use ${APPEARANCE_ACTIONS.join('|')}.`,
);
}
/** The boolean a `settings <setting> <state>` positional spells, in any casing. */
export function parseSettingState(state: string): boolean {
const normalized = state.toLowerCase();
if (SETTING_STATE_ON.includes(normalized)) return true;
if (SETTING_STATE_OFF.includes(normalized)) return false;
throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`);
}