diff --git a/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts b/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts index f6bee85501..470945eda6 100644 --- a/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-launch-accessibility.test.ts @@ -13,6 +13,8 @@ vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({ ...(await importOriginal()), emitDiagnostic: vi.fn(), })); +// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts. +vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() })); vi.mock('../simulator.ts', () => ({ ensureBootedSimulator: vi.fn() })); import { ensureBootedSimulator } from '../simulator.ts'; diff --git a/packages/platform-apple/src/core/__tests__/app-launch-open.test.ts b/packages/platform-apple/src/core/__tests__/app-launch-open.test.ts index 6c4d604584..91a1c96d5d 100644 --- a/packages/platform-apple/src/core/__tests__/app-launch-open.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-launch-open.test.ts @@ -8,6 +8,8 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, runCmd: vi.fn(actual.runCmd) }; }); +// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts. +vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() })); vi.mock('../simulator.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, ensureBootedSimulator: vi.fn(actual.ensureBootedSimulator) }; diff --git a/packages/platform-apple/src/core/__tests__/app-launch-url.test.ts b/packages/platform-apple/src/core/__tests__/app-launch-url.test.ts index 91ea9cc409..3e0e133fb8 100644 --- a/packages/platform-apple/src/core/__tests__/app-launch-url.test.ts +++ b/packages/platform-apple/src/core/__tests__/app-launch-url.test.ts @@ -7,6 +7,8 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, runCmd: vi.fn(actual.runCmd) }; }); +// Keyboard intro preparation has its own coverage in ios-simulator-keyboard.test.ts. +vi.mock('../ios-simulator-keyboard.ts', () => ({ prepareIosSimulatorKeyboardIntros: vi.fn() })); vi.mock('../simulator.ts', async (importOriginal) => { const actual = await importOriginal(); return { ...actual, ensureBootedSimulator: vi.fn(actual.ensureBootedSimulator) }; diff --git a/packages/platform-apple/src/core/__tests__/fixtures/keyboard-intros-shown.plist b/packages/platform-apple/src/core/__tests__/fixtures/keyboard-intros-shown.plist new file mode 100644 index 0000000000..df86b562ad Binary files /dev/null and b/packages/platform-apple/src/core/__tests__/fixtures/keyboard-intros-shown.plist differ diff --git a/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts b/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts new file mode 100644 index 0000000000..f2ed2b4df7 --- /dev/null +++ b/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts @@ -0,0 +1,230 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { beforeEach, test, vi } from 'vitest'; +import { build, type PlistValue } from 'plist'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { mkdtempForTest } from '../../__tests__/tmp-dir.ts'; +import { withFakeAppleTool } from '../../__tests__/fake-apple-tool.ts'; +import { + IOS_TEST_DEVICE, + IOS_TEST_SIMULATOR, + MACOS_TEST_DEVICE, +} from './apple-core-stub-helpers.ts'; + +vi.mock('@agent-device/host-kit/diagnostics', async (importOriginal) => ({ + ...(await importOriginal()), + emitDiagnostic: vi.fn(), +})); +vi.mock('../simulator.ts', () => ({ ensureBootedSimulator: vi.fn() })); +// withFakeAppleTool installs a scoped provider, which never reads this host's preferences, so the +// host-read tests below call the prepare step outside it with runXcrun answered here. +vi.mock('../tool-provider.ts', async (importOriginal) => { + const actual = await importOriginal(); + return { ...actual, runXcrun: vi.fn(actual.runXcrun) }; +}); +vi.mock('../ios-simulator-accessibility.ts', () => ({ + prepareIosSimulatorAccessibility: vi.fn(), +})); +const { emitDiagnostic } = await import('@agent-device/host-kit/diagnostics'); +const { ensureBootedSimulator } = await import('../simulator.ts'); +const { runXcrun, withAppleToolProvider } = await import('../tool-provider.ts'); +const actualRunXcrun = ( + await vi.importActual('../tool-provider.ts') +).runXcrun; +const { openIosApp } = await import('../app-launch.ts'); +const { prepareIosSimulatorKeyboardIntros } = await import('../ios-simulator-keyboard.ts'); + +let setPath: string; +let device: DeviceInfo; + +beforeEach(async () => { + vi.clearAllMocks(); + vi.mocked(runXcrun).mockImplementation(actualRunXcrun); + setPath = await mkdtempForTest('agent-device-keyboard-set-'); + device = { ...IOS_TEST_SIMULATOR, simulatorSetPath: setPath }; +}); + +function preferencesDir(): string { + const dir = path.join(setPath, device.id, 'data/Library/Preferences'); + fs.mkdirSync(dir, { recursive: true }); + return dir; +} + +function writePreferences(contents: Record): void { + fs.writeFileSync( + path.join(preferencesDir(), 'com.apple.keyboard.preferences.plist'), + build(contents), + ); +} + +const keyWrite = (key: string) => [ + 'simctl', + '--set', + setPath, + 'spawn', + device.id, + 'defaults', + 'write', + 'com.apple.keyboard.preferences', + key, + '-bool', + 'YES', +]; + +const writtenKeys = (calls: string[][]) => + calls.filter((args) => args.includes('defaults')).map((args) => args.at(-3)); + +async function prepare(failKey?: string): Promise { + vi.mocked(runXcrun).mockImplementation(async (args) => { + if (failKey && args.includes(failKey)) throw new Error('denied'); + return { exitCode: 0, stdout: '', stderr: '' }; + }); + await prepareIosSimulatorKeyboardIntros(device); + return vi.mocked(runXcrun).mock.calls.map(([args]) => [...args]); +} + +test('marks both intros as shown on a simulator whose preferences file is missing', async () => { + assert.deepEqual(await prepare(), [ + keyWrite('DidShowContinuousPathIntroduction'), + keyWrite('MultilingualKeyboardTip'), + ]); +}); + +for (const [label, preferences, expected] of [ + [ + 'both keys are on', + { DidShowContinuousPathIntroduction: true, MultilingualKeyboardTip: true }, + [], + ], + ['one key is on', { DidShowContinuousPathIntroduction: true }, ['MultilingualKeyboardTip']], + ['a key is 1', { DidShowContinuousPathIntroduction: 1, MultilingualKeyboardTip: true }, []], + [ + 'a key is off', + { DidShowContinuousPathIntroduction: false, MultilingualKeyboardTip: true }, + ['DidShowContinuousPathIntroduction'], + ], +] as const) { + test(`writes only the missing keys when ${label} on this host`, async () => { + writePreferences(preferences); + assert.deepEqual(writtenKeys(await prepare()), expected); + }); +} + +test('reads a binary preferences file', async () => { + fs.copyFileSync( + new URL('./fixtures/keyboard-intros-shown.plist', import.meta.url), + path.join(preferencesDir(), 'com.apple.keyboard.preferences.plist'), + ); + assert.deepEqual(await prepare(), []); +}); + +test('each write is bounded by the keyboard timeout, not the accessibility one', async () => { + await prepare(); + assert.deepEqual( + vi.mocked(runXcrun).mock.calls.map(([, options]) => options), + [{ timeoutMs: 15_000 }, { timeoutMs: 15_000 }], + ); +}); + +const scoped = (task: () => Promise) => + withAppleToolProvider({} as Parameters[0], task); + +test('a scoped (remote) tool provider writes even when this host has both keys', async () => { + writePreferences({ DidShowContinuousPathIntroduction: true, MultilingualKeyboardTip: true }); + assert.deepEqual(writtenKeys(await scoped(() => prepare())), [ + 'DidShowContinuousPathIntroduction', + 'MultilingualKeyboardTip', + ]); +}); + +test('a failed write warns with its key and still writes the other key', async () => { + const calls = await prepare('DidShowContinuousPathIntroduction'); + assert.deepEqual(writtenKeys(calls), [ + 'DidShowContinuousPathIntroduction', + 'MultilingualKeyboardTip', + ]); + assert.deepEqual( + vi + .mocked(emitDiagnostic) + .mock.calls.map(([event]) => [ + event.level, + event.phase, + (event.data as { key?: string }).key, + ]), + [['warn', 'ios_simulator_keyboard_intro_prepare_failed', 'DidShowContinuousPathIntroduction']], + ); +}); + +for (const other of [ + IOS_TEST_DEVICE, + MACOS_TEST_DEVICE, + { ...IOS_TEST_SIMULATOR, appleOs: 'tvos' }, + { ...IOS_TEST_SIMULATOR, appleOs: 'visionos' }, +] as DeviceInfo[]) { + test(`does not write keyboard preferences for ${other.kind}/${other.appleOs}`, async () => { + device = other; + assert.deepEqual(await prepare(), []); + }); +} + +for (const app of ['com.example.app', 'myapp://home']) { + test(`open marks the intros after boot and before launching ${app}`, async () => { + let booted = false; + vi.mocked(ensureBootedSimulator).mockImplementation(async () => { + booted = true; + }); + const writeBootStates: boolean[] = []; + await withFakeAppleTool( + (args) => { + if (args.includes('defaults')) writeBootStates.push(booted); + return ''; + }, + async ({ calls }) => { + await openIosApp(device, app, { appBundleId: 'com.example.app' }); + assert.deepEqual(writeBootStates, [true, true]); + const launch = calls.findIndex((args) => args[3] === 'launch' || args[3] === 'openurl'); + assert.deepEqual(writtenKeys(calls.slice(0, launch)), [ + 'DidShowContinuousPathIntroduction', + 'MultilingualKeyboardTip', + ]); + }, + ); + }); +} + +test('a guest write that exits non-zero warns with its key', async () => { + await withFakeAppleTool( + (args) => (args.includes('MultilingualKeyboardTip') ? { exitCode: 1, stderr: 'denied' } : ''), + async () => { + await prepareIosSimulatorKeyboardIntros(device); + }, + ); + assert.deepEqual( + vi.mocked(emitDiagnostic).mock.calls.map(([event]) => (event.data as { key?: string }).key), + ['MultilingualKeyboardTip'], + ); +}); + +test('a failed write does not block the launch', async () => { + await withFakeAppleTool( + (args) => (args.includes('defaults') ? { exitCode: 1, stderr: 'denied' } : ''), + async ({ calls }) => { + await openIosApp(device, 'com.example.app', { appBundleId: 'com.example.app' }); + assert.equal(calls.at(-1)?.[3], 'launch'); + }, + ); +}); + +test('open that launches the app first marks the intros once', async () => { + vi.mocked(runXcrun).mockResolvedValue({ exitCode: 0, stdout: '', stderr: '' }); + await openIosApp(device, 'MyApp', { + appBundleId: 'com.example.app', + url: 'https://example.com/item', + launchArgs: ['-Flag', 'YES'], + }); + assert.deepEqual( + vi.mocked(runXcrun).mock.calls.map(([args]) => args[3]), + ['spawn', 'spawn', 'launch', 'openurl'], + ); +}); diff --git a/packages/platform-apple/src/core/app-launch.ts b/packages/platform-apple/src/core/app-launch.ts index 9f296b6e3a..7d2be65e9a 100644 --- a/packages/platform-apple/src/core/app-launch.ts +++ b/packages/platform-apple/src/core/app-launch.ts @@ -104,7 +104,10 @@ export async function openIosApp( await terminateIosSimulatorApp(device, bundleId); } } - await openIosSimulatorUrl(device, explicitUrl, undefined, options?.runnerOptions); + // An app launched first has already marked the keyboard intros for this open. + await openIosSimulatorUrl(device, explicitUrl, undefined, options?.runnerOptions, { + keyboardPrepared: shouldLaunchAppBeforeUrl, + }); return; } const appBundleId = options?.appBundleId ?? (await resolveIosApp(device, app)); @@ -168,13 +171,13 @@ async function openIosSimulatorUrl( url: string, launchArgs: string[] | undefined, runnerOptions?: AppleRunnerCommandOptions, + { keyboardPrepared = false } = {}, ): Promise { if (launchArgs && launchArgs.length > 0) { throw new AppError('INVALID_ARGS', IOS_SIMULATOR_LAUNCH_ARGS_WITH_URL_MESSAGE); } await ensureBootedSimulator(device); - const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts'); - await prepareIosSimulatorAccessibility(device); + await prepareIosSimulatorForLaunch(device, { keyboard: !keyboardPrepared }); const args = buildSimctlArgsForDevice(device, ['openurl', device.id, url]); try { await runXcrun(args, { @@ -198,6 +201,19 @@ async function openIosSimulatorUrl( } } +async function prepareIosSimulatorForLaunch( + device: DeviceInfo, + options: { keyboard: boolean }, +): Promise { + const keyboard = options.keyboard + ? import('./ios-simulator-keyboard.ts').then((module) => + module.prepareIosSimulatorKeyboardIntros(device), + ) + : undefined; + const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts'); + await Promise.all([keyboard, prepareIosSimulatorAccessibility(device)]); +} + export async function openIosDevice(device: DeviceInfo): Promise { if (isMacOs(device)) { return; @@ -273,8 +289,7 @@ async function launchIosSimulatorApp( ): Promise { await assertNotSystemSurfaceHost(bundleId); await ensureBootedSimulator(device); - const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts'); - await prepareIosSimulatorAccessibility(device); + await prepareIosSimulatorForLaunch(device, { keyboard: true }); let consecutiveFBSFailures = 0; const MAX_CONSECUTIVE_FBS_FAILURES = 3; diff --git a/packages/platform-apple/src/core/ios-simulator-accessibility.ts b/packages/platform-apple/src/core/ios-simulator-accessibility.ts index ee2e9f1c8a..7607e7eeab 100644 --- a/packages/platform-apple/src/core/ios-simulator-accessibility.ts +++ b/packages/platform-apple/src/core/ios-simulator-accessibility.ts @@ -1,11 +1,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 { parseApplePlist } from './plist.ts'; -import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts'; -import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts'; +import { + enableSimulatorBoolPreference, + readHostSimulatorPreferences, +} from './simulator-preferences.ts'; const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000; @@ -15,19 +14,11 @@ const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000; */ export async function enableIosSimulatorAppAccessibility(device: DeviceInfo): Promise { if (!isHandheldAppleSimulator(device)) return; - await runXcrun( - buildSimctlArgsForDevice(device, [ - 'spawn', - device.id, - 'defaults', - 'write', - 'com.apple.Accessibility', - 'ApplicationAccessibilityEnabled', - '-bool', - 'YES', - ]), - { timeoutMs: ACCESSIBILITY_PREPARE_TIMEOUT_MS }, - ); + await enableSimulatorBoolPreference(device, { + domain: 'com.apple.Accessibility', + key: 'ApplicationAccessibilityEnabled', + timeoutMs: ACCESSIBILITY_PREPARE_TIMEOUT_MS, + }); } /** @@ -57,23 +48,10 @@ export async function prepareIosSimulatorAccessibility(device: DeviceInfo): Prom async function readHostAppAccessibility( device: DeviceInfo, ): 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', - ); - const parsed = await parseApplePlist(await readHostBinaryFile(preferences)); - if (!parsed) return 'unknown'; - const value = parsed.ApplicationAccessibilityEnabled; - if (value === undefined || value === true || value === 1) return 'enabled'; - if (value === false || value === 0) return 'disabled'; - return 'unknown'; - } catch { - return 'unknown'; - } + const parsed = await readHostSimulatorPreferences(device, 'com.apple.Accessibility'); + if (!parsed) return 'unknown'; + const value = parsed.ApplicationAccessibilityEnabled; + if (value === undefined || value === true || value === 1) return 'enabled'; + if (value === false || value === 0) return 'disabled'; + return 'unknown'; } diff --git a/packages/platform-apple/src/core/ios-simulator-keyboard.ts b/packages/platform-apple/src/core/ios-simulator-keyboard.ts new file mode 100644 index 0000000000..aeca3e1a43 --- /dev/null +++ b/packages/platform-apple/src/core/ios-simulator-keyboard.ts @@ -0,0 +1,48 @@ +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 { + enableSimulatorBoolPreference, + readHostSimulatorPreferences, +} from './simulator-preferences.ts'; + +const KEYBOARD_PREFERENCES_DOMAIN = 'com.apple.keyboard.preferences'; +// The keyboard sets each key once its sheet has been shown: the swipe-typing introduction, and the +// "Type English and " tip on a keyboard with a second typing language. +const KEYBOARD_INTRO_KEYS = ['DidShowContinuousPathIntroduction', 'MultilingualKeyboardTip']; +// Longer than the accessibility write's 2 s: right after a first boot, a guest write took 8-12 s, +// and a write stopped at its timeout does not land, so the sheet would still cover the keyboard. +const KEYBOARD_INTRO_WRITE_TIMEOUT_MS = 15_000; + +/** + * Before a launch: marks the keyboard's first-use sheets as shown, because on a fresh simulator they + * cover the keyboard on the first text entry. Writes only the keys this host's copy of the + * preferences does not already have; a simulator this host cannot read gets both on every launch. + * A failure only warns, so it never blocks a launch. + */ +export async function prepareIosSimulatorKeyboardIntros(device: DeviceInfo): Promise { + if (!isHandheldAppleSimulator(device)) return; + const preferences = await readHostSimulatorPreferences(device, KEYBOARD_PREFERENCES_DOMAIN); + const missing = KEYBOARD_INTRO_KEYS.filter((key) => !isSet(preferences?.[key])); + await Promise.all( + missing.map(async (key) => { + try { + await enableSimulatorBoolPreference(device, { + domain: KEYBOARD_PREFERENCES_DOMAIN, + key, + timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS, + }); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'ios_simulator_keyboard_intro_prepare_failed', + data: { deviceId: device.id, key, error: normalizeError(error) }, + }); + } + }), + ); +} + +function isSet(value: unknown): boolean { + return value === true || value === 1; +} diff --git a/packages/platform-apple/src/core/simulator-preferences.ts b/packages/platform-apple/src/core/simulator-preferences.ts new file mode 100644 index 0000000000..39aaae27fe --- /dev/null +++ b/packages/platform-apple/src/core/simulator-preferences.ts @@ -0,0 +1,49 @@ +import path from 'node:path'; +import type { DeviceInfo } from '@agent-device/kernel/device'; +import { hostHomeDirectory, readHostBinaryFile } from '@agent-device/host-kit/host-file'; +import { parseApplePlist } from './plist.ts'; +import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts'; +import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts'; + +/** + * Reads one preferences domain of a simulator from this host, without a guest call. `null` means + * it could not be read locally: a missing or malformed file, or a scoped (remote) tool provider. + */ +export async function readHostSimulatorPreferences( + device: DeviceInfo, + domain: string, +): Promise | null> { + if (hasScopedAppleToolProvider()) return null; + try { + const { udid, simulatorSetPath } = simulatorAddressFor(device); + const setPath = + simulatorSetPath ?? path.join(hostHomeDirectory(), 'Library/Developer/CoreSimulator/Devices'); + const file = path.join(setPath, udid, `data/Library/Preferences/${domain}.plist`); + return await parseApplePlist(await readHostBinaryFile(file)); + } catch { + return null; + } +} + +/** + * Sets a boolean preference to YES inside the simulator through `defaults`. Rejects when the write + * fails, times out, or exits non-zero, on a local or a scoped (remote) tool provider. + */ +export async function enableSimulatorBoolPreference( + device: DeviceInfo, + preference: { domain: string; key: string; timeoutMs: number }, +): Promise { + await runXcrun( + buildSimctlArgsForDevice(device, [ + 'spawn', + device.id, + 'defaults', + 'write', + preference.domain, + preference.key, + '-bool', + 'YES', + ]), + { timeoutMs: preference.timeoutMs }, + ); +} diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index 919a9ff987..0d9add14a9 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -246,21 +246,15 @@ test('Limrun iOS uses shared deep-link classification', async () => { ]); assert.deepEqual(limrunMockState.iosLaunchApp.mock.calls, []); assert.deepEqual(limrunMockState.iosOpenUrl.mock.calls, []); + const write = (domain: string, key: string) => [ + ['spawn', 'booted', 'defaults', 'write', domain, key, '-bool', 'YES'], + undefined, + ]; assert.deepEqual(limrunMockState.iosSimctl.mock.calls, [ [['list', 'devices', '-j'], undefined], - [ - [ - 'spawn', - 'booted', - 'defaults', - 'write', - 'com.apple.Accessibility', - 'ApplicationAccessibilityEnabled', - '-bool', - 'YES', - ], - undefined, - ], + write('com.apple.keyboard.preferences', 'DidShowContinuousPathIntroduction'), + write('com.apple.keyboard.preferences', 'MultilingualKeyboardTip'), + write('com.apple.Accessibility', 'ApplicationAccessibilityEnabled'), [['openurl', 'booted', 'example://screen'], undefined], ]); } finally { diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 0d4d560f70..353a860905 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -419,7 +419,7 @@ Runner and daemon lifecycle (applies to simulators too): close keeps a healthy iOS simulator XCTest runner warm by default so the next open on that simulator (same udid in the same simulator set) skips the runner build, unless --shutdown was requested, the session was recording, or its device lease ends on close. A lease allocated with retainOnClose can keep the runner between sessions; releasing or expiring that lease stops its runner unless a session outside the lease has taken over the device. A retained runner auto-stops after an idle window (default 5 minutes); set AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS to override, or 0 to disable idle stopping. Lease release, expiry, and graceful daemon shutdown still clean up runners they own. Only a ready runner with an observed listener is retained; close retires unfinished prewarm recovery. Losing the retained listener stops that generation, and graceful daemon shutdown stops idle retained runners rather than handing them off without supervision. Each AGENT_DEVICE_STATE_DIR runs its own daemon. It self-exits after an idle window (default 5 minutes, matching the runner idle-stop default) once it has no open sessions, no in-flight requests, and no active recording; set AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS to override, or 0 to disable idle reap. A client starting a local daemon waits while the daemon process stays alive and keeps publishing startup progress, so an overloaded host makes startup slower, not failed. It stops at a ceiling (default 120 s; set AGENT_DEVICE_DAEMON_STARTUP_TIMEOUT_MS to a positive integer number of milliseconds to override) and names the outcome in error details.reason: startup-listen-denied (the host refused the daemon's loopback listen, as a sandbox does; rerun agent-device with host access), startup-exited (the process ended before registering for another cause), startup-stalled (alive, no startup progress for a fixed 60 s window the ceiling variable does not change), or startup-ceiling (a startup was still live when the ceiling passed — this client's daemon or another client's; the client stops its own launch and never signals another client's live daemon. Only a progressing own launch outlasts the 60 s stall window, so a ceiling set below 60 s also ends a silent own launch this way). details.phases carries the startup phase timings it observed and details.startupTimeoutMs the effective ceiling. Branch on details.reason, never on the message. The variable is read only when a client must start a daemon: a value that is not a positive integer fails with INVALID_ARGS before the daemon spawns, and a client that only attaches to or reuses a running daemon never reads it. A sandbox around the client can also refuse the client's own connect to a daemon that runs outside it, with EPERM or EACCES; that is not a startup outcome and needs no daemon launch. The command then fails with details.reason daemon-connect-denied, naming that errno, the transport, port and daemon it could not reach. A connect refused with another errno is ordinary unreachability and is reported as such. That daemon keeps running: the client replaced, retired and signaled nothing. Rerun agent-device with host access. - On iOS simulators, open prepares app accessibility before launching an app or URL. If a running app has an empty accessibility tree after an earlier XCTest session, use open --relaunch, then snapshot -i. A preparation failure is logged and does not block launch. + On iOS simulators, open prepares app accessibility and marks the keyboard's first-use sheets (the swipe-typing introduction and the multilingual keyboard tip) as shown before launching an app or URL, so they do not cover the keyboard on the first text entry. If a running app has an empty accessibility tree after an earlier XCTest session, use open --relaunch, then snapshot -i. A preparation failure is logged and does not block launch. A command that needs the shared local daemon starts it for its state dir when none runs (device status and device release --stale never contact one). When the running daemon comes from another version or build, the command replaces it only if the daemon reports no work: no in-flight request, session, repair session, or live lease (a streaming resumable upload and a host human-control hold that names no lease are not counted); otherwise it fails with details.reason daemon-busy and leaves the daemon alone. A daemon that agreed to leave is waited for up to 60 s and never signaled while it drains; one still running then fails with details.reason daemon-drain-timeout unless it answers nothing and is provably a daemon process, which is force-retired. A daemon from a release that predates this check is never replaced and fails with daemon-incompatible. End a busy or older daemon deliberately with agent-device daemon stop --state-dir . Node clients pick daemonLifecycle 'attach' (never starts or replaces a daemon; fails with daemon-not-running or daemon-incompatible) or 'managed' (the default until 0.22), and ensureDaemon() starts or replaces one explicitly. daemon stop --state-dir stops a detached daemon with process signals after verifying its identity; on non-Windows hosts it waits up to 75 s for the daemon to finish its own teardown before it forces the exit, while on Windows the stop signal force-terminates the daemon (mode forced, cleanupConfidence unknown). For a live embedded runtime, stop refuses with details.reason daemon-owner-embedded and a hint naming the host PID. Close that runtime in its host process with the handle returned by startAgentDevice(). Stop refuses live unrecognized ownership with daemon-owner-unrecognized and sends no request or signal. Stop retires an embedded or unrecognized registration when its recorded host lifetime has provably exited. Without --clean, an unreadable daemon.json fails with daemon-record-unreadable. daemon status shows host-owned or owner-not-recognized. Managed clients reuse a matching embedded runtime. Takeover, drain, and timeout recovery refuse a live embedded or unrecognized owner without a signal; a provably exited owner is retired so the state directory stays usable. Detached stop and cleanup use the lifetime and ownership from one registration read. --clean requires proven detached ownership; embedded, unrecognized and unreadable records fail with daemon-clean-not-detached because that cleanup walks the owner's whole process tree. A macOS or BSD daemon registered before this release stores a raw lstart rendering, which cannot be compared against this build's start-time token: stop then refuses with details.terminationReason identity-unverified and sends no signal, keeping daemon.json and the lock. Older registrations that store a Linux /proc or Windows start-time token still stop normally; a Linux registration read through the ps fallback (for example with an unreadable boot_id) has the macOS and BSD limits. Stop such a daemon with the same (older) agent-device build that started it, or end it as its owner (SIGTERM to the recorded PID) before running this build against that state dir; deleting the state dir also works once the owner is known dead. On macOS or BSD, do not run an older and a newer build on one host: runner leases and device claims are host-global, so the older build can read a newer start-time token as a reused process, and records that an older build wrote stay unverified until their owner stops the process. That covers the daemon registration, the companion tunnel, runner leases, and other records that store a process start time. diff --git a/src/core/interactors/limrun-ios-tools.test.ts b/src/core/interactors/limrun-ios-tools.test.ts index 1a8eeafa0c..308b5d0abb 100644 --- a/src/core/interactors/limrun-ios-tools.test.ts +++ b/src/core/interactors/limrun-ios-tools.test.ts @@ -72,6 +72,31 @@ test('normal launch prepares app accessibility through the instance-scoped simct expect(calls[launch]).toEqual(['launch', 'booted', 'com.example.app']); }); +test('a guest preference write that exits non-zero rejects through the Limrun adapter', async () => { + const f = await sessionWithClient({ code: 1, stdout: '', stderr: 'denied' }); + const tools = createLimrunAppleToolProvider(f.session, new AbortController().signal); + const write = ['spawn', f.device.id, 'defaults', 'write', 'com.apple.keyboard.preferences']; + await expect( + withAppleToolProvider(tools, () => + runXcrun(buildSimctlArgsForDevice(f.device, [...write, 'DidShowContinuousPathIntroduction'])), + ), + ).rejects.toMatchObject({ code: 'COMMAND_FAILED', details: { exitCode: 1, stderr: 'denied' } }); +}); + +test('every open writes the keyboard intro keys through the Limrun adapter', async () => { + const { interactor, simctl } = await sessionWithClient(); + for (let open = 0; open < 2; open += 1) { + simctl.mockClear(); + await interactor.open('com.example.app'); + const calls = simctl.mock.calls.map(([args]) => args); + expect( + calls + .filter((args) => args.includes('com.apple.keyboard.preferences')) + .map((args) => args[5]), + ).toEqual(['DidShowContinuousPathIntroduction', 'MultilingualKeyboardTip']); + } +}); + test('a url open launches with arguments before opening the url', async () => { const { interactor, simctl } = await sessionWithClient(); await interactor.open('com.example.app', { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 77728d842b..48aed2287e 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -236,6 +236,7 @@ Exact behavior: `agent-device help close`. - On a local iOS Simulator, the first capture after `open` waits for the app's first screen. If the wait ends first, the snapshot warns with `postGestureOutcome.kind: "loading"` or `"unsettled"`. Run `snapshot -i` or `wait text ` before you act. An app whose first screen has no labeled controls, such as a game canvas, always waits the full time; pass `--no-post-gesture-stabilization` to skip the wait. - `open --wait ` waits for a device that another session holds. A claim held by another workspace is not waited for: `open` returns the recovery command at once. `install` and `reinstall` never wait. - If an app on an iOS simulator shows an empty accessibility tree after an earlier XCTest session, run `open --relaunch`, then `snapshot -i`. +- On iOS simulators, `open` marks the keyboard's swipe-typing introduction and multilingual keyboard tip as shown before it launches the app, so neither sheet covers the keyboard on the first text entry. A failed write is logged and does not stop the launch. - Android React Native: `open --relaunch` needs an installed package name, not an APK path. For Metro-served JS changes, run `metro reload` instead. - `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url` apply to the app that `open` opens. A later `open` without these flags applies them again only when it opens the same app. It opens another app, such as a system app, without them. An `open` that passes these flags for another app also removes the earlier hints from the app an earlier `open` applied them to. - ADB-backed Android: `open settings --relaunch` restarts the app that the intent opened. It fails when the intent matches more than one activity.