Skip to content

Commit 8f3eb3d

Browse files
feat(android): add settings bluetooth on|off (#3721)
* feat(android): add settings bluetooth on|off Toggle the Android Bluetooth adapter from `settings`, next to wifi and airplane. QA automation for media playback uses it to stand in for a Bluetooth audio device disconnecting mid-session. - Runs `svc bluetooth enable|disable` from Android 8.1 (API 27). From Android 13 AOSP's `svc` forwards that to `cmd bluetooth_manager`, so one command serves every supported level. - The adapter is proven with `pm list features` before the write, so a device or emulator image without android.hardware.bluetooth is refused with UNSUPPORTED_OPERATION and reason android_bluetooth_adapter_missing, unchanged. Builds older than Android 8.1 are refused with android_bluetooth_command_unavailable, and an unreadable API level fails with the getprop output before any write. - `svc bluetooth` exits 0 when the adapter refuses the change, so the write is confirmed by polling `settings get global bluetooth_on` for up to 2 s (host-kit pollUntilSettled). A state that never arrives fails with COMMAND_FAILED and reason bluetooth-not-applied, or bluetooth-unreadable with the stored value; success reports the resulting `bluetooth` state. - Refusals before the write disclose dispatched: no, failures after it dispatched: unknown. A cancelled request stops before the write. - Apple targets refuse the setting at admission through the existing per-owner facts. - `pm list features` now has one parser, androidFeatureListDeclares, which TV discovery and the Bluetooth check share. The API-level read moves out of the permission module into device-sdk-int.ts and keeps its result. The three copies of the underFakeTimers test helper become one in test-utils. * fix(settings): refuse --app on bluetooth and parse the API level strictly - bluetooth is device-wide, so the catalog declares it the way mobile-data does: the app rides the request input and a named app is refused with setting_app_not_consumed before dispatch. - readAndroidSdkInt accepts only a whole positive integer. parseInt read `27garbage` as 27, which would let the Bluetooth gate dispatch on an unreadable API level. - The docs and changelog say the old-build refusal applies only once the adapter check passes, and describe bluetooth-unreadable as an unrecognized bluetooth_on value. * fix(android): load the Bluetooth setting only when it runs settings.ts imported settings-bluetooth.ts statically, so importing mechanics.ts also evaluated settings-bluetooth.ts and the inventory-parsers.ts it pulls in. The eager-closure budget caught the growth (176 to 179 modules). The bluetooth case now imports the module when it runs, the way device-boot and lifecycle load theirs. * refactor(settings): share the global-toggle read-back and derive device-wide client arms - mobile-data and bluetooth now go through one setAndroidGlobalToggle in settings-global-toggle.ts: the svc write, the abort check, the settings-global read-back poll, the typed settle error, and dispatch disclosure. Each setting only declares its service, row, value map, reasons, interval and hint. mobile-data gains the exit-code handling bluetooth already had, and settings-bluetooth.ts keeps only the adapter and API-level preflight. - SettingsUpdateOptions derives one arm for every catalog entry with app: 'input' and a device-level mobile scope, replacing the hand-written mobile-data arm. client.settings.update({ setting: 'bluetooth', state: 'off' }) now type-checks. A type test asserts every SettingName has an arm. * fix(android): give each global-toggle read its own timeout pollUntilSettled sleeps up to the deadline and then samples once more. Each `settings get global` read took the deadline's remaining time as its adb timeout, so that last read ran with a 1 ms budget and failed as an adb timeout instead of reaching the typed not-applied reason. Reads now get a fixed 1 s budget; the 2 s settle window still bounds polling. * refactor(android): type the global-toggle result by its state key AndroidGlobalToggle is generic over its stateKey, so setAndroidBluetooth returns { bluetooth } and the mobile-data toggle { mobileData } again instead of a string-keyed record.
1 parent 82c0d70 commit 8f3eb3d

25 files changed

Lines changed: 793 additions & 186 deletions

‎packages/contracts/src/client-settings.test.ts‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { describe, expect, expectTypeOf, test, vi } from 'vitest';
22
import type { SettingsUpdateOptions } from './client-settings.ts';
3+
import type { SettingName } from './settings-catalog.ts';
34

45
type Permission = Extract<SettingsUpdateOptions, { setting: 'permission' }>;
56

@@ -43,6 +44,23 @@ describe('public client permission vocabulary', () => {
4344
});
4445
});
4546

