From 95bad44b7c0947591fedfdf88533cb1052097b96 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 13:14:33 +0530 Subject: [PATCH 1/6] refactor(ios): share the simulator host preferences read --- .../src/core/ios-simulator-accessibility.ts | 33 +++++-------------- .../src/core/simulator-host-preferences.ts | 26 +++++++++++++++ 2 files changed, 35 insertions(+), 24 deletions(-) create mode 100644 packages/platform-apple/src/core/simulator-host-preferences.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..b45836f27a 100644 --- a/packages/platform-apple/src/core/ios-simulator-accessibility.ts +++ b/packages/platform-apple/src/core/ios-simulator-accessibility.ts @@ -1,11 +1,9 @@ -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 { buildSimctlArgsForDevice } from './simctl.ts'; +import { readHostSimulatorPreferences } from './simulator-host-preferences.ts'; +import { runXcrun } from './tool-provider.ts'; const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000; @@ -57,23 +55,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/simulator-host-preferences.ts b/packages/platform-apple/src/core/simulator-host-preferences.ts new file mode 100644 index 0000000000..7d3fa4b3d3 --- /dev/null +++ b/packages/platform-apple/src/core/simulator-host-preferences.ts @@ -0,0 +1,26 @@ +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 { simulatorAddressFor } from './simctl.ts'; +import { hasScopedAppleToolProvider } 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; + } +} From f7ac129aeb8fc797157228218406180d8e960e42 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 13:14:33 +0530 Subject: [PATCH 2/6] fix(ios): mark the keyboard intro sheets as shown before a simulator launch --- .../app-launch-accessibility.test.ts | 2 + .../core/__tests__/app-launch-open.test.ts | 2 + .../src/core/__tests__/app-launch-url.test.ts | 2 + .../fixtures/keyboard-intros-shown.plist | Bin 0 -> 114 bytes .../__tests__/ios-simulator-keyboard.test.ts | 189 ++++++++++++++++++ .../platform-apple/src/core/app-launch.ts | 14 +- .../src/core/ios-simulator-keyboard.ts | 48 +++++ src/__tests__/limrun-runtime.test.ts | 30 +-- src/commands/schema/cli-help.ts | 2 +- src/core/interactors/limrun-ios-tools.test.ts | 21 ++ 10 files changed, 292 insertions(+), 18 deletions(-) create mode 100644 packages/platform-apple/src/core/__tests__/fixtures/keyboard-intros-shown.plist create mode 100644 packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts create mode 100644 packages/platform-apple/src/core/ios-simulator-keyboard.ts 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 0000000000000000000000000000000000000000..df86b562ade0dfacab8022a0e682eb71a7576d5e GIT binary patch literal 114 zcmYc)$jK}&F)+Bq$i&PXFCgw)np2XQlbM%ZnwaCATA7reSdcnOB-$S{#sAlHr+GQk0)knp~2ZpU26`!K?1=!vF@1j1ZcE6-vV>UjR5Z9OeK3 literal 0 HcmV?d00001 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..c7765864ea --- /dev/null +++ b/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts @@ -0,0 +1,189 @@ +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 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 as the simulator writes it', 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('a scoped (remote) tool provider writes even when this host has both keys', async () => { + writePreferences({ DidShowContinuousPathIntroduction: true, MultilingualKeyboardTip: true }); + const calls = await withAppleToolProvider({} as Parameters[0], () => + prepare(), + ); + assert.deepEqual(writtenKeys(calls), [ + 'DidShowContinuousPathIntroduction', + 'MultilingualKeyboardTip', + ]); +}); + +test('a failed write warns and still writes the other key', async () => { + const calls = await prepare('MultilingualKeyboardTip'); + assert.deepEqual(writtenKeys(calls), [ + 'DidShowContinuousPathIntroduction', + 'MultilingualKeyboardTip', + ]); + assert.deepEqual( + vi.mocked(emitDiagnostic).mock.calls.map(([event]) => event.phase), + ['ios_simulator_keyboard_intro_prepare_failed'], + ); +}); + +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 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'); + }, + ); +}); diff --git a/packages/platform-apple/src/core/app-launch.ts b/packages/platform-apple/src/core/app-launch.ts index 9f296b6e3a..6d5b6d92a4 100644 --- a/packages/platform-apple/src/core/app-launch.ts +++ b/packages/platform-apple/src/core/app-launch.ts @@ -173,8 +173,7 @@ async function openIosSimulatorUrl( 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); const args = buildSimctlArgsForDevice(device, ['openurl', device.id, url]); try { await runXcrun(args, { @@ -198,6 +197,14 @@ async function openIosSimulatorUrl( } } +/** Runs after boot and before an app or URL launch on a simulator. */ +async function prepareIosSimulatorForLaunch(device: DeviceInfo): Promise { + const { prepareIosSimulatorKeyboardIntros } = await import('./ios-simulator-keyboard.ts'); + await prepareIosSimulatorKeyboardIntros(device); + const { prepareIosSimulatorAccessibility } = await import('./ios-simulator-accessibility.ts'); + await prepareIosSimulatorAccessibility(device); +} + export async function openIosDevice(device: DeviceInfo): Promise { if (isMacOs(device)) { return; @@ -273,8 +280,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); let consecutiveFBSFailures = 0; const MAX_CONSECUTIVE_FBS_FAILURES = 3; 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..242187703e --- /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 { buildSimctlArgsForDevice } from './simctl.ts'; +import { readHostSimulatorPreferences } from './simulator-host-preferences.ts'; +import { runXcrun } from './tool-provider.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']; +const KEYBOARD_INTRO_WRITE_TIMEOUT_MS = 5_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 input. Writes only the keys this host's copy of the + * preferences does not already have, and 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) => preferences?.[key] !== true); + const results = await Promise.allSettled( + missing.map((key) => + runXcrun( + buildSimctlArgsForDevice(device, [ + 'spawn', + device.id, + 'defaults', + 'write', + KEYBOARD_PREFERENCES_DOMAIN, + key, + '-bool', + 'YES', + ]), + { timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS }, + ), + ), + ); + for (const result of results) { + if (result.status === 'fulfilled') continue; + emitDiagnostic({ + level: 'warn', + phase: 'ios_simulator_keyboard_intro_prepare_failed', + data: { deviceId: device.id, error: normalizeError(result.reason) }, + }); + } +} diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index 919a9ff987..b55cc32391 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -246,23 +246,27 @@ test('Limrun iOS uses shared deep-link classification', async () => { ]); assert.deepEqual(limrunMockState.iosLaunchApp.mock.calls, []); assert.deepEqual(limrunMockState.iosOpenUrl.mock.calls, []); - assert.deepEqual(limrunMockState.iosSimctl.mock.calls, [ - [['list', 'devices', '-j'], undefined], + const simctlCalls = limrunMockState.iosSimctl.mock.calls; + assert.deepEqual( + simctlCalls.filter(([args]) => !args.includes('com.apple.keyboard.preferences')), [ + [['list', 'devices', '-j'], undefined], [ - 'spawn', - 'booted', - 'defaults', - 'write', - 'com.apple.Accessibility', - 'ApplicationAccessibilityEnabled', - '-bool', - 'YES', + [ + 'spawn', + 'booted', + 'defaults', + 'write', + 'com.apple.Accessibility', + 'ApplicationAccessibilityEnabled', + '-bool', + 'YES', + ], + undefined, ], - undefined, + [['openurl', 'booted', 'example://screen'], undefined], ], - [['openurl', 'booted', 'example://screen'], undefined], - ]); + ); } finally { try { await runtime.shutdown(); diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 0d4d560f70..9a35cea493 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 fill. 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..e497cc11fd 100644 --- a/src/core/interactors/limrun-ios-tools.test.ts +++ b/src/core/interactors/limrun-ios-tools.test.ts @@ -72,6 +72,27 @@ test('normal launch prepares app accessibility through the instance-scoped simct expect(calls[launch]).toEqual(['launch', 'booted', 'com.example.app']); }); +test('normal launch marks the keyboard intros through the instance-scoped simctl adapter', async () => { + const { interactor, simctl } = await sessionWithClient(); + await interactor.open('com.example.app'); + const calls = simctl.mock.calls.map(([args]) => args); + const launch = calls.findIndex((args) => args[0] === 'launch'); + expect( + calls.slice(0, launch).filter((args) => args.includes('com.apple.keyboard.preferences')), + ).toEqual( + ['DidShowContinuousPathIntroduction', 'MultilingualKeyboardTip'].map((key) => [ + 'spawn', + 'booted', + 'defaults', + 'write', + 'com.apple.keyboard.preferences', + key, + '-bool', + 'YES', + ]), + ); +}); + test('a url open launches with arguments before opening the url', async () => { const { interactor, simctl } = await sessionWithClient(); await interactor.open('com.example.app', { From c2c85496f7e93508ad09fe51fe818525c618f82d Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 13:49:11 +0530 Subject: [PATCH 3/6] fix(ios): write the keyboard intro keys once per open and once per remote simulator --- .../__tests__/ios-simulator-keyboard.test.ts | 63 ++++++++++++--- .../platform-apple/src/core/app-launch.ts | 25 ++++-- .../src/core/ios-simulator-keyboard.ts | 77 ++++++++++++------- src/__tests__/limrun-runtime.test.ts | 32 +++----- src/core/interactors/limrun-ios-tools.test.ts | 21 ++--- 5 files changed, 135 insertions(+), 83 deletions(-) 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 index c7765864ea..daab65384c 100644 --- a/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts +++ b/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts @@ -98,6 +98,7 @@ for (const [label, preferences, expected] of [ [], ], ['one key is on', { DidShowContinuousPathIntroduction: true }, ['MultilingualKeyboardTip']], + ['a key is 1', { DidShowContinuousPathIntroduction: 1, MultilingualKeyboardTip: true }, []], [ 'a key is off', { DidShowContinuousPathIntroduction: false, MultilingualKeyboardTip: true }, @@ -110,7 +111,7 @@ for (const [label, preferences, expected] of [ }); } -test('reads a binary preferences file as the simulator writes it', async () => { +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'), @@ -118,26 +119,57 @@ test('reads a binary preferences file as the simulator writes it', async () => { 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 }); - const calls = await withAppleToolProvider({} as Parameters[0], () => - prepare(), - ); - assert.deepEqual(writtenKeys(calls), [ + assert.deepEqual(writtenKeys(await scoped(() => prepare())), [ 'DidShowContinuousPathIntroduction', 'MultilingualKeyboardTip', ]); }); -test('a failed write warns and still writes the other key', async () => { - const calls = await prepare('MultilingualKeyboardTip'); +test('a scoped provider writes each key once per simulator and retries a failed one', async () => { + await scoped(() => prepare('MultilingualKeyboardTip')); + vi.mocked(runXcrun).mockClear(); + assert.deepEqual(writtenKeys(await scoped(() => prepare())), ['MultilingualKeyboardTip']); + vi.mocked(runXcrun).mockClear(); + assert.deepEqual(await scoped(() => prepare()), []); +}); + +test('a local simulator writes again while its preferences file is missing, as after an erase', async () => { + await prepare(); + vi.mocked(runXcrun).mockClear(); + assert.deepEqual(writtenKeys(await 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.phase), - ['ios_simulator_keyboard_intro_prepare_failed'], + 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']], ); }); @@ -187,3 +219,16 @@ test('a failed write does not block the launch', async () => { }, ); }); + +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 6d5b6d92a4..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,12 +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); - await prepareIosSimulatorForLaunch(device); + await prepareIosSimulatorForLaunch(device, { keyboard: !keyboardPrepared }); const args = buildSimctlArgsForDevice(device, ['openurl', device.id, url]); try { await runXcrun(args, { @@ -197,12 +201,17 @@ async function openIosSimulatorUrl( } } -/** Runs after boot and before an app or URL launch on a simulator. */ -async function prepareIosSimulatorForLaunch(device: DeviceInfo): Promise { - const { prepareIosSimulatorKeyboardIntros } = await import('./ios-simulator-keyboard.ts'); - await prepareIosSimulatorKeyboardIntros(device); +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 prepareIosSimulatorAccessibility(device); + await Promise.all([keyboard, prepareIosSimulatorAccessibility(device)]); } export async function openIosDevice(device: DeviceInfo): Promise { @@ -280,7 +289,7 @@ async function launchIosSimulatorApp( ): Promise { await assertNotSystemSurfaceHost(bundleId); await ensureBootedSimulator(device); - await prepareIosSimulatorForLaunch(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-keyboard.ts b/packages/platform-apple/src/core/ios-simulator-keyboard.ts index 242187703e..1533a0c2ab 100644 --- a/packages/platform-apple/src/core/ios-simulator-keyboard.ts +++ b/packages/platform-apple/src/core/ios-simulator-keyboard.ts @@ -1,48 +1,67 @@ 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 { buildSimctlArgsForDevice } from './simctl.ts'; +import { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts'; import { readHostSimulatorPreferences } from './simulator-host-preferences.ts'; -import { runXcrun } from './tool-provider.ts'; +import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.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']; -const KEYBOARD_INTRO_WRITE_TIMEOUT_MS = 5_000; +// Longer than the accessibility write's 2 s: right after a first boot, a guest write took 8-12 s, +// and a write that runs out of time leaves the sheet to appear on the first text entry. +const KEYBOARD_INTRO_WRITE_TIMEOUT_MS = 15_000; + +// Keys written to simulators this host cannot read (a scoped, remote tool provider), so a later +// open skips them. Only an erase resets them, and agent-device never erases a simulator. +const writtenRemoteKeys = new Map>(); /** * 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 input. Writes only the keys this host's copy of the + * cover the keyboard on the first text entry. Writes only the keys this host's copy of the * preferences does not already have, and 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) => preferences?.[key] !== true); - const results = await Promise.allSettled( - missing.map((key) => - runXcrun( - buildSimctlArgsForDevice(device, [ - 'spawn', - device.id, - 'defaults', - 'write', - KEYBOARD_PREFERENCES_DOMAIN, - key, - '-bool', - 'YES', - ]), - { timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS }, - ), - ), + const { udid, simulatorSetPath } = simulatorAddressFor(device); + const remoteKey = `${simulatorSetPath ?? ''}/${udid}`; + const remoteWritten = hasScopedAppleToolProvider() + ? (writtenRemoteKeys.get(remoteKey) ?? new Set()) + : undefined; + const missing = KEYBOARD_INTRO_KEYS.filter( + (key) => !isSet(preferences?.[key]) && !remoteWritten?.has(key), + ); + await Promise.all( + missing.map(async (key) => { + try { + await runXcrun( + buildSimctlArgsForDevice(device, [ + 'spawn', + device.id, + 'defaults', + 'write', + KEYBOARD_PREFERENCES_DOMAIN, + key, + '-bool', + 'YES', + ]), + { timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS }, + ); + remoteWritten?.add(key); + } catch (error) { + emitDiagnostic({ + level: 'warn', + phase: 'ios_simulator_keyboard_intro_prepare_failed', + data: { deviceId: device.id, key, error: normalizeError(error) }, + }); + } + }), ); - for (const result of results) { - if (result.status === 'fulfilled') continue; - emitDiagnostic({ - level: 'warn', - phase: 'ios_simulator_keyboard_intro_prepare_failed', - data: { deviceId: device.id, error: normalizeError(result.reason) }, - }); - } + if (remoteWritten?.size) writtenRemoteKeys.set(remoteKey, remoteWritten); +} + +function isSet(value: unknown): boolean { + return value === true || value === 1; } diff --git a/src/__tests__/limrun-runtime.test.ts b/src/__tests__/limrun-runtime.test.ts index b55cc32391..0d9add14a9 100644 --- a/src/__tests__/limrun-runtime.test.ts +++ b/src/__tests__/limrun-runtime.test.ts @@ -246,27 +246,17 @@ test('Limrun iOS uses shared deep-link classification', async () => { ]); assert.deepEqual(limrunMockState.iosLaunchApp.mock.calls, []); assert.deepEqual(limrunMockState.iosOpenUrl.mock.calls, []); - const simctlCalls = limrunMockState.iosSimctl.mock.calls; - assert.deepEqual( - simctlCalls.filter(([args]) => !args.includes('com.apple.keyboard.preferences')), - [ - [['list', 'devices', '-j'], undefined], - [ - [ - 'spawn', - 'booted', - 'defaults', - 'write', - 'com.apple.Accessibility', - 'ApplicationAccessibilityEnabled', - '-bool', - 'YES', - ], - undefined, - ], - [['openurl', 'booted', 'example://screen'], undefined], - ], - ); + 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], + write('com.apple.keyboard.preferences', 'DidShowContinuousPathIntroduction'), + write('com.apple.keyboard.preferences', 'MultilingualKeyboardTip'), + write('com.apple.Accessibility', 'ApplicationAccessibilityEnabled'), + [['openurl', 'booted', 'example://screen'], undefined], + ]); } finally { try { await runtime.shutdown(); diff --git a/src/core/interactors/limrun-ios-tools.test.ts b/src/core/interactors/limrun-ios-tools.test.ts index e497cc11fd..bb54322210 100644 --- a/src/core/interactors/limrun-ios-tools.test.ts +++ b/src/core/interactors/limrun-ios-tools.test.ts @@ -72,25 +72,14 @@ test('normal launch prepares app accessibility through the instance-scoped simct expect(calls[launch]).toEqual(['launch', 'booted', 'com.example.app']); }); -test('normal launch marks the keyboard intros through the instance-scoped simctl adapter', async () => { +test('a second open on the same lease does not write the keyboard intros again', async () => { const { interactor, simctl } = await sessionWithClient(); await interactor.open('com.example.app'); + simctl.mockClear(); + await interactor.open('com.example.app'); const calls = simctl.mock.calls.map(([args]) => args); - const launch = calls.findIndex((args) => args[0] === 'launch'); - expect( - calls.slice(0, launch).filter((args) => args.includes('com.apple.keyboard.preferences')), - ).toEqual( - ['DidShowContinuousPathIntroduction', 'MultilingualKeyboardTip'].map((key) => [ - 'spawn', - 'booted', - 'defaults', - 'write', - 'com.apple.keyboard.preferences', - key, - '-bool', - 'YES', - ]), - ); + expect(calls.filter((args) => args.includes('com.apple.keyboard.preferences'))).toEqual([]); + expect(calls).toContainEqual(['launch', 'booted', 'com.example.app']); }); test('a url open launches with arguments before opening the url', async () => { From 45ca5e5f1f4bf6a754678fb0df7bd278cfaf611f Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 13:49:12 +0530 Subject: [PATCH 4/6] docs(ios): note the keyboard intro preparation in the open reference --- src/commands/schema/cli-help.ts | 2 +- website/docs/docs/commands.md | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 9a35cea493..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 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 fill. 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/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. From a516f0dcc6d78b0321d23b12152edf87e2ca74f8 Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 14:14:26 +0530 Subject: [PATCH 5/6] docs(ios): say why the keyboard intro write timeout is longer --- packages/platform-apple/src/core/ios-simulator-keyboard.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/platform-apple/src/core/ios-simulator-keyboard.ts b/packages/platform-apple/src/core/ios-simulator-keyboard.ts index 1533a0c2ab..41ffaa8fcc 100644 --- a/packages/platform-apple/src/core/ios-simulator-keyboard.ts +++ b/packages/platform-apple/src/core/ios-simulator-keyboard.ts @@ -10,7 +10,7 @@ const KEYBOARD_PREFERENCES_DOMAIN = 'com.apple.keyboard.preferences'; // "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 that runs out of time leaves the sheet to appear on the first text entry. +// 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; // Keys written to simulators this host cannot read (a scoped, remote tool provider), so a later From 4ec0d4bce7a60c070e63ef4be05946af743078ac Mon Sep 17 00:00:00 2001 From: parbez Date: Tue, 24 Nov 2026 16:11:48 +0530 Subject: [PATCH 6/6] refactor(ios): write simulator bool preferences through one helper and drop the remote key cache --- .../__tests__/ios-simulator-keyboard.test.ts | 30 ++++++------- .../src/core/ios-simulator-accessibility.ts | 25 ++++------- .../src/core/ios-simulator-keyboard.ts | 43 ++++++------------- ...references.ts => simulator-preferences.ts} | 27 +++++++++++- src/core/interactors/limrun-ios-tools.test.ts | 29 ++++++++++--- 5 files changed, 81 insertions(+), 73 deletions(-) rename packages/platform-apple/src/core/{simulator-host-preferences.ts => simulator-preferences.ts} (56%) 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 index daab65384c..f2ed2b4df7 100644 --- a/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts +++ b/packages/platform-apple/src/core/__tests__/ios-simulator-keyboard.test.ts @@ -138,23 +138,6 @@ test('a scoped (remote) tool provider writes even when this host has both keys', ]); }); -test('a scoped provider writes each key once per simulator and retries a failed one', async () => { - await scoped(() => prepare('MultilingualKeyboardTip')); - vi.mocked(runXcrun).mockClear(); - assert.deepEqual(writtenKeys(await scoped(() => prepare())), ['MultilingualKeyboardTip']); - vi.mocked(runXcrun).mockClear(); - assert.deepEqual(await scoped(() => prepare()), []); -}); - -test('a local simulator writes again while its preferences file is missing, as after an erase', async () => { - await prepare(); - vi.mocked(runXcrun).mockClear(); - assert.deepEqual(writtenKeys(await 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), [ @@ -210,6 +193,19 @@ for (const app of ['com.example.app', 'myapp://home']) { }); } +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' } : ''), diff --git a/packages/platform-apple/src/core/ios-simulator-accessibility.ts b/packages/platform-apple/src/core/ios-simulator-accessibility.ts index b45836f27a..7607e7eeab 100644 --- a/packages/platform-apple/src/core/ios-simulator-accessibility.ts +++ b/packages/platform-apple/src/core/ios-simulator-accessibility.ts @@ -1,9 +1,10 @@ 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 { buildSimctlArgsForDevice } from './simctl.ts'; -import { readHostSimulatorPreferences } from './simulator-host-preferences.ts'; -import { runXcrun } from './tool-provider.ts'; +import { + enableSimulatorBoolPreference, + readHostSimulatorPreferences, +} from './simulator-preferences.ts'; const ACCESSIBILITY_PREPARE_TIMEOUT_MS = 2_000; @@ -13,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, + }); } /** diff --git a/packages/platform-apple/src/core/ios-simulator-keyboard.ts b/packages/platform-apple/src/core/ios-simulator-keyboard.ts index 41ffaa8fcc..aeca3e1a43 100644 --- a/packages/platform-apple/src/core/ios-simulator-keyboard.ts +++ b/packages/platform-apple/src/core/ios-simulator-keyboard.ts @@ -1,9 +1,10 @@ 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 { buildSimctlArgsForDevice, simulatorAddressFor } from './simctl.ts'; -import { readHostSimulatorPreferences } from './simulator-host-preferences.ts'; -import { hasScopedAppleToolProvider, runXcrun } from './tool-provider.ts'; +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 @@ -13,43 +14,24 @@ const KEYBOARD_INTRO_KEYS = ['DidShowContinuousPathIntroduction', 'MultilingualK // 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; -// Keys written to simulators this host cannot read (a scoped, remote tool provider), so a later -// open skips them. Only an erase resets them, and agent-device never erases a simulator. -const writtenRemoteKeys = new Map>(); - /** * 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, and a failure only warns, so it never blocks a launch. + * 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 { udid, simulatorSetPath } = simulatorAddressFor(device); - const remoteKey = `${simulatorSetPath ?? ''}/${udid}`; - const remoteWritten = hasScopedAppleToolProvider() - ? (writtenRemoteKeys.get(remoteKey) ?? new Set()) - : undefined; - const missing = KEYBOARD_INTRO_KEYS.filter( - (key) => !isSet(preferences?.[key]) && !remoteWritten?.has(key), - ); + const missing = KEYBOARD_INTRO_KEYS.filter((key) => !isSet(preferences?.[key])); await Promise.all( missing.map(async (key) => { try { - await runXcrun( - buildSimctlArgsForDevice(device, [ - 'spawn', - device.id, - 'defaults', - 'write', - KEYBOARD_PREFERENCES_DOMAIN, - key, - '-bool', - 'YES', - ]), - { timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS }, - ); - remoteWritten?.add(key); + await enableSimulatorBoolPreference(device, { + domain: KEYBOARD_PREFERENCES_DOMAIN, + key, + timeoutMs: KEYBOARD_INTRO_WRITE_TIMEOUT_MS, + }); } catch (error) { emitDiagnostic({ level: 'warn', @@ -59,7 +41,6 @@ export async function prepareIosSimulatorKeyboardIntros(device: DeviceInfo): Pro } }), ); - if (remoteWritten?.size) writtenRemoteKeys.set(remoteKey, remoteWritten); } function isSet(value: unknown): boolean { diff --git a/packages/platform-apple/src/core/simulator-host-preferences.ts b/packages/platform-apple/src/core/simulator-preferences.ts similarity index 56% rename from packages/platform-apple/src/core/simulator-host-preferences.ts rename to packages/platform-apple/src/core/simulator-preferences.ts index 7d3fa4b3d3..39aaae27fe 100644 --- a/packages/platform-apple/src/core/simulator-host-preferences.ts +++ b/packages/platform-apple/src/core/simulator-preferences.ts @@ -2,8 +2,8 @@ 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 { simulatorAddressFor } from './simctl.ts'; -import { hasScopedAppleToolProvider } from './tool-provider.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 @@ -24,3 +24,26 @@ export async function readHostSimulatorPreferences( 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/core/interactors/limrun-ios-tools.test.ts b/src/core/interactors/limrun-ios-tools.test.ts index bb54322210..308b5d0abb 100644 --- a/src/core/interactors/limrun-ios-tools.test.ts +++ b/src/core/interactors/limrun-ios-tools.test.ts @@ -72,14 +72,29 @@ test('normal launch prepares app accessibility through the instance-scoped simct expect(calls[launch]).toEqual(['launch', 'booted', 'com.example.app']); }); -test('a second open on the same lease does not write the keyboard intros again', async () => { +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(); - await interactor.open('com.example.app'); - 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'))).toEqual([]); - expect(calls).toContainEqual(['launch', 'booted', 'com.example.app']); + 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 () => {