Repository navigation
Expand file tree
/
Copy pathsettings.ts
More file actions
466 lines (443 loc) · 16.7 KB
/
Copy pathsettings.ts
File metadata and controls
466 lines (443 loc) · 16.7 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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
import {
AppError,
sessionAppRequiredDetails,
summarizeCommandAttemptFailures,
type CommandAttemptFailure,
} from '@agent-device/kernel/errors';
import type { DeviceInfo } from '@agent-device/kernel/device';
import { deviceShellArgv } from '@agent-device/kernel/device-shell';
import { requireLocationCoordinates } from '@agent-device/kernel/location-coordinates';
import {
parseAppearanceAction,
parseSettingState,
parseTextSizeCategory,
resolveSettingsApp,
SETTINGS_APP_NOT_PACKAGE_REASON,
textSizeSettingPayload,
type ReadSettingResult,
type SettingOptions,
type TextSizeSettingPayload,
} from '@agent-device/contracts/settings';
import {
TEXT_SIZE_CATEGORIES,
type ReadableSetting,
type SettingName,
} from '@agent-device/contracts/settings-catalog';
import { runAndroidAdb, runAndroidShell } from './adb.ts';
import { setAndroidAirplaneMode } from './settings-airplane.ts';
import { setAndroidGlobalToggle, type AndroidGlobalToggle } from './settings-global-toggle.ts';
import { androidAdbResultError } from './adb-executor.ts';
import { resolveAndroidApp } from './app-deployment-resolution.ts';
import {
parseAndroidPermissionRequest,
requireAndroidPermissionUser,
setAndroidPermission,
} from './settings-permission.ts';
/** The settings {@link setAndroidSetting} applies over adb, wherever an owner runs it. */
export const ANDROID_SETTINGS = [
'wifi',
'bluetooth',
'airplane',
'mobile-data',
'keep-awake',
'location',
'animations',
'appearance',
'text-size',
'fingerprint',
'clear-app-state',
'permission',
] as const satisfies readonly SettingName[];
export type AndroidSetting = (typeof ANDROID_SETTINGS)[number];
const ANDROID_ANIMATION_SCALE_SETTINGS = [
'window_animation_scale',
'transition_animation_scale',
'animator_duration_scale',
] as const;
/**
* The text-size ladder as Android `system font_scale` multipliers. The seven standard rungs are the
* Dynamic Type body ratios against the default size (14/17 … 23/17); the five accessibility rungs
* are Android's own range up to 3.2, the largest multiplier its tooling documents. Rungs must stay
* strictly increasing, because a read names the nearest rung to whatever the device holds.
*/
const TEXT_SIZE_FONT_SCALES = {
'extra-small': '0.82',
small: '0.88',
medium: '0.94',
large: '1.0',
'extra-large': '1.12',
'extra-extra-large': '1.24',
'extra-extra-extra-large': '1.35',
'accessibility-medium': '1.5',
'accessibility-large': '1.75',
'accessibility-extra-large': '2.0',
'accessibility-extra-extra-large': '2.5',
'accessibility-extra-extra-extra-large': '3.2',
} as const satisfies Record<(typeof TEXT_SIZE_CATEGORIES)[number], string>;
/** The scale a device with no `font_scale` row holds: Android's own default, which is `large`. */
const DEFAULT_FONT_SCALE = TEXT_SIZE_FONT_SCALES.large;
// fallow-ignore-next-line complexity
export async function setAndroidSetting(
device: DeviceInfo,
setting: string,
state: string,
appPackage?: string,
options?: SettingOptions,
signal?: AbortSignal,
): Promise<Record<string, unknown> | void> {
const normalized = ANDROID_SETTINGS.find((name) => name === setting.toLowerCase());
if (normalized === undefined)
throw new AppError('INVALID_ARGS', `Unsupported setting: ${setting}`);
switch (normalized) {
case 'wifi': {
const enabled = parseSettingState(state);
await runAndroidShell(device, ['svc', 'wifi', enabled ? 'enable' : 'disable']);
return;
}
case 'bluetooth': {
const { setAndroidBluetooth } = await import('./settings-bluetooth.ts');
return await setAndroidBluetooth(device, parseSettingState(state), signal);
}
case 'airplane': {
return await setAndroidAirplaneMode(device, parseSettingState(state));
}
case 'mobile-data': {
return await setAndroidGlobalToggle(
device,
MOBILE_DATA_TOGGLE,
parseSettingState(state),
signal,
);
}
case 'keep-awake': {
// `svc power stayon true` is a no-op when the stored mask already covers the plugged-in
// sources (a device holding 15 answers "Updated" with the value unchanged — verified on
// a Redmi K60, Android 14). The write goes to the setting itself with the explicit
// BATTERY_PLUGGED_ANY mask, and the result carries the read-back state.
const enabled = parseSettingState(state);
await runAndroidShell(device, [
'settings',
'put',
'global',
'stay_on_while_plugged_in',
enabled ? '7' : '0',
]);
const applied = await runAndroidShell(device, [
'settings',
'get',
'global',
'stay_on_while_plugged_in',
]);
return {
keepAwake: enabled ? 'enabled' : 'disabled',
stayOnWhilePluggedIn: applied.stdout.trim(),
};
}
case 'location': {
if (state.toLowerCase() === 'set') {
if (device.kind !== 'emulator') {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Android precise location coordinates are supported only on emulators.',
{
deviceId: device.id,
hint: 'Use an Android emulator for adb emu geo fix, or configure location through device/provider tooling.',
},
);
}
const { latitude, longitude } = requireLocationCoordinates(options);
await runAndroidAdb(device, ['emu', 'geo', 'fix', String(longitude), String(latitude)]);
return { latitude, longitude };
}
const enabled = parseSettingState(state);
const mode = enabled ? '3' : '0';
await runAndroidShell(device, ['settings', 'put', 'secure', 'location_mode', mode]);
return;
}
case 'animations': {
const enabled = parseSettingState(state);
const scale = enabled ? '1' : '0';
for (const key of ANDROID_ANIMATION_SCALE_SETTINGS) {
await runAndroidShell(device, ['settings', 'put', 'global', key, scale]);
}
return { scale, keys: [...ANDROID_ANIMATION_SCALE_SETTINGS] };
}
case 'appearance': {
const target = await resolveAndroidAppearanceTarget(device, state);
await runAndroidShell(device, ['cmd', 'uimode', 'night', target === 'dark' ? 'yes' : 'no']);
return;
}
case 'clear-app-state': {
if (state.toLowerCase() !== 'clear') {
throw new AppError('INVALID_ARGS', 'settings clear-app-state only supports clear.');
}
if (!appPackage) {
throw new AppError(
'INVALID_ARGS',
'settings clear-app-state requires an app id or an active app session.',
sessionAppRequiredDetails(),
);
}
const packageName = await resolveAndroidSettingsPackage(device, normalized, appPackage);
await runAndroidShell(device, ['am', 'force-stop', packageName], {
allowFailure: true,
});
const result = await runAndroidShell(device, ['pm', 'clear', packageName], {
allowFailure: true,
});
if (result.exitCode !== 0 || !/\bSuccess\b/i.test(result.stdout)) {
// exec-guard-allow: pm clear can exit 0 without printing Success; the
// guard also covers that non-exit failure mode.
throw new AppError(
'COMMAND_FAILED',
`Failed to clear Android app data for ${packageName}`,
{
package: packageName,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
},
);
}
return { package: packageName, cleared: true };
}
case 'fingerprint': {
const action = parseAndroidFingerprintAction(state);
await runAndroidFingerprintCommand(device, action);
return;
}
case 'permission': {
if (!appPackage) {
throw new AppError(
'INVALID_ARGS',
'permission setting requires an active app in session',
sessionAppRequiredDetails(),
);
}
const request = parseAndroidPermissionRequest(state, options);
const userId = await requireAndroidPermissionUser(device);
return await setAndroidPermission(
device,
await resolveAndroidSettingsPackage(device, normalized, appPackage, userId),
request,
userId,
);
}
case 'text-size': {
return await setAndroidTextSize(device, state);
}
default:
return normalized satisfies never;
}
}
/** The installed package an app-scoped setting lands on, by package or app name. */
async function resolveAndroidSettingsPackage(
device: DeviceInfo,
setting: string,
app: string,
userId?: number,
): Promise<string> {
const resolved = await resolveSettingsApp(app, (target) =>
resolveAndroidApp(device, target, { installedOnly: true, userId }),
);
if (resolved.type === 'intent') {
throw new AppError(
'INVALID_ARGS',
`settings ${setting} requires a package name, not an intent.`,
{
reason: SETTINGS_APP_NOT_PACKAGE_REASON,
dispatched: 'no',
app,
hint: 'Run apps --all for the exact package name, then retry with it in --app.',
},
);
}
return resolved.value;
}
/** Exhaustive over the readable settings, so a new one is a compile error here. */
const ANDROID_READABLE_SETTINGS = {
'text-size': readAndroidTextSize,
} as const satisfies Record<ReadableSetting, (device: DeviceInfo) => Promise<ReadSettingResult>>;
/** Answers `settings <setting>` with the value the Android target holds. */
export async function readAndroidSetting(
device: DeviceInfo,
setting: ReadableSetting,
): Promise<ReadSettingResult> {
return await ANDROID_READABLE_SETTINGS[setting](device);
}
async function setAndroidTextSize(
device: DeviceInfo,
state: string,
): Promise<TextSizeSettingPayload> {
const category = parseTextSizeCategory(state);
const fontScale = TEXT_SIZE_FONT_SCALES[category];
await runAndroidShell(device, ['settings', 'put', 'system', 'font_scale', fontScale]);
return textSizeSettingPayload(category, fontScale);
}
/**
* Reads `font_scale` back as a ladder rung. A multiplier that is not one this module writes — an OEM
* default, or a value someone set by hand — still has a nearest rung, and the payload keeps the
* exact multiplier beside it so the normalization stays auditable rather than looking like a match.
*/
async function readAndroidTextSize(device: DeviceInfo): Promise<TextSizeSettingPayload> {
const result = await runAndroidShell(device, ['settings', 'get', 'system', 'font_scale']);
const reported = result.stdout.trim();
// `null` is the sentinel `settings get` prints for a row that was never written, and the only
// answer that means "the device holds its default". Empty output is a read that saw nothing, and
// inventing a multiplier for it would report a size the device was never asked to hold.
const fontScale = reported === 'null' ? DEFAULT_FONT_SCALE : reported;
// A strict decimal, not `parseFloat`'s longest numeric prefix: a device answering `1.2-beta` or
// `12 apples` has a value this ladder cannot order, and reporting it as a rung would hide that.
const scale = /^(\d+(\.\d+)?)$/.test(fontScale) ? Number(fontScale) : Number.NaN;
if (!Number.isFinite(scale) || scale <= 0) {
throw new AppError(
'COMMAND_FAILED',
`Android reported an unusable font scale: ${reported || '(empty)'}`,
{
deviceId: device.id,
fontScale: reported,
hint: 'Run `adb shell settings get system font_scale` to see what the device holds.',
},
);
}
return textSizeSettingPayload(nearestTextSizeCategory(scale), fontScale);
}
function nearestTextSizeCategory(scale: number): (typeof TEXT_SIZE_CATEGORIES)[number] {
let nearest: (typeof TEXT_SIZE_CATEGORIES)[number] = TEXT_SIZE_CATEGORIES[0];
let nearestDistance = Number.POSITIVE_INFINITY;
for (const category of TEXT_SIZE_CATEGORIES) {
const distance = Math.abs(Number.parseFloat(TEXT_SIZE_FONT_SCALES[category]) - scale);
if (distance >= nearestDistance) continue;
nearest = category;
nearestDistance = distance;
}
return nearest;
}
/**
* Reads back only the global `mobile_data` row, where a single-SIM device stores the switch. A
* multi-SIM device keeps it per subscription; that read-back is uncovered until a dual-SIM run shows
* which row to read.
*/
const MOBILE_DATA_TOGGLE: AndroidGlobalToggle<'mobileData'> = {
service: 'data',
row: 'mobile_data',
label: 'mobile data',
stateKey: 'mobileData',
parseRow: (storedValue) => {
if (storedValue === '1') return 'enabled';
if (storedValue === '0') return 'disabled';
return undefined;
},
notAppliedReason: 'mobile-data-not-applied',
unreadableReason: 'mobile-data-unreadable',
sampleIntervalMs: 100,
hint: 'Run `adb shell settings get global mobile_data` to see what the device holds. A target without an active SIM, or with more than one, can accept svc data without changing that row.',
};
type AndroidFingerprintAction = 'match' | 'nonmatch';
function parseAndroidFingerprintAction(state: string): AndroidFingerprintAction {
const normalized = state.trim().toLowerCase();
if (normalized === 'match') return 'match';
if (normalized === 'nonmatch') return 'nonmatch';
throw new AppError('INVALID_ARGS', `Invalid fingerprint state: ${state}. Use match|nonmatch.`);
}
async function runAndroidFingerprintCommand(
device: DeviceInfo,
action: AndroidFingerprintAction,
): Promise<void> {
const attempts = androidFingerprintCommandAttempts(device, action);
const failures: CommandAttemptFailure[] = [];
for (const args of attempts) {
const result = await runAndroidAdb(device, args, { allowFailure: true });
if (result.exitCode === 0) return;
failures.push({
args,
stdout: result.stdout,
stderr: result.stderr,
exitCode: result.exitCode,
});
}
const attemptsPayload = summarizeCommandAttemptFailures(failures);
const capabilityMissing =
failures.length > 0 &&
failures.every((failure) =>
isAndroidFingerprintCapabilityMissing(failure.stdout, failure.stderr),
);
if (capabilityMissing) {
throw new AppError(
'UNSUPPORTED_OPERATION',
'Android fingerprint simulation is not supported on this target/runtime.',
{
deviceId: device.id,
action,
hint: 'Use an Android emulator with biometric support, or a device/runtime that exposes cmd fingerprint.',
attempts: attemptsPayload,
},
);
}
throw new AppError('COMMAND_FAILED', 'Failed to simulate Android fingerprint.', {
deviceId: device.id,
action,
attempts: attemptsPayload,
});
}
function androidFingerprintCommandAttempts(
device: DeviceInfo,
action: AndroidFingerprintAction,
): (readonly string[])[] {
const fingerprintId = action === 'match' ? '1' : '9999';
const attempts: (readonly string[])[] = [
deviceShellArgv('adb', 'shell', ['cmd', 'fingerprint', 'touch', fingerprintId]),
deviceShellArgv('adb', 'shell', ['cmd', 'fingerprint', 'finger', fingerprintId]),
];
if (device.kind === 'emulator') {
attempts.push(['emu', 'finger', 'touch', fingerprintId]);
}
return attempts;
}
function isAndroidFingerprintCapabilityMissing(stdout: string, stderr: string): boolean {
const text = `${stdout}\n${stderr}`.toLowerCase();
return (
text.includes('unknown command') ||
text.includes("can't find service: fingerprint") ||
text.includes('service fingerprint was not found') ||
text.includes('fingerprint cmd unavailable') ||
text.includes('emu command is not supported') ||
text.includes('emulator console is not running') ||
(text.includes('fingerprint') && text.includes('not found'))
);
}
async function resolveAndroidAppearanceTarget(
device: DeviceInfo,
state: string,
): Promise<'light' | 'dark'> {
const action = parseAppearanceAction(state);
if (action !== 'toggle') return action;
const currentResult = await runAndroidShell(device, ['cmd', 'uimode', 'night'], {
allowFailure: true,
});
if (currentResult.exitCode !== 0) {
throw androidAdbResultError('Failed to read current Android appearance', currentResult);
}
const current = parseAndroidAppearance(currentResult.stdout, currentResult.stderr);
if (!current) {
throw new AppError(
'COMMAND_FAILED',
'Unable to determine current Android appearance for toggle',
{
stdout: currentResult.stdout,
stderr: currentResult.stderr,
},
);
}
if (current === 'auto') return 'dark';
return current === 'dark' ? 'light' : 'dark';
}
function parseAndroidAppearance(stdout: string, stderr: string): 'light' | 'dark' | 'auto' | null {
const match = /night mode:\s*(yes|no|auto)\b/i.exec(`${stdout}\n${stderr}`);
if (!match) return null;
const value = match[1]?.toLowerCase();
if (value === 'yes') return 'dark';
if (value === 'no') return 'light';
if (value === 'auto') return 'auto';
return null;
}