47+
describe('public client settings cover the catalog', () => {
48+
test('every catalog setting has an update arm', () => {
49+
type SettingWithoutArm = {
50+
[Name in SettingName]: [Extract<SettingsUpdateOptions, { setting: Name }>] extends [never]
51+
? Name
52+
: never;
53+
}[SettingName];
54+
expectTypeOf<SettingWithoutArm>().toEqualTypeOf<never>();
55+
});
56+
57+
test('the device-wide toggles take on|off and an app to refuse', () => {
58+
type Toggle = Extract<SettingsUpdateOptions, { setting: 'mobile-data' | 'bluetooth' }>;
59+
expectTypeOf<Toggle['state']>().toEqualTypeOf<'on' | 'off'>();
60+
expectTypeOf<Toggle['app']>().toEqualTypeOf<string | undefined>();
61+
});
62+
});
63+
4664
/**
4765
* The client-facing vocabulary is a type surface. Deriving it from `settings.ts` must not put that
4866
* module, and with it `AppError`, on the client's runtime path — a value import here would load it.

‎packages/contracts/src/client-settings.ts‎

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,19 +36,32 @@ type StateOnlySettingOptions = {
3636
: { setting: Name; state: SettingState<Name> });
3737
}[StateOnlySetting];
3838

39+
/** Switches that change the whole Android device; naming an app is refused with `setting_app_not_consumed`. */
40+
type DeviceLevelToggleSetting = {
41+
[Name in SettingName]: (typeof SETTINGS)[Name] extends {
42+
app: 'input';
43+
appScope: { mobile: 'device-level' };
44+
}
45+
? Name
46+
: never;
47+
}[SettingName];
48+
49+
type DeviceLevelToggleOptions = {
50+
[Name in DeviceLevelToggleSetting]: DeviceCommandBaseOptions & {
51+
setting: Name;
52+
state: SettingState<Name>;
53+
app?: string;
54+
};
55+
}[DeviceLevelToggleSetting];
56+
3957
export type SettingsUpdateOptions =
4058
| StateOnlySettingOptions
59+
| DeviceLevelToggleOptions
4160
| (DeviceCommandBaseOptions & {
4261
setting: 'clear-app-state';
4362
state: 'clear';
4463
app?: string;
4564
})
46-
/** Android only. Naming an app is refused with `setting_app_not_consumed`. */
47-
| (DeviceCommandBaseOptions & {
48-
setting: 'mobile-data';
49-
state: 'on' | 'off';
50-
app?: string;
51-
})
5265
/** On Apple simulators `on`/`off` is a location-permission change for `app` (or the session app). */
5366
| (DeviceCommandBaseOptions & {
5467
setting: 'location';

‎packages/contracts/src/settings-catalog.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,12 @@ export const SETTINGS = {
101101
forms: [{ kind: 'on-off' }],
102102
help: 'Android switches Wi-Fi with svc wifi; an Apple simulator overrides only its status bar.',
103103
},
104+
bluetooth: {
105+
forms: [{ kind: 'on-off' }],
106+
app: 'input',
107+
appScope: { mobile: 'device-level' },
108+
help: 'Android over adb turns its Bluetooth adapter on or off with svc bluetooth, from Android 8.1. It reports the bluetooth state the device holds afterwards, or fails with bluetooth-not-applied or bluetooth-unreadable. A device without an adapter refuses with android_bluetooth_adapter_missing, and an adapter on a build older than 8.1 with android_bluetooth_command_unavailable, before anything changes. --app is refused.',
109+
},
104110
airplane: {
105111
forms: [{ kind: 'on-off' }],
106112
help: 'Android applies it through the connectivity service (Android 11+) and reports the airplaneMode that service holds; older builds fail without changing anything. An Apple simulator overrides only its status bar.',

‎packages/contracts/src/settings.test.ts‎

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ function expectInvalidArgs(run: () => unknown, message: string): void {
4141
describe('settings usage', () => {
4242
test('folds settings that share a form into one line', () => {
4343
expect(SETTINGS_USAGE_OVERRIDE.split(' | ')).toEqual([
44-
'settings <wifi|airplane|mobile-data|location|animations> <on|off>',
44+
'settings <wifi|bluetooth|airplane|mobile-data|location|animations> <on|off>',
4545
'settings location set <lat> <lon>',
4646
'settings appearance <light|dark|toggle>',
4747
`settings text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`,
@@ -56,7 +56,7 @@ describe('settings usage', () => {
5656

5757
test('the invalid-args message lists the same forms, with the last one as an alternative', () => {
5858
expect(SETTINGS_INVALID_ARGS_MESSAGE).toMatch(
59-
/^settings requires <wifi\|airplane\|mobile-data\|location\|animations> <on\|off>, .*, or permission <grant\|reset> <accessibility\|screen-recording\|input-monitoring>$/,
59+
/^settings requires <wifi\|bluetooth\|airplane\|mobile-data\|location\|animations> <on\|off>, .*, or permission <grant\|reset> <accessibility\|screen-recording\|input-monitoring>$/,
6060
);
6161
});
6262

@@ -70,6 +70,10 @@ describe('parseSettingsMutation', () => {
7070
expect(parseSettingsMutation(['WiFi', 'ON'])).toEqual({ setting: 'wifi', state: 'on' });
7171
expect(parseSettingsMutation(['airplane', '0'])).toEqual({ setting: 'airplane', state: 'off' });
7272
expect(parseSettingsMutation(['wifi', ' true '])).toEqual({ setting: 'wifi', state: 'on' });
73+
expect(parseSettingsMutation(['Bluetooth', 'off'])).toEqual({
74+
setting: 'bluetooth',
75+
state: 'off',
76+
});
7377
});
7478

7579
test('refuses a state outside a choice with the accepted states', () => {
@@ -84,10 +88,7 @@ describe('parseSettingsMutation', () => {
8488
});
8589

8690
test('refuses an unknown setting and extra positionals with the usage', () => {
87-
expectInvalidArgs(
88-
() => parseSettingsMutation(['bluetooth', 'on']),
89-
SETTINGS_INVALID_ARGS_MESSAGE,
90-
);
91+
expectInvalidArgs(() => parseSettingsMutation(['nfc', 'on']), SETTINGS_INVALID_ARGS_MESSAGE);
9192
expectInvalidArgs(
9293
() => parseSettingsMutation(['reset-keychain', 'clear', 'extra']),
9394
SETTINGS_INVALID_ARGS_MESSAGE,
@@ -238,14 +239,17 @@ describe('settingsAppScope', () => {
238239
});
239240
});
240241

241-
describe('settingsAppScope mobile-data', () => {
242-
test('mobile-data switches the whole device wherever it is served', () => {
243-
expect(settingsAppScope('mobile', 'mobile-data', 'on')).toBe('device-level');
244-
expect(settingsAppScope('mobile', 'mobile-data', 'off')).toBe('device-level');
245-
// No Apple target serves it; its refusal belongs to the leaf, not to the app.
246-
expect(settingsAppScope('apple', 'mobile-data', 'on')).toBe('unknown');
247-
expect(settingsAppScope('macos-host', 'mobile-data', 'on')).toBe('unknown');
248-
});
242+
describe('settingsAppScope device-wide radios', () => {
243+
test.each(['mobile-data', 'bluetooth'])(
244+
'%s switches the whole device wherever it is served',
245+
(setting) => {
246+
expect(settingsAppScope('mobile', setting, 'on')).toBe('device-level');
247+
expect(settingsAppScope('mobile', setting, 'off')).toBe('device-level');
248+
// No Apple target serves it; its refusal belongs to the leaf, not to the app.
249+
expect(settingsAppScope('apple', setting, 'on')).toBe('unknown');
250+
expect(settingsAppScope('macos-host', setting, 'on')).toBe('unknown');
251+
},
252+
);
249253
});
250254

251255
describe('settingsAppNotConsumedRefusal', () => {

‎packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -179,6 +179,7 @@ function settingsFacts(device: DeviceInfo) {
179179
unsupported,
180180
write: {
181181
wifi: available,
182+
bluetooth: available,
182183
airplane: available,
183184
'mobile-data': available,
184185
location: available,

‎packages/daemon/src/execution/handlers/__tests__/snapshot-settings-handler.test.ts‎

Lines changed: 49 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,29 @@ test('settings text-size reads the category the owner holds without mutating any
227227
expect(fixtureSettingsMutations).toHaveLength(0);
228228
});
229229

230+
test('settings bluetooth on an iOS simulator is refused at admission, before dispatch', async () => {
231+
const sessionStore = makeSessionStore();
232+
const sessionName = 'ios-bluetooth';
233+
sessionStore.publish(sessionName, makeSession(sessionName, iosSimulatorDevice));
234+
235+
const response = await handleSnapshotCommands({
236+
createCommandSurface: fakeCreateCommandSurface,
237+
platformServices: daemonPlatformServicesFixture(),
238+
req: snapshotRequest(sessionName, 'settings', { positionals: ['bluetooth', 'on'] }),
239+
sessionName,
240+
logPath: '/tmp/daemon.log',
241+
sessionStore,
242+
});
243+
244+
expect(response?.ok).toBe(false);
245+
if (response && !response.ok) {
246+
expect(response.error.code).toBe('UNSUPPORTED_OPERATION');
247+
expect(response.error.message).toBe('settings bluetooth is not supported on this device');
248+
expect(response.error.details?.reason).toBe('unsupported-platform-leaf');
249+
}
250+
expect(fixtureSettingsMutations).toHaveLength(0);
251+
});
252+
230253
test('settings on the macOS host refuses a setting it does not serve, read and write alike', async () => {
231254
const sessionStore = makeSessionStore();
232255
const sessionName = 'macos-settings';
@@ -655,31 +678,34 @@ test('settings mobile-data reaches the Android owner as an on/off mutation', asy
655678
expect(fixtureSettingsMutations.at(-1)).toMatchObject({ setting: 'mobile-data', state: 'off' });
656679
});
657680

658-
test('settings Android mobile-data refuses a named app before reaching the owner', async () => {
659-
const sessionStore = makeSessionStore();
660-
const sessionName = 'android-mobile-data-app-refused';
661-
sessionStore.publish(sessionName, makeSession(sessionName, androidDevice));
681+
test.each(['mobile-data', 'bluetooth'])(
682+
'settings Android %s refuses a named app before reaching the owner',
683+
async (setting) => {
684+
const sessionStore = makeSessionStore();
685+
const sessionName = `android-${setting}-app-refused`;
686+
sessionStore.publish(sessionName, makeSession(sessionName, androidDevice));
662687

663-
const response = await handleSnapshotCommands({
664-
createCommandSurface: fakeCreateCommandSurface,
665-
platformServices: daemonPlatformServicesFixture(),
666-
req: snapshotRequest(sessionName, 'settings', {
667-
positionals: ['mobile-data', 'off'],
668-
input: { app: 'com.example.app' },
669-
}),
670-
sessionName,
671-
logPath: '/tmp/daemon.log',
672-
sessionStore,
673-
});
688+
const response = await handleSnapshotCommands({
689+
createCommandSurface: fakeCreateCommandSurface,
690+
platformServices: daemonPlatformServicesFixture(),
691+
req: snapshotRequest(sessionName, 'settings', {
692+
positionals: [setting, 'off'],
693+
input: { app: 'com.example.app' },
694+
}),
695+
sessionName,
696+
logPath: '/tmp/daemon.log',
697+
sessionStore,
698+
});
674699

675-
expect(response?.ok).toBe(false);
676-
expect(fixtureSettingsMutations).toHaveLength(0);
677-
if (response && !response.ok) {
678-
expect(response.error.code).toBe('INVALID_ARGS');
679-
expect(response.error.details?.reason).toBe('setting_app_not_consumed');
680-
expect(response.error.details?.dispatched).toBe('no');
681-
}
682-
});
700+
expect(response?.ok).toBe(false);
701+
expect(fixtureSettingsMutations).toHaveLength(0);
702+
if (response && !response.ok) {
703+
expect(response.error.code).toBe('INVALID_ARGS');
704+
expect(response.error.details?.reason).toBe('setting_app_not_consumed');
705+
expect(response.error.details?.dispatched).toBe('no');
706+
}
707+
},
708+
);
683709

684710
test('settings macOS permission grant refuses a named app before reaching the owner', async () => {
685711
const sessionStore = makeSessionStore();

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

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { test, vi } from 'vitest';
22
import assert from 'node:assert/strict';
3+
import { underFakeTimers } from './test-utils/fake-timers.ts';
34
import type { DeviceInfo } from '@agent-device/kernel/device';
45
import { deviceShellArgv, type ShellWord } from '@agent-device/kernel/device-shell';
56
import { button, node, text } from './alert-fixtures.ts';
@@ -23,19 +24,6 @@ const dialog = [
2324
button(2, 'Cancel', 'android:id/button2', { x: 210, y: 612 }),
2425
];
2526

26-
/** Runs an alert action whose polls sleep between captures, without waiting the sleeps out. */
27-
async function underFakeTimers<T>(run: () => Promise<T>): Promise<T> {
28-
vi.useFakeTimers();
29-
try {
30-
const outcome = run();
31-
outcome.catch(() => {});
32-
await vi.runAllTimersAsync();
33-
return await outcome;
34-
} finally {
35-
vi.useRealTimers();
36-
}
37-
}
38-
3927
/** The dialog is in the tree until the button press lands, then gone — the real timeline. */
4028
function dialogUntilPressed(nodes = dialog) {
4129
return async () => (runAndroidAdb.mock.calls.length === 0 ? nodes : []);
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { test } from 'vitest';
2+
import assert from 'node:assert/strict';
3+
import { readAndroidSdkInt } from '../device-sdk-int.ts';
4+
import { withFakeAdb, type FakeAdbResponse } from './test-utils/fake-adb.ts';
5+
6+
test.each([
7+
{ response: '34\n', expected: 34 },
8+
{ response: '', expected: null },
9+
{ response: 'unknown', expected: null },
10+
{ response: '0', expected: null },
11+
{ response: '27garbage', expected: null },
12+
{ response: { stderr: 'error: closed', exitCode: 1 }, expected: null },
13+
] satisfies { response: FakeAdbResponse; expected: number | null }[])(
14+
'readAndroidSdkInt reads $response as $expected',
15+
async ({ response, expected }) => {
16+
await withFakeAdb(
17+
() => response,
18+
async ({ calls, device }) => {
19+
assert.equal((await readAndroidSdkInt(device)).sdkInt, expected);
20+
assert.deepEqual(calls, [['shell', 'getprop', 'ro.build.version.sdk']]);
21+
},
22+
);
23+
},
24+
);

‎packages/platform-android/src/__tests__/fill-verification.test.ts‎

Lines changed: 2 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,10 @@
88
// whether any of a commit reached the field, which both the soft-success guard and the IME rebind
99
// share.
1010

11-
import { afterEach, beforeEach, test, vi } from 'vitest';
11+
import { afterEach, beforeEach, test } from 'vitest';
1212
import './test-utils/android-host-test-setup.ts';
1313
import assert from 'node:assert/strict';
14+
import { underFakeTimers } from './test-utils/fake-timers.ts';
1415
import type { DeviceInfo } from '@agent-device/kernel/device';
1516
import { withAndroidAdbProvider, type AndroidAdbProvider } from '../adb-executor.ts';
1617
import type { AndroidFillVerificationNode } from '../fill-diagnostics.ts';
@@ -145,25 +146,6 @@ test('a value that never lands is a mismatch read from the last sample', async (
145146
);
146147
});
147148

148-
/**
149-
* Runs the sampler with its sleeps advanced instead of waited out. The clock moves in slices
150-
* shorter than a sample interval so the helper session's own timers never fire ahead of its replies.
151-
*/
152-
async function underFakeTimers<T>(run: () => Promise<T>): Promise<T> {
153-
vi.useFakeTimers();
154-
try {
155-
let done = false;
156-
const outcome = run().finally(() => {
157-
done = true;
158-
});
159-
outcome.catch(() => {});
160-
while (!done) await vi.advanceTimersByTimeAsync(10);
161-
return await outcome;
162-
} finally {
163-
vi.useRealTimers();
164-
}
165-
}
166-
167149
test('the pre-action target read shares the daemon-session helper with the samples', async () => {
168150
const session = createFillHelperSession();
169151

0 commit comments

Comments
 (0)