Skip to content
18 changes: 18 additions & 0 deletions packages/command-surface/src/capture/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,24 @@ describe('settings CLI permission', () => {
}
});

test('reads timezone as a written value the daemon parses again', () => {
const timeZone = settingsCliReader(['timezone', 'Asia/Kolkata'], {
targetApp: 'com.example.app',
} as CliFlags);
expect(timeZone).toEqual({
setting: 'timezone',
state: 'Asia/Kolkata',
app: 'com.example.app',
});
expect(settingsDaemonWriter(timeZone)).toMatchObject({
positionals: ['timezone', 'Asia/Kolkata'],
input: { app: 'com.example.app' },
});
expect(() => settingsCliReader(['timezone', '+05:30'], 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) => {
Expand Down
6 changes: 3 additions & 3 deletions packages/command-surface/src/capture/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, or app permissions on the selected target. Platform support varies by setting and action.';
'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.';

const settingsCommandMetadata = defineFieldCommandMetadata(
SETTINGS_COMMAND_NAME,
Expand All @@ -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`, 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`, `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`.',
Comment thread
imranbarbhuiya marked this conversation as resolved.
Resolved
),
latitude: numberField(),
longitude: numberField(),
Expand Down Expand Up @@ -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',
searchHint: 'wifi airplane location dark mode permission grant revoke 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.',
'',
Expand Down
11 changes: 11 additions & 0 deletions packages/contracts/src/client-settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,17 @@ describe('public client settings cover the catalog', () => {
expectTypeOf<Toggle['state']>().toEqualTypeOf<'on' | 'off'>();
expectTypeOf<Toggle['app']>().toEqualTypeOf<string | undefined>();
});

test('timezone takes a value or reset, and an app to refuse', () => {
type Value = Extract<SettingsUpdateOptions, { setting: 'timezone' }>;
expectTypeOf<{
setting: 'timezone';
state: 'Asia/Kolkata';
}>().toExtend<SettingsUpdateOptions>();
expectTypeOf<{ setting: 'timezone'; state: 'reset' }>().toExtend<SettingsUpdateOptions>();
expectTypeOf<{ setting: 'timezone' }>().not.toExtend<SettingsUpdateOptions>();
expectTypeOf<Value['app']>().toEqualTypeOf<string | undefined>();
});
});

/**
Expand Down
10 changes: 8 additions & 2 deletions packages/contracts/src/client-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import type {
PermissionAction,
PermissionMode,
SETTINGS,
SETTING_RESET_STATE,
SettingName,
} from './settings-catalog.ts';

Expand All @@ -19,7 +20,9 @@ type FormState<Form> = Form extends { kind: 'on-off' }
? 'on' | 'off'
: Form extends { kind: 'choice'; states: readonly (infer State)[] }
? State
: never;
: Form extends { kind: 'value' }
? typeof SETTING_RESET_STATE | (string & {})
: never;

type SettingState<Name extends SettingName> = FormState<(typeof SETTINGS)[Name]['forms'][number]>;

Expand All @@ -36,7 +39,10 @@ type StateOnlySettingOptions = {
: { setting: Name; state: SettingState<Name> });
}[StateOnlySetting];

/** Switches that change the whole Android device; naming an app is refused with `setting_app_not_consumed`. */
/**
* Settings that change the whole device on Android and wherever else they run; naming an app is
* refused with `setting_app_not_consumed`.
*/
type DeviceLevelToggleSetting = {
[Name in SettingName]: (typeof SETTINGS)[Name] extends {
app: 'input';
Expand Down
11 changes: 11 additions & 0 deletions packages/contracts/src/settings-catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,9 @@ export const TEXT_SIZE_CATEGORIES = [

export const APPEARANCE_ACTIONS = ['light', 'dark', 'toggle'] as const;

/** The state a `value` setting takes to hand the value back to the device's own default. */
export const SETTING_RESET_STATE = 'reset';

export type PermissionAction = (typeof PERMISSION_ACTIONS)[number];
export type PermissionMode = (typeof PERMISSION_MODES)[number];
export type MobilePermissionTarget = (typeof MOBILE_PERMISSION_TARGETS)[number];
Expand Down Expand Up @@ -81,6 +84,8 @@ export type SettingForm = Readonly<
modes?: readonly PermissionMode[];
}
| { kind: 'app-id' }
/** One value the setting validates itself, or {@link SETTING_RESET_STATE}. */
| { kind: 'value'; placeholder: string }
>;

export type SettingDefinition = Readonly<{
Expand Down Expand Up @@ -144,6 +149,12 @@ export const SETTINGS = {
readable: true,
help: 'Reads the preferred text size without a category and applies one with it, on iPhone and iPad simulators (simctl content size) and Android (system font_scale). Android has no ladder of its own: a read names the nearest rung and reports the multiplier as platformValue. A running app adopts a new size at its next configuration change, so relaunch it.',
},
timezone: {
forms: [{ kind: 'value', placeholder: 'iana-zone' }],
app: 'input',
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.',
},
faceid: {
forms: [{ kind: 'choice', states: ['match', 'nonmatch', 'enroll', 'unenroll'] }],
help: 'Simulates Face ID on iPhone and iPad simulators.',
Expand Down
55 changes: 54 additions & 1 deletion packages/contracts/src/settings.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
parseSettingsMutation,
parseSettingState,
parseTextSizeCategory,
parseTimeZoneId,
readTextSizeCategory,
settingsAppNotConsumedRefusal,
settingsAppScope,
Expand Down Expand Up @@ -44,6 +45,7 @@ describe('settings usage', () => {
'settings location set <lat> <lon>',
'settings appearance <light|dark|toggle>',
`settings text-size [${TEXT_SIZE_CATEGORIES.join('|')}]`,
'settings timezone <iana-zone|reset>',
'settings <faceid|touchid> <match|nonmatch|enroll|unenroll>',
'settings fingerprint <match|nonmatch>',
'settings clear-app-state [app-id]',
Expand Down Expand Up @@ -229,6 +231,51 @@ describe('text-size', () => {
});
});

describe('timezone', () => {
test('a time zone Intl knows passes through as written so device read-back decides', () => {
expect(parseSettingsMutation(['Timezone', 'Asia/Kolkata'])).toEqual({
setting: 'timezone',
state: 'Asia/Kolkata',
});
expect(parseTimeZoneId('america/new_york')).toBe('america/new_york');
expect(parseTimeZoneId(' Etc/GMT+5 ')).toBe('Etc/GMT+5');
expect(parseTimeZoneId('Asia/Kolkata')).toBe('Asia/Kolkata');
expect(parseTimeZoneId('asia/kolkata')).toBe('asia/kolkata');
expect(parseTimeZoneId('US/Pacific')).toBe('US/Pacific');
expect(parseTimeZoneId('us/pacific')).toBe('us/pacific');
});

test('an offset or a name the time zone data does not know is refused', () => {
for (const value of ['+05:30', 'Mars/Olympus_Mons', 'Asia/', '']) {
expectInvalidArgs(() => parseTimeZoneId(value), `Invalid time zone: ${value}.`);
}
});

test('reset is a state of its own, and timezone takes exactly one value', () => {
expect(parseSettingsMutation(['timezone', 'RESET'])).toEqual({
setting: 'timezone',
state: 'reset',
});
expectInvalidArgs(
() => parseSettingsMutation(['timezone']),
'settings timezone requires a state: <iana-zone|reset>.',
);
expectInvalidArgs(
() => parseSettingsMutation(['timezone', 'Asia/Kolkata', 'extra']),
SETTINGS_INVALID_ARGS_MESSAGE,
);
});

test('timezone writes answer with the zone set or the reset', () => {
expect(describeSettingWrite('timezone', 'Asia/Kolkata', undefined)).toBe(
'Time zone set to Asia/Kolkata',
);
expect(describeSettingWrite('timezone', 'reset', undefined)).toBe(
'Time zone reset to the device default',
);
});
});

describe('owner parsers', () => {
test('parsePermissionTarget accepts the mobile targets only', () => {
expect(parsePermissionTarget(' Camera ')).toBe('camera');
Expand Down Expand Up @@ -281,7 +328,13 @@ describe('settingsAppScope', () => {
});
});

describe('settingsAppScope device-wide radios', () => {
describe('settingsAppScope device-wide settings', () => {
test('timezone changes the whole device on every mobile family', () => {
expect(settingsAppScope('apple', 'timezone', 'reset')).toBe('device-level');
expect(settingsAppScope('mobile', 'timezone', 'Asia/Kolkata')).toBe('device-level');
expect(settingsAppScope('macos-host', 'timezone', 'reset')).toBe('unknown');
});

test.each(['mobile-data', 'keep-awake', 'bluetooth'])(
'%s switches the whole device wherever it is served',
(setting) => {
Expand Down
57 changes: 57 additions & 0 deletions packages/contracts/src/settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
SETTINGS,
settingDefinition,
SETTING_NAMES,
SETTING_RESET_STATE,
TEXT_SIZE_CATEGORIES,
type AppearanceAction,
type MobilePermissionTarget,
Expand Down Expand Up @@ -69,6 +70,11 @@ export function describeSettingWrite(
): string {
if (setting === 'clear-app-state') return `Cleared user data for ${appBundleId}`;
if (setting === 'text-size') return `Text size set to ${state}`;
if (setting === 'timezone') {
return state === SETTING_RESET_STATE
? 'Time zone reset to the device default'
: `Time zone set to ${state}`;
}
return `Updated setting: ${setting}`;
}

Expand Down Expand Up @@ -218,6 +224,8 @@ function formUsage(form: SettingForm, readable: boolean): string {
}
case 'app-id':
return '[app-id]';
case 'value':
return `<${form.placeholder}|${SETTING_RESET_STATE}>`;
}
}

Expand Down Expand Up @@ -300,6 +308,9 @@ function parseFormPositionals(
case 'on-off':
if (positionals.length !== 2) throw invalidSettingsArgs();
return { setting, state: readSettingState(state) ? 'on' : 'off' };
case 'value':
if (positionals.length !== 2) throw invalidSettingsArgs();
return { setting, state: parseSettingValue(setting, positionals[1] ?? '') };
default:
if (positionals.length !== 2) throw invalidSettingsArgs();
return { setting, state };
Expand Down Expand Up @@ -392,10 +403,56 @@ function formAcceptsState(form: SettingForm, state: string | undefined): boolean
case 'permission':
return findVocabularyName(form.actions, state) !== undefined;
case 'app-id':
case 'value':
return true;
}
}

/** The settings whose form is a `value`: each one validates its own value before dispatch. */
type ValueSetting = {
[Name in SettingName]: Extract<
(typeof SETTINGS)[Name]['forms'][number],
{ kind: 'value' }
> extends never
? never
: Name;
}[SettingName];

const VALUE_PARSERS = {
timezone: parseTimeZoneId,
} as const satisfies Record<ValueSetting, (value: string) => string>;

/** The value as the owners write it, or `reset`, so no device is handed a value it cannot read. */
function parseSettingValue(setting: SettingName, value: string): string {
if (normalizeName(value) === SETTING_RESET_STATE) return SETTING_RESET_STATE;
const parser: (raw: string) => string = VALUE_PARSERS[setting as ValueSetting];
return parser(value);
}

const TIME_ZONE_NAME_PATTERN = /^[A-Za-z][\w+-]*(\/[\w+-]+)*$/;

/**
* An IANA time zone name the host's time zone data knows, kept as written; the target device
* checks it on read-back. Offsets such as `+05:30` are refused because neither owner takes one.
*/
export function parseTimeZoneId(value: string): string {
const name = value.trim();
if (TIME_ZONE_NAME_PATTERN.test(name) && isKnownTimeZone(name)) return name;
throw new AppError(
'INVALID_ARGS',
`Invalid time zone: ${value}. Use an IANA time zone name, such as Asia/Kolkata or America/New_York.`,
);
}

function isKnownTimeZone(name: string): boolean {
try {
new Intl.DateTimeFormat('en-US', { timeZone: name });
return true;
} catch {
return false;
}
}

function normalizeName(value: string | undefined): string | undefined {
return value?.trim().toLowerCase();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,7 @@ function settingsFacts(device: DeviceInfo) {
animations: available,
appearance: available,
'text-size': available,
timezone: available,
fingerprint: available,
'clear-app-state': available,
permission: available,
Expand Down Expand Up @@ -227,6 +228,7 @@ function settingsFacts(device: DeviceInfo) {
'reset-keychain': available,
permission: available,
'text-size': handheld,
timezone: handheld,
faceid: handheld,
touchid: handheld,
},
Expand Down
Loading
Loading