diff --git a/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/SystemLocaleCommand.java b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/SystemLocaleCommand.java
new file mode 100644
index 0000000000..3466f87f30
--- /dev/null
+++ b/android/snapshot-helper/src/main/java/com/callstack/agentdevice/snapshothelper/SystemLocaleCommand.java
@@ -0,0 +1,46 @@
+package com.callstack.agentdevice.snapshothelper;
+
+import android.content.res.Configuration;
+import android.os.LocaleList;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+/**
+ * Sets the system locale list. It runs through {@code app_process} as the shell user, which holds
+ * CHANGE_CONFIGURATION and WRITE_SETTINGS; no installed app can hold the first. This is the same
+ * persistent configuration update the Settings language picker makes, so it survives a reboot and
+ * running apps receive a configuration change.
+ *
+ *
Usage: {@code app_process /system/bin }. It prints {@code
+ * previous=} and {@code current=}, or {@code error=} and exits 1.
+ */
+public final class SystemLocaleCommand {
+ private SystemLocaleCommand() {}
+
+ public static void main(String[] args) {
+ try {
+ if (args.length != 1 || args[0].isEmpty()) {
+ throw new IllegalArgumentException("Pass one comma-separated list of language tags");
+ }
+ LocaleList requested = LocaleList.forLanguageTags(args[0]);
+ Object activityManager =
+ Class.forName("android.app.ActivityManager").getMethod("getService").invoke(null);
+ Class> service = Class.forName("android.app.IActivityManager");
+ Method getConfiguration = service.getMethod("getConfiguration");
+ Configuration previous = (Configuration) getConfiguration.invoke(activityManager);
+ Configuration update = new Configuration();
+ update.setLocales(requested);
+ Configuration.class.getField("userSetLocale").setBoolean(update, true);
+ service
+ .getMethod("updatePersistentConfiguration", Configuration.class)
+ .invoke(activityManager, update);
+ Configuration current = (Configuration) getConfiguration.invoke(activityManager);
+ System.out.println("previous=" + previous.getLocales().toLanguageTags());
+ System.out.println("current=" + current.getLocales().toLanguageTags());
+ } catch (Throwable error) {
+ Throwable cause = error instanceof InvocationTargetException ? error.getCause() : error;
+ System.out.println("error=" + cause);
+ System.exit(1);
+ }
+ }
+}
diff --git a/packages/command-surface/src/capture/settings.test.ts b/packages/command-surface/src/capture/settings.test.ts
index c2e0609521..59d809425a 100644
--- a/packages/command-surface/src/capture/settings.test.ts
+++ b/packages/command-surface/src/capture/settings.test.ts
@@ -114,6 +114,20 @@ describe('settings CLI permission', () => {
);
});
+ test('reads locale as a written value the daemon parses again', () => {
+ const locale = settingsCliReader(['locale', 'en_IN'], {
+ targetApp: 'com.example.app',
+ } as CliFlags);
+ expect(locale).toEqual({ setting: 'locale', state: 'en-IN', app: 'com.example.app' });
+ expect(settingsDaemonWriter(locale)).toMatchObject({
+ positionals: ['locale', 'en-IN'],
+ input: { app: 'com.example.app' },
+ });
+ expect(() => settingsCliReader(['locale', 'english'], flags())).toThrow(
+ expect.objectContaining({ code: 'INVALID_ARGS' }),
+ );
+ });
+
test.each(['mobile-data', 'bluetooth'])(
'forwards --app on %s so the daemon refuses it instead of dropping it',
(setting) => {
diff --git a/packages/command-surface/src/capture/settings.ts b/packages/command-surface/src/capture/settings.ts
index abf82994bb..3c71e125a2 100644
--- a/packages/command-surface/src/capture/settings.ts
+++ b/packages/command-surface/src/capture/settings.ts
@@ -25,7 +25,7 @@ import { defineFieldCommandMetadata } from '../field-command-contract.ts';
const SETTINGS_COMMAND_NAME = 'settings';
const settingsCommandDescription =
- 'Read or change supported operating-system settings, animation scales, appearance, time zone, or app permissions on the selected target. Platform support varies by setting and action.';
+ 'Read or change supported operating-system settings, animation scales, appearance, locale, time zone, or app permissions on the selected target. Platform support varies by setting and action.';
const settingsCommandMetadata = defineFieldCommandMetadata(
SETTINGS_COMMAND_NAME,
@@ -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`, `keep-awake`, `bluetooth`, `timezone`, 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`, `bluetooth`, `locale`, `timezone`, 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(),
@@ -101,7 +101,7 @@ export const settingsCommandFacet = defineCommandFacet({
effect: 'destructive',
text: {
summary: 'Change OS settings and app permissions',
- searchHint: 'wifi airplane location dark mode permission grant revoke timezone',
+ searchHint: 'wifi airplane location dark mode permission grant revoke language timezone',
cliDetail: [
'A bare readable setting reads the value the target holds. A target that does not serve a setting refuses it with UNSUPPORTED_OPERATION before anything changes.',
'',
diff --git a/packages/contracts/src/client-settings.test.ts b/packages/contracts/src/client-settings.test.ts
index b55a12f4bf..6537bd9f6a 100644
--- a/packages/contracts/src/client-settings.test.ts
+++ b/packages/contracts/src/client-settings.test.ts
@@ -86,6 +86,14 @@ describe('public client settings cover the catalog', () => {
expectTypeOf<{ setting: 'timezone' }>().not.toExtend();
expectTypeOf().toEqualTypeOf();
});
+
+ test('locale takes a value or reset, and an app to refuse', () => {
+ type Value = Extract;
+ expectTypeOf<{ setting: 'locale'; state: 'en_IN' }>().toExtend();
+ expectTypeOf<{ setting: 'locale'; state: 'reset' }>().toExtend();
+ expectTypeOf<{ setting: 'locale' }>().not.toExtend();
+ expectTypeOf().toEqualTypeOf();
+ });
});
/**
diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts
index 69bf0bcb01..3f4adce3cd 100644
--- a/packages/contracts/src/settings-catalog.ts
+++ b/packages/contracts/src/settings-catalog.ts
@@ -155,6 +155,12 @@ export const SETTINGS = {
appScope: { apple: 'device-level', mobile: 'device-level' },
help: 'Sets the device time zone from an IANA name, such as Asia/Kolkata, on iPhone and iPad simulators (sets TZ in simulator launchd; applies only to apps launched afterwards and is lost when the simulator reboots; the status bar keeps the host time) and Android (the system time zone, with automatic time zone turned off). reset hands it back to the device default: the host Mac time zone on a simulator, and automatic time zone on Android, which applies the network zone a moment later. The response reports the time zone held before. --app is refused.',
},
+ locale: {
+ forms: [{ kind: 'value', placeholder: 'locale-id' }],
+ app: 'input',
+ appScope: { apple: 'device-level', mobile: 'device-level' },
+ help: 'Sets the device language and region from one locale id, such as en_IN or fr-CA, on iPhone and iPad simulators (AppleLanguages and AppleLocale) and Android (the system locale list). reset removes the simulator override, which leaves English with no region, and applies the system image default on Android. The response reports the locale held before. An iOS app reads the locale at launch, so relaunch it; Android applies it to running apps at once. --app is refused.',
+ },
faceid: {
forms: [{ kind: 'choice', states: ['match', 'nonmatch', 'enroll', 'unenroll'] }],
help: 'Simulates Face ID on iPhone and iPad simulators.',
diff --git a/packages/contracts/src/settings.test.ts b/packages/contracts/src/settings.test.ts
index 49a731d255..00f3872295 100644
--- a/packages/contracts/src/settings.test.ts
+++ b/packages/contracts/src/settings.test.ts
@@ -3,6 +3,7 @@ import {
describeSettingRead,
describeSettingWrite,
parseAppearanceAction,
+ parseLocaleId,
parsePermissionAction,
parsePermissionTarget,
parseSettingsMutation,
@@ -46,6 +47,7 @@ describe('settings usage', () => {
'settings appearance ',
`settings text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`,
'settings timezone ',
+ 'settings locale ',
'settings ',
'settings fingerprint ',
'settings clear-app-state [app-id]',
@@ -276,6 +278,47 @@ describe('timezone', () => {
});
});
+describe('locale', () => {
+ test('a locale id is carried as its BCP 47 tag whichever separator and casing it uses', () => {
+ expect(parseSettingsMutation(['Locale', 'en_in'])).toEqual({
+ setting: 'locale',
+ state: 'en-IN',
+ });
+ expect(parseLocaleId('fr-CA')).toBe('fr-CA');
+ expect(parseLocaleId(' zh_hans_cn ')).toBe('zh-Hans-CN');
+ expect(parseLocaleId('es_419')).toBe('es-419');
+ expect(parseLocaleId('EN')).toBe('en');
+ });
+
+ test('a locale with an extension or variant, or no language, is refused before dispatch', () => {
+ for (const value of ['en-US-u-ca-buddhist', 'en_US_POSIX', 'english', 'x', '']) {
+ expectInvalidArgs(() => parseLocaleId(value), `Invalid locale id: ${value}.`);
+ }
+ });
+
+ test('reset is a state of its own, and locale takes exactly one value', () => {
+ expect(parseSettingsMutation(['locale', 'RESET'])).toEqual({
+ setting: 'locale',
+ state: 'reset',
+ });
+ expectInvalidArgs(
+ () => parseSettingsMutation(['locale']),
+ 'settings locale requires a state: .',
+ );
+ expectInvalidArgs(
+ () => parseSettingsMutation(['locale', 'en_IN', 'extra']),
+ SETTINGS_INVALID_ARGS_MESSAGE,
+ );
+ });
+
+ test('locale writes answer with the locale set or the reset', () => {
+ expect(describeSettingWrite('locale', 'en-IN', undefined)).toBe('Locale set to en-IN');
+ expect(describeSettingWrite('locale', 'reset', undefined)).toBe(
+ 'Locale reset to the device default',
+ );
+ });
+});
+
describe('owner parsers', () => {
test('parsePermissionTarget accepts the mobile targets only', () => {
expect(parsePermissionTarget(' Camera ')).toBe('camera');
@@ -335,6 +378,12 @@ describe('settingsAppScope device-wide settings', () => {
expect(settingsAppScope('macos-host', 'timezone', 'reset')).toBe('unknown');
});
+ test('locale changes the whole device on every mobile family', () => {
+ expect(settingsAppScope('apple', 'locale', 'reset')).toBe('device-level');
+ expect(settingsAppScope('mobile', 'locale', 'en-IN')).toBe('device-level');
+ expect(settingsAppScope('macos-host', 'locale', 'reset')).toBe('unknown');
+ });
+
test.each(['mobile-data', 'keep-awake', 'bluetooth'])(
'%s switches the whole device wherever it is served',
(setting) => {
diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts
index 578df33147..cd88822e0b 100644
--- a/packages/contracts/src/settings.ts
+++ b/packages/contracts/src/settings.ts
@@ -75,6 +75,11 @@ export function describeSettingWrite(
? 'Time zone reset to the device default'
: `Time zone set to ${state}`;
}
+ if (setting === 'locale') {
+ return state === SETTING_RESET_STATE
+ ? 'Locale reset to the device default'
+ : `Locale set to ${state}`;
+ }
return `Updated setting: ${setting}`;
}
@@ -419,6 +424,7 @@ type ValueSetting = {
}[SettingName];
const VALUE_PARSERS = {
+ locale: parseLocaleId,
timezone: parseTimeZoneId,
} as const satisfies Record string>;
@@ -453,6 +459,30 @@ function isKnownTimeZone(name: string): boolean {
}
}
+/** A language, an optional script, and an optional region: the parts every owner can write. */
+const LOCALE_ID_PATTERN = /^[a-z]{2,3}(-[A-Z][a-z]{3})?(-([A-Z]{2}|\d{3}))?$/;
+
+/**
+ * The BCP 47 tag of a locale id written with `-` or `_` in any casing, such as `en-IN` for `en_in`.
+ * Extensions and variants are refused: neither owner can apply them.
+ */
+export function parseLocaleId(value: string): string {
+ const canonical = canonicalLocale(value.trim().replaceAll('_', '-'));
+ if (canonical !== undefined && LOCALE_ID_PATTERN.test(canonical)) return canonical;
+ throw new AppError(
+ 'INVALID_ARGS',
+ `Invalid locale id: ${value}. Use a language with an optional script and region, such as en_IN, fr-CA, or zh-Hans-CN.`,
+ );
+}
+
+function canonicalLocale(tag: string): string | undefined {
+ try {
+ return Intl.getCanonicalLocales(tag)[0];
+ } catch {
+ return undefined;
+ }
+}
+
function normalizeName(value: string | undefined): string | undefined {
return value?.trim().toLowerCase();
}
diff --git a/packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts b/packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts
index 2d7521258b..dffa3f86ea 100644
--- a/packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts
+++ b/packages/daemon/src/__tests__/support/snapshot-runtime-fixture.ts
@@ -191,6 +191,7 @@ function settingsFacts(device: DeviceInfo) {
appearance: available,
'text-size': available,
timezone: available,
+ locale: available,
fingerprint: available,
'clear-app-state': available,
permission: available,
@@ -229,6 +230,7 @@ function settingsFacts(device: DeviceInfo) {
permission: available,
'text-size': handheld,
timezone: handheld,
+ locale: handheld,
faceid: handheld,
touchid: handheld,
},
diff --git a/packages/daemon/src/execution/handlers/__tests__/snapshot-settings-handler.test.ts b/packages/daemon/src/execution/handlers/__tests__/snapshot-settings-handler.test.ts
index bc11ede6a5..e4a1425d4f 100644
--- a/packages/daemon/src/execution/handlers/__tests__/snapshot-settings-handler.test.ts
+++ b/packages/daemon/src/execution/handlers/__tests__/snapshot-settings-handler.test.ts
@@ -751,6 +751,63 @@ test('settings timezone refuses an invalid zone and a tvOS leaf before reaching
expect(fixtureSettingsMutations).toHaveLength(0);
});
+test.each([
+ { positionals: ['locale', 'fr_ca'], state: 'fr-CA', message: 'Locale set to fr-CA' },
+ {
+ positionals: ['locale', 'RESET'],
+ state: 'reset',
+ message: 'Locale reset to the device default',
+ },
+])('settings $positionals reaches the owner as the parsed value', async (row) => {
+ const sessionStore = makeSessionStore();
+ const sessionName = `ios-${row.positionals[0]}-${row.state}`;
+ sessionStore.publish(sessionName, makeSession(sessionName, iosSimulatorDevice));
+
+ const response = await handleSnapshotCommands({
+ createCommandSurface: fakeCreateCommandSurface,
+ platformServices: daemonPlatformServicesFixture(),
+ req: snapshotRequest(sessionName, 'settings', { positionals: row.positionals }),
+ sessionName,
+ logPath: '/tmp/daemon.log',
+ sessionStore,
+ });
+
+ expect(response?.ok && response.data).toMatchObject({ state: row.state, message: row.message });
+ expect(fixtureSettingsMutations.at(-1)).toMatchObject({
+ setting: row.positionals[0],
+ state: row.state,
+ });
+});
+
+test('settings locale refuses an invalid id and a tvOS leaf before reaching the owner', async () => {
+ const sessionStore = makeSessionStore();
+ sessionStore.publish('ios-locale-invalid', makeSession('ios-locale-invalid', iosSimulatorDevice));
+ sessionStore.publish('tvos-locale', makeSession('tvos-locale', tvOsSimulatorDevice));
+
+ const invalid = await handleSnapshotCommands({
+ createCommandSurface: fakeCreateCommandSurface,
+ platformServices: daemonPlatformServicesFixture(),
+ req: snapshotRequest('ios-locale-invalid', 'settings', {
+ positionals: ['locale', 'en-u-nu-thai'],
+ }),
+ sessionName: 'ios-locale-invalid',
+ logPath: '/tmp/daemon.log',
+ sessionStore,
+ });
+ const tvos = await handleSnapshotCommands({
+ createCommandSurface: fakeCreateCommandSurface,
+ platformServices: daemonPlatformServicesFixture(),
+ req: snapshotRequest('tvos-locale', 'settings', { positionals: ['locale', 'en_IN'] }),
+ sessionName: 'tvos-locale',
+ logPath: '/tmp/daemon.log',
+ sessionStore,
+ });
+
+ expect(invalid?.ok === false && invalid.error.code).toBe('INVALID_ARGS');
+ expect(tvos?.ok === false && tvos.error.code).toBe('UNSUPPORTED_OPERATION');
+ expect(fixtureSettingsMutations).toHaveLength(0);
+});
+
// A macOS permission is a host-level TCC grant, so naming an app is refused rather than dropped.
test('settings mobile-data reaches the Android owner as an on/off mutation', async () => {
const sessionStore = makeSessionStore();
@@ -774,6 +831,7 @@ test.each([
['mobile-data', 'off'],
['keep-awake', 'off'],
['bluetooth', 'off'],
+ ['locale', 'en_IN'],
['timezone', 'Asia/Kolkata'],
])('settings Android %s refuses a named app before reaching the owner', async (setting, state) => {
const sessionStore = makeSessionStore();
diff --git a/packages/platform-android/src/__tests__/settings-locale.test.ts b/packages/platform-android/src/__tests__/settings-locale.test.ts
new file mode 100644
index 0000000000..9e437ec526
--- /dev/null
+++ b/packages/platform-android/src/__tests__/settings-locale.test.ts
@@ -0,0 +1,129 @@
+import { expect, test, vi } from 'vitest';
+import { setAndroidSetting } from '../settings.ts';
+import { ANDROID_EMULATOR } from './test-utils/device-fixtures.ts';
+import { withFakeAdb, type FakeAdbResponse } from './test-utils/fake-adb.ts';
+
+vi.mock('../automation-helper-artifact.ts', () => ({
+ prepareAndroidAutomationHelper: vi.fn(async () => ({
+ artifact: { manifest: { packageName: 'com.callstack.agentdevice.snapshothelper' } },
+ })),
+}));
+
+const APK = '/data/app/~~a1==/com.callstack.agentdevice.snapshothelper-b2==/base.apk';
+const PM_PATH = 'shell pm path com.callstack.agentdevice.snapshothelper';
+/** `pm path` lists a split before the base APK, which is the one that holds the helper classes. */
+const PM_PATH_OUTPUT = `package:${APK.replace('base.apk', 'split_config.arm64_v8a.apk')}\npackage:${APK}\n`;
+const LOCALE_COMMAND = `shell env 'CLASSPATH=${APK}' app_process /system/bin com.callstack.agentdevice.snapshothelper.SystemLocaleCommand`;
+
+/** A device whose locale command answers like the helper class: `previous=` and `current=` lines. */
+function localeDevice(options: {
+ applied?: (requested: string) => string;
+ defaultLocale?: string;
+}) {
+ let current = 'en-US';
+ return (args: string[]): FakeAdbResponse => {
+ const flat = args.join(' ');
+ if (flat === PM_PATH) return PM_PATH_OUTPUT;
+ if (flat === 'shell getprop ro.product.locale') return `${options.defaultLocale ?? 'en-US'}\n`;
+ if (flat.startsWith(`${LOCALE_COMMAND} `)) {
+ const requested = flat.slice(LOCALE_COMMAND.length + 1);
+ const previous = current;
+ current = options.applied?.(requested) ?? requested;
+ return `previous=${previous}\ncurrent=${current}\n`;
+ }
+ return { stderr: `unexpected args: ${flat}`, exitCode: 1 };
+ };
+}
+
+test('settings locale runs the helper class as the shell user and reports the prior locale', async () => {
+ await withFakeAdb(localeDevice({}), async ({ calls, device }) => {
+ const result = await setAndroidSetting(device, 'locale', 'en-IN');
+ expect(result).toEqual({ locale: 'en-IN', previousLocale: 'en-US' });
+ expect(calls.map((args) => args.join(' '))).toContain(`${LOCALE_COMMAND} en-IN`);
+ });
+});
+
+test('settings locale runs through app_process on a physical Android device as well as an emulator', async () => {
+ const physical = { ...ANDROID_EMULATOR, id: 'R5CT1234', kind: 'device' as const };
+ await withFakeAdb(
+ localeDevice({}),
+ async ({ calls, device }) => {
+ const result = await setAndroidSetting(device, 'locale', 'en-IN');
+ expect(result).toEqual({ locale: 'en-IN', previousLocale: 'en-US' });
+ expect(calls.map((args) => args.join(' '))).toContain(`${LOCALE_COMMAND} en-IN`);
+ },
+ { device: physical },
+ );
+});
+
+test('settings locale reset applies the locale the image boots with', async () => {
+ await withFakeAdb(localeDevice({ defaultLocale: 'fr-FR' }), async ({ calls, device }) => {
+ expect(await setAndroidSetting(device, 'locale', 'reset')).toMatchObject({ locale: 'fr-FR' });
+ expect(calls.map((args) => args.join(' '))).toContain(`${LOCALE_COMMAND} fr-FR`);
+ });
+});
+
+test('settings locale reset refuses with dispatched no when ro.product.locale is empty', async () => {
+ await withFakeAdb(localeDevice({ defaultLocale: '' }), async ({ device }) => {
+ await expect(setAndroidSetting(device, 'locale', 'reset')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { dispatched: 'no' },
+ });
+ });
+});
+
+test('settings locale fails with dispatched no when pm path reports no base APK', async () => {
+ const script = (args: string[]): FakeAdbResponse => {
+ if (args.join(' ') === PM_PATH) return 'package:/data/app/split_config.arm64_v8a.apk\n';
+ return { stderr: `unexpected args: ${args.join(' ')}`, exitCode: 1 };
+ };
+ await withFakeAdb(script, async ({ device }) => {
+ await expect(setAndroidSetting(device, 'locale', 'en-IN')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { dispatched: 'no' },
+ });
+ });
+});
+
+test('settings locale fails with locale-not-applied when the device keeps another locale', async () => {
+ await withFakeAdb(localeDevice({ applied: () => 'en-US' }), async ({ device }) => {
+ await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { reason: 'locale-not-applied', dispatched: 'unknown', locale: 'de-DE' },
+ });
+ });
+});
+
+test('settings locale fails when app_process exits non-zero after printing a locale', async () => {
+ const script = (args: string[]): FakeAdbResponse => {
+ const flat = args.join(' ');
+ if (flat === PM_PATH) return PM_PATH_OUTPUT;
+ if (flat.startsWith(LOCALE_COMMAND)) {
+ return { stdout: 'previous=en-US\ncurrent=de-DE\n', exitCode: 1 };
+ }
+ return { stderr: `unexpected args: ${flat}`, exitCode: 1 };
+ };
+ await withFakeAdb(script, async ({ device }) => {
+ await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { dispatched: 'unknown', exitCode: 1 },
+ });
+ });
+});
+
+test('settings locale surfaces the helper error when the update is refused', async () => {
+ const script = (args: string[]): FakeAdbResponse => {
+ const flat = args.join(' ');
+ if (flat === PM_PATH) return PM_PATH_OUTPUT;
+ if (flat.startsWith(LOCALE_COMMAND)) {
+ return { stdout: 'error=java.lang.SecurityException: denied\n', exitCode: 1 };
+ }
+ return { stderr: `unexpected args: ${flat}`, exitCode: 1 };
+ };
+ await withFakeAdb(script, async ({ device }) => {
+ await expect(setAndroidSetting(device, 'locale', 'de-DE')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { dispatched: 'unknown', helperError: 'java.lang.SecurityException: denied' },
+ });
+ });
+});
diff --git a/packages/platform-android/src/helper-package-install.ts b/packages/platform-android/src/helper-package-install.ts
index af82ef01b1..e507b1a40b 100644
--- a/packages/platform-android/src/helper-package-install.ts
+++ b/packages/platform-android/src/helper-package-install.ts
@@ -283,7 +283,8 @@ async function readInstalledAndroidPackageSha256(
}
}
-function readBaseApkPath(output: string): string | undefined {
+/** The base APK path among the `package:` lines `pm path` prints. */
+export function readBaseApkPath(output: string): string | undefined {
return output
.split(/\r?\n/)
.map((line) => (line.startsWith('package:') ? line.slice('package:'.length).trim() : ''))
diff --git a/packages/platform-android/src/runtime.test.ts b/packages/platform-android/src/runtime.test.ts
index cc8e4325fc..b06020dff7 100644
--- a/packages/platform-android/src/runtime.test.ts
+++ b/packages/platform-android/src/runtime.test.ts
@@ -416,13 +416,15 @@ test('admits both clipboard halves and the app switcher on every real Android ki
// R57: the deep link opens through `am start` on the same cell.
expect(binding.facts.operations.triggerAppEvent).toEqual({ available: true });
expect(binding.operations.triggerAppEvent).toBeTypeOf('function');
- // R58: settings run over adb (`appops`, `settings put`, `pm clear`, `cmd alarm`, …) on both
- // emulators and physical devices, and so does the read leg (`settings get system font_scale`).
+ // R58: settings run over adb (`appops`, `settings put`, `pm clear`, `cmd alarm`, `app_process`,
+ // …) on both emulators and physical devices, and so does the read leg (`settings get system
+ // font_scale`).
const { setSetting, readSetting } = binding.facts.operations;
for (const setting of ANDROID_SETTINGS) {
expect(runtimeSubjectFact(setSetting, setting)).toEqual({ available: true });
}
expect(runtimeSubjectFact(setSetting, 'timezone')).toEqual({ available: true });
+ expect(runtimeSubjectFact(setSetting, 'locale')).toEqual({ available: true });
expect(runtimeSubjectFact(setSetting, 'reset-keychain')).toMatchObject({
available: false,
reason: 'unsupported-platform-leaf',
diff --git a/packages/platform-android/src/runtime.ts b/packages/platform-android/src/runtime.ts
index 3f6510f842..119d243bb6 100644
--- a/packages/platform-android/src/runtime.ts
+++ b/packages/platform-android/src/runtime.ts
@@ -411,6 +411,7 @@ export function createAndroidPlatformRuntime(host: PlatformRuntimeHost): Platfor
appearance: available,
'text-size': available,
timezone: available,
+ locale: available,
fingerprint: available,
'clear-app-state': available,
permission: available,
diff --git a/packages/platform-android/src/settings-locale.ts b/packages/platform-android/src/settings-locale.ts
new file mode 100644
index 0000000000..324517049e
--- /dev/null
+++ b/packages/platform-android/src/settings-locale.ts
@@ -0,0 +1,91 @@
+import { SETTING_RESET_STATE } from '@agent-device/contracts/settings-catalog';
+import type { DeviceInfo } from '@agent-device/kernel/device';
+import { AppError, discloseDispatch, type ReasonTable } from '@agent-device/kernel/errors';
+import { runAndroidShell } from './adb.ts';
+import { androidAdbResultError } from './adb-failure.ts';
+
+/** The `error.details.reason` a locale write states when the device kept another locale. */
+const ANDROID_LOCALE_REASONS = {
+ // The Android system locale list did not start with the requested locale after the update.
+ localeNotApplied: { reason: 'locale-not-applied' },
+} as const satisfies ReasonTable<'settings'>;
+
+/** The helper class that runs as the shell user through `app_process`; see its Javadoc. */
+const SYSTEM_LOCALE_COMMAND = 'com.callstack.agentdevice.snapshothelper.SystemLocaleCommand';
+
+/**
+ * Sets the system locale list to one locale, a BCP 47 tag the settings contract already parsed.
+ * `adb shell` has no command for it (`cmd locale` sets per-app locales only, and
+ * `persist.sys.locale` needs root and a framework restart), so the helper APK's
+ * {@link SYSTEM_LOCALE_COMMAND} makes the update as the shell user. reset applies
+ * `ro.product.locale`, the locale the image boots with before anyone picks one.
+ */
+export async function setAndroidLocale(
+ device: DeviceInfo,
+ state: string,
+ signal?: AbortSignal,
+): Promise> {
+ const requested = state === SETTING_RESET_STATE ? await readAndroidDefaultLocale(device) : state;
+ const { prepareAndroidAutomationHelper } = await import('./automation-helper-artifact.ts');
+ const prepared = await prepareAndroidAutomationHelper(device, signal);
+ const apkPath = await readInstalledApkPath(device, prepared.artifact.manifest.packageName);
+ signal?.throwIfAborted();
+ const result = await runAndroidShell(
+ device,
+ ['env', `CLASSPATH=${apkPath}`, 'app_process', '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/system/bin', SYSTEM_LOCALE_COMMAND, requested],
+ { allowFailure: true, signal },
+ );
+ const fields = readKeyValueLines(result.stdout);
+ if (result.exitCode !== 0 || fields.current === undefined) {
+ throw discloseDispatch(
+ androidAdbResultError('Failed to set the Android system locale', result, {
+ locale: requested,
+ ...(fields.error === undefined ? {} : { helperError: fields.error }),
+ }),
+ 'unknown',
+ );
+ }
+ const current = fields.current.split(',')[0] ?? '';
+ if (current.toLowerCase() !== requested.toLowerCase()) {
+ throw new AppError('COMMAND_FAILED', `Android kept the locale ${current || '(empty)'}.`, {
+ reason: ANDROID_LOCALE_REASONS.localeNotApplied.reason,
+ dispatched: 'unknown',
+ locale: requested,
+ locales: fields.current,
+ });
+ }
+ return { locale: current, previousLocale: fields.previous?.split(',')[0] ?? null };
+}
+
+async function readAndroidDefaultLocale(device: DeviceInfo): Promise {
+ const result = await runAndroidShell(device, ['getprop', 'ro.product.locale']);
+ const reported = result.stdout.trim();
+ if (reported.length > 0) return reported;
+ throw new AppError('COMMAND_FAILED', 'Android reported no default locale in ro.product.locale.', {
+ deviceId: device.id,
+ dispatched: 'no',
+ hint: 'Pass the locale to restore, such as settings locale en-US.',
+ });
+}
+
+/** The helper's base APK, which holds the class `app_process` loads. */
+async function readInstalledApkPath(device: DeviceInfo, packageName: string): Promise {
+ const { readBaseApkPath } = await import('./helper-package-install.ts');
+ const result = await runAndroidShell(device, ['pm', 'path', packageName]);
+ const apkPath = readBaseApkPath(result.stdout);
+ if (apkPath !== undefined) return apkPath;
+ throw new AppError('COMMAND_FAILED', `Android reported no base APK path for ${packageName}.`, {
+ deviceId: device.id,
+ dispatched: 'no',
+ stdout: result.stdout,
+ });
+}
+
+function readKeyValueLines(output: string): Record {
+ const fields: Record = {};
+ for (const line of output.split('\n')) {
+ const separator = line.indexOf('=');
+ if (separator > 0) fields[line.slice(0, separator).trim()] = line.slice(separator + 1).trim();
+ }
+ return fields;
+}
diff --git a/packages/platform-android/src/settings.ts b/packages/platform-android/src/settings.ts
index 3524348e93..cf2586dcf7 100644
--- a/packages/platform-android/src/settings.ts
+++ b/packages/platform-android/src/settings.ts
@@ -59,6 +59,7 @@ export const ANDROID_SETTINGS = [
'appearance',
'text-size',
'timezone',
+ 'locale',
'fingerprint',
'clear-app-state',
'permission',
@@ -234,6 +235,10 @@ export async function setAndroidSetting(
const { setAndroidTimeZone } = await import('./settings-timezone.ts');
return await setAndroidTimeZone(device, state);
}
+ case 'locale': {
+ const { setAndroidLocale } = await import('./settings-locale.ts');
+ return await setAndroidLocale(device, state, signal);
+ }
default:
return normalized satisfies never;
}
diff --git a/packages/platform-apple/src/core/__tests__/settings-locale.test.ts b/packages/platform-apple/src/core/__tests__/settings-locale.test.ts
new file mode 100644
index 0000000000..f12908f607
--- /dev/null
+++ b/packages/platform-apple/src/core/__tests__/settings-locale.test.ts
@@ -0,0 +1,126 @@
+import { expect, test } from 'vitest';
+
+import { setIosSetting } from '../app-settings.ts';
+import { withFakeAppleTool, type FakeAppleToolResponse } from '../../__tests__/fake-apple-tool.ts';
+import { IOS_TEST_SIMULATOR } from './apple-core-stub-helpers.ts';
+
+const BOOTED_SIM_LIST_JSON = JSON.stringify({
+ devices: { 'com.apple.CoreSimulator.SimRuntime.iOS-18-0': [{ udid: 'sim-1', state: 'Booted' }] },
+});
+const MISSING_KEY = {
+ stderr: "Error: Could not find key 'AppleLocale' in domain 'kCFPreferencesAnyApplication'.",
+ exitCode: 1,
+};
+
+/** The global domain as `defaults export -g -` prints it. */
+function exportedDomain(defaults: ReadonlyMap): string {
+ const entries = [...defaults].map(([key, value]) =>
+ key === 'AppleLanguages'
+ ? `${key}\n\n${value
+ .split(',')
+ .map((language) => `${language}`)
+ .join('\n')}\n`
+ : `${key}\n${value}`,
+ );
+ return `\n\n\n${entries.join('\n')}\n\n\n`;
+}
+
+/** A simulator's global domain, driven through `simctl spawn`. */
+function simulator(initial: { locale?: string } = {}) {
+ const defaults = new Map();
+ if (initial.locale !== undefined) {
+ defaults.set('AppleLanguages', 'en-US,en-IN');
+ defaults.set('AppleLocale', initial.locale);
+ }
+ return (args: string[]): FakeAppleToolResponse => {
+ if (args[0] === 'simctl' && args.includes('list')) return BOOTED_SIM_LIST_JSON;
+ const spawned = args.join(' ').replace(/^simctl spawn sim-1 /, '');
+ if (spawned === 'defaults export -g -') return exportedDomain(defaults);
+ const write = /^defaults write -g (\w+) -(?:array|string) (\S+)$/.exec(spawned);
+ if (write) {
+ defaults.set(write[1]!, write[2]!);
+ return '';
+ }
+ const remove = /^defaults delete -g (\w+)$/.exec(spawned);
+ if (remove) return defaults.delete(remove[1]!) ? '' : MISSING_KEY;
+ return { stderr: `unexpected xcrun args: ${args.join(' ')}`, exitCode: 1 };
+ };
+}
+
+function spawnedCalls(calls: string[][]): string[] {
+ return calls
+ .filter((args) => args[1] === 'spawn')
+ .map((args) => args.slice(3).join(' '))
+ .filter((call) => !call.includes(' export '));
+}
+
+async function set(state: string) {
+ return await setIosSetting(IOS_TEST_SIMULATOR, 'locale', state, undefined, undefined, {});
+}
+
+test('settings locale writes AppleLanguages as a tag and AppleLocale with an underscore', async () => {
+ await withFakeAppleTool(simulator({ locale: 'en_US' }), async ({ calls }) => {
+ expect(await set('zh-Hans-CN')).toMatchObject({
+ locale: 'zh-Hans-CN',
+ previousLocale: 'en-US',
+ warnings: [expect.stringContaining('relaunch')],
+ });
+ expect(spawnedCalls(calls)).toEqual([
+ 'defaults write -g AppleLanguages -array zh-Hans-CN',
+ 'defaults write -g AppleLocale -string zh-Hans_CN',
+ ]);
+ });
+});
+
+test('settings locale writes a language-only tag without adding an underscore', async () => {
+ await withFakeAppleTool(simulator(), async ({ calls }) => {
+ expect(await set('en')).toMatchObject({ locale: 'en', previousLocale: null });
+ expect(spawnedCalls(calls)).toEqual([
+ 'defaults write -g AppleLanguages -array en',
+ 'defaults write -g AppleLocale -string en',
+ ]);
+ });
+});
+
+test('settings locale reset deletes both keys and reports the locale it held', async () => {
+ await withFakeAppleTool(simulator({ locale: 'en_US@rg=inzzzz' }), async ({ calls }) => {
+ // Foundation's keyword is dropped so the reported locale is one settings locale accepts.
+ expect(await set('reset')).toMatchObject({
+ locale: null,
+ previousLocale: 'en-US',
+ previousLanguages: ['en-US', 'en-IN'],
+ });
+ expect(spawnedCalls(calls)).toEqual([
+ 'defaults delete -g AppleLanguages',
+ 'defaults delete -g AppleLocale',
+ ]);
+ });
+});
+
+test('settings locale reset on a simulator that holds no locale deletes nothing', async () => {
+ await withFakeAppleTool(simulator(), async ({ calls }) => {
+ expect(await set('reset')).toMatchObject({
+ locale: null,
+ previousLocale: null,
+ previousLanguages: null,
+ });
+ expect(spawnedCalls(calls)).toEqual([]);
+ });
+});
+
+test('a Foundation locale settings locale cannot take is reported as null', async () => {
+ await withFakeAppleTool(simulator({ locale: 'en_US_POSIX' }), async () => {
+ expect(await set('fr-FR')).toMatchObject({ locale: 'fr-FR', previousLocale: null });
+ });
+});
+
+test('a failed defaults write fails the setting with the simctl output', async () => {
+ const script = (args: string[]): FakeAppleToolResponse =>
+ args.includes('write') ? { stderr: 'cfprefsd unavailable', exitCode: 1 } : simulator()(args);
+ await withFakeAppleTool(script, async () => {
+ await expect(set('en-IN')).rejects.toMatchObject({
+ code: 'COMMAND_FAILED',
+ details: { stderr: 'cfprefsd unavailable' },
+ });
+ });
+});
diff --git a/packages/platform-apple/src/core/app-settings.ts b/packages/platform-apple/src/core/app-settings.ts
index b1da500900..7605e997fc 100644
--- a/packages/platform-apple/src/core/app-settings.ts
+++ b/packages/platform-apple/src/core/app-settings.ts
@@ -25,6 +25,7 @@ import { closeIosApp } from './app-launch.ts';
import { applySimctlSetting } from './simctl-settings.ts';
import { readIosTextSize, setIosTextSize } from './settings-text-size.ts';
import { setIosTimeZone } from './settings-timezone.ts';
+import { setIosLocale } from './settings-locale.ts';
import { resolveIosApp } from './app-resolution.ts';
import { buildSimctlArgsForDevice } from './simctl.ts';
import { runSimctlForDevice } from './simctl-execution.ts';
@@ -51,6 +52,7 @@ const APPLE_SIMULATOR_SETTINGS = [
'permission',
'text-size',
'timezone',
+ 'locale',
'faceid',
'touchid',
] as const satisfies readonly SettingName[];
@@ -190,6 +192,8 @@ export async function setIosSetting(
}
case 'timezone':
return await setIosTimeZone(device, state);
+ case 'locale':
+ return await setIosLocale(device, state);
case 'appearance':
case 'permission':
case 'location':
diff --git a/packages/platform-apple/src/core/settings-locale.ts b/packages/platform-apple/src/core/settings-locale.ts
new file mode 100644
index 0000000000..9e2e43a418
--- /dev/null
+++ b/packages/platform-apple/src/core/settings-locale.ts
@@ -0,0 +1,99 @@
+import { parseLocaleId } from '@agent-device/contracts/settings';
+import { SETTING_RESET_STATE } from '@agent-device/contracts/settings-catalog';
+import type { DeviceInfo } from '@agent-device/kernel/device';
+import { requireExecSuccess } from '@agent-device/host-kit/command';
+import { runSimctlForDevice } from './simctl-execution.ts';
+
+/**
+ * Applies a BCP 47 tag the settings contract already parsed, or `reset`. The language and region
+ * live in the simulator's global preferences domain, which every app reads at launch. `simctl spawn`
+ * runs `defaults` inside the simulator, so the write goes through the simulator's own preferences
+ * daemon rather than a plist a running daemon would overwrite.
+ */
+export async function setIosLocale(
+ device: DeviceInfo,
+ state: string,
+): Promise> {
+ const locale = state === SETTING_RESET_STATE ? undefined : state;
+ const previous = await readLocaleDefaults(device);
+ if (locale === undefined) {
+ // Only the keys the domain holds: deleting an absent key fails, and reset already holds there.
+ for (const key of previous.keys) await runDefaults(device, ['delete', '-g', key]);
+ } else {
+ await runDefaults(device, ['write', '-g', 'AppleLanguages', '-array', locale]);
+ await runDefaults(device, [
+ 'write',
+ '-g',
+ 'AppleLocale',
+ '-string',
+ appleLocaleIdentifier(locale),
+ ]);
+ }
+ return {
+ locale: locale ?? null,
+ previousLocale: previous.locale,
+ previousLanguages: previous.languages,
+ warnings: ['Running apps keep the old locale until they relaunch; run open --relaunch.'],
+ };
+}
+
+/** `en-IN` is `en_IN` to Foundation; a script stays joined to the language, as in `zh-Hans_CN`. */
+function appleLocaleIdentifier(languageTag: string): string {
+ const parts = languageTag.split('-');
+ const region = parts.at(-1);
+ if (parts.length < 2 || region === undefined || !/^([A-Z]{2}|\d{3})$/.test(region)) {
+ return languageTag;
+ }
+ return `${parts.slice(0, -1).join('-')}_${region}`;
+}
+
+/**
+ * The locale keys the global domain holds. `defaults export` answers with the whole domain as an XML
+ * plist, so an absent key is just absent rather than a failure whose wording varies by runtime.
+ * The locale is reported as a tag `settings locale` accepts, so a reset can be undone with it:
+ * Foundation keeps keywords such as `@rg=inzzzz` that the command does not take, and the full
+ * list of preferred languages is reported beside it.
+ */
+async function readLocaleDefaults(device: DeviceInfo): Promise<{
+ locale: string | null;
+ languages: readonly string[] | null;
+ keys: readonly string[];
+}> {
+ const { stdout } = await runSimctlChecked(
+ device,
+ ['defaults', 'export', '-g', '-'],
+ 'Failed to read the iOS simulator locale',
+ );
+ const keys = LOCALE_KEYS.filter((key) => stdout.includes(`${key}`));
+ const appleLocale = /AppleLocale<\/key>\s*([^<]*)<\/string>/.exec(stdout)?.[1];
+ const languages = /AppleLanguages<\/key>\s*([\s\S]*?)<\/array>/.exec(stdout)?.[1];
+ return {
+ locale: appleLocale === undefined ? null : acceptedLocale(appleLocale.split('@')[0] ?? ''),
+ languages:
+ languages === undefined
+ ? null
+ : [...languages.matchAll(/([^<]*)<\/string>/g)].map((match) => match[1] ?? ''),
+ keys,
+ };
+}
+
+function acceptedLocale(appleLocale: string): string | null {
+ try {
+ return parseLocaleId(appleLocale);
+ } catch {
+ return null;
+ }
+}
+
+const LOCALE_KEYS = ['AppleLanguages', 'AppleLocale'] as const;
+
+async function runDefaults(device: DeviceInfo, args: readonly string[]): Promise {
+ await runSimctlChecked(device, ['defaults', ...args], 'Failed to set the iOS simulator locale');
+}
+
+async function runSimctlChecked(device: DeviceInfo, args: readonly string[], message: string) {
+ return requireExecSuccess(
+ await runSimctlForDevice(device, ['spawn', device.id, ...args], { allowFailure: true }),
+ message,
+ );
+}
diff --git a/packages/platform-apple/src/system/runtime.test.ts b/packages/platform-apple/src/system/runtime.test.ts
index 5fd3f77bd6..265db34665 100644
--- a/packages/platform-apple/src/system/runtime.test.ts
+++ b/packages/platform-apple/src/system/runtime.test.ts
@@ -134,26 +134,35 @@ test.each([
{
appleOs: 'ios',
kind: 'simulator',
- served: ['wifi', 'location', 'text-size', 'timezone', 'faceid', 'touchid', 'reset-keychain'],
+ served: [
+ 'wifi',
+ 'location',
+ 'text-size',
+ 'locale',
+ 'timezone',
+ 'faceid',
+ 'touchid',
+ 'reset-keychain',
+ ],
refused: ['animations', 'fingerprint'],
},
{
appleOs: 'ipados',
kind: 'simulator',
- served: ['appearance', 'text-size', 'timezone', 'faceid', 'touchid'],
+ served: ['appearance', 'text-size', 'locale', 'timezone', 'faceid', 'touchid'],
refused: ['animations', 'fingerprint'],
},
{
appleOs: 'tvos',
kind: 'simulator',
served: ['wifi', 'appearance', 'clear-app-state'],
- refused: ['text-size', 'timezone', 'faceid', 'touchid'],
+ refused: ['text-size', 'locale', 'timezone', 'faceid', 'touchid'],
},
{
appleOs: 'macos',
kind: 'device',
served: ['appearance', 'permission'],
- refused: ['wifi', 'text-size', 'timezone', 'clear-app-state', 'reset-keychain'],
+ refused: ['wifi', 'text-size', 'locale', 'timezone', 'clear-app-state', 'reset-keychain'],
},
] as const)('an Apple $appleOs $kind serves each setting on its own fact', (row) => {
const { setSetting } = appleSystemFacts(appleDevice(row.appleOs, row.kind));
diff --git a/packages/platform-apple/src/system/runtime.ts b/packages/platform-apple/src/system/runtime.ts
index 7d5890d5c9..da0c6e700d 100644
--- a/packages/platform-apple/src/system/runtime.ts
+++ b/packages/platform-apple/src/system/runtime.ts
@@ -64,7 +64,7 @@ const macOsSettingUnavailable = Object.freeze({
} as const);
/**
* Content size and BiometricKit_Sim notifications answer only on iPhone and iPad simulators. The
- * time zone write is admitted there too, and nowhere else in the Apple family.
+ * locale and time zone writes are admitted there too, and nowhere else in the Apple family.
*/
const handheldSimulatorUnavailable = Object.freeze({
available: false,
@@ -197,6 +197,7 @@ function appleSettingsFacts(device: DeviceInfo) {
permission: available,
'text-size': handheld,
timezone: handheld,
+ locale: handheld,
faceid: handheld,
touchid: handheld,
} satisfies Record,
diff --git a/packages/provider-limrun/src/interaction-operations.test.ts b/packages/provider-limrun/src/interaction-operations.test.ts
index 297d688cfd..4dba2a0a74 100644
--- a/packages/provider-limrun/src/interaction-operations.test.ts
+++ b/packages/provider-limrun/src/interaction-operations.test.ts
@@ -141,10 +141,11 @@ test('app-event delivery is admitted on both direct-session legs', () => {
expect(factsFor(iosDevice, false).triggerAppEvent).toEqual(liveSessionUnavailable);
});
-test('iOS inherits shared settings except keychain reset and time zone', () => {
+test('iOS inherits shared settings except keychain reset, locale and time zone', () => {
const android = limrunAndroidSettingsFacts();
expect(runtimeSubjectFact(android.setSetting, 'animations').available).toBe(true);
expect(runtimeSubjectFact(android.setSetting, 'timezone').available).toBe(true);
+ expect(runtimeSubjectFact(android.setSetting, 'locale').available).toBe(true);
const ios = limrunAppleSettingsFacts(testIosRunner.facts);
for (const setting of [
'appearance',
@@ -163,6 +164,10 @@ test('iOS inherits shared settings except keychain reset and time zone', () => {
available: false,
reason: 'unsupported-provider-mode',
});
+ expect(runtimeSubjectFact(ios.setSetting, 'locale')).toMatchObject({
+ available: false,
+ reason: 'unsupported-provider-mode',
+ });
expect(runtimeSubjectFact(ios.readSetting, 'text-size').available).toBe(true);
expect(limrunAndroidSettingsFacts(liveSessionUnavailable).setSetting).toEqual(
liveSessionUnavailable,
diff --git a/packages/provider-limrun/src/interaction-operations.ts b/packages/provider-limrun/src/interaction-operations.ts
index e97cc3bf09..bf9eef8e8b 100644
--- a/packages/provider-limrun/src/interaction-operations.ts
+++ b/packages/provider-limrun/src/interaction-operations.ts
@@ -198,6 +198,7 @@ export function limrunAndroidSettingsFacts(
appearance: available,
'text-size': available,
timezone: available,
+ locale: available,
fingerprint: available,
'clear-app-state': available,
permission: available,
@@ -225,6 +226,10 @@ export function limrunAppleSettingsFacts(
PLATFORM_RUNTIME_REASONS.unsupportedProviderMode.reason,
'Limrun iOS does not expose simulator launchd time zone overrides; set it on a local simulator.',
),
+ locale: unavailableFact(
+ PLATFORM_RUNTIME_REASONS.unsupportedProviderMode.reason,
+ 'Limrun iOS does not expose simulator locale preferences; set it on a local simulator.',
+ ),
},
}
: (setting ?? unsupported),
diff --git a/test/integration/android-emulator-e2e/live-harness.ts b/test/integration/android-emulator-e2e/live-harness.ts
index 1faa3b5d4b..40f8fc04d1 100644
--- a/test/integration/android-emulator-e2e/live-harness.ts
+++ b/test/integration/android-emulator-e2e/live-harness.ts
@@ -88,6 +88,7 @@ export async function cleanupSession(context: LiveContext): Promise {
['bind fixture before Android permission reset', ['open', context.appId]],
['reset Android microphone permission', ['settings', 'permission', 'reset', 'microphone']],
['reset Android time zone', ['settings', 'timezone', 'reset']],
+ ['reset Android locale', ['settings', 'locale', 'reset']],
] as const) {
try {
await runStep(context, `cleanup: ${step}`, [...args]);
diff --git a/test/integration/android-emulator-e2e/live-lifecycle-scenario.ts b/test/integration/android-emulator-e2e/live-lifecycle-scenario.ts
index 1d281240e9..5cc1d84730 100644
--- a/test/integration/android-emulator-e2e/live-lifecycle-scenario.ts
+++ b/test/integration/android-emulator-e2e/live-lifecycle-scenario.ts
@@ -18,6 +18,7 @@ export async function assertLifecycleAndSystem(context: LiveContext): Promise {
verifyCommand(context, C.settings, 'time zone set and reset report what they changed');
}
+/** Each write reports what it set, and reset reports what it replaced. */
+async function assertLocaleRoundTrip(context: LiveContext): Promise {
+ const locale = await runStep(context, 'set Android en_IN locale', [
+ 'settings',
+ 'locale',
+ 'en_IN',
+ ]);
+ assert.equal(locale.json?.data?.locale, 'en-IN', JSON.stringify(locale.json));
+ const localeReset = await runStep(context, 'reset Android locale', [
+ 'settings',
+ 'locale',
+ 'reset',
+ ]);
+ assert.equal(localeReset.json?.data?.previousLocale, 'en-IN', JSON.stringify(localeReset.json));
+ verifyCommand(context, C.settings, 'locale set and reset report what they changed');
+}
+
// Leaves the fixture on Automation lab with its permission controls on screen: Android
// snapshots only carry on-screen nodes, and a relaunch always lands above the controls.
async function openAutomationLab(context: LiveContext, step: string): Promise {
diff --git a/test/integration/ios-simulator-e2e/live-full-scenarios.ts b/test/integration/ios-simulator-e2e/live-full-scenarios.ts
index 16d249f71e..c78b97e207 100644
--- a/test/integration/ios-simulator-e2e/live-full-scenarios.ts
+++ b/test/integration/ios-simulator-e2e/live-full-scenarios.ts
@@ -101,10 +101,11 @@ export async function assertLifecycleAndSystem(context: LiveContext): Promise {
JSON.stringify(zoneReset.json),
);
}
+
+/** Each write reports what it set, and reset reports what it cleared. */
+async function assertLocaleRoundTrip(context: LiveContext): Promise {
+ const locale = await runStep(context, 'set en_IN locale', ['settings', 'locale', 'en_IN']);
+ assert.equal(locale.json?.data?.locale, 'en-IN', JSON.stringify(locale.json));
+ const localeReset = await runStep(context, 'reset locale', ['settings', 'locale', 'reset']);
+ assert.equal(localeReset.json?.data?.locale, null, JSON.stringify(localeReset.json));
+ assert.equal(localeReset.json?.data?.previousLocale, 'en-IN', JSON.stringify(localeReset.json));
+}
diff --git a/test/integration/ios-simulator-e2e/live-harness.ts b/test/integration/ios-simulator-e2e/live-harness.ts
index 56e924ab16..ab1c76ee82 100644
--- a/test/integration/ios-simulator-e2e/live-harness.ts
+++ b/test/integration/ios-simulator-e2e/live-harness.ts
@@ -104,6 +104,7 @@ export async function cleanupSession(context: LiveContext): Promise {
[MICROPHONE_PERMISSION_RESET_STEP, ['settings', 'permission', 'reset', 'microphone']],
['restore light appearance', ['settings', 'appearance', 'light']],
['reset time zone', ['settings', 'timezone', 'reset']],
+ ['reset locale', ['settings', 'locale', 'reset']],
['restore portrait orientation', ['orientation', 'portrait']],
);
}
diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md
index ec80f7c685..e305c22aa2 100644
--- a/website/docs/docs/commands.md
+++ b/website/docs/docs/commands.md
@@ -1755,7 +1755,7 @@ agent-device trigger-app-event screenshot_taken '{"source":"qa"}'
Change OS settings and app permissions.
```bash
-agent-device settings | settings location set | settings appearance | 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 timezone | settings | settings fingerprint | settings clear-app-state [app-id] | settings reset-keychain clear | settings permission | settings permission photos [full|limited] | settings permission [--app ]
+agent-device settings | settings location set | settings appearance | 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 timezone | settings locale | settings | settings fingerprint | settings clear-app-state [app-id] | settings reset-keychain clear | settings permission | settings permission photos [full|limited] | settings permission [--app ]
```
| Option | What it does |
@@ -1774,6 +1774,7 @@ agent-device settings mobile-data off
agent-device settings location set 37.3349 -122.009
agent-device settings animations off
agent-device settings text-size accessibility-extra-large
+agent-device settings locale en_IN
agent-device settings timezone Asia/Kolkata
agent-device settings appearance dark
agent-device settings faceid match
@@ -1802,6 +1803,13 @@ Device settings:
- Pair `settings mobile-data on` with `settings wifi off` to move a session, such as a video stream, from Wi-Fi to cellular. On a multi-SIM device, or one without an active SIM, the command can fail even when the switch took effect.
- `settings text-size` without a category reads the current size. It works on iPhone and iPad simulators and on Android. A running app picks up a new size only after `open --relaunch`.
+Language and region:
+
+- `settings locale ` sets the language and region together on iPhone and iPad simulators and on Android devices and emulators, and takes `reset`. Each response reports the previous locale as `previousLocale`.
+- A locale id is a language with an optional script and region, written with `-` or `_`, such as `en_IN`, `fr-CA`, or `zh-Hans-CN`. Extensions and variants are refused with `INVALID_ARGS` before anything changes.
+- On iOS simulators, a running app keeps its old locale until `open --relaunch`. `settings locale reset` removes the override, which leaves English with no region. The reported `previousLocale` is a value `settings locale` accepts, and `previousLanguages` lists every preferred language.
+- On Android devices and emulators, running apps take the new locale at once. `settings locale reset` applies `ro.product.locale`, the locale the system image boots with.
+
Time zone:
- `settings timezone ` sets the time zone on iPhone and iPad simulators and on Android devices and emulators, and takes `reset`. Each response reports the previous time zone as `previousTimeZone`.
@@ -1823,7 +1831,7 @@ App state:
Permissions:
- On iOS and Android, `permission` applies to the session app. Pass `--app ` to target an installed app without opening it, for example to grant a permission before first launch. `--app` counts only on the command line; `AGENT_DEVICE_TARGET_APP` never retargets a settings change.
-- Refusals change nothing: `app_not_installed` (install the app or fix the id), `session_app_required` (run `open ` or name the app), `setting_app_not_package` (an Android intent alias such as `settings` is not a package), and `setting_app_not_consumed` (a device-wide setting such as `location set`, `mobile-data`, `bluetooth`, or `timezone` takes no app).
+- Refusals change nothing: `app_not_installed` (install the app or fix the id), `session_app_required` (run `open ` or name the app), `setting_app_not_package` (an Android intent alias such as `settings` is not a package), and `setting_app_not_consumed` (a device-wide setting such as `location set`, `mobile-data`, `bluetooth`, `locale`, or `timezone` takes no app).
- On iOS simulators, targeting `notifications` with `grant`, `deny`, or `reset` returns `ios-notification-permission-unsupported`. Use `alert accept` or `alert dismiss` to answer the notification prompt.
- On iOS simulators, the simulator decides which other permissions it can change and refuses the rest. `grant all` skips a refused service with a warning.
- On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`.
diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md
index 04ce6b1ac7..73458c8759 100644
--- a/website/docs/docs/error-reasons.md
+++ b/website/docs/docs/error-reasons.md
@@ -375,6 +375,7 @@ Treat a reason that this page does not list as unknown, not as an error in the r
| `mobile-data-unreadable` | The device answered the mobile-data read-back with a value that is neither 0 nor 1. |
| `keep-awake-not-applied` | The device kept the screen turning off after `svc power stayon` accepted the request. |
| `keep-awake-unreadable` | The device answered the keep-awake read-back with a value that is not a stay-on mask. |
+| `locale-not-applied` | The Android system locale list did not start with the requested locale after the update. |
| `time-zone-not-applied` | `persist.sys.timezone` did not hold the requested zone after `cmd alarm set-timezone`. |
| `setting_app_not_package` | The named app resolves to an intent such as `settings`, not to an installed package. |
| `app-no-data-container` | `clear-app-state` was refused because the installed app owns no data container. |
diff --git a/website/docs/docs/limrun.md b/website/docs/docs/limrun.md
index f48a5706e7..49f202c465 100644
--- a/website/docs/docs/limrun.md
+++ b/website/docs/docs/limrun.md
@@ -187,7 +187,7 @@ Remote simulator logs do not include sender or process image paths. Filters that
On iOS, `settings` supports `appearance`, `permission`, `location`, `wifi`, `airplane`, `faceid`, `touchid`, `text-size`, and `clear-app-state`, with the same arguments as a local simulator. You can also read the current text size.
-Wi-Fi and airplane settings change the status-bar appearance; they do not disconnect the simulator. `clear-app-state` stops your app and removes its data. Use `open` when you are ready to launch it again. `reset-keychain`, `mobile-data`, and `timezone` are unavailable on Limrun iOS. On Android, `settings mobile-data on|off` and `settings timezone ` work as on a local device. Fold commands are unavailable on Limrun.
+Wi-Fi and airplane settings change the status-bar appearance; they do not disconnect the simulator. `clear-app-state` stops your app and removes its data. Use `open` when you are ready to launch it again. `reset-keychain`, `mobile-data`, `locale`, and `timezone` are unavailable on Limrun iOS. On Android, `settings mobile-data on|off`, `settings locale `, and `settings timezone ` work as on a local device. Fold commands are unavailable on Limrun.
To drive Limrun only through MCP, see [Use a provider only through MCP](/docs/device-clouds#use-a-provider-only-through-mcp). For Limrun, `artifacts` lists the network capture file only when you connect with `--provider-network-logs`; otherwise there are no provider artifacts to fetch.
diff --git a/website/docs/docs/revyl.md b/website/docs/docs/revyl.md
index 858b977efa..c12e7a2b7f 100644
--- a/website/docs/docs/revyl.md
+++ b/website/docs/docs/revyl.md
@@ -117,7 +117,7 @@ report a refused command as a success:
- `swipe` and `gesture` refuse. Use `scroll`, which plans the path itself and sends one drag.
- `keyboard`, `clipboard`, `alert`, `fold`, `telephony`, and `tv-remote` are not supported.
- The other `settings` refuse: `wifi`, `airplane`, `mobile-data`, `bluetooth`, `animations`,
- `text-size`, `timezone`, `faceid`, `touchid`, and `fingerprint`. Revyl's devices refuse airplane mode, and the
+ `text-size`, `locale`, `timezone`, `faceid`, `touchid`, and `fingerprint`. Revyl's devices refuse airplane mode, and the
worker has no action for the rest.
- `reinstall` refuses, as described above.
- `uninstall`, `apps`, `push`, `logs`, `network dump`, `artifacts`, and `recordings` are not