From 8e223afb6345465a2b0a8d22a9d927b908ef57c8 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 23:45:20 +0530 Subject: [PATCH 1/9] refactor(ios): share the host path of a simulator's data directory --- .../src/core/ios-simulator-accessibility.ts | 13 +++++-------- .../platform-apple/src/core/simulator-data-path.ts | 12 ++++++++++++ 2 files changed, 17 insertions(+), 8 deletions(-) create mode 100644 packages/platform-apple/src/core/simulator-data-path.ts diff --git a/packages/platform-apple/src/core/ios-simulator-accessibility.ts b/packages/platform-apple/src/core/ios-simulator-accessibility.ts index ee2e9f1c8a..3a0f376de4 100644 --- a/packages/platform-apple/src/core/ios-simulator-accessibility.ts +++ b/packages/platform-apple/src/core/ios-simulator-accessibility.ts @@ -2,9 +2,10 @@ import path from 'node:path'; import { isHandheldAppleSimulator, type DeviceInfo } from '@agent-device/kernel/device'; import { normalizeError } from '@agent-device/kernel/errors'; import { emitDiagnostic } from '@agent-device/host-kit/diagnostics'; -import { hostHomeDirectory, readHostBinaryFile } from '@agent-device/host-kit/host-file'; +import { readHostBinaryFile } from '@agent-device/host-kit/host-file'; import { parseApplePlist } from './plist.ts'; -import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts'; +import { buildSimctlArgsForDevice } from './simctl.ts'; +import { hostSimulatorDataPath } from './simulator-data-path.ts'; import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts'; const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000; @@ -59,13 +60,9 @@ async function readHostAppAccessibility( ): Promise<'enabled' | 'disabled' | 'unknown'> { if (hasScopedAppleToolProvider()) return 'unknown'; try { - const { udid, simulatorSetPath } = simulatorAddressFor(device); - const setPath = - simulatorSetPath ?? path.join(hostHomeDirectory(), 'Library/Developer/CoreSimulator/Devices'); const preferences = path.join( - setPath, - udid, - 'data/Library/Preferences/com.apple.Accessibility.plist', + hostSimulatorDataPath(device), + 'Library/Preferences/com.apple.Accessibility.plist', ); const parsed = await parseApplePlist(await readHostBinaryFile(preferences)); if (!parsed) return 'unknown'; diff --git a/packages/platform-apple/src/core/simulator-data-path.ts b/packages/platform-apple/src/core/simulator-data-path.ts new file mode 100644 index 0000000000..eb8c2a9bbc --- /dev/null +++ b/packages/platform-apple/src/core/simulator-data-path.ts @@ -0,0 +1,12 @@ +import path from 'node:path'; +import { hostHomeDirectory } from '@agent-device/host-kit/host-file'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { simulatorAddressFor } from './simctl.ts'; + +/** The simulator's `data` directory, the root of its file system, as this host stores it. */ +export function hostSimulatorDataPath(device: DeviceInfo): string { + const { udid, simulatorSetPath } = simulatorAddressFor(device); + const setPath = + simulatorSetPath ?? path.join(hostHomeDirectory(), 'Library/Developer/CoreSimulator/Devices'); + return path.join(setPath, udid, 'data'); +} From 1df52f6e639d170a3f5d85bf1cfbe9c44b266861 Mon Sep 17 00:00:00 2001 From: parbez Date: Mon, 23 Nov 2026 23:45:20 +0530 Subject: [PATCH 2/9] feat(ios): set notification permission on simulators through SpringBoard's settings file --- packages/contracts/src/settings-catalog.ts | 2 +- packages/contracts/src/settings.ts | 7 +- .../maestro/src/internal/support-matrix.ts | 4 +- .../src/core/__tests__/app-settings.test.ts | 88 +++++- .../simctl-settings-notifications.test.ts | 275 ++++++++++++++++++ .../core/__tests__/simctl-settings.test.ts | 33 ++- .../platform-apple/src/core/app-settings.ts | 14 +- .../src/core/simctl-settings.ts | 70 ++++- .../core/simulator-notification-permission.ts | 274 +++++++++++++++++ .../ios-alert-settings.test.ts | 26 ++ .../limrun-ios-settings.test.ts | 30 +- website/docs/docs/commands.md | 1 + website/docs/docs/error-reasons.md | 3 + website/docs/docs/run-maestro-flows.md | 4 +- 14 files changed, 786 insertions(+), 45 deletions(-) create mode 100644 packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts create mode 100644 packages/platform-apple/src/core/simulator-notification-permission.ts diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts index ad96f20d96..32d518d2ae 100644 --- a/packages/contracts/src/settings-catalog.ts +++ b/packages/contracts/src/settings-catalog.ts @@ -178,7 +178,7 @@ export const SETTINGS = { ], app: 'input', appScope: { apple: 'app-scoped', mobile: 'app-scoped', 'macos-host': 'device-level' }, - help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', + help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, notifications restarts SpringBoard, which returns to the Home Screen, so change it before open. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', }, } as const satisfies Record; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b9bc4b8a1d..f412cf6c86 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -79,7 +79,7 @@ export type SettingOptions = { longitude?: number; }; -/** The settings a simulator changes through `simctl` alone, whichever host runs that `simctl`. */ +/** The settings a simulator changes through `simctl`, whichever host runs that `simctl`. */ type SimctlSetting = 'appearance' | 'permission' | 'location'; /** @@ -102,6 +102,11 @@ export type SimctlSettingRequest = { appBundleId?: string; /** Resolves the app a privacy change names to the bundle id `simctl privacy` writes. */ resolveApp: (app: string) => Promise; + /** + * The simulator's notification settings file on this host, which `notifications` writes since + * `simctl privacy` refuses it; absent where the runner cannot reach the simulator's files. + */ + notificationSettingsPath?: string; options?: SettingOptions; }; diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts index 7e130ab643..bce25852e8 100644 --- a/packages/maestro/src/internal/support-matrix.ts +++ b/packages/maestro/src/internal/support-matrix.ts @@ -1,5 +1,5 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ - 'Flows: launchApp (with clearState, permissions, and Apple-only launch arguments; permissions apply after state clearing but before launch, and a launchApp without permissions touches nothing — there is no silent all: allow default); setPermissions (mid-flow permission grants, denials, and resets; all resolves in the backend — each simctl privacy service on iOS, the declared permissions on Android — with specific entries overriding after it); runFlow file/inline; runFlow.when and repeat.while conditions (platform, visible, notVisible, and true, all re-evaluated before every repeat iteration); onFlowStart/onFlowComplete; repeat with times, while, or both; and retry.', + 'Flows: launchApp (with clearState, permissions, and Apple-only launch arguments; permissions apply after state clearing but before launch, and a launchApp without permissions touches nothing — there is no silent all: allow default); setPermissions (mid-flow permission grants, denials, and resets; all resolves in the backend — each simctl privacy service and notifications on iOS, the declared permissions on Android — with specific entries overriding after it); runFlow file/inline; runFlow.when and repeat.while conditions (platform, visible, notVisible, and true, all re-evaluated before every repeat iteration); onFlowStart/onFlowComplete; repeat with times, while, or both; and retry.', 'Interactions: tapOn, doubleTapOn, longPressOn, inputText on the focused element, eraseText (up to 10000 characters), openLink, hideKeyboard, basic pressKey, and back; selector targets poll until available and support recursive index, childOf, above, below, leftOf, rightOf, containsChild, containsDescendants, points, and optional; outer command labels are metadata, not target selectors.', 'Assertions and navigation: assertVisible, assertNotVisible, assertTrue (literal values and ${VAR} lookups only; "", "false", "0", "null", and "undefined" are falsy, everything else is truthy), extendedWaitUntil, scroll, scrollUntilVisible, absolute/percentage/target swipe, takeScreenshot, waitForAnimationToEnd, clearState, stopApp, and killApp (system-initiated process death: am kill on ADB-backed Android devices, which refuse a foreground target with android-kill-requires-background-app — background the app first, for example pressKey: Home — and fail a target whose process survives with android-kill-process-survived; iOS, Limrun, and WebDriver-provider backends run it as stopApp).', 'Scripts: ordered runScript file/env scripts with http.post, json, and output variables; evalScript inline expressions run flow-scoped JavaScript and write output.* leaves for later steps.', @@ -7,7 +7,7 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ export const MAESTRO_COMPAT_LIMITATIONS = [ 'On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.', - 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict: current runtimes refuse a targeted notifications change and leave notifications untouched under all.', + 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and returns the simulator to the Home Screen, so set them in launchApp permissions rather than mid-flow.', 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', diff --git a/packages/platform-apple/src/core/__tests__/app-settings.test.ts b/packages/platform-apple/src/core/__tests__/app-settings.test.ts index ba44053a01..ca70c01555 100644 --- a/packages/platform-apple/src/core/__tests__/app-settings.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-settings.test.ts @@ -39,6 +39,11 @@ import { retryWithPolicy } from '@agent-device/host-kit/retry'; import { assertRejectsAppError } from '../../__tests__/app-error.ts'; import { withFakeAppleTool, type FakeAppleToolResponse } from '../../__tests__/fake-apple-tool.ts'; import { IOS_TEST_SIMULATOR, MACOS_TEST_DEVICE } from './apple-core-stub-helpers.ts'; +import { build as buildPlist, parse as parsePlist } from 'plist'; +import { + SIMULATOR_NOTIFICATION_REASONS, + SIMULATOR_NOTIFICATION_SETTINGS_FILE, +} from '../simulator-notification-permission.ts'; bindTestCommandHost(); @@ -612,7 +617,7 @@ test('setIosSetting permission runs the simctl plan on the simulator udid and su await withFakeAppleTool( (args) => { if (isSimctlListApps(args)) return INSTALLED_APPS_JSON; - if (args.join(' ') === 'simctl privacy sim-1 revoke notifications com.example.app') { + if (args.join(' ') === 'simctl privacy sim-1 revoke siri com.example.app') { return { stderr: 'Failed to revoke access\nOperation not permitted', exitCode: 1 }; } return unexpectedArgs(args); @@ -626,13 +631,13 @@ test('setIosSetting permission runs the simctl plan on the simulator udid and su 'deny', 'com.example.app', { - permissionTarget: 'notifications', + permissionTarget: 'siri', }, process.env, ), { code: 'UNSUPPORTED_OPERATION', - message: /does not support setting notifications permission/i, + message: /does not support setting siri permission/i, }, ); assert.deepEqual(calls.at(-1), [ @@ -640,13 +645,88 @@ test('setIosSetting permission runs the simctl plan on the simulator udid and su 'privacy', 'sim-1', 'revoke', - 'notifications', + 'siri', 'com.example.app', ]); }, ); }); +/** A simulator set holding sim-1 with a notification settings file in SpringBoard's layout. */ +async function simulatorSetWithNotificationSettings(): Promise<{ set: string; file: string }> { + const set = await mkdtempForTest('agent-device-ios-notification-set-'); + const file = path.join(set, 'sim-1/data', SIMULATOR_NOTIFICATION_SETTINGS_FILE); + await fs.mkdir(path.dirname(file), { recursive: true }); + await fs.writeFile(file, buildPlist({ sectionInfo: {}, sectionInfoVersionNumber: 3 })); + return { set, file }; +} + +test('setIosSetting notifications writes the settings file of the simulator on this host', async () => { + mockEnsureBootedSimulator.mockResolvedValue(undefined); + const { set, file } = await simulatorSetWithNotificationSettings(); + const simctl: string[][] = []; + mockRunCmd.mockImplementation(async (cmd, args) => { + assert.equal(cmd, 'xcrun'); + const unscoped = args.slice(args.indexOf('--set') + 2); + simctl.push(unscoped); + const stdout = unscoped.join(' ') === 'listapps sim-1' ? INSTALLED_APPS_JSON : ''; + return { stdout, stderr: '', exitCode: 0 }; + }); + + const result = await setIosSetting( + { ...IOS_TEST_SIMULATOR, simulatorSetPath: set }, + 'permission', + 'grant', + 'Example', + { permissionTarget: 'notifications' }, + process.env, + ); + + assert.equal(result?.permission, 'notifications'); + const store = parsePlist(await fs.readFile(file, 'utf8')) as { + sectionInfo: Record; + }; + assert.deepEqual(Object.keys(store.sectionInfo), ['com.example.app']); + assert.deepEqual(simctl.at(-1), [ + 'spawn', + 'sim-1', + 'launchctl', + 'start', + 'com.apple.usernotificationsd', + ]); +}); + +test('setIosSetting notifications refuses a simulator a scoped tool provider runs', async () => { + mockEnsureBootedSimulator.mockResolvedValue(undefined); + const { set, file } = await simulatorSetWithNotificationSettings(); + const before = await fs.readFile(file); + + const tool = (args: string[]) => + installedAppsTool(args.filter((arg) => arg !== '--set' && arg !== set)); + await withFakeAppleTool(tool, async ({ calls }) => { + await assertRejectsAppError( + () => + setIosSetting( + { ...IOS_TEST_SIMULATOR, simulatorSetPath: set }, + 'permission', + 'grant', + 'com.example.app', + { permissionTarget: 'notifications' }, + process.env, + ), + { + code: 'UNSUPPORTED_OPERATION', + reason: SIMULATOR_NOTIFICATION_REASONS.unreachable.reason, + }, + ); + assert.equal( + calls.some((args) => args.includes('launchctl')), + false, + ); + }); + assert.deepEqual(await fs.readFile(file), before); +}); + function installedAppsTool(args: string[]): FakeAppleToolResponse { if (isSimctlListApps(args)) return INSTALLED_APPS_JSON; if (args[0] === 'simctl' && args[1] === 'privacy') return ''; diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts new file mode 100644 index 0000000000..9c63ccf8ad --- /dev/null +++ b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts @@ -0,0 +1,275 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { expect, test, vi } from 'vitest'; +import { build, buildBinary, parse, parseBinary, type PlistValue } from 'plist'; +import type { SimctlSettingRequest } from '@agent-device/contracts/settings'; +import { AppError } from '@agent-device/kernel/errors'; +import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; +import { applySimctlSetting } from '../simctl-settings.ts'; +import { + SIMULATOR_NOTIFICATION_REASONS, + SPRINGBOARD_RESTART_WARNING, +} from '../simulator-notification-permission.ts'; + +// Another app's record, which a write must carry over byte for byte. +const HOME_RECORD = new Uint8Array([0x62, 0x70, 0x6c, 0x69, 0x73, 0x74, 0x30, 0x30, 1, 2, 3]); + +const SETTINGS: Record = { + sectionInfo: { 'com.apple.Home': HOME_RECORD }, + sectionInfoVersionNumber: 3, +}; + +const RESTART = [ + ['spawn', 'SIM-1', 'launchctl', 'stop', 'com.apple.SpringBoard'], + ['spawn', 'SIM-1', 'launchctl', 'stop', 'com.apple.usernotificationsd'], + ['spawn', 'SIM-1', 'launchctl', 'start', 'com.apple.SpringBoard'], + ['spawn', 'SIM-1', 'launchctl', 'start', 'com.apple.usernotificationsd'], +]; + +async function settingsFile( + store: PlistValue = SETTINGS, + format: 'xml' | 'binary' = 'xml', +): Promise { + const file = path.join(await mkdtempForTest('agent-device-bulletin-'), 'settings.plist'); + fs.writeFileSync(file, format === 'xml' ? build(store) : buildBinary(store)); + return file; +} + +function readSettings(file: string): Record { + const bytes = fs.readFileSync(file); + const binary = bytes.subarray(0, 8).toString() === 'bplist00'; + return (binary ? parseBinary(bytes) : parse(bytes.toString('utf8'))) as Record< + string, + PlistValue + >; +} + +function sections(file: string): Record { + return readSettings(file).sectionInfo as Record; +} + +/** The section id and authorization status an app's `BBSectionInfo` archive holds. */ +function recordOf(record: Uint8Array | undefined): { sectionID: PlistValue; status: PlistValue } { + if (!record) return expect.unreachable('expected a record for the app'); + const objects = (parseBinary(record) as { $objects: Array> }) + .$objects; + const info = objects[1]!; + const settings = objects[info.sectionInfoSettings!.UID] as unknown as Record; + return { + sectionID: objects[info.sectionID!.UID] as unknown as PlistValue, + status: settings.authorizationStatus!, + }; +} + +function recordingRunner(onRun: (args: string[]) => void = () => {}) { + return vi.fn(async (args: string[]) => { + onRun(args); + return { stdout: '', stderr: '' }; + }); +} + +function permission( + runSimctl: SimctlSettingRequest['runSimctl'], + state: string, + permissionTarget: string, + notificationSettingsPath: string | undefined, +): SimctlSettingRequest { + return { + runSimctl, + udid: 'SIM-1', + deviceId: 'SIM-1', + setting: 'permission', + state, + appBundleId: 'com.example.app', + resolveApp: async (app) => app, + ...(notificationSettingsPath ? { notificationSettingsPath } : {}), + options: { permissionTarget }, + }; +} + +test.for([ + { state: 'grant', status: 2 }, + { state: 'deny', status: 1 }, +])( + '$state notifications writes status $status between the SpringBoard stop and start', + async ({ state, status }) => { + const file = await settingsFile(); + const runSimctl = recordingRunner(); + + const result = await applySimctlSetting(permission(runSimctl, state, 'notifications', file)); + + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); + expect(result).toEqual({ + permission: 'notifications', + warnings: [SPRINGBOARD_RESTART_WARNING], + }); + expect(recordOf(sections(file)['com.example.app'])).toEqual({ + sectionID: 'com.example.app', + status, + }); + expect(sections(file)['com.apple.Home']).toEqual(HOME_RECORD); + expect(readSettings(file).sectionInfoVersionNumber).toBe(3); + }, +); + +test('reset notifications removes the app record and keeps the others', async () => { + const file = await settingsFile(); + await applySimctlSetting(permission(recordingRunner(), 'grant', 'notifications', file)); + + await applySimctlSetting(permission(recordingRunner(), 'reset', 'notifications', file)); + + expect(Object.keys(sections(file))).toEqual(['com.apple.Home']); +}); + +test('a binary settings file is written back as binary', async () => { + const file = await settingsFile(SETTINGS, 'binary'); + + await applySimctlSetting(permission(recordingRunner(), 'grant', 'notifications', file)); + + expect(fs.readFileSync(file).subarray(0, 8).toString()).toBe('bplist00'); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +test('the edit applies to the file SpringBoard writes as it stops, not the one read before', async () => { + const file = await settingsFile(); + const flushed = new Uint8Array([7, 7, 7]); + const runSimctl = recordingRunner((args) => { + if (args.join(' ') !== 'spawn SIM-1 launchctl stop com.apple.SpringBoard') return; + const store = readSettings(file); + (store.sectionInfo as Record)['com.apple.Maps'] = flushed; + fs.writeFileSync(file, build(store)); + }); + + await applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + + expect(sections(file)['com.apple.Maps']).toEqual(flushed); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +test('a settings file that changes layout during the stop still restarts both services', async () => { + const file = await settingsFile(); + const runSimctl = recordingRunner((args) => { + if (args.join(' ') === 'spawn SIM-1 launchctl stop com.apple.SpringBoard') { + fs.writeFileSync(file, build({ ...SETTINGS, sectionInfoVersionNumber: 4 })); + } + }); + + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)), + ).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: SIMULATOR_NOTIFICATION_REASONS.unrecognized.reason }, + }); + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); +}); + +test.for([ + { label: 'a newer layout version', store: { ...SETTINGS, sectionInfoVersionNumber: 4 } }, + { label: 'a key SpringBoard does not write', store: { ...SETTINGS, sectionOrder: [] } }, + { label: 'no sectionInfo', store: { sectionInfoVersionNumber: 3 } }, + { label: 'a sectionInfo array', store: { ...SETTINGS, sectionInfo: [] } }, + { + label: 'a record that is not data', + store: { ...SETTINGS, sectionInfo: { 'com.apple.Home': 'record' } }, + }, + { label: 'a top-level array', store: [SETTINGS] }, +] as const)('a settings file with $label is refused before the restart', async ({ store }) => { + const file = await settingsFile(store as PlistValue); + const before = fs.readFileSync(file); + const runSimctl = recordingRunner(); + + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)), + ).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { + reason: SIMULATOR_NOTIFICATION_REASONS.unrecognized.reason, + deviceId: 'SIM-1', + appBundleId: 'com.example.app', + }, + }); + expect(runSimctl).not.toHaveBeenCalled(); + expect(fs.readFileSync(file)).toEqual(before); +}); + +test('a settings file that does not parse is refused before the restart', async () => { + const file = await settingsFile(); + fs.writeFileSync(file, 'bplist00 truncated'); + const runSimctl = recordingRunner(); + + await expect( + applySimctlSetting(permission(runSimctl, 'deny', 'notifications', file)), + ).rejects.toMatchObject({ + details: { reason: SIMULATOR_NOTIFICATION_REASONS.unrecognized.reason }, + }); + expect(runSimctl).not.toHaveBeenCalled(); +}); + +test.for([ + { + label: 'is missing', + path: (file: string) => `${file}.absent`, + reason: SIMULATOR_NOTIFICATION_REASONS.missing.reason, + }, + { + label: 'is out of reach of this host', + path: () => undefined, + reason: SIMULATOR_NOTIFICATION_REASONS.unreachable.reason, + }, +])('a settings file that $label is refused before the restart', async ({ path, reason }) => { + const runSimctl = recordingRunner(); + + await expect( + applySimctlSetting(permission(runSimctl, 'reset', 'notifications', path(await settingsFile()))), + ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', details: { reason } }); + expect(runSimctl).not.toHaveBeenCalled(); +}); + +test.for([ + { state: 'grant', action: 'grant', status: 2 }, + { state: 'deny', action: 'revoke', status: 1 }, +])('$state all sets notifications last, with one restart', async ({ state, action, status }) => { + const file = await settingsFile(); + const runSimctl = recordingRunner(); + + const result = (await applySimctlSetting(permission(runSimctl, state, 'all', file))) as { + permissions: string[]; + warnings: string[]; + }; + + const argvs = runSimctl.mock.calls.map(([args]) => args); + expect(argvs.slice(-RESTART.length)).toEqual(RESTART); + expect(argvs.slice(0, -RESTART.length).every((args) => args[0] === 'privacy')).toBe(true); + expect(argvs).toContainEqual(['privacy', 'SIM-1', action, 'camera', 'com.example.app']); + expect(result.permissions.at(-1)).toBe('notifications'); + expect(result.warnings).toEqual([SPRINGBOARD_RESTART_WARNING]); + expect(recordOf(sections(file)['com.example.app']).status).toBe(status); +}); + +test('grant all stops at a restart failure and names the services it changed', async () => { + const file = await settingsFile(); + const failed = new AppError('COMMAND_FAILED', 'simctl exited with code 1', { + stderr: 'launchctl: no such process', + }); + const runSimctl = vi.fn(async (args: string[]) => { + if (args[0] === 'spawn') throw failed; + return { stdout: '', stderr: '' }; + }); + + await expect(applySimctlSetting(permission(runSimctl, 'grant', 'all', file))).rejects.toBe( + failed, + ); + expect(failed.details?.permissions).toContain('camera'); + expect(failed.details?.permissions).not.toContain('notifications'); +}); + +test('reset all with a settings file stays one simctl privacy call', async () => { + const file = await settingsFile(); + const runSimctl = recordingRunner(); + + await applySimctlSetting(permission(runSimctl, 'reset', 'all', file)); + + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual([ + ['privacy', 'SIM-1', 'reset', 'all', 'com.example.app'], + ]); +}); diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts index 3e1b717709..4b99d52308 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts @@ -133,7 +133,8 @@ test.for([ }, ); -// Every target but the narrower ones that share a row (contacts-limited, location). +// Every target but the narrower ones that share a row (contacts-limited, location) and +// notifications, which SpringBoard's settings file holds. const EVERY_SERVICE = [ 'calendar', 'camera', @@ -142,7 +143,6 @@ const EVERY_SERVICE = [ 'media-library', 'microphone', 'motion', - 'notifications', 'photos', 'reminders', 'siri', @@ -171,7 +171,7 @@ test.for([ // The simulator records `all` as one kTCCServiceAll row that iOS does not consult. const runSimctl = recordingRunner( services.map((service) => - service === 'notifications' ? refusal(wording) : { stdout: '', stderr: '' }, + service === 'siri' ? refusal(wording) : { stdout: '', stderr: '' }, ), ); @@ -189,8 +189,11 @@ test.for([ ); expect(result).toEqual({ permission: 'all', - permissions: services.filter((service) => service !== 'notifications'), - warnings: ['Skipped notifications: this iOS runtime does not let simctl privacy change it.'], + permissions: services.filter((service) => service !== 'siri'), + warnings: [ + 'Skipped siri: this iOS runtime does not let simctl privacy change it.', + 'Skipped notifications: iOS simulator notification permission needs the simulator files on this host.', + ], }); }, ); @@ -270,13 +273,13 @@ test('a privacy service the runtime refuses is unsupported; other failures pass setting: 'permission', state: 'grant', appBundleId: 'com.example.app', - options: { permissionTarget: 'notifications' }, + options: { permissionTarget: 'siri' }, }); await expect(applySimctlSetting(grant)).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: - 'iOS simulator does not support setting notifications permission via simctl privacy on this runtime.', + 'iOS simulator does not support setting siri permission via simctl privacy on this runtime.', details: { deviceId: 'SIM-1', appBundleId: 'com.example.app' }, cause: refused, }); @@ -297,25 +300,23 @@ test('a refused privacy service reports the device id the caller names, not the setting: 'permission', state: 'grant', appBundleId: 'com.example.app', - options: { permissionTarget: 'notifications' }, + options: { permissionTarget: 'siri' }, }), ), ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', details: { deviceId: 'limrun:ios:lease-a', appBundleId: 'com.example.app' }, }); - expect(argvs(runSimctl)).toEqual([ - ['privacy', 'booted', 'grant', 'notifications', 'com.example.app'], - ]); + expect(argvs(runSimctl)).toEqual([['privacy', 'booted', 'grant', 'siri', 'com.example.app']]); }); test.for([ - { state: 'deny', action: 'revoke', target: 'notifications', wording: 'Failed to revoke access' }, + { state: 'deny', action: 'revoke', target: 'siri', wording: 'Failed to revoke access' }, { state: 'grant', action: 'grant', target: 'calendar', wording: 'Failed to set access' }, { state: 'grant', action: 'grant', - target: 'notifications', + target: 'motion', wording: 'Underlying error (domain=NSPOSIXErrorDomain, code=1):\n\tFailed to create TCC authorization record', }, @@ -362,18 +363,18 @@ test('a refused targeted reset fails instead of a reset all that would clear ear }); await applySimctlSetting(permission('grant', 'microphone')); - const error = await appErrorFrom(applySimctlSetting(permission('reset', 'notifications'))); + const error = await appErrorFrom(applySimctlSetting(permission('reset', 'siri'))); expect(error).toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: - 'iOS simulator does not support resetting notifications permission via simctl privacy on this runtime.', + 'iOS simulator does not support resetting siri permission via simctl privacy on this runtime.', details: { deviceId: 'SIM-1', appBundleId: 'com.example.app' }, cause: refused, }); expect(argvs(runSimctl)).toEqual([ ['privacy', 'SIM-1', 'grant', 'microphone', 'com.example.app'], - ['privacy', 'SIM-1', 'reset', 'notifications', 'com.example.app'], + ['privacy', 'SIM-1', 'reset', 'siri', 'com.example.app'], ]); }); diff --git a/packages/platform-apple/src/core/app-settings.ts b/packages/platform-apple/src/core/app-settings.ts index e1727cb8a3..10071eca32 100644 --- a/packages/platform-apple/src/core/app-settings.ts +++ b/packages/platform-apple/src/core/app-settings.ts @@ -1,3 +1,4 @@ +import path from 'node:path'; import { parsePermissionAction, parseSettingState, @@ -26,6 +27,8 @@ import { applySimctlSetting } from './simctl-settings.ts'; import { readIosTextSize, setIosTextSize } from './settings-text-size.ts'; import { resolveIosApp } from './app-resolution.ts'; import { buildSimctlArgsForDevice } from './simctl.ts'; +import { hostSimulatorDataPath } from './simulator-data-path.ts'; +import { SIMULATOR_NOTIFICATION_SETTINGS_FILE } from './simulator-notification-permission.ts'; import { runSimctlForDevice } from './simctl-execution.ts'; import { invalidateSimulatorStatusBarOverrideCache, @@ -34,7 +37,7 @@ import { withSimulatorStatusBarHeld, } from './screenshot-status-bar.ts'; import { ensureBootedSimulator, requireSimulatorDevice } from './simulator.ts'; -import { resolveAppleToolProvider, runXcrun } from './tool-provider.ts'; +import { hasScopedAppleToolProvider, resolveAppleToolProvider, runXcrun } from './tool-provider.ts'; const MACOS_HOST_SETTINGS = ['appearance', 'permission'] as const satisfies readonly SettingName[]; @@ -197,6 +200,15 @@ export async function setIosSetting( state, appBundleId, resolveApp: (app) => resolveIosSettingsApp(device, app), + // A scoped tool provider runs the simulator on another host, out of reach of this one's files. + ...(hasScopedAppleToolProvider() + ? {} + : { + notificationSettingsPath: path.join( + hostSimulatorDataPath(device), + SIMULATOR_NOTIFICATION_SETTINGS_FILE, + ), + }), options, }); default: diff --git a/packages/platform-apple/src/core/simctl-settings.ts b/packages/platform-apple/src/core/simctl-settings.ts index 7394ef8954..e95b0c5d4c 100644 --- a/packages/platform-apple/src/core/simctl-settings.ts +++ b/packages/platform-apple/src/core/simctl-settings.ts @@ -8,6 +8,11 @@ import { import { type MobilePermissionTarget } from '@agent-device/contracts/settings-catalog'; import { AppError, sessionAppRequiredDetails } from '@agent-device/kernel/errors'; import { requireLocationCoordinates } from '@agent-device/kernel/location-coordinates'; +import { + isNotificationSettingsRefusal, + setSimulatorNotificationPermission, + SPRINGBOARD_RESTART_WARNING, +} from './simulator-notification-permission.ts'; /** Changes one simulator setting through `simctl`; the Apple package owns this plan for every runner. */ export async function applySimctlSetting( @@ -54,6 +59,10 @@ async function setPermission( const action = permissionAction === 'deny' ? 'revoke' : permissionAction; const target = parseIosPrivacyService(options?.permissionTarget, options?.permissionMode); const appBundleId = await requireAppBundleId(request); + if (target === 'notifications') { + await setNotificationPermission(request, action, appBundleId); + return { permission: 'notifications', warnings: [SPRINGBOARD_RESTART_WARNING] }; + } if (target === 'all' && action !== 'reset') { return await setEveryIosPrivacyService(request, action, appBundleId); } @@ -65,14 +74,19 @@ async function setPermission( } } -/** The `simctl privacy` service for every target except `photos`, whose service depends on its mode. */ -const IOS_PRIVACY_SERVICES: Record, string> = { +/** + * The `simctl privacy` service for every target except `photos`, whose service depends on its mode, + * and `notifications`, which `simctl privacy` refuses and SpringBoard's settings file holds instead. + */ +const IOS_PRIVACY_SERVICES: Record< + Exclude, + string +> = { all: 'all', camera: 'camera', microphone: 'microphone', contacts: 'contacts', 'contacts-limited': 'contacts-limited', - notifications: 'notifications', calendar: 'calendar', location: 'location', 'location-always': 'location-always', @@ -105,12 +119,13 @@ const IOS_ALL_TARGETS = { siri: true, } as const satisfies Record, boolean>; -/** The services a grant of `all` changes, one `simctl privacy` call each. */ +/** The services a grant of `all` changes through `simctl privacy`, one call each. */ const IOS_ALL_GRANTED_SERVICES: readonly string[] = ( Object.keys(IOS_ALL_TARGETS) as (keyof typeof IOS_ALL_TARGETS)[] -) - .filter((target) => IOS_ALL_TARGETS[target]) - .map((target) => (target === 'photos' ? 'photos' : IOS_PRIVACY_SERVICES[target])); +).flatMap((target) => { + if (!IOS_ALL_TARGETS[target] || target === 'notifications') return []; + return [target === 'photos' ? 'photos' : IOS_PRIVACY_SERVICES[target]]; +}); /** * The services a revoke of `all` changes: every granted one, and limited photo access @@ -119,18 +134,20 @@ const IOS_ALL_GRANTED_SERVICES: readonly string[] = ( const IOS_ALL_REVOKED_SERVICES: readonly string[] = [...IOS_ALL_GRANTED_SERVICES, 'photos-add']; /** - * `all` for grant and revoke, as one `simctl privacy` call per service. The simulator records - * `simctl privacy grant all` as a single `kTCCServiceAll` row that iOS 27 does not consult, so the - * app still prompts, and a revoke of `all` leaves every per-service grant in place. A service the - * runtime refuses is skipped with a warning, as Android skips a permission it cannot change. Any - * other failure stops the sequence, and its error carries the services already changed in - * `details.permissions`. A reset of `all` stays one call: it removes every row. + * `all` for grant and revoke, as one `simctl privacy` call per service, then notifications. The + * simulator records `simctl privacy grant all` as a single `kTCCServiceAll` row that iOS 27 does + * not consult, so the app still prompts, and a revoke of `all` leaves every per-service grant in + * place. A service the runtime refuses, or a notification settings file this cannot write, is + * skipped with a warning, as Android skips a permission it cannot change. Any other failure stops + * the sequence, and its error carries the services already changed in `details.permissions`. A + * reset of `all` stays one call: it removes every row. */ async function setEveryIosPrivacyService( - { runSimctl, udid, deviceId }: SimctlSettingRequest, + request: SimctlSettingRequest, action: 'grant' | 'revoke', appBundleId: string, ): Promise> { + const { runSimctl, udid, deviceId } = request; const applied: string[] = []; const warnings: string[] = []; let lastRefusal: unknown; @@ -145,12 +162,35 @@ async function setEveryIosPrivacyService( warnings.push(`Skipped ${service}: this iOS runtime does not let simctl privacy change it.`); } } + try { + await setNotificationPermission(request, action, appBundleId); + applied.push('notifications'); + warnings.push(SPRINGBOARD_RESTART_WARNING); + } catch (error) { + if (!isNotificationSettingsRefusal(error)) throw withAppliedServices(error, applied); + warnings.push(`Skipped notifications: ${error.message}`); + } if (applied.length === 0) { throw iosPrivacyServiceRefusedError(action, 'all', appBundleId, deviceId, lastRefusal); } return { permission: 'all', permissions: applied, ...(warnings.length > 0 ? { warnings } : {}) }; } +async function setNotificationPermission( + { runSimctl, udid, deviceId, notificationSettingsPath }: SimctlSettingRequest, + action: 'grant' | 'revoke' | 'reset', + appBundleId: string, +): Promise { + await setSimulatorNotificationPermission({ + runSimctl, + udid, + deviceId, + appBundleId, + action, + settingsPath: notificationSettingsPath, + }); +} + /** The error that stopped `all` partway, naming the services it had already changed. */ function withAppliedServices(error: unknown, applied: readonly string[]): unknown { if (!(error instanceof AppError) || applied.length === 0) return error; @@ -199,7 +239,7 @@ function parseIosPrivacyService( `Permission mode is only supported for photos. Received: ${permissionMode}.`, ); } - return IOS_PRIVACY_SERVICES[normalized]; + return normalized === 'notifications' ? normalized : IOS_PRIVACY_SERVICES[normalized]; } function parseIosAppearance(stdout: string, stderr: string): 'light' | 'dark' | null { diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts new file mode 100644 index 0000000000..ec863f4140 --- /dev/null +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -0,0 +1,274 @@ +import { + readHostBinaryFile, + renameHostPath, + writeHostBinaryFile, +} from '@agent-device/host-kit/host-file'; +import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; +import type { PlistValue } from 'plist'; + +/** The file under a simulator's data directory where SpringBoard keeps each app's notification settings. */ +export const SIMULATOR_NOTIFICATION_SETTINGS_FILE = + 'Library/BulletinBoard/VersionedSectionInfo.plist'; + +export const SIMULATOR_NOTIFICATION_REASONS = { + // The simulator's files are not on this host, so its notification settings cannot be written. + unreachable: { reason: 'ios-notification-settings-unreachable' }, + // The simulator has no notification settings file yet; SpringBoard creates it on its first start. + missing: { reason: 'ios-notification-settings-missing' }, + // The notification settings file is not in the layout this command writes, so it is left alone. + unrecognized: { reason: 'ios-notification-settings-unrecognized' }, +} as const satisfies ReasonTable<'settings'>; + +/** The `sectionInfoVersionNumber` of the layout the written record follows (iOS 27). */ +const SECTION_INFO_VERSION = 3; + +/** `BBSectionInfoSettings.authorizationStatus`, as `UNAuthorizationStatus` numbers it. */ +const AUTHORIZATION_STATUS = { grant: 2, revoke: 1 } as const; + +/** The services that hold the settings in memory, and write them back to the file as they stop. */ +const NOTIFICATION_SERVICES = ['com.apple.SpringBoard', 'com.apple.usernotificationsd']; + +/** Seconds from the Unix epoch to the Cocoa reference date, 2001-01-01. */ +const COCOA_EPOCH_SECONDS = 978_307_200; + +export const SPRINGBOARD_RESTART_WARNING = + 'Restarted SpringBoard to apply the notification permission, so the simulator is back on the Home Screen. Change notifications before open, then open the app.'; + +type NotificationPermissionRequest = { + runSimctl: (args: string[]) => Promise; + udid: string; + deviceId: string; + appBundleId: string; + action: 'grant' | 'revoke' | 'reset'; + /** The settings file on this host; absent where the runner cannot reach the simulator's files. */ + settingsPath: string | undefined; +}; + +type SettingsFile = { + format: 'xml' | 'binary'; + store: Record; + sections: Record; +}; + +/** + * Sets an app's notification permission on a simulator. `simctl privacy` refuses notifications, so + * this writes the record SpringBoard keeps when a user answers the prompt: one NSKeyedArchiver + * `BBSectionInfo` per bundle id, or none for a reset. SpringBoard and `usernotificationsd` write + * their copy back as they stop, so the edit lands between their stop and start, and the restart + * leaves the simulator on the Home Screen. A file in any other layout is refused, not rewritten. + */ +export async function setSimulatorNotificationPermission( + request: NotificationPermissionRequest, +): Promise { + const { runSimctl, udid, settingsPath } = request; + if (settingsPath === undefined) { + throw notificationSettingsError( + request, + 'unreachable', + 'iOS simulator notification permission needs the simulator files on this host.', + 'Answer the app notification prompt instead, or use a simulator on the host that runs agent-device.', + ); + } + // Read before the stop as well, so a file this cannot write refuses without a restart. + await readSettingsFile(request, settingsPath); + try { + for (const service of NOTIFICATION_SERVICES) { + await runSimctl(['spawn', udid, 'launchctl', 'stop', service]); + } + const file = await readSettingsFile(request, settingsPath); + if (request.action === 'reset') { + delete file.sections[request.appBundleId]; + } else { + file.sections[request.appBundleId] = await sectionInfoArchive( + request.appBundleId, + AUTHORIZATION_STATUS[request.action], + ); + } + await writeSettingsFile(settingsPath, file); + } finally { + for (const service of NOTIFICATION_SERVICES) { + await runSimctl(['spawn', udid, 'launchctl', 'start', service]); + } + } +} + +async function readSettingsFile( + request: NotificationPermissionRequest, + settingsPath: string, +): Promise { + let bytes: Uint8Array; + try { + bytes = await readHostBinaryFile(settingsPath); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + throw notificationSettingsError( + request, + 'missing', + `iOS simulator has no notification settings file at ${settingsPath}.`, + 'Boot the simulator to the Home Screen once so SpringBoard creates the file, then retry.', + ); + } + const { parse, parseBinary } = await import('plist'); + const format = new TextDecoder().decode(bytes.subarray(0, 8)) === 'bplist00' ? 'binary' : 'xml'; + let store: PlistValue; + try { + store = format === 'binary' ? parseBinary(bytes) : parse(new TextDecoder().decode(bytes)); + } catch { + store = null; + } + if (isRecognizedStore(store)) return { format, store, sections: store.sectionInfo }; + throw notificationSettingsError( + request, + 'unrecognized', + `iOS simulator notification settings at ${settingsPath} are not in the layout this command writes (sectionInfoVersionNumber ${SECTION_INFO_VERSION}).`, + 'Answer the app notification prompt instead, or change notifications in the Settings app.', + ); +} + +/** Only the two keys SpringBoard writes, so a rewrite cannot change a value it does not know. */ +function isRecognizedStore( + store: PlistValue, +): store is { sectionInfo: Record; sectionInfoVersionNumber: number } { + if (!isDictionary(store)) return false; + const { sectionInfo, sectionInfoVersionNumber, ...rest } = store; + return ( + Object.keys(rest).length === 0 && + sectionInfoVersionNumber === SECTION_INFO_VERSION && + isDictionary(sectionInfo) && + Object.values(sectionInfo).every((record) => record instanceof Uint8Array) + ); +} + +function isDictionary(value: PlistValue | undefined): value is Record { + return ( + typeof value === 'object' && + value !== null && + !Array.isArray(value) && + !(value instanceof Uint8Array) && + !(value instanceof Date) + ); +} + +/** Writes beside the file and renames over it, so a failed write leaves the old settings whole. */ +async function writeSettingsFile(settingsPath: string, file: SettingsFile): Promise { + const { build, buildBinary } = await import('plist'); + const temporaryPath = `${settingsPath}.agent-device.tmp`; + await writeHostBinaryFile( + temporaryPath, + file.format === 'binary' + ? buildBinary(file.store) + : new TextEncoder().encode(build(file.store)), + ); + await renameHostPath(temporaryPath, settingsPath); +} + +/** A plist UID, the reference type of an NSKeyedArchiver object table. */ +const uid = (index: number): PlistValue => ({ UID: index }); + +/** + * The `BBSectionInfo` archive iOS 27 writes after a user answers the prompt. The app's display name + * is the bundle id, as nothing here reads the installed app's name. + */ +async function sectionInfoArchive(bundleId: string, status: 1 | 2): Promise { + const { buildBinary } = await import('plist'); + const allowed = status === AUTHORIZATION_STATUS.grant; + const settings = { + $class: uid(4), + authorizationStatus: status, + authorizationExpirationDate: uid(0), + lastUserGrantedAuthorizationDate: uid(0), + alertType: 1, + pushSettings: allowed ? 63 : 0, + showsInNotificationCenter: allowed, + showsInLockScreen: allowed, + showsOnExternalDevices: allowed, + notificationCenterSetting: allowed ? 2 : 1, + lockScreenSetting: allowed ? 2 : 1, + remoteNotificationsSetting: allowed ? 2 : 1, + carPlaySetting: 0, + criticalAlertSetting: 0, + timeSensitiveSetting: 0, + userConfiguredTimeSensitiveSetting: false, + directMessagesSettingKey: 0, + userConfiguredDirectMessagesSetting: false, + announceSetting: 1, + announcePriority: 0, + bulletinGroupingSetting: 0, + contentPreviewSetting: 0, + prioritizationSetting: 2, + summarizationSetting: 2, + scheduledDeliverySetting: 1, + showsCustomSettingsLink: false, + muteAssertion: uid(0), + }; + const info = { + $class: uid(10), + sectionID: uid(2), + sectionInfoSettings: uid(3), + lastSettingChangeDate: uid(5), + appName: uid(7), + displayName: uid(8), + version: uid(9), + lastSettingSource: 2, + sectionType: 0, + sectionCategory: 0, + subsectionPriority: 0, + suppressFromSettings: false, + suppressedSettings: 0, + isRestricted: false, + isModificationAllowed: false, + hasEverBeenUserChanged: false, + isAppClip: false, + isLocked: false, + hideWeeApp: false, + customSettingsBundle: uid(0), + customSettingsDetailControllerClass: uid(0), + icon: uid(0), + subsections: uid(0), + subsectionID: uid(0), + managedSectionInfoSettings: uid(0), + factorySectionID: uid(0), + dataProviderIDs: uid(0), + pathToWeeAppPluginBundle: uid(0), + }; + const objects: PlistValue[] = [ + '$null', + info, + bundleId, + settings, + { $classname: 'BBSectionInfoSettings', $classes: ['BBSectionInfoSettings', 'NSObject'] }, + { 'NS.time': Date.now() / 1000 - COCOA_EPOCH_SECONDS, $class: uid(6) }, + { $classname: 'NSDate', $classes: ['NSDate', 'NSObject'] }, + bundleId, + bundleId, + 0, + { $classname: 'BBSectionInfo', $classes: ['BBSectionInfo', 'NSObject'] }, + ]; + return buildBinary({ + $version: 100_000, + $archiver: 'NSKeyedArchiver', + $top: { root: uid(1) }, + $objects: objects, + }); +} + +/** Whether an error is the refusal of a settings file this cannot write, which `all` skips. */ +export function isNotificationSettingsRefusal(error: unknown): error is AppError { + if (!(error instanceof AppError)) return false; + const reason = error.details?.reason; + return Object.values(SIMULATOR_NOTIFICATION_REASONS).some((row) => row.reason === reason); +} + +function notificationSettingsError( + { deviceId, appBundleId }: NotificationPermissionRequest, + reason: keyof typeof SIMULATOR_NOTIFICATION_REASONS, + message: string, + hint: string, +): AppError { + return new AppError('UNSUPPORTED_OPERATION', message, { + reason: SIMULATOR_NOTIFICATION_REASONS[reason].reason, + deviceId, + appBundleId, + hint, + }); +} diff --git a/test/integration/provider-scenarios/ios-alert-settings.test.ts b/test/integration/provider-scenarios/ios-alert-settings.test.ts index f0532010da..a9592ecb11 100644 --- a/test/integration/provider-scenarios/ios-alert-settings.test.ts +++ b/test/integration/provider-scenarios/ios-alert-settings.test.ts @@ -15,6 +15,7 @@ import { } from '@agent-device/test-kit'; import { createAppLogStartResult, createDurableResourceEnvelope } from '@agent-device/capture-kit'; import type { DeviceInfo } from '@agent-device/kernel/device'; +import { AppError } from '@agent-device/kernel/errors'; import { applePlugin } from '@agent-device/platform-apple'; import type { AlertRuntimeInput } from '@agent-device/contracts/alert-runtime'; import { assertFlatToolCall } from './assertions.ts'; @@ -162,6 +163,31 @@ test('Provider-backed integration iOS Settings permission and alert flow uses pr ...selection, }); + // A scoped tool provider keeps the simulator's files out of reach, so `all` skips the + // notification settings file and a targeted change refuses before any restart. + const all = await client.settings.update({ + setting: 'permission', + state: 'grant', + permission: 'all', + ...selection, + }); + assert.equal((all.permissions as string[]).includes('notifications'), false); + assert.match(String((all.warnings as string[]).at(-1)), /^Skipped notifications: /); + await assert.rejects( + () => + client.settings.update({ + setting: 'permission', + state: 'grant', + permission: 'notifications', + ...selection, + }), + (error: unknown) => { + assert.ok(error instanceof AppError); + assert.equal(error.details?.reason, 'ios-notification-settings-unreachable'); + return true; + }, + ); + const alertGet = await client.command.alert({ action: 'get', ...selection }); assert.equal(alertGet.title, 'Camera Access'); diff --git a/test/integration/provider-scenarios/limrun-ios-settings.test.ts b/test/integration/provider-scenarios/limrun-ios-settings.test.ts index c17a788c93..94a72425d0 100644 --- a/test/integration/provider-scenarios/limrun-ios-settings.test.ts +++ b/test/integration/provider-scenarios/limrun-ios-settings.test.ts @@ -73,23 +73,47 @@ test('a Limrun iOS permission the runtime refuses reports the local unsupported setting: 'permission', state: 'grant', appBundleId: 'com.example.ios', - options: { permissionTarget: 'notifications' }, + options: { permissionTarget: 'siri' }, }); await expect(refusal).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', message: - 'iOS simulator does not support setting notifications permission via simctl privacy on this runtime.', + 'iOS simulator does not support setting siri permission via simctl privacy on this runtime.', details: { appBundleId: 'com.example.ios' }, }); expect(state.simctl.mock.calls).toEqual([ - [['privacy', 'booted', 'grant', 'notifications', 'com.example.ios']], + [['privacy', 'booted', 'grant', 'siri', 'com.example.ios']], ]); } finally { await dispose(); } }); +test('a Limrun iOS notifications permission refuses before any simctl call', async () => { + const { binding, dispose } = await bindLimrunDeployment( + 'ios', + new AbortController().signal, + createLimrunRuntimeDependencies({ env: {}, cwd: process.cwd() }).ios, + ); + try { + await expect( + binding.operations.setSetting!({ + setting: 'permission', + state: 'grant', + appBundleId: 'com.example.ios', + options: { permissionTarget: 'notifications' }, + }), + ).rejects.toMatchObject({ + code: 'UNSUPPORTED_OPERATION', + details: { reason: 'ios-notification-settings-unreachable', appBundleId: 'com.example.ios' }, + }); + expect(state.simctl).not.toHaveBeenCalled(); + } finally { + await dispose(); + } +}); + test('a Limrun iOS simctl failure that is not a refusal stays a command failure', async () => { state.simctl.mockImplementation(() => ({ wait: async () => ({ code: 2, stdout: '', stderr: 'Invalid device: booted' }), diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 46f80623cf..abff3deed3 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1791,6 +1791,7 @@ 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`, or `bluetooth` takes no app). - On iOS simulators, the simulator decides which permissions it can change and refuses the rest. `grant all` skips a refused service with a warning. +- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard. The simulator returns to the Home Screen after about 10 seconds, so change notifications before `open`. `grant all` and `deny all` include notifications; `reset all` leaves them. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. - On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`. - Android kills a running app when you revoke one of its granted permissions. After `deny` or `reset`, run `open --relaunch` when the warning says so. - On macOS, `grant` opens System Settings when access needs your approval; it never grants silently. `deny` is unsupported. diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index 5d853bf9b7..c0897dbab0 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -358,6 +358,9 @@ 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. | | `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. | +| `ios-notification-settings-unreachable` | The simulator's files are not on this host, so its notification settings cannot be written. | +| `ios-notification-settings-missing` | The simulator has no notification settings file yet; SpringBoard creates it on its first start. | +| `ios-notification-settings-unrecognized` | The notification settings file is not in the layout this command writes, so it is left alone. | ### `shake` diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index e82e224193..722e0c6dd1 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -23,14 +23,14 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Supported subset -- Flows: `launchApp` (with `clearState`, `permissions`, and Apple-only launch arguments; `permissions` apply after state clearing but before launch, and a `launchApp` without `permissions` touches nothing — there is no silent `all: allow` default); `setPermissions` (mid-flow permission grants, denials, and resets; `all` resolves in the backend — each simctl privacy service on iOS, the declared permissions on Android — with specific entries overriding after it); `runFlow` file/inline; `runFlow.when` and `repeat.while` conditions (`platform`, `visible`, `notVisible`, and `true`, all re-evaluated before every `repeat` iteration); `onFlowStart`/`onFlowComplete`; `repeat` with `times`, `while`, or both; and retry. +- Flows: `launchApp` (with `clearState`, `permissions`, and Apple-only launch arguments; `permissions` apply after state clearing but before launch, and a `launchApp` without `permissions` touches nothing — there is no silent `all: allow` default); `setPermissions` (mid-flow permission grants, denials, and resets; `all` resolves in the backend — each simctl privacy service and notifications on iOS, the declared permissions on Android — with specific entries overriding after it); `runFlow` file/inline; `runFlow.when` and `repeat.while` conditions (`platform`, `visible`, `notVisible`, and `true`, all re-evaluated before every `repeat` iteration); `onFlowStart`/`onFlowComplete`; `repeat` with `times`, `while`, or both; and retry. - Interactions: `tapOn`, `doubleTapOn`, `longPressOn`, `inputText` on the focused element, `eraseText` (up to 10000 characters), `openLink`, `hideKeyboard`, basic `pressKey`, and `back`; selector targets poll until available and support recursive `index`, `childOf`, `above`, `below`, `leftOf`, `rightOf`, `containsChild`, `containsDescendants`, points, and `optional`; outer command labels are metadata, not target selectors. - Assertions and navigation: `assertVisible`, `assertNotVisible`, `assertTrue` (literal values and `${VAR}` lookups only; `""`, `"false"`, `"0"`, `"null"`, and `"undefined"` are falsy, everything else is truthy), `extendedWaitUntil`, `scroll`, `scrollUntilVisible`, absolute/percentage/target `swipe`, `takeScreenshot`, `waitForAnimationToEnd`, `clearState`, `stopApp`, and `killApp` (system-initiated process death: `am kill` on ADB-backed Android devices, which refuse a foreground target with `android-kill-requires-background-app` — background the app first, for example `pressKey: Home` — and fail a target whose process survives with `android-kill-process-survived`; iOS, Limrun, and WebDriver-provider backends run it as `stopApp`). - Scripts: ordered `runScript` file/env scripts with `http.post`, `json`, and `output` variables; `evalScript` inline expressions run flow-scoped JavaScript and write `output.*` leaves for later steps. ## Boundaries -- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict: current runtimes refuse a targeted `notifications` change and leave notifications untouched under `all`. +- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and returns the simulator to the Home Screen, so set them in `launchApp` `permissions` rather than mid-flow. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. - Environment: flow `env` is the default, `AD_VAR_*` overrides it, and CLI `-e KEY=VALUE` wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and `AD_*` stays reserved. From c9859769a145ed65912ebd790940bbb183ec718e Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 00:16:08 +0530 Subject: [PATCH 3/9] feat(ios): reset notifications under reset all and skip a restart that changes nothing --- packages/contracts/src/settings-catalog.ts | 2 +- .../simctl-settings-notifications.test.ts | 88 ++++++++++++++++++- .../core/__tests__/simctl-settings.test.ts | 10 ++- .../src/core/simctl-settings.ts | 47 +++++++--- .../core/simulator-notification-permission.ts | 45 +++++++++- website/docs/docs/commands.md | 2 +- 6 files changed, 172 insertions(+), 22 deletions(-) diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts index 32d518d2ae..70c0d2e8d8 100644 --- a/packages/contracts/src/settings-catalog.ts +++ b/packages/contracts/src/settings-catalog.ts @@ -178,7 +178,7 @@ export const SETTINGS = { ], app: 'input', appScope: { apple: 'app-scoped', mobile: 'app-scoped', 'macos-host': 'device-level' }, - help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, notifications restarts SpringBoard, which returns to the Home Screen, so change it before open. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', + help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard, which returns to the Home Screen, so change it before open. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', }, } as const satisfies Record; diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts index 9c63ccf8ad..65949057be 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts @@ -263,13 +263,97 @@ test('grant all stops at a restart failure and names the services it changed', a expect(failed.details?.permissions).not.toContain('notifications'); }); -test('reset all with a settings file stays one simctl privacy call', async () => { +test('reset all clears every privacy row, then removes the app notification record', async () => { const file = await settingsFile(); + await applySimctlSetting(permission(recordingRunner(), 'grant', 'notifications', file)); const runSimctl = recordingRunner(); - await applySimctlSetting(permission(runSimctl, 'reset', 'all', file)); + const result = await applySimctlSetting(permission(runSimctl, 'reset', 'all', file)); expect(runSimctl.mock.calls.map(([args]) => args)).toEqual([ ['privacy', 'SIM-1', 'reset', 'all', 'com.example.app'], + ...RESTART, ]); + expect(result).toEqual({ + permission: 'all', + permissions: ['all', 'notifications'], + warnings: [SPRINGBOARD_RESTART_WARNING], + }); + expect(Object.keys(sections(file))).toEqual(['com.apple.Home']); +}); + +test('reset all that simctl refuses leaves the notification record alone', async () => { + const file = await settingsFile(); + await applySimctlSetting(permission(recordingRunner(), 'grant', 'notifications', file)); + const refused = new AppError('COMMAND_FAILED', 'simctl exited with code 1', { + stderr: 'Failed to reset access\nOperation not permitted', + }); + const runSimctl = vi.fn(async (_args: string[]) => { + throw refused; + }); + + await expect( + applySimctlSetting(permission(runSimctl, 'reset', 'all', file)), + ).rejects.toMatchObject({ code: 'UNSUPPORTED_OPERATION', cause: refused }); + expect(runSimctl).toHaveBeenCalledTimes(1); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +test.for([ + { held: 'grant', state: 'grant' }, + { held: 'deny', state: 'deny' }, + { held: undefined, state: 'reset' }, +])( + '$state notifications on a file that already holds it changes nothing and restarts nothing', + async ({ held, state }) => { + const file = await settingsFile(); + if (held) await applySimctlSetting(permission(recordingRunner(), held, 'notifications', file)); + const before = fs.readFileSync(file); + const runSimctl = recordingRunner(); + + const result = await applySimctlSetting(permission(runSimctl, state, 'notifications', file)); + + expect(result).toEqual({ permission: 'notifications' }); + expect(runSimctl).not.toHaveBeenCalled(); + expect(fs.readFileSync(file)).toEqual(before); + }, +); + +test.for([ + { label: 'another status', record: undefined }, + { label: 'an archive that does not parse', record: new Uint8Array([1, 2, 3]) }, +])('a record with $label is rewritten with a restart', async ({ record }) => { + const file = await settingsFile(); + if (record) { + fs.writeFileSync( + file, + build({ + ...SETTINGS, + sectionInfo: { 'com.apple.Home': HOME_RECORD, 'com.example.app': record }, + }), + ); + } else { + await applySimctlSetting(permission(recordingRunner(), 'deny', 'notifications', file)); + } + const runSimctl = recordingRunner(); + + await applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +test('grant all on a file that already holds the grant counts notifications without a restart', async () => { + const file = await settingsFile(); + await applySimctlSetting(permission(recordingRunner(), 'grant', 'notifications', file)); + const runSimctl = recordingRunner(); + + const result = (await applySimctlSetting(permission(runSimctl, 'grant', 'all', file))) as { + permissions: string[]; + warnings?: string[]; + }; + + expect(runSimctl.mock.calls.every(([args]) => args[0] === 'privacy')).toBe(true); + expect(result.permissions.at(-1)).toBe('notifications'); + expect(result.warnings).toBeUndefined(); }); diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts index 4b99d52308..bc83a5d48b 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings.test.ts @@ -198,7 +198,7 @@ test.for([ }, ); -test('reset all stays one simctl call, which clears every service', async () => { +test('reset all is one simctl privacy call, which clears every service', async () => { const runSimctl = recordingRunner(); const result = await applySimctlSetting( @@ -211,7 +211,13 @@ test('reset all stays one simctl call, which clears every service', async () => ); expect(argvs(runSimctl)).toEqual([['privacy', 'SIM-1', 'reset', 'all', 'com.example.app']]); - expect(result).toBeUndefined(); + expect(result).toEqual({ + permission: 'all', + permissions: ['all'], + warnings: [ + 'Skipped notifications: iOS simulator notification permission needs the simulator files on this host.', + ], + }); }); test('grant all fails as unsupported only when the runtime refuses every service', async () => { diff --git a/packages/platform-apple/src/core/simctl-settings.ts b/packages/platform-apple/src/core/simctl-settings.ts index e95b0c5d4c..4caa4dd8fe 100644 --- a/packages/platform-apple/src/core/simctl-settings.ts +++ b/packages/platform-apple/src/core/simctl-settings.ts @@ -60,8 +60,11 @@ async function setPermission( const target = parseIosPrivacyService(options?.permissionTarget, options?.permissionMode); const appBundleId = await requireAppBundleId(request); if (target === 'notifications') { - await setNotificationPermission(request, action, appBundleId); - return { permission: 'notifications', warnings: [SPRINGBOARD_RESTART_WARNING] }; + const restarted = await setNotificationPermission(request, action, appBundleId); + return { + permission: 'notifications', + ...(restarted ? { warnings: [SPRINGBOARD_RESTART_WARNING] } : {}), + }; } if (target === 'all' && action !== 'reset') { return await setEveryIosPrivacyService(request, action, appBundleId); @@ -72,6 +75,11 @@ async function setPermission( if (!isIosPrivacyServiceRefusal(error)) throw error; throw iosPrivacyServiceRefusedError(action, target, appBundleId, deviceId, error); } + if (target !== 'all') return; + // A reset of `all` is one call that removes every privacy row, then notifications. + const applied = ['all']; + const warnings = await setNotificationsUnderAll(request, action, appBundleId, applied); + return { permission: 'all', permissions: applied, ...(warnings.length > 0 ? { warnings } : {}) }; } /** @@ -139,8 +147,7 @@ const IOS_ALL_REVOKED_SERVICES: readonly string[] = [...IOS_ALL_GRANTED_SERVICES * not consult, so the app still prompts, and a revoke of `all` leaves every per-service grant in * place. A service the runtime refuses, or a notification settings file this cannot write, is * skipped with a warning, as Android skips a permission it cannot change. Any other failure stops - * the sequence, and its error carries the services already changed in `details.permissions`. A - * reset of `all` stays one call: it removes every row. + * the sequence, and its error carries the services already changed in `details.permissions`. */ async function setEveryIosPrivacyService( request: SimctlSettingRequest, @@ -162,26 +169,40 @@ async function setEveryIosPrivacyService( warnings.push(`Skipped ${service}: this iOS runtime does not let simctl privacy change it.`); } } + warnings.push(...(await setNotificationsUnderAll(request, action, appBundleId, applied))); + if (applied.length === 0) { + throw iosPrivacyServiceRefusedError(action, 'all', appBundleId, deviceId, lastRefusal); + } + return { permission: 'all', permissions: applied, ...(warnings.length > 0 ? { warnings } : {}) }; +} + +/** + * Notifications as the last step of `all`: the restart warning when they change, none when the file + * already holds them, or a skip warning when the file cannot be written. Any other failure carries + * what `all` already changed. + */ +async function setNotificationsUnderAll( + request: SimctlSettingRequest, + action: 'grant' | 'revoke' | 'reset', + appBundleId: string, + applied: string[], +): Promise { try { - await setNotificationPermission(request, action, appBundleId); + const restarted = await setNotificationPermission(request, action, appBundleId); applied.push('notifications'); - warnings.push(SPRINGBOARD_RESTART_WARNING); + return restarted ? [SPRINGBOARD_RESTART_WARNING] : []; } catch (error) { if (!isNotificationSettingsRefusal(error)) throw withAppliedServices(error, applied); - warnings.push(`Skipped notifications: ${error.message}`); + return [`Skipped notifications: ${error.message}`]; } - if (applied.length === 0) { - throw iosPrivacyServiceRefusedError(action, 'all', appBundleId, deviceId, lastRefusal); - } - return { permission: 'all', permissions: applied, ...(warnings.length > 0 ? { warnings } : {}) }; } async function setNotificationPermission( { runSimctl, udid, deviceId, notificationSettingsPath }: SimctlSettingRequest, action: 'grant' | 'revoke' | 'reset', appBundleId: string, -): Promise { - await setSimulatorNotificationPermission({ +): Promise { + return await setSimulatorNotificationPermission({ runSimctl, udid, deviceId, diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index ec863f4140..d9f9d604ed 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -56,10 +56,11 @@ type SettingsFile = { * `BBSectionInfo` per bundle id, or none for a reset. SpringBoard and `usernotificationsd` write * their copy back as they stop, so the edit lands between their stop and start, and the restart * leaves the simulator on the Home Screen. A file in any other layout is refused, not rewritten. + * Resolves `false`, with no restart, when the file already holds the asked-for status. */ export async function setSimulatorNotificationPermission( request: NotificationPermissionRequest, -): Promise { +): Promise { const { runSimctl, udid, settingsPath } = request; if (settingsPath === undefined) { throw notificationSettingsError( @@ -69,8 +70,13 @@ export async function setSimulatorNotificationPermission( 'Answer the app notification prompt instead, or use a simulator on the host that runs agent-device.', ); } - // Read before the stop as well, so a file this cannot write refuses without a restart. - await readSettingsFile(request, settingsPath); + // Read before the stop as well, so a file this cannot write refuses without a restart. SpringBoard + // writes a prompt answer to the file at once (iOS 27.2), so a file that already holds the status + // is what the services hold too. + const current = await readSettingsFile(request, settingsPath); + if ((await recordedStatus(current, request.appBundleId)) === wantedStatus(request.action)) { + return false; + } try { for (const service of NOTIFICATION_SERVICES) { await runSimctl(['spawn', udid, 'launchctl', 'stop', service]); @@ -90,6 +96,39 @@ export async function setSimulatorNotificationPermission( await runSimctl(['spawn', udid, 'launchctl', 'start', service]); } } + return true; +} + +/** The status the action leaves, with `null` for a reset's absent record. */ +function wantedStatus(action: NotificationPermissionRequest['action']): number | null { + return action === 'reset' ? null : AUTHORIZATION_STATUS[action]; +} + +/** + * The `authorizationStatus` an app's record holds, `null` when it has none, and `undefined` when + * its archive cannot be read, which never matches a wanted status. + */ +async function recordedStatus( + file: SettingsFile, + bundleId: string, +): Promise { + const record = file.sections[bundleId]; + if (record === undefined) return null; + const { parseBinary } = await import('plist'); + try { + const archive = parseBinary(record as Uint8Array) as { + $top: { root: { UID: number } }; + $objects: Array>; + }; + const info = archive.$objects[archive.$top.root.UID]; + const settingsRef = info?.sectionInfoSettings; + const settings = + typeof settingsRef === 'object' ? archive.$objects[settingsRef.UID] : undefined; + const status = settings?.authorizationStatus; + return typeof status === 'number' ? status : undefined; + } catch { + return undefined; + } } async function readSettingsFile( diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index abff3deed3..54798e56c3 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1791,7 +1791,7 @@ 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`, or `bluetooth` takes no app). - On iOS simulators, the simulator decides which permissions it can change and refuses the rest. `grant all` skips a refused service with a warning. -- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard. The simulator returns to the Home Screen after about 10 seconds, so change notifications before `open`. `grant all` and `deny all` include notifications; `reset all` leaves them. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. +- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, unless the app already holds that state. The simulator returns to the Home Screen after about 10 seconds, so change notifications before `open`. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. - On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`. - Android kills a running app when you revoke one of its granted permissions. After `deny` or `reset`, run `open --relaunch` when the warning says so. - On macOS, `grant` opens System Settings when access needs your approval; it never grants silently. `deny` is unsupported. From 84bca59e4950354fa73324bc38abc4072740c321 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 01:53:50 +0530 Subject: [PATCH 4/9] fix(ios): wait out the notification restart, reopen the app it closed, and keep the settings path host-only --- packages/contracts/src/settings.ts | 7 +- .../src/core/__tests__/app-settings.test.ts | 22 +- .../simctl-settings-notifications.test.ts | 251 +++++++++++++++++- packages/platform-apple/src/core/plist.ts | 17 +- .../src/core/simctl-settings.ts | 37 +-- .../core/simulator-notification-permission.ts | 157 +++++++++-- website/docs/docs/error-reasons.md | 2 + 7 files changed, 430 insertions(+), 63 deletions(-) diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index f412cf6c86..b9bc4b8a1d 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -79,7 +79,7 @@ export type SettingOptions = { longitude?: number; }; -/** The settings a simulator changes through `simctl`, whichever host runs that `simctl`. */ +/** The settings a simulator changes through `simctl` alone, whichever host runs that `simctl`. */ type SimctlSetting = 'appearance' | 'permission' | 'location'; /** @@ -102,11 +102,6 @@ export type SimctlSettingRequest = { appBundleId?: string; /** Resolves the app a privacy change names to the bundle id `simctl privacy` writes. */ resolveApp: (app: string) => Promise; - /** - * The simulator's notification settings file on this host, which `notifications` writes since - * `simctl privacy` refuses it; absent where the runner cannot reach the simulator's files. - */ - notificationSettingsPath?: string; options?: SettingOptions; }; diff --git a/packages/platform-apple/src/core/__tests__/app-settings.test.ts b/packages/platform-apple/src/core/__tests__/app-settings.test.ts index ca70c01555..897c4d6cee 100644 --- a/packages/platform-apple/src/core/__tests__/app-settings.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-settings.test.ts @@ -665,11 +665,21 @@ test('setIosSetting notifications writes the settings file of the simulator on t mockEnsureBootedSimulator.mockResolvedValue(undefined); const { set, file } = await simulatorSetWithNotificationSettings(); const simctl: string[][] = []; + // `launchctl list` shows SpringBoard's process between its stop and its start. + let springBoardPid = '1'; mockRunCmd.mockImplementation(async (cmd, args) => { assert.equal(cmd, 'xcrun'); const unscoped = args.slice(args.indexOf('--set') + 2); simctl.push(unscoped); - const stdout = unscoped.join(' ') === 'listapps sim-1' ? INSTALLED_APPS_JSON : ''; + const command = unscoped.join(' '); + if (command === 'spawn sim-1 launchctl stop com.apple.SpringBoard') springBoardPid = '-'; + if (command === 'spawn sim-1 launchctl start com.apple.SpringBoard') springBoardPid = '2'; + const stdout = + command === 'listapps sim-1' + ? INSTALLED_APPS_JSON + : command === 'spawn sim-1 launchctl list' + ? `${springBoardPid}\t0\tcom.apple.SpringBoard` + : ''; return { stdout, stderr: '', exitCode: 0 }; }); @@ -687,13 +697,9 @@ test('setIosSetting notifications writes the settings file of the simulator on t sectionInfo: Record; }; assert.deepEqual(Object.keys(store.sectionInfo), ['com.example.app']); - assert.deepEqual(simctl.at(-1), [ - 'spawn', - 'sim-1', - 'launchctl', - 'start', - 'com.apple.usernotificationsd', - ]); + assert.ok( + simctl.some((args) => args.join(' ') === 'spawn sim-1 launchctl start com.apple.SpringBoard'), + ); }); test('setIosSetting notifications refuses a simulator a scoped tool provider runs', async () => { diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts index 65949057be..ad66a0f588 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts @@ -2,10 +2,10 @@ import fs from 'node:fs'; import path from 'node:path'; import { expect, test, vi } from 'vitest'; import { build, buildBinary, parse, parseBinary, type PlistValue } from 'plist'; -import type { SimctlSettingRequest } from '@agent-device/contracts/settings'; +import { renameHostPath } from '@agent-device/host-kit/host-file'; import { AppError } from '@agent-device/kernel/errors'; import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; -import { applySimctlSetting } from '../simctl-settings.ts'; +import { applySimctlSetting, type AppleSimctlSettingRequest } from '../simctl-settings.ts'; import { SIMULATOR_NOTIFICATION_REASONS, SPRINGBOARD_RESTART_WARNING, @@ -19,13 +19,27 @@ const SETTINGS: Record = { sectionInfoVersionNumber: 3, }; +vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, renameHostPath: vi.fn(actual.renameHostPath) }; +}); + +const LIST = ['spawn', 'SIM-1', 'launchctl', 'list']; + +// Whether the app runs, the stop, a read until both services exit, the start, and a read until +// SpringBoard is back. const RESTART = [ + LIST, ['spawn', 'SIM-1', 'launchctl', 'stop', 'com.apple.SpringBoard'], ['spawn', 'SIM-1', 'launchctl', 'stop', 'com.apple.usernotificationsd'], + LIST, ['spawn', 'SIM-1', 'launchctl', 'start', 'com.apple.SpringBoard'], ['spawn', 'SIM-1', 'launchctl', 'start', 'com.apple.usernotificationsd'], + LIST, ]; +const APP_JOB = 'UIKitApplication:com.example.app[1a2b][rb-legacy]'; + async function settingsFile( store: PlistValue = SETTINGS, format: 'xml' | 'binary' = 'xml', @@ -61,19 +75,42 @@ function recordOf(record: Uint8Array | undefined): { sectionID: PlistValue; stat }; } -function recordingRunner(onRun: (args: string[]) => void = () => {}) { +/** + * A simulator's `launchctl`: `stop` ends a job and `start` gives it a process, unless a test holds + * the job in its old state; a SpringBoard stop ends the app, and `simctl launch` brings it back. + */ +function recordingRunner( + onRun: (args: string[]) => void = () => {}, + { appRunning = false, held = [] as string[] } = {}, +) { + const pids = new Map([ + ['com.apple.SpringBoard', 100], + ['com.apple.usernotificationsd', 101], + [APP_JOB, appRunning ? 200 : undefined], + ]); return vi.fn(async (args: string[]) => { onRun(args); - return { stdout: '', stderr: '' }; + const [, , tool, verb, label = ''] = args; + if (tool === 'launchctl' && !held.includes(label)) { + if (verb === 'stop') pids.set(label, undefined); + if (verb === 'stop' && label === 'com.apple.SpringBoard') pids.set(APP_JOB, undefined); + if (verb === 'start') pids.set(label, 300); + } + if (args[0] === 'launch') pids.set(APP_JOB, 400); + const rows = [...pids].map(([job, pid]) => `${pid ?? '-'}\t0\t${job}`); + return { + stdout: verb === 'list' ? ['PID\tStatus\tLabel', ...rows].join('\n') : '', + stderr: '', + }; }); } function permission( - runSimctl: SimctlSettingRequest['runSimctl'], + runSimctl: AppleSimctlSettingRequest['runSimctl'], state: string, permissionTarget: string, notificationSettingsPath: string | undefined, -): SimctlSettingRequest { +): AppleSimctlSettingRequest { return { runSimctl, udid: 'SIM-1', @@ -160,7 +197,7 @@ test('a settings file that changes layout during the stop still restarts both se code: 'UNSUPPORTED_OPERATION', details: { reason: SIMULATOR_NOTIFICATION_REASONS.unrecognized.reason }, }); - expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART.slice(0, -1)); }); test.for([ @@ -357,3 +394,203 @@ test('grant all on a file that already holds the grant counts notifications with expect(result.permissions.at(-1)).toBe('notifications'); expect(result.warnings).toBeUndefined(); }); + +test('an app that was running is opened again once SpringBoard is back', async () => { + const file = await settingsFile(); + const runSimctl = recordingRunner(() => {}, { appRunning: true }); + + const result = await applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual([ + ...RESTART, + ['launch', 'SIM-1', 'com.example.app'], + ]); + expect(result).toEqual({ + permission: 'notifications', + warnings: [ + 'Restarted SpringBoard to apply the notification permission, and opened com.example.app again because it was running.', + ], + }); +}); + +test('a failed reopen keeps the applied change and says the app stayed closed', async () => { + const file = await settingsFile(); + const fake = recordingRunner(() => {}, { appRunning: true }); + const runSimctl = vi.fn(async (args: string[]) => { + if (args[0] === 'launch') throw new AppError('COMMAND_FAILED', 'simctl exited with code 4'); + return await fake(args); + }); + + const result = (await applySimctlSetting( + permission(runSimctl, 'grant', 'notifications', file), + )) as { warnings: string[] }; + + expect(result.warnings).toEqual([ + `${SPRINGBOARD_RESTART_WARNING} Opening com.example.app again failed: simctl exited with code 4`, + ]); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +test('the edit waits for SpringBoard to exit, so its last write cannot replace the edit', async () => { + const file = await settingsFile(); + const flushed = new Uint8Array([7, 7, 7]); + let exiting = 0; + // SpringBoard ignores the stop and start verbs here; this test decides when it reports no process. + const fake = recordingRunner(() => {}, { held: ['com.apple.SpringBoard'] }); + const runSimctl = vi.fn(async (args: string[]) => { + const answer = await fake(args); + const calls = fake.mock.calls.map(([call]) => call.join(' ')); + const stopped = calls.some((call) => call.endsWith('stop com.apple.SpringBoard')); + const started = calls.some((call) => call.endsWith('start com.apple.SpringBoard')); + if (args.join(' ') !== LIST.join(' ') || !stopped || started) return answer; + exiting += 1; + if (exiting < 3) return answer; + // SpringBoard writes its copy as it exits, then reports no process. + const store = readSettings(file); + (store.sectionInfo as Record)['com.apple.Maps'] = flushed; + fs.writeFileSync(file, build(store)); + return { + ...answer, + stdout: answer.stdout.replace(/^\d+(\t0\tcom\.apple\.SpringBoard)$/m, '-$1'), + }; + }); + + await applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + + expect(exiting).toBe(3); + expect(sections(file)['com.apple.Maps']).toEqual(flushed); + expect(recordOf(sections(file)['com.example.app']).status).toBe(2); +}); + +/** Moves fake time on between the real file reads until the change settles. */ +async function advanceUntilSettled(pending: Promise): Promise { + let settled = false; + pending.then( + () => (settled = true), + () => (settled = true), + ); + for (let step = 0; step < 200 && !settled; step += 1) { + await new Promise((resolve) => setImmediate(resolve)); + await vi.advanceTimersByTimeAsync(200); + } +} + +test.for([ + { label: 'SpringBoard never exits', held: 'com.apple.SpringBoard', verb: 'stop', written: false }, + { + label: 'usernotificationsd never exits', + held: 'com.apple.usernotificationsd', + verb: 'stop', + written: false, + }, + { + label: 'SpringBoard never comes back', + held: 'com.apple.SpringBoard', + verb: 'start', + written: true, + }, +])( + 'a restart where $label fails after 10 seconds and still starts both', + async ({ held, verb, written }) => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + try { + const file = await settingsFile(); + const before = fs.readFileSync(file); + const fake = recordingRunner(); + // The held job keeps the state it had before the verb. + const runSimctl = vi.fn(async (args: string[]) => { + if (args[3] === verb && args[4] === held) return { stdout: '', stderr: '' }; + return await fake(args); + }); + + const pending = applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + const settled = expect(pending).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason }, + }); + await advanceUntilSettled(pending); + await settled; + + const argvs = runSimctl.mock.calls.map(([args]) => args.join(' ')); + expect(argvs).toContain('spawn SIM-1 launchctl start com.apple.SpringBoard'); + expect(argvs).toContain('spawn SIM-1 launchctl start com.apple.usernotificationsd'); + expect(fs.readFileSync(file).equals(before)).toBe(!written); + } finally { + vi.useRealTimers(); + } + }, +); + +test('a record that does not hold after the restart fails as not applied', async () => { + const file = await settingsFile(); + const original = fs.readFileSync(file); + const runSimctl = recordingRunner((args) => { + // SpringBoard comes back with the settings it held before the edit. + if (args.join(' ') === 'spawn SIM-1 launchctl start com.apple.SpringBoard') { + fs.writeFileSync(file, original); + } + }); + + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)), + ).rejects.toMatchObject({ + code: 'COMMAND_FAILED', + details: { reason: SIMULATOR_NOTIFICATION_REASONS.notApplied.reason }, + }); +}); + +test('a failed rename removes its temporary file and leaves the settings whole', async () => { + const file = await settingsFile(); + const before = fs.readFileSync(file); + vi.mocked(renameHostPath).mockRejectedValueOnce(new Error('EXDEV: cross-device link')); + const runSimctl = recordingRunner(); + + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)), + ).rejects.toThrow('EXDEV'); + + expect(fs.readdirSync(path.dirname(file))).toEqual([path.basename(file)]); + expect(fs.readFileSync(file)).toEqual(before); + expect(runSimctl.mock.calls.map(([args]) => args.join(' '))).toContain( + 'spawn SIM-1 launchctl start com.apple.SpringBoard', + ); +}); + +test('grant all fails on a restart that times out instead of skipping notifications', async () => { + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + try { + const file = await settingsFile(); + const fake = recordingRunner(); + const runSimctl = vi.fn(async (args: string[]) => + args.join(' ') === 'spawn SIM-1 launchctl stop com.apple.SpringBoard' + ? { stdout: '', stderr: '' } + : await fake(args), + ); + + const pending = applySimctlSetting(permission(runSimctl, 'grant', 'all', file)); + const settled = expect(pending).rejects.toMatchObject({ + details: { + reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason, + permissions: expect.arrayContaining(['camera']), + }, + }); + await advanceUntilSettled(pending); + await settled; + } finally { + vi.useRealTimers(); + } +}); + +test('another running app is not the one reopened', async () => { + const file = await settingsFile(); + const fake = recordingRunner(); + const runSimctl = vi.fn(async (args: string[]) => { + const answer = await fake(args); + if (args.join(' ') !== LIST.join(' ')) return answer; + return { ...answer, stdout: `${answer.stdout}\n300\t0\tUIKitApplication:com.apple.Maps[9f9f]` }; + }); + + await applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); + + expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); +}); diff --git a/packages/platform-apple/src/core/plist.ts b/packages/platform-apple/src/core/plist.ts index 14a69520db..4f86d881a6 100644 --- a/packages/platform-apple/src/core/plist.ts +++ b/packages/platform-apple/src/core/plist.ts @@ -1,5 +1,6 @@ import { readHostTextFile } from '@agent-device/host-kit/host-file'; import { parseXmlDocumentSync, visitXmlPlistEntries } from '@agent-device/xml'; +import type { PlistValue } from 'plist'; import { APPLE_PLIST_TIMEOUT_MS, readApplePlistJson, @@ -65,10 +66,20 @@ function readXmlPlistString(plist: string, key: string): string | undefined { /** Parses downloaded app metadata on hosts without Apple's plist tools. */ export async function parseApplePlist(bytes: Uint8Array): Promise | null> { - const { parse } = await import('plist'); - const binary = new TextDecoder().decode(bytes.subarray(0, 8)) === 'bplist00'; - const value = parse(binary ? bytes : new TextDecoder().decode(bytes)); + const { value } = await readApplePlist(bytes); return value !== null && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : null; } + +/** A binary or XML plist's value, with the format it was stored in so a rewrite can keep it. */ +export async function readApplePlist( + bytes: Uint8Array, +): Promise<{ format: 'binary' | 'xml'; value: PlistValue }> { + const { parse } = await import('plist'); + const binary = new TextDecoder().decode(bytes.subarray(0, 8)) === 'bplist00'; + return { + format: binary ? 'binary' : 'xml', + value: parse(binary ? bytes : new TextDecoder().decode(bytes)), + }; +} diff --git a/packages/platform-apple/src/core/simctl-settings.ts b/packages/platform-apple/src/core/simctl-settings.ts index 4caa4dd8fe..3a2f9959da 100644 --- a/packages/platform-apple/src/core/simctl-settings.ts +++ b/packages/platform-apple/src/core/simctl-settings.ts @@ -10,13 +10,21 @@ import { AppError, sessionAppRequiredDetails } from '@agent-device/kernel/errors import { requireLocationCoordinates } from '@agent-device/kernel/location-coordinates'; import { isNotificationSettingsRefusal, + notificationRestartWarnings, setSimulatorNotificationPermission, - SPRINGBOARD_RESTART_WARNING, } from './simulator-notification-permission.ts'; +/** + * A setting request with what only a runner on the simulator's own host has: the simulator's + * notification settings file, which `notifications` writes since `simctl privacy` refuses it. + */ +export type AppleSimctlSettingRequest = SimctlSettingRequest & { + notificationSettingsPath?: string; +}; + /** Changes one simulator setting through `simctl`; the Apple package owns this plan for every runner. */ export async function applySimctlSetting( - request: SimctlSettingRequest, + request: AppleSimctlSettingRequest, ): Promise | void> { switch (request.setting) { case 'appearance': @@ -52,7 +60,7 @@ async function setAppearance({ runSimctl, udid, state }: SimctlSettingRequest): } async function setPermission( - request: SimctlSettingRequest, + request: AppleSimctlSettingRequest, ): Promise | void> { const { runSimctl, udid, deviceId, state, options } = request; const permissionAction = parsePermissionAction(state); @@ -60,11 +68,8 @@ async function setPermission( const target = parseIosPrivacyService(options?.permissionTarget, options?.permissionMode); const appBundleId = await requireAppBundleId(request); if (target === 'notifications') { - const restarted = await setNotificationPermission(request, action, appBundleId); - return { - permission: 'notifications', - ...(restarted ? { warnings: [SPRINGBOARD_RESTART_WARNING] } : {}), - }; + const warnings = await setNotificationPermission(request, action, appBundleId); + return { permission: 'notifications', ...(warnings.length > 0 ? { warnings } : {}) }; } if (target === 'all' && action !== 'reset') { return await setEveryIosPrivacyService(request, action, appBundleId); @@ -150,7 +155,7 @@ const IOS_ALL_REVOKED_SERVICES: readonly string[] = [...IOS_ALL_GRANTED_SERVICES * the sequence, and its error carries the services already changed in `details.permissions`. */ async function setEveryIosPrivacyService( - request: SimctlSettingRequest, + request: AppleSimctlSettingRequest, action: 'grant' | 'revoke', appBundleId: string, ): Promise> { @@ -182,27 +187,28 @@ async function setEveryIosPrivacyService( * what `all` already changed. */ async function setNotificationsUnderAll( - request: SimctlSettingRequest, + request: AppleSimctlSettingRequest, action: 'grant' | 'revoke' | 'reset', appBundleId: string, applied: string[], ): Promise { try { - const restarted = await setNotificationPermission(request, action, appBundleId); + const warnings = await setNotificationPermission(request, action, appBundleId); applied.push('notifications'); - return restarted ? [SPRINGBOARD_RESTART_WARNING] : []; + return warnings; } catch (error) { if (!isNotificationSettingsRefusal(error)) throw withAppliedServices(error, applied); return [`Skipped notifications: ${error.message}`]; } } +/** Sets notifications and answers with the warnings its restart, if any, leaves. */ async function setNotificationPermission( - { runSimctl, udid, deviceId, notificationSettingsPath }: SimctlSettingRequest, + { runSimctl, udid, deviceId, notificationSettingsPath }: AppleSimctlSettingRequest, action: 'grant' | 'revoke' | 'reset', appBundleId: string, -): Promise { - return await setSimulatorNotificationPermission({ +): Promise { + const outcome = await setSimulatorNotificationPermission({ runSimctl, udid, deviceId, @@ -210,6 +216,7 @@ async function setNotificationPermission( action, settingsPath: notificationSettingsPath, }); + return notificationRestartWarnings(appBundleId, outcome); } /** The error that stopped `all` partway, naming the services it had already changed. */ diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index d9f9d604ed..c5bb309cee 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -1,10 +1,13 @@ import { readHostBinaryFile, + removeHostPath, renameHostPath, writeHostBinaryFile, } from '@agent-device/host-kit/host-file'; +import { Deadline, sleep } from '@agent-device/host-kit/retry'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { PlistValue } from 'plist'; +import { readApplePlist } from './plist.ts'; /** The file under a simulator's data directory where SpringBoard keeps each app's notification settings. */ export const SIMULATOR_NOTIFICATION_SETTINGS_FILE = @@ -17,6 +20,10 @@ export const SIMULATOR_NOTIFICATION_REASONS = { missing: { reason: 'ios-notification-settings-missing' }, // The notification settings file is not in the layout this command writes, so it is left alone. unrecognized: { reason: 'ios-notification-settings-unrecognized' }, + // SpringBoard or usernotificationsd did not stop, or SpringBoard did not start, within 10 seconds. + restartTimeout: { reason: 'ios-notification-restart-timeout' }, + // The file read back after the restart does not hold the written status. + notApplied: { reason: 'ios-notification-settings-not-applied' }, } as const satisfies ReasonTable<'settings'>; /** The `sectionInfoVersionNumber` of the layout the written record follows (iOS 27). */ @@ -27,6 +34,11 @@ const AUTHORIZATION_STATUS = { grant: 2, revoke: 1 } as const; /** The services that hold the settings in memory, and write them back to the file as they stop. */ const NOTIFICATION_SERVICES = ['com.apple.SpringBoard', 'com.apple.usernotificationsd']; +const SPRINGBOARD = 'com.apple.SpringBoard'; + +/** How long a stop or a start may take before the change fails, and how often it is read. */ +const SERVICE_WAIT_MS = 10_000; +const SERVICE_POLL_MS = 200; /** Seconds from the Unix epoch to the Cocoa reference date, 2001-01-01. */ const COCOA_EPOCH_SECONDS = 978_307_200; @@ -35,7 +47,7 @@ export const SPRINGBOARD_RESTART_WARNING = 'Restarted SpringBoard to apply the notification permission, so the simulator is back on the Home Screen. Change notifications before open, then open the app.'; type NotificationPermissionRequest = { - runSimctl: (args: string[]) => Promise; + runSimctl: (args: string[]) => Promise<{ readonly stdout: string }>; udid: string; deviceId: string; appBundleId: string; @@ -44,6 +56,14 @@ type NotificationPermissionRequest = { settingsPath: string | undefined; }; +/** + * What a change did: nothing when the file already held it, else a restart, which reopens the app + * when it was running so a test that changes notifications mid-flow keeps its app in front. + */ +export type NotificationPermissionOutcome = + | { restarted: false } + | { restarted: true; reopened: boolean; reopenFailure?: string }; + type SettingsFile = { format: 'xml' | 'binary'; store: Record; @@ -56,12 +76,11 @@ type SettingsFile = { * `BBSectionInfo` per bundle id, or none for a reset. SpringBoard and `usernotificationsd` write * their copy back as they stop, so the edit lands between their stop and start, and the restart * leaves the simulator on the Home Screen. A file in any other layout is refused, not rewritten. - * Resolves `false`, with no restart, when the file already holds the asked-for status. */ export async function setSimulatorNotificationPermission( request: NotificationPermissionRequest, -): Promise { - const { runSimctl, udid, settingsPath } = request; +): Promise { + const { runSimctl, udid, settingsPath, appBundleId } = request; if (settingsPath === undefined) { throw notificationSettingsError( request, @@ -73,14 +92,18 @@ export async function setSimulatorNotificationPermission( // Read before the stop as well, so a file this cannot write refuses without a restart. SpringBoard // writes a prompt answer to the file at once (iOS 27.2), so a file that already holds the status // is what the services hold too. + const wanted = wantedStatus(request.action); const current = await readSettingsFile(request, settingsPath); - if ((await recordedStatus(current, request.appBundleId)) === wantedStatus(request.action)) { - return false; - } + if ((await recordedStatus(current, appBundleId)) === wanted) return { restarted: false }; + const wasRunning = runningJobs(await listJobs(request)).some((label) => + label.startsWith(`UIKitApplication:${appBundleId}[`), + ); try { for (const service of NOTIFICATION_SERVICES) { await runSimctl(['spawn', udid, 'launchctl', 'stop', service]); } + // `launchctl stop` only signals, and a service still exiting writes its copy over the edit. + await waitForJobs(request, NOTIFICATION_SERVICES, 'stopped'); const file = await readSettingsFile(request, settingsPath); if (request.action === 'reset') { delete file.sections[request.appBundleId]; @@ -96,7 +119,83 @@ export async function setSimulatorNotificationPermission( await runSimctl(['spawn', udid, 'launchctl', 'start', service]); } } - return true; + await waitForJobs(request, [SPRINGBOARD], 'running'); + const written = await readSettingsFile(request, settingsPath); + if ((await recordedStatus(written, appBundleId)) !== wanted) { + throw new AppError( + 'COMMAND_FAILED', + `iOS simulator notification settings for ${appBundleId} did not hold after SpringBoard restarted.`, + { + reason: SIMULATOR_NOTIFICATION_REASONS.notApplied.reason, + deviceId: request.deviceId, + appBundleId, + }, + ); + } + if (!wasRunning) return { restarted: true, reopened: false }; + try { + await runSimctl(['launch', udid, appBundleId]); + return { restarted: true, reopened: true }; + } catch (error) { + return { restarted: true, reopened: false, reopenFailure: (error as Error).message }; + } +} + +/** The warning a change carries: none when nothing restarted. */ +export function notificationRestartWarnings( + appBundleId: string, + outcome: NotificationPermissionOutcome, +): string[] { + if (!outcome.restarted) return []; + if (outcome.reopened) { + return [ + `Restarted SpringBoard to apply the notification permission, and opened ${appBundleId} again because it was running.`, + ]; + } + if (outcome.reopenFailure !== undefined) { + return [ + `${SPRINGBOARD_RESTART_WARNING} Opening ${appBundleId} again failed: ${outcome.reopenFailure}`, + ]; + } + return [SPRINGBOARD_RESTART_WARNING]; +} + +/** `launchctl list` inside the simulator: one `PID Status Label` row per job, `-` for no process. */ +async function listJobs({ runSimctl, udid }: NotificationPermissionRequest): Promise { + return (await runSimctl(['spawn', udid, 'launchctl', 'list'])).stdout; +} + +/** The labels of the jobs that have a process. */ +function runningJobs(list: string): string[] { + return list.split('\n').flatMap((line) => { + const [pid, , label] = line.trim().split(/\s+/); + return label && /^\d+$/.test(pid ?? '') && Number(pid) > 0 ? [label] : []; + }); +} + +/** Polls until every label is stopped or running, and fails with a typed reason past the bound. */ +async function waitForJobs( + request: NotificationPermissionRequest, + labels: readonly string[], + state: 'stopped' | 'running', +): Promise { + const deadline = Deadline.fromTimeoutMs(SERVICE_WAIT_MS); + for (;;) { + const running = runningJobs(await listJobs(request)); + if (labels.every((label) => running.includes(label) === (state === 'running'))) return; + if (deadline.isExpired()) { + throw new AppError( + 'COMMAND_FAILED', + `iOS simulator ${labels.join(' and ')} did not ${state === 'stopped' ? 'stop' : 'start'} within ${SERVICE_WAIT_MS / 1000} seconds.`, + { + reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason, + deviceId: request.deviceId, + appBundleId: request.appBundleId, + }, + ); + } + await sleep(SERVICE_POLL_MS); + } } /** The status the action leaves, with `null` for a reset's absent record. */ @@ -147,15 +246,15 @@ async function readSettingsFile( 'Boot the simulator to the Home Screen once so SpringBoard creates the file, then retry.', ); } - const { parse, parseBinary } = await import('plist'); - const format = new TextDecoder().decode(bytes.subarray(0, 8)) === 'bplist00' ? 'binary' : 'xml'; - let store: PlistValue; + let plist: Awaited> | undefined; try { - store = format === 'binary' ? parseBinary(bytes) : parse(new TextDecoder().decode(bytes)); + plist = await readApplePlist(bytes); } catch { - store = null; + plist = undefined; + } + if (plist && isRecognizedStore(plist.value)) { + return { format: plist.format, store: plist.value, sections: plist.value.sectionInfo }; } - if (isRecognizedStore(store)) return { format, store, sections: store.sectionInfo }; throw notificationSettingsError( request, 'unrecognized', @@ -192,13 +291,18 @@ function isDictionary(value: PlistValue | undefined): value is Record { const { build, buildBinary } = await import('plist'); const temporaryPath = `${settingsPath}.agent-device.tmp`; - await writeHostBinaryFile( - temporaryPath, - file.format === 'binary' - ? buildBinary(file.store) - : new TextEncoder().encode(build(file.store)), - ); - await renameHostPath(temporaryPath, settingsPath); + try { + await writeHostBinaryFile( + temporaryPath, + file.format === 'binary' + ? buildBinary(file.store) + : new TextEncoder().encode(build(file.store)), + ); + await renameHostPath(temporaryPath, settingsPath); + } catch (error) { + await removeHostPath(temporaryPath); + throw error; + } } /** A plist UID, the reference type of an NSKeyedArchiver object table. */ @@ -291,11 +395,16 @@ async function sectionInfoArchive(bundleId: string, status: 1 | 2): Promise row.reason === reason); + return error instanceof AppError && SETTINGS_REFUSALS.includes(String(error.details?.reason)); } function notificationSettingsError( diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index c0897dbab0..ef079d616c 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -361,6 +361,8 @@ Treat a reason that this page does not list as unknown, not as an error in the r | `ios-notification-settings-unreachable` | The simulator's files are not on this host, so its notification settings cannot be written. | | `ios-notification-settings-missing` | The simulator has no notification settings file yet; SpringBoard creates it on its first start. | | `ios-notification-settings-unrecognized` | The notification settings file is not in the layout this command writes, so it is left alone. | +| `ios-notification-restart-timeout` | SpringBoard or usernotificationsd did not stop, or SpringBoard did not start, within 10 seconds. | +| `ios-notification-settings-not-applied` | The file read back after the restart does not hold the written status. | ### `shake` From 165784f781540c403c44d22936fa1d496148b8c9 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:00:50 +0530 Subject: [PATCH 5/9] fix(ios): count SpringBoard as stopped once launchd replaces its process, and document the reopen --- packages/contracts/src/settings-catalog.ts | 2 +- .../maestro/src/internal/support-matrix.ts | 2 +- .../simctl-settings-notifications.test.ts | 36 +++++++++----- .../core/simulator-notification-permission.ts | 48 +++++++++++-------- website/docs/docs/commands.md | 2 +- website/docs/docs/run-maestro-flows.md | 2 +- 6 files changed, 58 insertions(+), 34 deletions(-) diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts index 70c0d2e8d8..dfa8a634c8 100644 --- a/packages/contracts/src/settings-catalog.ts +++ b/packages/contracts/src/settings-catalog.ts @@ -178,7 +178,7 @@ export const SETTINGS = { ], app: 'input', appScope: { apple: 'app-scoped', mobile: 'app-scoped', 'macos-host': 'device-level' }, - help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard, which returns to the Home Screen, so change it before open. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', + help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard and brings back the app if it was running; deny|reset end the app first, so it starts fresh. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', }, } as const satisfies Record; diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts index bce25852e8..2517cc9b20 100644 --- a/packages/maestro/src/internal/support-matrix.ts +++ b/packages/maestro/src/internal/support-matrix.ts @@ -7,7 +7,7 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ export const MAESTRO_COMPAT_LIMITATIONS = [ 'On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.', - 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and returns the simulator to the Home Screen, so set them in launchApp permissions rather than mid-flow.', + 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running; a deny or reset ends the app first, so it starts fresh.', 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts index ad66a0f588..ccf9e5d4b2 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts @@ -76,13 +76,15 @@ function recordOf(record: Uint8Array | undefined): { sectionID: PlistValue; stat } /** - * A simulator's `launchctl`: `stop` ends a job and `start` gives it a process, unless a test holds - * the job in its old state; a SpringBoard stop ends the app, and `simctl launch` brings it back. + * A simulator's `launchctl`: launchd starts SpringBoard again with a new pid the moment it stops + * (iOS 27.2), `usernotificationsd` stays down until its start, and a held job ignores both verbs. + * The app keeps running across the restart, and `simctl launch` brings it up if it is not. */ function recordingRunner( onRun: (args: string[]) => void = () => {}, - { appRunning = false, held = [] as string[] } = {}, + { appRunning = false, held = [] as string[], respawn = true } = {}, ) { + let nextPid = 500; const pids = new Map([ ['com.apple.SpringBoard', 100], ['com.apple.usernotificationsd', 101], @@ -92,11 +94,11 @@ function recordingRunner( onRun(args); const [, , tool, verb, label = ''] = args; if (tool === 'launchctl' && !held.includes(label)) { - if (verb === 'stop') pids.set(label, undefined); - if (verb === 'stop' && label === 'com.apple.SpringBoard') pids.set(APP_JOB, undefined); - if (verb === 'start') pids.set(label, 300); + const respawns = respawn && label === 'com.apple.SpringBoard'; + if (verb === 'stop') pids.set(label, respawns ? nextPid++ : undefined); + if (verb === 'start') pids.set(label, pids.get(label) ?? nextPid++); } - if (args[0] === 'launch') pids.set(APP_JOB, 400); + if (args[0] === 'launch') pids.set(APP_JOB, pids.get(APP_JOB) ?? nextPid++); const rows = [...pids].map(([job, pid]) => `${pid ?? '-'}\t0\t${job}`); return { stdout: verb === 'list' ? ['PID\tStatus\tLabel', ...rows].join('\n') : '', @@ -408,7 +410,7 @@ test('an app that was running is opened again once SpringBoard is back', async ( expect(result).toEqual({ permission: 'notifications', warnings: [ - 'Restarted SpringBoard to apply the notification permission, and opened com.example.app again because it was running.', + 'Restarted SpringBoard to apply the notification permission, and brought com.example.app back to the front because it was running.', ], }); }); @@ -445,13 +447,13 @@ test('the edit waits for SpringBoard to exit, so its last write cannot replace t if (args.join(' ') !== LIST.join(' ') || !stopped || started) return answer; exiting += 1; if (exiting < 3) return answer; - // SpringBoard writes its copy as it exits, then reports no process. + // SpringBoard writes its copy as it exits, and launchd starts a new one. const store = readSettings(file); (store.sectionInfo as Record)['com.apple.Maps'] = flushed; fs.writeFileSync(file, build(store)); return { ...answer, - stdout: answer.stdout.replace(/^\d+(\t0\tcom\.apple\.SpringBoard)$/m, '-$1'), + stdout: answer.stdout.replace(/^\d+(\t0\tcom\.apple\.SpringBoard)$/m, '900$1'), }; }); @@ -496,7 +498,8 @@ test.for([ try { const file = await settingsFile(); const before = fs.readFileSync(file); - const fake = recordingRunner(); + // Without a respawn, a SpringBoard that ignores its start stays down. + const fake = recordingRunner(() => {}, { respawn: verb !== 'start' }); // The held job keeps the state it had before the verb. const runSimctl = vi.fn(async (args: string[]) => { if (args[3] === verb && args[4] === held) return { stdout: '', stderr: '' }; @@ -594,3 +597,14 @@ test('another running app is not the one reopened', async () => { expect(runSimctl.mock.calls.map(([args]) => args)).toEqual(RESTART); }); + +test('a usernotificationsd that was not running does not hold up the restart', async () => { + const file = await settingsFile(); + const fake = recordingRunner(); + await fake(['spawn', 'SIM-1', 'launchctl', 'stop', 'com.apple.usernotificationsd']); + fake.mockClear(); + + await applySimctlSetting(permission(fake, 'grant', 'notifications', file)); + + expect(fake.mock.calls.map(([args]) => args)).toEqual(RESTART); +}); diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index c5bb309cee..f6d9edbcdf 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -57,8 +57,9 @@ type NotificationPermissionRequest = { }; /** - * What a change did: nothing when the file already held it, else a restart, which reopens the app - * when it was running so a test that changes notifications mid-flow keeps its app in front. + * What a change did: nothing when the file already held it, else a restart, which brings back the + * app when it was running so a test that changes notifications mid-flow keeps its app in front. The + * app outlives the restart, but iOS ends it on a deny or reset, so `simctl launch` starts it fresh. */ export type NotificationPermissionOutcome = | { restarted: false } @@ -95,15 +96,21 @@ export async function setSimulatorNotificationPermission( const wanted = wantedStatus(request.action); const current = await readSettingsFile(request, settingsPath); if ((await recordedStatus(current, appBundleId)) === wanted) return { restarted: false }; - const wasRunning = runningJobs(await listJobs(request)).some((label) => + const before = jobProcesses(await listJobs(request)); + const wasRunning = [...before.keys()].some((label) => label.startsWith(`UIKitApplication:${appBundleId}[`), ); try { for (const service of NOTIFICATION_SERVICES) { await runSimctl(['spawn', udid, 'launchctl', 'stop', service]); } - // `launchctl stop` only signals, and a service still exiting writes its copy over the edit. - await waitForJobs(request, NOTIFICATION_SERVICES, 'stopped'); + // `launchctl stop` only signals, and a process still exiting writes its copy over the edit. + // launchd starts SpringBoard again at once (iOS 27.2), so a process is gone once its pid is. + await waitForJobs(request, 'stop', (pids) => + NOTIFICATION_SERVICES.every( + (label) => !before.has(label) || pids.get(label) !== before.get(label), + ), + ); const file = await readSettingsFile(request, settingsPath); if (request.action === 'reset') { delete file.sections[request.appBundleId]; @@ -119,7 +126,7 @@ export async function setSimulatorNotificationPermission( await runSimctl(['spawn', udid, 'launchctl', 'start', service]); } } - await waitForJobs(request, [SPRINGBOARD], 'running'); + await waitForJobs(request, 'start', (pids) => pids.has(SPRINGBOARD)); const written = await readSettingsFile(request, settingsPath); if ((await recordedStatus(written, appBundleId)) !== wanted) { throw new AppError( @@ -149,7 +156,7 @@ export function notificationRestartWarnings( if (!outcome.restarted) return []; if (outcome.reopened) { return [ - `Restarted SpringBoard to apply the notification permission, and opened ${appBundleId} again because it was running.`, + `Restarted SpringBoard to apply the notification permission, and brought ${appBundleId} back to the front because it was running.`, ]; } if (outcome.reopenFailure !== undefined) { @@ -165,28 +172,31 @@ async function listJobs({ runSimctl, udid }: NotificationPermissionRequest): Pro return (await runSimctl(['spawn', udid, 'launchctl', 'list'])).stdout; } -/** The labels of the jobs that have a process. */ -function runningJobs(list: string): string[] { - return list.split('\n').flatMap((line) => { - const [pid, , label] = line.trim().split(/\s+/); - return label && /^\d+$/.test(pid ?? '') && Number(pid) > 0 ? [label] : []; - }); +/** The pid of each job that has a process. */ +function jobProcesses(list: string): Map { + return new Map( + list.split('\n').flatMap((line) => { + const [pid, , label] = line.trim().split(/\s+/); + return label && /^\d+$/.test(pid ?? '') && Number(pid) > 0 ? [[label, Number(pid)]] : []; + }), + ); } -/** Polls until every label is stopped or running, and fails with a typed reason past the bound. */ +/** Polls `launchctl list` until `done` holds, and fails with a typed reason past the bound. */ async function waitForJobs( request: NotificationPermissionRequest, - labels: readonly string[], - state: 'stopped' | 'running', + step: 'stop' | 'start', + done: (pids: ReadonlyMap) => boolean, ): Promise { const deadline = Deadline.fromTimeoutMs(SERVICE_WAIT_MS); for (;;) { - const running = runningJobs(await listJobs(request)); - if (labels.every((label) => running.includes(label) === (state === 'running'))) return; + if (done(jobProcesses(await listJobs(request)))) return; if (deadline.isExpired()) { throw new AppError( 'COMMAND_FAILED', - `iOS simulator ${labels.join(' and ')} did not ${state === 'stopped' ? 'stop' : 'start'} within ${SERVICE_WAIT_MS / 1000} seconds.`, + step === 'stop' + ? `iOS simulator SpringBoard or usernotificationsd kept running within ${SERVICE_WAIT_MS / 1000} seconds of launchctl stop.` + : `iOS simulator SpringBoard did not start within ${SERVICE_WAIT_MS / 1000} seconds.`, { reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason, deviceId: request.deviceId, diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 54798e56c3..6b66310ce1 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1791,7 +1791,7 @@ 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`, or `bluetooth` takes no app). - On iOS simulators, the simulator decides which permissions it can change and refuses the rest. `grant all` skips a refused service with a warning. -- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, unless the app already holds that state. The simulator returns to the Home Screen after about 10 seconds, so change notifications before `open`. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. +- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, which takes about 10 seconds, unless the app already holds that state. An app that was running comes back to the front: a `grant` keeps its process, while a `deny` or `reset` ends it, as iOS does when a permission is taken back, so it starts fresh. Otherwise the simulator is left on the Home Screen. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once; their `simctl privacy` changes already end a running app, as before. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. - On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`. - Android kills a running app when you revoke one of its granted permissions. After `deny` or `reset`, run `open --relaunch` when the warning says so. - On macOS, `grant` opens System Settings when access needs your approval; it never grants silently. `deny` is unsupported. diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 722e0c6dd1..eea2b0ea4f 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and returns the simulator to the Home Screen, so set them in `launchApp` `permissions` rather than mid-flow. +- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running; a deny or reset ends the app first, so it starts fresh. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. - Environment: flow `env` is the default, `AD_VAR_*` overrides it, and CLI `-e KEY=VALUE` wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and `AD_*` stays reserved. From eec04ce2044780c216c072cf764dbbcd28c7c4d1 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:12:11 +0530 Subject: [PATCH 6/9] docs(ios): say a grant can also restart the app the notification change brings back --- packages/contracts/src/settings-catalog.ts | 2 +- packages/maestro/src/internal/support-matrix.ts | 2 +- .../src/core/simulator-notification-permission.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/run-maestro-flows.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts index dfa8a634c8..f6e9bb845a 100644 --- a/packages/contracts/src/settings-catalog.ts +++ b/packages/contracts/src/settings-catalog.ts @@ -178,7 +178,7 @@ export const SETTINGS = { ], app: 'input', appScope: { apple: 'app-scoped', mobile: 'app-scoped', 'macos-host': 'device-level' }, - help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard and brings back the app if it was running; deny|reset end the app first, so it starts fresh. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', + help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard and brings back the app if it was running, fresh when iOS ended it, as it does on deny|reset. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', }, } as const satisfies Record; diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts index 2517cc9b20..76ac42508a 100644 --- a/packages/maestro/src/internal/support-matrix.ts +++ b/packages/maestro/src/internal/support-matrix.ts @@ -7,7 +7,7 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ export const MAESTRO_COMPAT_LIMITATIONS = [ 'On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.', - 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running; a deny or reset ends the app first, so it starts fresh.', + 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh when iOS ended it, as it does on a deny or reset.', 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index f6d9edbcdf..cd10bf3752 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -59,7 +59,7 @@ type NotificationPermissionRequest = { /** * What a change did: nothing when the file already held it, else a restart, which brings back the * app when it was running so a test that changes notifications mid-flow keeps its app in front. The - * app outlives the restart, but iOS ends it on a deny or reset, so `simctl launch` starts it fresh. + * app can outlive the restart, but iOS ends it on a deny or reset, and then `simctl launch` starts it fresh. */ export type NotificationPermissionOutcome = | { restarted: false } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 6b66310ce1..703fe52714 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1791,7 +1791,7 @@ 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`, or `bluetooth` takes no app). - On iOS simulators, the simulator decides which permissions it can change and refuses the rest. `grant all` skips a refused service with a warning. -- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, which takes about 10 seconds, unless the app already holds that state. An app that was running comes back to the front: a `grant` keeps its process, while a `deny` or `reset` ends it, as iOS does when a permission is taken back, so it starts fresh. Otherwise the simulator is left on the Home Screen. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once; their `simctl privacy` changes already end a running app, as before. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. +- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, which takes about 10 seconds, unless the app already holds that state. An app that was running comes back to the front. iOS can end it during the change, always on a `deny` or `reset`, and then it starts fresh. Otherwise the simulator is left on the Home Screen. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once; their `simctl privacy` changes already end a running app, as before. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. - On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`. - Android kills a running app when you revoke one of its granted permissions. After `deny` or `reset`, run `open --relaunch` when the warning says so. - On macOS, `grant` opens System Settings when access needs your approval; it never grants silently. `deny` is unsupported. diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index eea2b0ea4f..0287b253fc 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running; a deny or reset ends the app first, so it starts fresh. +- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh when iOS ended it, as it does on a deny or reset. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. - Environment: flow `env` is the default, `AD_VAR_*` overrides it, and CLI `-e KEY=VALUE` wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and `AD_*` stays reserved. From a1c6017b2aee22e9a60b6404da9e5c5ab350d309 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:51:04 +0530 Subject: [PATCH 7/9] refactor(apple): read simulator launchctl rows through one parser --- .../src/core/__tests__/app-resolution.test.ts | 17 +++++++++ .../src/core/__tests__/launchctl-jobs.test.ts | 37 +++++++++++++++++++ .../platform-apple/src/core/app-resolution.ts | 12 +++--- .../platform-apple/src/core/launchctl-jobs.ts | 21 +++++++++++ .../core/simulator-notification-permission.ts | 10 ++--- .../src/snapshot-target.test.ts | 10 +++++ .../platform-apple/src/snapshot-target.ts | 8 ++-- 7 files changed, 97 insertions(+), 18 deletions(-) create mode 100644 packages/platform-apple/src/core/__tests__/launchctl-jobs.test.ts create mode 100644 packages/platform-apple/src/core/launchctl-jobs.ts diff --git a/packages/platform-apple/src/core/__tests__/app-resolution.test.ts b/packages/platform-apple/src/core/__tests__/app-resolution.test.ts index c3ba95b894..7f922f80f7 100644 --- a/packages/platform-apple/src/core/__tests__/app-resolution.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-resolution.test.ts @@ -174,6 +174,23 @@ test('detectSoleRunningIosSimulatorApp cross-references launchctl against instal }); }); +test('detectSoleRunningIosSimulatorApp counts an app job that launchctl lists without a process', async () => { + mockRunSimctl.mockImplementation(async (args: string[]) => { + if (args[0] === 'spawn') { + return { + exitCode: 0, + stdout: 'PID\tStatus\tLabel\n-\t0\tUIKitApplication:com.example.demo[abcd][rb-legacy]', + }; + } + return { stdout: JSON.stringify({ 'com.example.demo': { CFBundleDisplayName: 'Demo' } }) }; + }); + + assert.deepEqual(await detectSoleRunningIosSimulatorApp(bootedSimulator), { + bundleId: 'com.example.demo', + name: 'Demo', + }); +}); + test('detectSoleRunningIosSimulatorApp refuses to guess between two running apps', async () => { mockLaunchctlAndListapps(['com.apple.Preferences', 'com.example.demo']); diff --git a/packages/platform-apple/src/core/__tests__/launchctl-jobs.test.ts b/packages/platform-apple/src/core/__tests__/launchctl-jobs.test.ts new file mode 100644 index 0000000000..ad048a7185 --- /dev/null +++ b/packages/platform-apple/src/core/__tests__/launchctl-jobs.test.ts @@ -0,0 +1,37 @@ +import { expect, test } from 'vitest'; +import { readLaunchctlJobs, uiKitApplicationBundleId } from '../launchctl-jobs.ts'; + +test('a launchctl list row reads as its label and pid, with no pid for a job without a process', () => { + const output = [ + 'PID\tStatus\tLabel', + '-\t0\tcom.apple.cfprefsd', + '412\t0\tcom.apple.SpringBoard', + '0\t0\tcom.apple.zero', + '1.5\t0\tcom.apple.fraction', + '', + ' 98 -9 UIKitApplication:com.example.app[1a2b][rb-legacy] ', + 'truncated', + ].join('\n'); + + expect(readLaunchctlJobs(output)).toEqual([ + { label: 'Label', pid: undefined }, + { label: 'com.apple.cfprefsd', pid: undefined }, + { label: 'com.apple.SpringBoard', pid: 412 }, + { label: 'com.apple.zero', pid: undefined }, + { label: 'com.apple.fraction', pid: undefined }, + { label: 'UIKitApplication:com.example.app[1a2b][rb-legacy]', pid: 98 }, + ]); +}); + +test.for([ + { label: 'UIKitApplication:com.example.app[1a2b][rb-legacy]', bundleId: 'com.example.app' }, + { + label: 'UIKitApplication:com.example.app.beta[ff][rb-legacy]', + bundleId: 'com.example.app.beta', + }, + { label: 'UIKitApplication:com.example.app', bundleId: undefined }, + { label: 'com.apple.SpringBoard', bundleId: undefined }, + { label: 'x.UIKitApplication:com.example.app[1a2b]', bundleId: undefined }, +])('$label names the app $bundleId', ({ label, bundleId }) => { + expect(uiKitApplicationBundleId(label)).toBe(bundleId); +}); diff --git a/packages/platform-apple/src/core/app-resolution.ts b/packages/platform-apple/src/core/app-resolution.ts index d927a6f12c..df5638d320 100644 --- a/packages/platform-apple/src/core/app-resolution.ts +++ b/packages/platform-apple/src/core/app-resolution.ts @@ -134,7 +134,6 @@ function resolveIosAppAlias(app: string): string { // Bounded so an error-path probe never turns into a long wait. const IOS_FOREGROUND_APP_PROBE_TIMEOUT_MS = 3_000; -const UIKIT_APPLICATION_JOB_PATTERN = /UIKitApplication:([^[\s]+)\[/; /** * Identifies the sole installed app currently running on a booted simulator, @@ -188,12 +187,11 @@ async function listRunningIosSimulatorBundleIds(device: DeviceInfo): Promise { + const bundleId = uiKitApplicationBundleId(label); + return bundleId ? [bundleId] : []; + }); } /** diff --git a/packages/platform-apple/src/core/launchctl-jobs.ts b/packages/platform-apple/src/core/launchctl-jobs.ts new file mode 100644 index 0000000000..f7a6be27bf --- /dev/null +++ b/packages/platform-apple/src/core/launchctl-jobs.ts @@ -0,0 +1,21 @@ +/** + * One row of `launchctl list` inside a simulator (`PID Status Label`), with `pid` undefined for a + * job that has no process, which launchctl prints as `-`. + */ +export type LaunchctlJob = { label: string; pid: number | undefined }; + +export function readLaunchctlJobs(output: string): LaunchctlJob[] { + return output.split('\n').flatMap((line) => { + const [pidText, , label] = line.trim().split(/\s+/); + if (!pidText || !label) return []; + const pid = Number(pidText); + return [{ label, pid: Number.isSafeInteger(pid) && pid > 0 ? pid : undefined }]; + }); +} + +const UIKIT_APPLICATION_LABEL = /^UIKitApplication:([^[\s]+)\[/; + +/** The bundle id a `UIKitApplication:[…]` job label names. */ +export function uiKitApplicationBundleId(label: string): string | undefined { + return UIKIT_APPLICATION_LABEL.exec(label)?.[1]; +} diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index cd10bf3752..a33b72a11c 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -7,6 +7,7 @@ import { import { Deadline, sleep } from '@agent-device/host-kit/retry'; import { AppError, type ReasonTable } from '@agent-device/kernel/errors'; import type { PlistValue } from 'plist'; +import { readLaunchctlJobs, uiKitApplicationBundleId } from './launchctl-jobs.ts'; import { readApplePlist } from './plist.ts'; /** The file under a simulator's data directory where SpringBoard keeps each app's notification settings. */ @@ -97,8 +98,8 @@ export async function setSimulatorNotificationPermission( const current = await readSettingsFile(request, settingsPath); if ((await recordedStatus(current, appBundleId)) === wanted) return { restarted: false }; const before = jobProcesses(await listJobs(request)); - const wasRunning = [...before.keys()].some((label) => - label.startsWith(`UIKitApplication:${appBundleId}[`), + const wasRunning = [...before.keys()].some( + (label) => uiKitApplicationBundleId(label) === appBundleId, ); try { for (const service of NOTIFICATION_SERVICES) { @@ -175,10 +176,7 @@ async function listJobs({ runSimctl, udid }: NotificationPermissionRequest): Pro /** The pid of each job that has a process. */ function jobProcesses(list: string): Map { return new Map( - list.split('\n').flatMap((line) => { - const [pid, , label] = line.trim().split(/\s+/); - return label && /^\d+$/.test(pid ?? '') && Number(pid) > 0 ? [[label, Number(pid)]] : []; - }), + readLaunchctlJobs(list).flatMap(({ label, pid }) => (pid === undefined ? [] : [[label, pid]])), ); } diff --git a/packages/platform-apple/src/snapshot-target.test.ts b/packages/platform-apple/src/snapshot-target.test.ts index ebc5805b8a..849e93c315 100644 --- a/packages/platform-apple/src/snapshot-target.test.ts +++ b/packages/platform-apple/src/snapshot-target.test.ts @@ -335,3 +335,13 @@ test('a discovery that settles leaves no timer or abort listener behind for its vi.useRealTimers(); } }); + +test('an app job that launchctl lists without a process is not a target', async () => { + const fixture = targetFixture(); + (fixture.state as { pid: number | string }).pid = '-'; + await withAppleToolProvider(fixture.provider, async () => { + await expect(fixture.resolve(ios, app, signal())).rejects.toMatchObject({ + details: { reason: 'simulator-target-unavailable' }, + }); + }); +}); diff --git a/packages/platform-apple/src/snapshot-target.ts b/packages/platform-apple/src/snapshot-target.ts index b85dff527e..f1b85fd833 100644 --- a/packages/platform-apple/src/snapshot-target.ts +++ b/packages/platform-apple/src/snapshot-target.ts @@ -11,6 +11,7 @@ import { simulatorAddressFor, type SimulatorAddress, } from './core/simctl.ts'; +import { readLaunchctlJobs, uiKitApplicationBundleId } from './core/launchctl-jobs.ts'; import { runSimctlForDevice } from './core/simctl-execution.ts'; import { readSnapshotTargetProcessStartTime } from './snapshot-process.ts'; @@ -213,11 +214,8 @@ function readApplicationJob( output: string, appBundleId: string, ): { pid: number; label: string } | undefined { - for (const line of output.split('\n')) { - const [pidText, , label] = line.trim().split(/\s+/); - if (!pidText || !label || !label.startsWith(`UIKitApplication:${appBundleId}[`)) continue; - const pid = Number(pidText); - if (Number.isSafeInteger(pid) && pid > 0) return { pid, label }; + for (const { label, pid } of readLaunchctlJobs(output)) { + if (pid !== undefined && uiKitApplicationBundleId(label) === appBundleId) return { pid, label }; } return undefined; } From e1abaa087b7df650be63e5ab009bf7a397e06042 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:51:04 +0530 Subject: [PATCH 8/9] test(ios): move a faked clock in the notification restart waits instead of real timers --- .../simctl-settings-notifications.test.ts | 40 ++++++++----------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts index ccf9e5d4b2..1ceae60818 100644 --- a/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts +++ b/packages/platform-apple/src/core/__tests__/simctl-settings-notifications.test.ts @@ -19,6 +19,15 @@ const SETTINGS: Record = { sectionInfoVersionNumber: 3, }; +// A poll's pause moves a faked clock on instead of waiting, so the 10-second bounds are reached in +// no real time, whatever the host load. +vi.mock('@agent-device/host-kit/retry', async (importOriginal) => ({ + ...(await importOriginal()), + sleep: vi.fn(async (ms: number) => { + if (vi.isFakeTimers()) vi.setSystemTime(Date.now() + ms); + }), +})); + vi.mock('@agent-device/host-kit/host-file', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, renameHostPath: vi.fn(actual.renameHostPath) }; @@ -464,19 +473,6 @@ test('the edit waits for SpringBoard to exit, so its last write cannot replace t expect(recordOf(sections(file)['com.example.app']).status).toBe(2); }); -/** Moves fake time on between the real file reads until the change settles. */ -async function advanceUntilSettled(pending: Promise): Promise { - let settled = false; - pending.then( - () => (settled = true), - () => (settled = true), - ); - for (let step = 0; step < 200 && !settled; step += 1) { - await new Promise((resolve) => setImmediate(resolve)); - await vi.advanceTimersByTimeAsync(200); - } -} - test.for([ { label: 'SpringBoard never exits', held: 'com.apple.SpringBoard', verb: 'stop', written: false }, { @@ -494,7 +490,7 @@ test.for([ ])( 'a restart where $label fails after 10 seconds and still starts both', async ({ held, verb, written }) => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + vi.useFakeTimers({ toFake: ['Date'] }); try { const file = await settingsFile(); const before = fs.readFileSync(file); @@ -506,13 +502,12 @@ test.for([ return await fake(args); }); - const pending = applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)); - const settled = expect(pending).rejects.toMatchObject({ + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'notifications', file)), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason }, }); - await advanceUntilSettled(pending); - await settled; const argvs = runSimctl.mock.calls.map(([args]) => args.join(' ')); expect(argvs).toContain('spawn SIM-1 launchctl start com.apple.SpringBoard'); @@ -560,7 +555,7 @@ test('a failed rename removes its temporary file and leaves the settings whole', }); test('grant all fails on a restart that times out instead of skipping notifications', async () => { - vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] }); + vi.useFakeTimers({ toFake: ['Date'] }); try { const file = await settingsFile(); const fake = recordingRunner(); @@ -570,15 +565,14 @@ test('grant all fails on a restart that times out instead of skipping notificati : await fake(args), ); - const pending = applySimctlSetting(permission(runSimctl, 'grant', 'all', file)); - const settled = expect(pending).rejects.toMatchObject({ + await expect( + applySimctlSetting(permission(runSimctl, 'grant', 'all', file)), + ).rejects.toMatchObject({ details: { reason: SIMULATOR_NOTIFICATION_REASONS.restartTimeout.reason, permissions: expect.arrayContaining(['camera']), }, }); - await advanceUntilSettled(pending); - await settled; } finally { vi.useRealTimers(); } From 2cae4b38c6f19ad9e6ac30b123eb40b5b7c9f2bb Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 09:56:13 +0530 Subject: [PATCH 9/9] docs(ios): stop saying iOS always ends the app on a notification deny or reset --- packages/contracts/src/settings-catalog.ts | 2 +- packages/maestro/src/internal/support-matrix.ts | 2 +- .../src/core/simulator-notification-permission.ts | 2 +- website/docs/docs/commands.md | 2 +- website/docs/docs/run-maestro-flows.md | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/packages/contracts/src/settings-catalog.ts b/packages/contracts/src/settings-catalog.ts index f6e9bb845a..32b6e9592a 100644 --- a/packages/contracts/src/settings-catalog.ts +++ b/packages/contracts/src/settings-catalog.ts @@ -178,7 +178,7 @@ export const SETTINGS = { ], app: 'input', appScope: { apple: 'app-scoped', mobile: 'app-scoped', 'macos-host': 'device-level' }, - help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard and brings back the app if it was running, fresh when iOS ended it, as it does on deny|reset. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', + help: 'Changes a permission of the --app app or the session app. An iOS simulator, local or Limrun, resolves --app to an installed bundle id or display name, and Android to an installed package. On an iOS simulator, a notifications change restarts SpringBoard and brings back the app if it was running, fresh if iOS ended it. On Android, deny|reset of a held permission kills a running app; the response reports priorGrantState and warns, and open --relaunch restores it. Android needs a resolvable foreground user and changes nothing without one. On the macOS host, grant|reset change the host TCC grants for the three desktop targets and take no --app.', }, } as const satisfies Record; diff --git a/packages/maestro/src/internal/support-matrix.ts b/packages/maestro/src/internal/support-matrix.ts index 76ac42508a..a27fe0fec9 100644 --- a/packages/maestro/src/internal/support-matrix.ts +++ b/packages/maestro/src/internal/support-matrix.ts @@ -7,7 +7,7 @@ export const MAESTRO_COMPAT_SUPPORTED_CAPABILITIES = [ export const MAESTRO_COMPAT_LIMITATIONS = [ 'On the native iOS runner, use tapOn on a visible dismissal control. If the app supports drag dismissal, use a swipe that stays above the keyboard.', - 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh when iOS ended it, as it does on a deny or reset.', + 'Permissions: every entry is one settings permission call, applied in order with all first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so location: inuse and location: never mean allow and deny there, while location: always and photos: limited are Apple-only and fail. On iOS, which service a runtime changes is simctl privacy’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh if iOS ended it.', 'Runtime: iOS and Android only; launchApp.clearState and standalone clearState support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading - unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported.', 'Expressions: evalScript and condition true: fields (runFlow.when and repeat.while share one evaluator) are evaluated as JavaScript (flow env and prior output leaves are string-typed); a true: field that is a boolean, a maestro.platform comparison, or plain literal text after ${VAR} lookups is decided without JavaScript, with the assertTrue falsy table for literal text. Other fields stay literal or ${VAR} lookup-only — assertTrue supports literals and bare lookups, and other expression-shaped payloads fail loud.', 'Environment: flow env is the default, AD_VAR_* overrides it, and CLI -e KEY=VALUE wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and AD_* stays reserved.', diff --git a/packages/platform-apple/src/core/simulator-notification-permission.ts b/packages/platform-apple/src/core/simulator-notification-permission.ts index a33b72a11c..49938741a3 100644 --- a/packages/platform-apple/src/core/simulator-notification-permission.ts +++ b/packages/platform-apple/src/core/simulator-notification-permission.ts @@ -60,7 +60,7 @@ type NotificationPermissionRequest = { /** * What a change did: nothing when the file already held it, else a restart, which brings back the * app when it was running so a test that changes notifications mid-flow keeps its app in front. The - * app can outlive the restart, but iOS ends it on a deny or reset, and then `simctl launch` starts it fresh. + * app can outlive the restart, but iOS sometimes ends it, and then `simctl launch` starts it fresh. */ export type NotificationPermissionOutcome = | { restarted: false } diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 703fe52714..98fec27a73 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -1791,7 +1791,7 @@ 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`, or `bluetooth` takes no app). - On iOS simulators, the simulator decides which permissions it can change and refuses the rest. `grant all` skips a refused service with a warning. -- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, which takes about 10 seconds, unless the app already holds that state. An app that was running comes back to the front. iOS can end it during the change, always on a `deny` or `reset`, and then it starts fresh. Otherwise the simulator is left on the Home Screen. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once; their `simctl privacy` changes already end a running app, as before. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. +- On iOS simulators, `notifications` writes the app's record in SpringBoard's notification settings, because `simctl privacy` refuses it, and restarts SpringBoard, which takes about 10 seconds, unless the app already holds that state. An app that was running comes back to the front, and starts fresh if iOS ended it during the change. Otherwise the simulator is left on the Home Screen. `grant all`, `deny all`, and `reset all` include notifications and restart SpringBoard at most once; their `simctl privacy` changes already end a running app, as before. A settings file in another layout refuses with `ios-notification-settings-unrecognized`, and a simulator on another host with `ios-notification-settings-unreachable`. - On Android, a permission group applies only the permissions the app declares. `full|limited` applies only to iOS `photos`. - Android kills a running app when you revoke one of its granted permissions. After `deny` or `reset`, run `open --relaunch` when the warning says so. - On macOS, `grant` opens System Settings when access needs your approval; it never grants silently. `deny` is unsupported. diff --git a/website/docs/docs/run-maestro-flows.md b/website/docs/docs/run-maestro-flows.md index 0287b253fc..5d11ae3866 100644 --- a/website/docs/docs/run-maestro-flows.md +++ b/website/docs/docs/run-maestro-flows.md @@ -30,7 +30,7 @@ Keep the target binding, such as `--platform ios`, on the `replay` or `test` com ## Boundaries -- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh when iOS ended it, as it does on a deny or reset. +- Permissions: every entry is one `settings permission` call, applied in order with `all` first; the step stops at the first entry the selected platform refuses, earlier entries stay applied, and the error names what landed. Android’s only allow level is while-in-use, so `location: inuse` and `location: never` mean `allow` and `deny` there, while `location: always` and `photos: limited` are Apple-only and fail. On iOS, which service a runtime changes is `simctl privacy`’s own verdict. Notifications are written to SpringBoard’s notification settings instead, which restarts SpringBoard and brings back an app that was running, fresh if iOS ended it. - Runtime: iOS and Android only; `launchApp.clearState` and standalone `clearState` support Android and iOS simulators, launch arguments are Apple-only (a map-form argument key gains a leading `-` unless its value is a boolean, as in Maestro), and other standalone device utility/state commands are unsupported. - Expressions: `evalScript` and condition `true:` fields (`runFlow.when` and `repeat.while` share one evaluator) are evaluated as JavaScript (flow `env` and prior `output` leaves are string-typed); a `true:` field that is a boolean, a `maestro.platform` comparison, or plain literal text after `${VAR}` lookups is decided without JavaScript, with the `assertTrue` falsy table for literal text. Other fields stay literal or `${VAR}` lookup-only — `assertTrue` supports literals and bare lookups, and other expression-shaped payloads fail loud. - Environment: flow `env` is the default, `AD_VAR_*` overrides it, and CLI `-e KEY=VALUE` wins over both; override keys follow the flow variable grammar (mixed case and dots allowed), and `AD_*` stays reserved.