Skip to content
83 changes: 83 additions & 0 deletions docs/evidence/android-keep-awake-2026-11-08.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
# Android keep-awake end-to-end run and the svc-true no-op, 2026-11-08

Evidence for #4290 (keep-awake on and off on Android): the
first backend draft lowered `on` to `svc power stayon true`, and a live run
proved that a no-op on real hardware — the command answers and the stored
value never moves when the mask already covers the plugged-in sources. The
shipped backend writes the setting itself and reports the read-back state.

## Device

- Xiaomi Redmi K60 (`2312DRAABC` model code), Android 14 (SDK 34), adb serial
`5p4hqglvpzxshiuw`, USB connected.

## The svc-true no-op (discovered live)

With the user's stored mask at `15`, the draft command changed nothing while
the CLI still acked the write:
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved

```sh
$ adb -s 5p4hqglvpzxshiuw shell "settings get global stay_on_while_plugged_in"
15
$ adb -s 5p4hqglvpzxshiuw shell "svc power stayon true; settings get global stay_on_while_plugged_in"
15
$ adb -s 5p4hqglvpzxshiuw shell "svc power stayon usb; settings get global stay_on_while_plugged_in"
2
```

`stayon true` does not rewrite a mask that already covers the plugged-in
sources; `stayon usb` rewrites to `2`. A write that skips no-op spellings is
the only reliable form.

## The shipped backend, end to end through the public CLI

Branch build of #4290, one command per state, device state read back with raw
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Resolved
`settings get` between the calls:

```sh
$ node bin/agent-device.mjs settings keep-awake on --platform android --serial 5p4hqglvpzxshiuw
Updated setting: keep-awake
$ adb -s 5p4hqglvpzxshiuw shell "settings get global stay_on_while_plugged_in"
7
$ node bin/agent-device.mjs settings keep-awake off --platform android --serial 5p4hqglvpzxshiuw
Updated setting: keep-awake
$ adb -s 5p4hqglvpzxshiuw shell "settings get global stay_on_while_plugged_in"
0
```

`15 → 7 → 0`. The user's stored mask was restored to `15` after the run. The
Comment thread
strzhao marked this conversation as resolved.
Resolved
CLI result carries the read-back state (`stayOnWhilePluggedIn`), so an ack can
never claim a write the device did not store.

## HarmonyOS note

HarmonyOS keep-awake moved out of #4290 (maintainer option B): no device was
reachable to prove a restore route, and on JDY-AL50 (HarmonyOS 7.0.0.111)
`power-shell timeout -r` acks but does not clear an active `-o` override (the
screen stayed up past 260s). The finding is recorded in the PR thread; a
future PR may bring the half back behind a proven restore route.

## The live Android repro at head 73d04eb4a (2026-11-23)

The review asked for a device where `svc power stayon true` fails, or the
hand-written mask dropped for the toggle read-back. The Redmi 2312DRAABC
(Android 14, MIUI) answers the question from the other side:

```sh
$ adb shell settings get global stay_on_while_plugged_in
0
$ adb shell svc power stayon true
$ adb shell settings get global stay_on_while_plugged_in
15
$ adb shell svc power stayon false
$ adb shell settings get global stay_on_while_plugged_in
0
```

