diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index 0407b8ff03..311cf5ab67 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -95,6 +95,8 @@ curl -sS http://127.0.0.1:${AGENT_DEVICE_DAEMON_HTTP_PORT}/rpc \ agent-device devices agent-device devices --platform ios --ios-simulator-device-set /tmp/tenant-a/simulators agent-device devices --platform android --android-device-allowlist emulator-5554,device-1234 +agent-device ensure-simulator --device "iPhone 16" --ios-simulator-device-set /tmp/tenant-a/simulators +agent-device ensure-simulator --device "iPhone 16" --runtime com.apple.CoreSimulator.SimRuntime.iOS-18-4 --ios-simulator-device-set /tmp/tenant-a/simulators --boot agent-device open [app|url] [url] agent-device open [app] --relaunch agent-device close [app] @@ -114,6 +116,12 @@ Isolation scoping quick reference: - Scope is applied before selectors (`--device`, `--udid`, `--serial`); out-of-scope selectors fail with `DEVICE_NOT_FOUND`. - With iOS simulator-set scope enabled, iOS physical devices are not enumerated. +Simulator provisioning quick reference: +- Use `ensure-simulator` to create or reuse a named iOS simulator inside a device set before starting a session. +- `--device ` is required (e.g. `"iPhone 16 Pro"`). `--runtime ` pins the runtime; omit to use the newest compatible one. +- `--boot` boots it immediately. Returns `udid`, `device`, `runtime`, `ios_simulator_device_set`, `created`, `booted`. +- Idempotent: safe to call repeatedly; reuses an existing matching simulator by default. + TV quick reference: - AndroidTV: `open`/`apps` use TV launcher discovery automatically. - TV target selection works on emulators/simulators and connected physical devices (AndroidTV + AppleTV). diff --git a/src/cli.ts b/src/cli.ts index dea549875d..8226b501a3 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -245,6 +245,20 @@ export async function runCli(argv: string[], deps: CliDeps = DEFAULT_CLI_DEPS): if (logTailStopper) logTailStopper(); return; } + if (command === 'ensure-simulator') { + const data = response.data as Record | undefined; + const udid = typeof data?.udid === 'string' ? data.udid : 'unknown'; + const device = typeof data?.device === 'string' ? data.device : 'unknown'; + const runtime = typeof data?.runtime === 'string' ? data.runtime : ''; + const created = data?.created === true; + const booted = data?.booted === true; + const action = created ? 'Created' : 'Reused'; + const bootedSuffix = booted ? ' (booted)' : ''; + process.stdout.write(`${action}: ${device} ${udid}${bootedSuffix}\n`); + if (runtime) process.stdout.write(`Runtime: ${runtime}\n`); + if (logTailStopper) logTailStopper(); + return; + } if (command === 'logs') { const data = response.data as Record | undefined; const pathOut = typeof data?.path === 'string' ? data.path : ''; diff --git a/src/daemon.ts b/src/daemon.ts index 5ba90d9b6a..6eb957d765 100644 --- a/src/daemon.ts +++ b/src/daemon.ts @@ -49,10 +49,11 @@ const leaseRegistry = new LeaseRegistry({ }); const version = readVersion(); const token = crypto.randomBytes(24).toString('hex'); -const selectorValidationExemptCommands = new Set(['session_list', 'devices']); +const selectorValidationExemptCommands = new Set(['session_list', 'devices', 'ensure-simulator']); const leaseAdmissionExemptCommands = new Set([ 'session_list', 'devices', + 'ensure-simulator', 'lease_allocate', 'lease_heartbeat', 'lease_release', diff --git a/src/daemon/handlers/session.ts b/src/daemon/handlers/session.ts index 9d97987299..7c2299f0fe 100644 --- a/src/daemon/handlers/session.ts +++ b/src/daemon/handlers/session.ts @@ -43,6 +43,7 @@ import { parseSelectorWaitPositionals, } from './session-replay-heal.ts'; import { parseReplayScript, writeReplayScript } from './session-replay-script.ts'; +import { ensureSimulatorExists } from '../../platforms/ios/ensure-simulator.ts'; type ReinstallOps = { ios: (device: DeviceInfo, app: string, appPath: string) => Promise<{ bundleId: string }>; @@ -99,12 +100,17 @@ function buildOpenResult(params: { appName?: string; appBundleId?: string; startup?: StartupPerfSample; + device?: DeviceInfo; }): Record { - const { sessionName, appName, appBundleId, startup } = params; + const { sessionName, appName, appBundleId, startup, device } = params; const result: Record = { session: sessionName }; if (appName) result.appName = appName; if (appBundleId) result.appBundleId = appBundleId; if (startup) result.startup = startup; + if (device?.platform === 'ios') { + result.device_udid = device.id; + result.ios_simulator_device_set = device.simulatorSetPath ?? null; + } return result; } @@ -593,6 +599,8 @@ async function handleAppStateCommand(params: { appName: appName ?? 'unknown', appBundleId: session.appBundleId, source: 'session', + device_udid: session.device.id, + ios_simulator_device_set: session.device.simulatorSetPath ?? null, }, }; } @@ -741,11 +749,51 @@ export async function handleSessionCommands(params: { device: s.device.name, id: s.device.id, createdAt: s.createdAt, + ...(s.device.platform === 'ios' && { + device_udid: s.device.id, + ios_simulator_device_set: s.device.simulatorSetPath ?? null, + }), })), }; return { ok: true, data }; } + if (command === 'ensure-simulator') { + try { + const flags = req.flags ?? {}; + const deviceName = flags.device; + const runtime = flags.runtime; + const iosSimulatorSetPath = resolveIosSimulatorDeviceSetPath(flags.iosSimulatorDeviceSet); + if (!deviceName) { + return { ok: false, error: { code: 'INVALID_ARGS', message: 'ensure-simulator requires --device ' } }; + } + const shouldBoot = flags.boot === true; + const reuseExisting = flags.reuseExisting !== false; + const result = await ensureSimulatorExists({ + deviceName, + runtime, + simulatorSetPath: iosSimulatorSetPath, + reuseExisting, + boot: shouldBoot, + ensureReady, + }); + return { + ok: true, + data: { + udid: result.udid, + device: result.device, + runtime: result.runtime, + ios_simulator_device_set: iosSimulatorSetPath ?? null, + created: result.created, + booted: result.booted, + }, + }; + } catch (err) { + const appErr = asAppError(err); + return { ok: false, error: { code: appErr.code, message: appErr.message, details: appErr.details } }; + } + } + if (command === 'devices') { try { const devices: DeviceInfo[] = []; @@ -1127,6 +1175,7 @@ export async function handleSessionCommands(params: { appName: openTarget, appBundleId, startup: startupSample, + device: session.device, }); sessionStore.recordAction(nextSession, { command, @@ -1205,6 +1254,7 @@ export async function handleSessionCommands(params: { appName: openTarget, appBundleId, startup: startupSample, + device, }); sessionStore.recordAction(session, { command, diff --git a/src/platforms/ios/ensure-simulator.ts b/src/platforms/ios/ensure-simulator.ts new file mode 100644 index 0000000000..28721b6fb5 --- /dev/null +++ b/src/platforms/ios/ensure-simulator.ts @@ -0,0 +1,177 @@ +import { AppError } from '../../utils/errors.ts'; +import { runCmd } from '../../utils/exec.ts'; +import type { DeviceInfo } from '../../utils/device.ts'; +import { buildSimctlArgs } from './simctl.ts'; +import { IOS_SIMCTL_LIST_TIMEOUT_MS } from './config.ts'; + +type SimctlDeviceRecord = { + name: string; + udid: string; + state: string; + isAvailable: boolean; +}; + +type SimctlListPayload = { + devices: Record; +}; + +export type EnsureSimulatorResult = { + udid: string; + device: string; + runtime: string; + created: boolean; + booted: boolean; +}; + +type EnsureSimulatorOptions = { + deviceName: string; + runtime?: string; + simulatorSetPath?: string | null; + reuseExisting: boolean; + boot: boolean; + ensureReady: (device: DeviceInfo) => Promise; +}; + +export async function ensureSimulatorExists(options: EnsureSimulatorOptions): Promise { + const { deviceName, runtime, simulatorSetPath, reuseExisting, boot, ensureReady } = options; + + if (process.platform !== 'darwin') { + throw new AppError('UNSUPPORTED_PLATFORM', 'ensure-simulator is only available on macOS'); + } + + const simctlOpts = { simulatorSetPath: simulatorSetPath ?? undefined }; + let udid: string; + let resolvedRuntime: string; + let created: boolean; + + if (reuseExisting) { + const existing = await findExistingSimulator({ deviceName, runtime, simctlOpts }); + if (existing) { + udid = existing.udid; + resolvedRuntime = existing.runtime; + created = false; + } else { + const result = await createSimulator({ deviceName, runtime, simctlOpts }); + udid = result.udid; + resolvedRuntime = await resolveSimulatorRuntime(udid, simctlOpts); + created = true; + } + } else { + const result = await createSimulator({ deviceName, runtime, simctlOpts }); + udid = result.udid; + resolvedRuntime = await resolveSimulatorRuntime(udid, simctlOpts); + created = true; + } + + let booted = false; + if (boot) { + const device: DeviceInfo = { + platform: 'ios', + id: udid, + name: deviceName, + kind: 'simulator', + target: 'mobile', + ...(simulatorSetPath ? { simulatorSetPath } : {}), + }; + await ensureReady(device); + booted = true; + } + + return { udid, device: deviceName, runtime: resolvedRuntime, created, booted }; +} + +type FindOptions = { + deviceName: string; + runtime?: string; + simctlOpts: { simulatorSetPath?: string }; +}; + +async function findExistingSimulator( + options: FindOptions, +): Promise<{ udid: string; runtime: string } | null> { + const { deviceName, runtime, simctlOpts } = options; + const result = await runCmd('xcrun', buildSimctlArgs(['list', 'devices', '-j'], simctlOpts), { + allowFailure: true, + timeoutMs: IOS_SIMCTL_LIST_TIMEOUT_MS, + }); + if (result.exitCode !== 0) return null; + + try { + const payload = JSON.parse(String(result.stdout ?? '')) as SimctlListPayload; + for (const [runtimeKey, devices] of Object.entries(payload.devices ?? {})) { + if (runtime && !normalizeRuntime(runtimeKey).includes(normalizeRuntime(runtime))) continue; + for (const device of devices) { + if (!device.isAvailable) continue; + if (device.name.toLowerCase() === deviceName.toLowerCase()) { + return { udid: device.udid, runtime: runtimeKey }; + } + } + } + return null; + } catch { + return null; + } +} + +type CreateOptions = { + deviceName: string; + runtime?: string; + simctlOpts: { simulatorSetPath?: string }; +}; + +async function createSimulator(options: CreateOptions): Promise<{ udid: string }> { + const { deviceName, runtime, simctlOpts } = options; + const createArgs = runtime + ? ['create', deviceName, deviceName, runtime] + : ['create', deviceName, deviceName]; + + const result = await runCmd('xcrun', buildSimctlArgs(createArgs, simctlOpts), { + allowFailure: true, + }); + + if (result.exitCode !== 0) { + throw new AppError('COMMAND_FAILED', 'Failed to create iOS simulator', { + deviceName, + runtime, + stdout: String(result.stdout ?? ''), + stderr: String(result.stderr ?? ''), + exitCode: result.exitCode, + hint: 'Ensure the device type and runtime identifiers are valid. Run `xcrun simctl list devicetypes` and `xcrun simctl list runtimes` to see available options.', + }); + } + + const udid = String(result.stdout ?? '').trim(); + if (!udid) { + throw new AppError('COMMAND_FAILED', 'simctl create returned no UDID', { + deviceName, + runtime, + stdout: String(result.stdout ?? ''), + stderr: String(result.stderr ?? ''), + }); + } + return { udid }; +} + +async function resolveSimulatorRuntime( + udid: string, + simctlOpts: { simulatorSetPath?: string }, +): Promise { + const result = await runCmd('xcrun', buildSimctlArgs(['list', 'devices', '-j'], simctlOpts), { + allowFailure: true, + timeoutMs: IOS_SIMCTL_LIST_TIMEOUT_MS, + }); + if (result.exitCode !== 0) return ''; + try { + const payload = JSON.parse(String(result.stdout ?? '')) as SimctlListPayload; + for (const [runtimeKey, devices] of Object.entries(payload.devices ?? {})) { + if (devices.some((d) => d.udid === udid)) return runtimeKey; + } + return ''; + } catch { + return ''; + } +} + +function normalizeRuntime(runtime: string): string { + return runtime.toLowerCase().replace(/[._-]/g, ''); +} diff --git a/src/utils/command-schema.ts b/src/utils/command-schema.ts index 3373bbfa20..5cab7e7d5b 100644 --- a/src/utils/command-schema.ts +++ b/src/utils/command-schema.ts @@ -18,6 +18,9 @@ export type CliFlags = { androidDeviceAllowlist?: string; out?: string; session?: string; + runtime?: string; + boot?: boolean; + reuseExisting?: boolean; verbose?: boolean; snapshotInteractiveOnly?: boolean; snapshotCompact?: boolean; @@ -191,6 +194,27 @@ const FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageLabel: '--headless', usageDescription: 'Boot: launch Android emulator without a GUI window', }, + { + key: 'runtime', + names: ['--runtime'], + type: 'string', + usageLabel: '--runtime ', + usageDescription: 'ensure-simulator: CoreSimulator runtime identifier (e.g. com.apple.CoreSimulator.SimRuntime.iOS-18-0)', + }, + { + key: 'boot', + names: ['--boot'], + type: 'boolean', + usageLabel: '--boot', + usageDescription: 'ensure-simulator: boot the simulator after ensuring it exists', + }, + { + key: 'reuseExisting', + names: ['--reuse-existing'], + type: 'boolean', + usageLabel: '--reuse-existing', + usageDescription: 'ensure-simulator: reuse an existing simulator (default: true)', + }, { key: 'iosSimulatorDeviceSet', names: ['--ios-simulator-device-set'], @@ -508,6 +532,12 @@ const COMMAND_SCHEMAS: Record = { positionalArgs: ['kind'], allowedFlags: [...SNAPSHOT_FLAGS], }, + 'ensure-simulator': { + description: 'Ensure an iOS simulator exists in a device set (create if missing)', + positionalArgs: [], + allowedFlags: ['runtime', 'boot', 'reuseExisting'], + skipCapabilityCheck: true, + }, devices: { description: 'List available devices', positionalArgs: [], diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 18bdab0f5c..aaa30e310b 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -54,6 +54,22 @@ agent-device devices --platform android --android-device-allowlist emulator-5554 - Android: `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST` (compat: `ANDROID_DEVICE_ALLOWLIST`) - CLI scope flags override environment values. +## Simulator provisioning + +```bash +agent-device ensure-simulator --device "iPhone 16" --platform ios +agent-device ensure-simulator --device "iPhone 16" --runtime com.apple.CoreSimulator.SimRuntime.iOS-18-4 --ios-simulator-device-set /tmp/tenant-a/simulators +agent-device ensure-simulator --device "iPhone 16" --ios-simulator-device-set /tmp/tenant-a/simulators --boot +``` + +- `ensure-simulator` ensures a named iOS simulator exists inside a device set, creating it via `simctl create` if missing. +- Requires `--device ` (the simulator name / device type, e.g. `"iPhone 16 Pro"`). +- `--runtime ` pins a specific CoreSimulator runtime (e.g. `com.apple.CoreSimulator.SimRuntime.iOS-18-4`). Omit to use the newest compatible runtime. +- `--boot` boots the simulator after ensuring it exists. +- Reuse of an existing matching simulator is the default; the command is idempotent. +- JSON output includes `udid`, `device`, `runtime`, `ios_simulator_device_set`, `created`, and `booted`. +- Does not require an active session — safe to call before `open`. + ## TV targets ```bash