`svc power stayon true` writes 15 from a 0 row on this unit — the original
lowering keeps the screen on here, and `false` returns the row to 0. The
shipped 7 write would clobber a 15 a dock or user had set, so the lowering now
rides the global-toggle machinery: `svc power stayon true|false`, the row
polled to a state (`0` disabled, any positive mask enabled), and the typed
`keep-awake-not-applied` / `keep-awake-unreadable` reasons on a read-back that
did not move or is not a mask. The result is `{ keepAwake }` only.
2 changes: 1 addition & 1 deletion packages/command-surface/src/capture/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ const settingsCommandMetadata = defineFieldCommandMetadata(
// A readable setting answers with no state; the parse decides per setting.
state: stringField(),
app: stringField(
'App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator, local or Limrun, matches display names and accepts only an installed bundle id, and Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`.',
'App the change targets, by bundle id, package name, or app name: the app `clear-app-state` clears, or the app a `permission` change (or an iOS-simulator `location on|off` privacy change) lands on. A name resolves to the installed app as `open` resolves it: an iOS simulator, local or Limrun, matches display names and accepts only an installed bundle id, and Android accepts only an installed package and refuses a name that resolves to an intent with `setting_app_not_package`. One that resolves to nothing is refused with `app_not_installed` before anything changes. The app need not be running. Without it the session app is used; a device-wide change (`location set` on any target, the Android `location on|off` toggle, `mobile-data`, `keep-awake`, macOS permissions) refuses one with `setting_app_not_consumed`. The CLI reads it only from this invocation, never from `AGENT_DEVICE_TARGET_APP` or config `targetApp`.',
),
latitude: numberField(),
longitude: numberField(),
Expand Down
6 changes: 6 additions & 0 deletions packages/contracts/src/settings-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,12 @@ export const SETTINGS = {
appScope: { mobile: 'device-level' },
help: 'Android only. Runs svc data and reports the stored mobileData state, or fails with mobile-data-not-applied or mobile-data-unreadable. Multi-SIM read-back is not covered yet, and --app is refused.',
},
'keep-awake': {
forms: [{ kind: 'on-off' }],
app: 'input',
appScope: { mobile: 'device-level' },
help: 'Android holds its screen on while the device charges (svc power stayon true writes the charging mask, false clears it and does not restore a mask a user set), so a device on battery can still sleep; the write survives a reboot and outlives the session, so run off when the hold ends. --app is refused.',
},
location: {
forms: [
{ kind: 'on-off', appScope: { apple: 'app-scoped', mobile: 'device-level' } },
Expand Down
6 changes: 3 additions & 3 deletions packages/contracts/src/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ function expectInvalidArgs(run: () => unknown, message: string): void {
describe('settings usage', () => {
test('folds settings that share a form into one line', () => {
expect(SETTINGS_USAGE_OVERRIDE.split(' | ')).toEqual([
'settings <wifi|bluetooth|airplane|mobile-data|location|animations> <on|off>',
'settings <wifi|bluetooth|airplane|mobile-data|keep-awake|location|animations> <on|off>',
'settings location set <lat> <lon>',
'settings appearance <light|dark|toggle>',
`settings text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`,
Expand All @@ -56,7 +56,7 @@ describe('settings usage', () => {

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

Expand Down Expand Up @@ -282,7 +282,7 @@ describe('settingsAppScope', () => {
});

describe('settingsAppScope device-wide radios', () => {
test.each(['mobile-data', 'bluetooth'])(
test.each(['mobile-data', 'keep-awake', 'bluetooth'])(
'%s switches the whole device wherever it is served',
(setting) => {
expect(settingsAppScope('mobile', setting, 'on')).toBe('device-level');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ function settingsFacts(device: DeviceInfo) {
bluetooth: available,
airplane: available,
'mobile-data': available,
'keep-awake': available,
location: available,
animations: available,
appearance: available,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -680,7 +680,7 @@ test('settings mobile-data reaches the Android owner as an on/off mutation', asy
expect(fixtureSettingsMutations.at(-1)).toMatchObject({ setting: 'mobile-data', state: 'off' });
});

test.each(['mobile-data', 'bluetooth'])(
test.each(['mobile-data', 'keep-awake', 'bluetooth'])(
'settings Android %s refuses a named app before reaching the owner',
async (setting) => {
const sessionStore = makeSessionStore();
Expand Down
83 changes: 83 additions & 0 deletions packages/platform-android/src/__tests__/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -651,3 +651,86 @@ test('setAndroidSetting mobile-data stops sampling when the request is cancelled
},
);
});

// --- settings keep-awake: svc power stayon with the mask read-back ---

test('setAndroidSetting keep-awake writes svc stayon and reads the mask back to a state', async () => {
for (const { state, word, row, keepAwake } of [
{ state: 'on', word: 'true', row: '15', keepAwake: 'enabled' },
{ state: 'off', word: 'false', row: '0', keepAwake: 'disabled' },
] as const) {
await withFakeAdb(
(args) => {
const joined = args.join(' ');
if (joined === `shell svc power stayon ${word}`) return '';
if (joined === 'shell settings get global stay_on_while_plugged_in') return row;
return undefined;
},
async ({ calls, device }) => {
const result = await setAndroidSetting(device, 'keep-awake', state);
assert.deepEqual(flatCalls(calls), [
`shell svc power stayon ${word}`,
'shell settings get global stay_on_while_plugged_in',
]);
assert.deepEqual(result, { keepAwake });
},
);
}
});

test('setAndroidSetting keep-awake reports not-applied when the row stays off', async () => {
await withFakeAdb(
(args) => {
const joined = args.join(' ');
if (joined === 'shell svc power stayon true') return '';
if (joined === 'shell settings get global stay_on_while_plugged_in') return '0';
return undefined;
},
async ({ device }) => {
await assert.rejects(
() => setAndroidSetting(device, 'keep-awake', 'on'),
(error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.code, 'COMMAND_FAILED');
assert.equal(error.details?.reason, 'keep-awake-not-applied');
return true;
},
);
},
);
});

test('setAndroidSetting keep-awake reports unreadable for a row that is not a mask', async () => {
await withFakeAdb(
(args) => {
const joined = args.join(' ');
if (joined === 'shell svc power stayon true') return '';
if (joined === 'shell settings get global stay_on_while_plugged_in') return 'null';
return undefined;
},
async ({ device }) => {
await assert.rejects(
() => setAndroidSetting(device, 'keep-awake', 'on'),
(error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.code, 'COMMAND_FAILED');
assert.equal(error.details?.reason, 'keep-awake-unreadable');
return true;
},
);
},
);
});

test('setAndroidSetting keep-awake runs nothing for a state svc cannot spell', async () => {
await withFakeAdb(
(args) => ({ stderr: `unexpected args: ${args.join(' ')}`, exitCode: 1 }),
async ({ calls, device }) => {
await assertRejectsAppError(() => setAndroidSetting(device, 'keep-awake', 'forever'), {
code: 'INVALID_ARGS',
message: /Invalid setting state: forever/,
});
assert.deepEqual(calls, []);
},
);
});
1 change: 1 addition & 0 deletions packages/platform-android/src/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -390,6 +390,7 @@ export function createAndroidPlatformRuntime(host: PlatformRuntimeHost): Platfor
bluetooth: available,
airplane: available,
'mobile-data': available,
'keep-awake': available,
location: available,
animations: available,
appearance: available,
Expand Down
23 changes: 17 additions & 6 deletions packages/platform-android/src/settings-global-toggle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export const ANDROID_GLOBAL_TOGGLE_REASONS = {
mobileDataNotApplied: { reason: 'mobile-data-not-applied' },
// The device answered the mobile-data read-back with a value that is neither 0 nor 1.
mobileDataUnreadable: { reason: 'mobile-data-unreadable' },
// The device kept the screen turning off after `svc power stayon` accepted the request.
keepAwakeNotApplied: { reason: 'keep-awake-not-applied' },
// The device answered the keep-awake read-back with a value that is not a stay-on mask.
keepAwakeUnreadable: { reason: 'keep-awake-unreadable' },
} as const satisfies ReasonTable<'settings'>;

/** The reason spellings a global-toggle read-back publishes, as `error.details.reason`. */
Expand All @@ -36,8 +40,13 @@ export type AndroidToggleState = 'enabled' | 'disabled';
* by polling the row until it holds the requested state.
*/
export type AndroidGlobalToggle<Key extends string = string> = Readonly<{
/** The `svc` service name: `svc <service> enable|disable`. */
/** The `svc` service name: `svc <service> enable|disable`, or `svc <service> <writeArgs...>` */
service: string;
/**
* The words after the service when the toggle's `svc` spelling is not `enable|disable`, such as
* `stayon true`. Omit it for the default `enable|disable` words.
*/
writeArgs?: (enabled: boolean) => readonly string[];
/** The `settings global` row the system service persists the switch in. */
row: string;
/** How the toggle is named in failure messages. */
Expand Down Expand Up @@ -67,11 +76,13 @@ export async function setAndroidGlobalToggle<Key extends string>(
if (signal?.aborted) throw discloseDispatch(createRequestCanceledError(), 'no');
const requested: AndroidToggleState = enabled ? 'enabled' : 'disabled';
try {
const result = await runAndroidShell(
device,
['svc', toggle.service, enabled ? 'enable' : 'disable'],
{ allowFailure: true, signal },
);
const writeArgs = toggle.writeArgs
? toggle.writeArgs(enabled)
: [enabled ? 'enable' : 'disable'];
const result = await runAndroidShell(device, ['svc', toggle.service, ...writeArgs], {
allowFailure: true,
signal,
});
if (result.exitCode !== 0) {
throw androidAdbResultError(
`Failed to turn Android ${toggle.label} ${enabled ? 'on' : 'off'}`,
Expand Down
27 changes: 27 additions & 0 deletions packages/platform-android/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export const ANDROID_SETTINGS = [
'bluetooth',
'airplane',
'mobile-data',
'keep-awake',
'location',
'animations',
'appearance',
Expand Down Expand Up @@ -127,6 +128,14 @@ export async function setAndroidSetting(
signal,
);
}
case 'keep-awake': {
return await setAndroidGlobalToggle(
device,
KEEP_AWAKE_TOGGLE,
parseSettingState(state),
signal,
);
}
case 'location': {
if (state.toLowerCase() === 'set') {
if (device.kind !== 'emulator') {
Expand Down Expand Up @@ -319,6 +328,24 @@ function nearestTextSizeCategory(scale: number): (typeof TEXT_SIZE_CATEGORIES)[n
* multi-SIM device keeps it per subscription; that read-back is uncovered until a dual-SIM run shows
* which row to read.
*/
/** Keep-awake rides `svc power stayon true|false`; the row is the stay-on mask itself. */
const KEEP_AWAKE_TOGGLE: AndroidGlobalToggle<'keepAwake'> = {
service: 'power',
writeArgs: (enabled) => ['stayon', enabled ? 'true' : 'false'],
row: 'stay_on_while_plugged_in',
label: 'keep-awake',
stateKey: 'keepAwake',
parseRow: (storedValue) => {
if (storedValue === '0') return 'disabled';
if (/^[1-9][0-9]*$/.test(storedValue)) return 'enabled';
return undefined;
},
notAppliedReason: ANDROID_GLOBAL_TOGGLE_REASONS.keepAwakeNotApplied.reason,
unreadableReason: ANDROID_GLOBAL_TOGGLE_REASONS.keepAwakeUnreadable.reason,
sampleIntervalMs: 100,
hint: 'Check the stay-on mask with: adb shell settings get global stay_on_while_plugged_in',
};

const MOBILE_DATA_TOGGLE: AndroidGlobalToggle<'mobileData'> = {
service: 'data',
row: 'mobile_data',
Expand Down
1 change: 1 addition & 0 deletions packages/platform-harmonyos/src/runtime.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,7 @@ test.each([
expect(binding.operations[operation]).toBeUndefined();
}
expect(runtimeSubjectFact(facts.operations.setSetting, 'clear-app-state').available).toBe(true);
expect(runtimeSubjectFact(facts.operations.setSetting, 'keep-awake').available).toBe(false);
expect(runtimeSubjectFact(facts.operations.setSetting, 'wifi').available).toBe(false);
expect(binding.operations.setSetting).toBeTypeOf('function');
await expect(binding.operations.ensureReady?.({})).resolves.toMatchObject({ booted: true });
Expand Down
2 changes: 1 addition & 1 deletion packages/platform-harmonyos/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function setHarmonySetting(
): Promise<Record<string, unknown>> {
if (setting !== 'clear-app-state') {
throw new AppError('UNSUPPORTED_OPERATION', `HarmonyOS setting "${setting}" is not supported`, {
hint: 'HarmonyOS currently supports settings clear-app-state for an app bundle only.',
hint: 'HarmonyOS currently supports settings clear-app-state only.',
});
}
if (state !== 'clear') {
Expand Down
1 change: 1 addition & 0 deletions packages/provider-limrun/src/interaction-operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,7 @@ export function limrunAndroidSettingsFacts(
bluetooth: available,
airplane: available,
'mobile-data': available,
'keep-awake': available,
location: available,
animations: available,
appearance: available,
Expand Down
2 changes: 1 addition & 1 deletion website/docs/docs/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -1728,7 +1728,7 @@ agent-device trigger-app-event screenshot_taken '{"source":"qa"}'
Change OS settings and app permissions.

```bash
agent-device settings <wifi|bluetooth|airplane|mobile-data|location|animations> <on|off> | settings location set <lat> <lon> | settings appearance <light|dark|toggle> | settings text-size [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] | settings <faceid|touchid> <match|nonmatch|enroll|unenroll> | settings fingerprint <match|nonmatch> | settings clear-app-state [app-id] | settings reset-keychain clear | settings permission <grant|deny|reset> <all|camera|microphone|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> | settings permission <grant|deny|reset> photos [full|limited] | settings permission <grant|reset> <accessibility|screen-recording|input-monitoring> [--app <id-or-name>]
agent-device settings <wifi|bluetooth|airplane|mobile-data|keep-awake|location|animations> <on|off> | settings location set <lat> <lon> | settings appearance <light|dark|toggle> | settings text-size [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] | settings <faceid|touchid> <match|nonmatch|enroll|unenroll> | settings fingerprint <match|nonmatch> | settings clear-app-state [app-id] | settings reset-keychain clear | settings permission <grant|deny|reset> <all|camera|microphone|contacts|contacts-limited|notifications|calendar|location|location-always|media-library|motion|reminders|siri> | settings permission <grant|deny|reset> photos [full|limited] | settings permission <grant|reset> <accessibility|screen-recording|input-monitoring> [--app <id-or-name>]
```

| Option | What it does |
Expand Down
Loading
Loading