diff --git a/README.md b/README.md index 89390b6e15..328267aa66 100644 --- a/README.md +++ b/README.md @@ -209,6 +209,8 @@ Flags: - `--device ` - `--udid ` (iOS) - `--serial ` (Android) +- `--ios-simulator-device-set ` constrain iOS simulator discovery/commands to one simulator set (`xcrun simctl --set`) +- `--android-device-allowlist ` constrain Android discovery/selection to comma/space-separated serials - `--activity ` (Android app launch only; package/Activity or package/.Activity; not for URL opens) - `--session ` - `--state-dir ` daemon state directory override (default: `~/.agent-device`) @@ -232,6 +234,11 @@ Flags: - `--on-error stop` batch: stop when a step fails - `--max-steps ` batch: max allowed steps per request +Isolation precedence: +- Discovery scope (`--ios-simulator-device-set`, `--android-device-allowlist`) is applied before selector matching (`--device`, `--udid`, `--serial`). +- If a selector points outside the scoped set/allowlist, command resolution fails with `DEVICE_NOT_FOUND` (no host-global fallback). +- When `--ios-simulator-device-set` is set (or its env equivalent), iOS discovery is simulator-set only (physical iOS devices are not enumerated). + TV targets: - Use `--target tv` together with `--platform ios|android|apple`. - TV target selection supports both simulator/emulator and connected physical devices (AppleTV + AndroidTV). @@ -465,6 +472,9 @@ pnpm build Environment selectors: - `ANDROID_DEVICE=Pixel_9_Pro_XL` or `ANDROID_SERIAL=emulator-5554` - `IOS_DEVICE="iPhone 17 Pro"` or `IOS_UDID=` +- `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET=` (or `IOS_SIMULATOR_DEVICE_SET=`) to scope all iOS simulator discovery/commands to one simulator set. +- `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST=` (or `ANDROID_DEVICE_ALLOWLIST=`) to scope Android discovery to allowlisted serials. +- CLI flags `--ios-simulator-device-set` / `--android-device-allowlist` override environment values. - `AGENT_DEVICE_IOS_BOOT_TIMEOUT_MS=` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`). - `AGENT_DEVICE_DAEMON_TIMEOUT_MS=` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`). - `AGENT_DEVICE_STATE_DIR=` override daemon state directory (metadata, logs, session artifacts). diff --git a/skills/agent-device/SKILL.md b/skills/agent-device/SKILL.md index dc2219b323..f5b0340a7c 100644 --- a/skills/agent-device/SKILL.md +++ b/skills/agent-device/SKILL.md @@ -26,6 +26,7 @@ Use this skill as a router, not a full manual. - Debug/crash: `open ` -> `logs clear --restart` -> reproduce -> `network dump` -> `logs path` -> targeted `grep` - Replay drift: `replay -u ` -> verify updated selectors - Remote multi-tenant run: allocate lease -> run commands with tenant isolation flags -> heartbeat/release lease +- Device-scope isolation run: set iOS simulator set / Android allowlist -> run selectors within scope only ## Canonical Flows @@ -92,6 +93,8 @@ curl -sS http://127.0.0.1:${AGENT_DEVICE_DAEMON_HTTP_PORT}/rpc \ ```bash 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 open [app|url] [url] agent-device open [app] --relaunch agent-device close [app] @@ -103,6 +106,12 @@ For Android emulators by AVD name, use `boot --platform android --device ` scopes iOS simulator discovery + command execution to one simulator set. +- `--android-device-allowlist ` scopes Android discovery/selection to comma/space separated serials. +- 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. + TV quick reference: - AndroidTV: `open`/`apps` use TV launcher discovery automatically. - TV target selection works on emulators/simulators and connected physical devices (AndroidTV + AppleTV). @@ -172,6 +181,8 @@ agent-device batch --steps-file /tmp/batch-steps.json --json - If using `--save-script`, prefer explicit path syntax (`--save-script=flow.ad` or `./flow.ad`). - For tenant-isolated remote runs, always pass `--tenant`, `--session-isolation tenant`, `--run-id`, and `--lease-id` together. - Use short lease TTLs and heartbeat only while work is active; release leases immediately after run completion/failure. +- Env equivalents for scoped runs: `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` (compat `IOS_SIMULATOR_DEVICE_SET`) and + `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST` (compat `ANDROID_DEVICE_ALLOWLIST`). ## Security and Trust Notes diff --git a/skills/agent-device/references/session-management.md b/skills/agent-device/references/session-management.md index 200501d7ee..0679c30f18 100644 --- a/skills/agent-device/references/session-management.md +++ b/skills/agent-device/references/session-management.md @@ -25,6 +25,22 @@ Sessions isolate device context. A device can only be held by one session at a t - For deterministic replay scripts, prefer selector-based actions and assertions. - Use `replay -u` to update selector drift during maintenance. +## Scoped device isolation + +Use scoped discovery when sessions must not see host-global device lists. + +```bash +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 +``` + +- Scope is applied before selectors (`--device`, `--udid`, `--serial`). +- If selector target is outside scope, resolution fails with `DEVICE_NOT_FOUND`. +- With iOS simulator-set scope enabled, iOS physical devices are not enumerated. +- Environment equivalents: + - `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` (compat: `IOS_SIMULATOR_DEVICE_SET`) + - `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST` (compat: `ANDROID_DEVICE_ALLOWLIST`) + ## Listing sessions ```bash diff --git a/src/core/dispatch.ts b/src/core/dispatch.ts index 02939b9679..e7432ee286 100644 --- a/src/core/dispatch.ts +++ b/src/core/dispatch.ts @@ -28,6 +28,7 @@ import type { RawSnapshotNode } from '../utils/snapshot.ts'; import type { CliFlags } from '../utils/command-schema.ts'; import { emitDiagnostic, withDiagnosticTimer } from '../utils/diagnostics.ts'; import { resolvePayloadInput } from '../utils/payload-input.ts'; +import { resolveAndroidSerialAllowlist, resolveIosSimulatorDeviceSetPath } from '../utils/device-isolation.ts'; export type BatchStep = { command: string; @@ -41,6 +42,8 @@ export type CommandFlags = Omit { const normalizedPlatform = normalizePlatformSelector(flags.platform); + const iosSimulatorSetPath = resolveIosSimulatorDeviceSetPath(flags.iosSimulatorDeviceSet); + const androidSerialAllowlist = resolveAndroidSerialAllowlist(flags.androidDeviceAllowlist); return await withDiagnosticTimer( 'resolve_target_device', async () => { @@ -60,23 +63,23 @@ export async function resolveTargetDevice(flags: CommandFlags): Promise { err.message.includes('--device=thymikee-iphone'), ); }); + +test('accepts matching ios simulator set selector for iOS simulator sessions', () => { + const session = makeSession({ + device: { + platform: 'ios', + id: 'sim-1', + name: 'iPhone 17', + kind: 'simulator', + target: 'mobile', + booted: true, + simulatorSetPath: '/tmp/tenant-a/simulator-set', + }, + }); + assert.doesNotThrow(() => + assertSessionSelectorMatches(session, { iosSimulatorDeviceSet: '/tmp/tenant-a/simulator-set' }), + ); +}); + +test('rejects android allowlist selector when session device is not allowlisted', () => { + const session = makeSession(); + assert.throws( + () => assertSessionSelectorMatches(session, { androidDeviceAllowlist: 'emulator-9999' }), + (err: unknown) => + err instanceof AppError && + err.code === 'INVALID_ARGS' && + err.message.includes('--android-device-allowlist=emulator-9999'), + ); +}); diff --git a/src/daemon/handlers/record-trace.ts b/src/daemon/handlers/record-trace.ts index 81d3b5c4e9..daaca57495 100644 --- a/src/daemon/handlers/record-trace.ts +++ b/src/daemon/handlers/record-trace.ts @@ -4,6 +4,7 @@ import { runCmd, runCmdBackground } from '../../utils/exec.ts'; import { resolveTargetDevice, type CommandFlags } from '../../core/dispatch.ts'; import { isCommandSupportedOnDevice } from '../../core/capabilities.ts'; import { runIosRunnerCommand, IOS_RUNNER_CONTAINER_BUNDLE_IDS } from '../../platforms/ios/runner-client.ts'; +import { buildSimctlArgsForDevice } from '../../platforms/ios/simctl.ts'; import type { DaemonRequest, DaemonResponse, SessionState } from '../types.ts'; import { SessionStore } from '../session-store.ts'; import { ensureDeviceReady } from '../device-ready.ts'; @@ -185,7 +186,7 @@ export async function handleRecordTraceCommands(params: { } activeSession.recording = { platform: 'ios-device-runner', outPath: resolvedOut, remotePath }; } else if (device.platform === 'ios') { - const { child, wait } = deps.runCmdBackground('xcrun', ['simctl', 'io', device.id, 'recordVideo', resolvedOut], { + const { child, wait } = deps.runCmdBackground('xcrun', buildSimctlArgsForDevice(device, ['io', device.id, 'recordVideo', resolvedOut]), { allowFailure: true, }); activeSession.recording = { platform: 'ios', outPath: resolvedOut, child, wait }; diff --git a/src/daemon/handlers/session.ts b/src/daemon/handlers/session.ts index 77a3a72291..8b148ba98c 100644 --- a/src/daemon/handlers/session.ts +++ b/src/daemon/handlers/session.ts @@ -10,6 +10,7 @@ import { isCommandSupportedOnDevice } from '../../core/capabilities.ts'; import { isDeepLinkTarget, resolveIosDeviceDeepLinkBundleId } from '../../core/open-target.ts'; import { AppError, asAppError, normalizeError } from '../../utils/errors.ts'; import { normalizePlatformSelector, type DeviceInfo } from '../../utils/device.ts'; +import { resolveAndroidSerialAllowlist, resolveIosSimulatorDeviceSetPath } from '../../utils/device-isolation.ts'; import type { DaemonRequest, DaemonResponse, SessionAction, SessionState } from '../types.ts'; import { SessionStore } from '../session-store.ts'; import { contextFromFlags } from '../context.ts'; @@ -516,23 +517,25 @@ export async function handleSessionCommands(params: { if (command === 'devices') { try { const devices: DeviceInfo[] = []; + const iosSimulatorSetPath = resolveIosSimulatorDeviceSetPath(req.flags?.iosSimulatorDeviceSet); + const androidSerialAllowlist = resolveAndroidSerialAllowlist(req.flags?.androidDeviceAllowlist); const requestedPlatform = normalizePlatformSelector(req.flags?.platform); if (requestedPlatform === 'android') { const { listAndroidDevices } = await import('../../platforms/android/devices.ts'); - devices.push(...(await listAndroidDevices())); + devices.push(...(await listAndroidDevices({ serialAllowlist: androidSerialAllowlist }))); } else if (requestedPlatform === 'ios') { const { listIosDevices } = await import('../../platforms/ios/devices.ts'); - devices.push(...(await listIosDevices())); + devices.push(...(await listIosDevices({ simulatorSetPath: iosSimulatorSetPath }))); } else { const { listAndroidDevices } = await import('../../platforms/android/devices.ts'); const { listIosDevices } = await import('../../platforms/ios/devices.ts'); try { - devices.push(...(await listAndroidDevices())); + devices.push(...(await listAndroidDevices({ serialAllowlist: androidSerialAllowlist }))); } catch { // ignore } try { - devices.push(...(await listIosDevices())); + devices.push(...(await listIosDevices({ simulatorSetPath: iosSimulatorSetPath }))); } catch { // ignore } @@ -540,7 +543,8 @@ export async function handleSessionCommands(params: { const filtered = req.flags?.target ? devices.filter((device) => (device.target ?? 'mobile') === req.flags?.target) : devices; - return { ok: true, data: { devices: filtered } }; + const publicDevices = filtered.map(({ simulatorSetPath: _simulatorSetPath, ...device }) => device); + return { ok: true, data: { devices: publicDevices } }; } catch (err) { const appErr = asAppError(err); return { ok: false, error: { code: appErr.code, message: appErr.message, details: appErr.details } }; diff --git a/src/daemon/session-selector.ts b/src/daemon/session-selector.ts index e18f80eb0e..c18b847912 100644 --- a/src/daemon/session-selector.ts +++ b/src/daemon/session-selector.ts @@ -2,6 +2,7 @@ import { AppError } from '../utils/errors.ts'; import type { CommandFlags } from '../core/dispatch.ts'; import type { SessionState } from './types.ts'; import { normalizePlatformSelector } from '../utils/device.ts'; +import { parseSerialAllowlist } from '../utils/device-isolation.ts'; export function assertSessionSelectorMatches( session: SessionState, @@ -32,6 +33,25 @@ export function assertSessionSelectorMatches( mismatches.push(`--device=${flags.device}`); } + if (flags.iosSimulatorDeviceSet) { + const requestedSetPath = flags.iosSimulatorDeviceSet.trim(); + const sessionSetPath = device.simulatorSetPath?.trim(); + if ( + device.platform !== 'ios' + || device.kind !== 'simulator' + || requestedSetPath !== sessionSetPath + ) { + mismatches.push(`--ios-simulator-device-set=${flags.iosSimulatorDeviceSet}`); + } + } + + if (flags.androidDeviceAllowlist) { + const allowlist = parseSerialAllowlist(flags.androidDeviceAllowlist); + if (device.platform !== 'android' || !allowlist.has(device.id)) { + mismatches.push(`--android-device-allowlist=${flags.androidDeviceAllowlist}`); + } + } + if (mismatches.length === 0) return; throw new AppError( diff --git a/src/platforms/android/devices.ts b/src/platforms/android/devices.ts index 998e0130a6..b480263ea4 100644 --- a/src/platforms/android/devices.ts +++ b/src/platforms/android/devices.ts @@ -3,6 +3,7 @@ import type { ExecResult } from '../../utils/exec.ts'; import { AppError, asAppError } from '../../utils/errors.ts'; import type { DeviceInfo } from '../../utils/device.ts'; import { Deadline, retryWithPolicy, TIMEOUT_PROFILES } from '../../utils/retry.ts'; +import { resolveAndroidSerialAllowlist } from '../../utils/device-isolation.ts'; import { bootFailureHint, classifyBootFailure } from '../boot-diagnostics.ts'; const EMULATOR_SERIAL_PREFIX = 'emulator-'; @@ -16,6 +17,10 @@ const ANDROID_TV_FEATURES = [ 'android.hardware.type.television', ] as const; +type AndroidDeviceDiscoveryOptions = { + serialAllowlist?: ReadonlySet; +}; + function commandOutput(result: ExecResult): string { return `${result.stdout}\n${result.stderr}`; } @@ -136,15 +141,20 @@ async function resolveAndroidTarget(serial: string): Promise<'mobile' | 'tv'> { return 'mobile'; } -export async function listAndroidDevices(): Promise { +export async function listAndroidDevices(options: AndroidDeviceDiscoveryOptions = {}): Promise { const adbAvailable = await whichCmd('adb'); if (!adbAvailable) { throw new AppError('TOOL_MISSING', 'adb not found in PATH'); } + const serialAllowlist = + options.serialAllowlist + ?? resolveAndroidSerialAllowlist(undefined); const entries = await listAndroidDeviceEntries(); + const filteredEntries = entries.filter((entry) => + !serialAllowlist || serialAllowlist.has(entry.serial)); - const devices = await Promise.all(entries.map(async ({ serial, rawModel }) => { + const devices = await Promise.all(filteredEntries.map(async ({ serial, rawModel }) => { const [name, booted, target] = await Promise.all([ resolveAndroidDeviceName(serial, rawModel), isAndroidBooted(serial), diff --git a/src/platforms/ios/__tests__/simctl.test.ts b/src/platforms/ios/__tests__/simctl.test.ts new file mode 100644 index 0000000000..2d59455953 --- /dev/null +++ b/src/platforms/ios/__tests__/simctl.test.ts @@ -0,0 +1,35 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { buildSimctlArgs, buildSimctlArgsForDevice } from '../simctl.ts'; +import type { DeviceInfo } from '../../../utils/device.ts'; + +const IOS_SIMULATOR: DeviceInfo = { + platform: 'ios', + id: 'sim-1', + name: 'iPhone 17', + kind: 'simulator', + target: 'mobile', +}; + +test('buildSimctlArgs uses --set when simulator set path is provided', () => { + const args = buildSimctlArgs(['list', 'devices', '-j'], { + simulatorSetPath: '/tmp/tenant-a/simulator-set', + }); + assert.deepEqual(args, ['simctl', '--set', '/tmp/tenant-a/simulator-set', 'list', 'devices', '-j']); +}); + +test('buildSimctlArgsForDevice includes simulator set from device metadata', () => { + const args = buildSimctlArgsForDevice( + { ...IOS_SIMULATOR, simulatorSetPath: '/tmp/tenant-b/simulator-set' }, + ['bootstatus', 'sim-1', '-b'], + ); + assert.deepEqual(args, ['simctl', '--set', '/tmp/tenant-b/simulator-set', 'bootstatus', 'sim-1', '-b']); +}); + +test('buildSimctlArgsForDevice leaves non-simulator commands unchanged', () => { + const args = buildSimctlArgsForDevice( + { ...IOS_SIMULATOR, kind: 'device' }, + ['bootstatus', 'sim-1', '-b'], + ); + assert.deepEqual(args, ['simctl', 'bootstatus', 'sim-1', '-b']); +}); diff --git a/src/platforms/ios/apps.ts b/src/platforms/ios/apps.ts index 0646ca0020..1f294208dd 100644 --- a/src/platforms/ios/apps.ts +++ b/src/platforms/ios/apps.ts @@ -4,6 +4,7 @@ import path from 'node:path'; import type { DeviceInfo } from '../../utils/device.ts'; import { AppError } from '../../utils/errors.ts'; import { runCmd } from '../../utils/exec.ts'; +import { resolveIosSimulatorDeviceSetPath } from '../../utils/device-isolation.ts'; import { Deadline, retryWithPolicy } from '../../utils/retry.ts'; import { isDeepLinkTarget, resolveIosDeviceDeepLinkBundleId } from '../../core/open-target.ts'; import { @@ -23,12 +24,25 @@ import { } from './devicectl.ts'; import { runIosRunnerCommand, IOS_RUNNER_CONTAINER_BUNDLE_IDS } from './runner-client.ts'; import { ensureBootedSimulator, ensureSimulator, getSimulatorState } from './simulator.ts'; +import { buildSimctlArgsForDevice } from './simctl.ts'; const ALIASES: Record = { settings: 'com.apple.Preferences', }; let cachedSimctlPrivacyServices: Set | null = null; -let cachedSimctlPrivacyServicesPath: string | undefined; +let cachedSimctlPrivacyServicesCacheKey: string | undefined; + +function simctlArgs(device: DeviceInfo, args: string[]): string[] { + return buildSimctlArgsForDevice(device, args); +} + +function runSimctl( + device: DeviceInfo, + args: string[], + options?: Parameters[2], +) { + return runCmd('xcrun', simctlArgs(device, args), options); +} function isMissingAppErrorOutput(output: string): boolean { return output.includes('not installed') || output.includes('not found') || output.includes('no such file'); @@ -67,7 +81,7 @@ export async function openIosApp( if (device.kind === 'simulator') { await ensureBootedSimulator(device); await runCmd('open', ['-a', 'Simulator'], { allowFailure: true }); - await runCmd('xcrun', ['simctl', 'openurl', device.id, explicitUrl]); + await runSimctl(device, ['openurl', device.id, explicitUrl]); return; } const appBundleId = options?.appBundleId ?? (await resolveIosApp(device, app)); @@ -87,7 +101,7 @@ export async function openIosApp( if (device.kind === 'simulator') { await ensureBootedSimulator(device); await runCmd('open', ['-a', 'Simulator'], { allowFailure: true }); - await runCmd('xcrun', ['simctl', 'openurl', device.id, deepLinkTarget]); + await runSimctl(device, ['openurl', device.id, deepLinkTarget]); return; } const bundleId = resolveIosDeviceDeepLinkBundleId(options?.appBundleId, deepLinkTarget); @@ -112,7 +126,7 @@ export async function openIosApp( export async function openIosDevice(device: DeviceInfo): Promise { if (device.kind !== 'simulator') return; - const state = await getSimulatorState(device.id); + const state = await getSimulatorState(device); if (state === 'Booted') return; await ensureBootedSimulator(device); @@ -123,7 +137,8 @@ export async function closeIosApp(device: DeviceInfo, app: string): Promise { if (device.kind === 'simulator') { await ensureBootedSimulator(device); - await runCmd('xcrun', ['simctl', 'io', device.id, 'screenshot', outPath]); + await runSimctl(device, ['io', device.id, 'screenshot', outPath]); return; } @@ -293,7 +308,7 @@ export function shouldFallbackToRunnerForIosScreenshot(error: unknown): boolean export async function readIosClipboardText(device: DeviceInfo): Promise { ensureSimulator(device, 'clipboard'); await ensureBootedSimulator(device); - const result = await runCmd('xcrun', ['simctl', 'pbpaste', device.id], { allowFailure: true }); + const result = await runSimctl(device, ['pbpaste', device.id], { allowFailure: true }); if (result.exitCode !== 0) { throw new AppError('COMMAND_FAILED', 'Failed to read iOS simulator clipboard', { stdout: result.stdout, @@ -307,7 +322,7 @@ export async function readIosClipboardText(device: DeviceInfo): Promise export async function writeIosClipboardText(device: DeviceInfo, text: string): Promise { ensureSimulator(device, 'clipboard'); await ensureBootedSimulator(device); - const result = await runCmd('xcrun', ['simctl', 'pbcopy', device.id], { + const result = await runSimctl(device, ['pbcopy', device.id], { allowFailure: true, stdin: text, }); @@ -331,7 +346,7 @@ export async function pushIosNotification( const payloadPath = path.join(tempDir, 'payload.apns'); try { await fs.writeFile(payloadPath, `${JSON.stringify(payload)}\n`, 'utf8'); - await runCmd('xcrun', ['simctl', 'push', device.id, bundleId, payloadPath]); + await runSimctl(device, ['push', device.id, bundleId, payloadPath]); } finally { await fs.rm(tempDir, { recursive: true, force: true }); } @@ -352,14 +367,13 @@ export async function setIosSetting( case 'wifi': { const enabled = parseSettingState(state); const mode = enabled ? 'active' : 'failed'; - await runCmd('xcrun', ['simctl', 'status_bar', device.id, 'override', '--wifiMode', mode]); + await runSimctl(device, ['status_bar', device.id, 'override', '--wifiMode', mode]); return; } case 'airplane': { const enabled = parseSettingState(state); if (enabled) { - await runCmd('xcrun', [ - 'simctl', + await runSimctl(device, [ 'status_bar', device.id, 'override', @@ -377,7 +391,7 @@ export async function setIosSetting( '', ]); } else { - await runCmd('xcrun', ['simctl', 'status_bar', device.id, 'clear']); + await runSimctl(device, ['status_bar', device.id, 'clear']); } return; } @@ -387,7 +401,7 @@ export async function setIosSetting( throw new AppError('INVALID_ARGS', 'location setting requires an active app in session'); } const action = enabled ? 'grant' : 'revoke'; - await runCmd('xcrun', ['simctl', 'privacy', device.id, action, 'location', appBundleId]); + await runSimctl(device, ['privacy', device.id, action, 'location', appBundleId]); return; } case 'faceid': @@ -395,7 +409,7 @@ export async function setIosSetting( const biometricSetting = normalized as IosBiometricSetting; const biometric = IOS_BIOMETRIC_SETTINGS[biometricSetting]; const action = parseBiometricAction(state, biometricSetting); - await runIosBiometricSimctlCommand(device.id, action, { + await runIosBiometricSimctlCommand(device, action, { settingName: biometricSetting, label: biometric.label, modalityAliases: biometric.modalityAliases, @@ -403,8 +417,8 @@ export async function setIosSetting( return; } case 'appearance': { - const target = await resolveIosAppearanceTarget(device.id, state); - await runCmd('xcrun', ['simctl', 'ui', device.id, 'appearance', target]); + const target = await resolveIosAppearanceTarget(device, state); + await runSimctl(device, ['ui', device.id, 'appearance', target]); return; } case 'permission': { @@ -416,7 +430,7 @@ export async function setIosSetting( } const action = mapIosPermissionAction(parsePermissionAction(state)); const target = parseIosPermissionTarget(options?.permissionTarget, options?.permissionMode); - await runIosPrivacyCommand(device.id, action, target, appBundleId); + await runIosPrivacyCommand(device, action, target, appBundleId); return; } default: @@ -436,7 +450,7 @@ export async function listIosApps( } export async function listSimulatorApps(device: DeviceInfo): Promise { - const result = await runCmd('xcrun', ['simctl', 'listapps', device.id], { allowFailure: true }); + const result = await runSimctl(device, ['listapps', device.id], { allowFailure: true }); const stdout = result.stdout as string; const trimmed = stdout.trim(); if (!trimmed) return []; @@ -481,11 +495,11 @@ function parseSettingState(state: string): boolean { throw new AppError('INVALID_ARGS', `Invalid setting state: ${state}`); } -async function resolveIosAppearanceTarget(deviceId: string, state: string): Promise<'light' | 'dark'> { +async function resolveIosAppearanceTarget(device: DeviceInfo, state: string): Promise<'light' | 'dark'> { const action = parseAppearanceAction(state); if (action !== 'toggle') return action; - const currentResult = await runCmd('xcrun', ['simctl', 'ui', deviceId, 'appearance'], { + const currentResult = await runSimctl(device, ['ui', device.id, 'appearance'], { allowFailure: true, }); if (currentResult.exitCode !== 0) { @@ -531,29 +545,29 @@ function mapIosPermissionAction(action: 'grant' | 'deny' | 'reset'): 'grant' | ' } async function runIosPrivacyCommand( - deviceId: string, + device: DeviceInfo, action: 'grant' | 'revoke' | 'reset', target: string, appBundleId: string, ): Promise { - const supportedServices = await getSimctlPrivacyServices(); + const supportedServices = await getSimctlPrivacyServices(device); if (!supportedServices.has(target)) { throw new AppError( 'UNSUPPORTED_OPERATION', `iOS simctl privacy does not support service "${target}" on this runtime.`, { - deviceId, + deviceId: device.id, appBundleId, hint: `Supported services: ${Array.from(supportedServices).sort().join(', ')}`, }, ); } - const args = ['simctl', 'privacy', deviceId, action, target, appBundleId]; + const args = ['privacy', device.id, action, target, appBundleId]; const isNotificationsTarget = target === 'notifications'; if (!(action === 'reset' && isNotificationsTarget)) { try { - await runCmd('xcrun', args); + await runSimctl(device, args); return; } catch (error) { if (!(isNotificationsTarget && isNotificationsOperationNotPermitted(error))) { @@ -563,7 +577,7 @@ async function runIosPrivacyCommand( 'UNSUPPORTED_OPERATION', 'iOS simulator does not support setting notifications permission via simctl privacy on this runtime.', { - deviceId, + deviceId: device.id, appBundleId, hint: 'Use reset notifications for reprompt behavior, or toggle notifications manually in Settings.', }, @@ -572,7 +586,7 @@ async function runIosPrivacyCommand( } try { - await runCmd('xcrun', args); + await runSimctl(device, args); return; } catch (error) { if (!isNotificationsOperationNotPermitted(error)) { @@ -581,13 +595,13 @@ async function runIosPrivacyCommand( } try { - await runCmd('xcrun', ['simctl', 'privacy', deviceId, 'reset', 'all', appBundleId]); + await runSimctl(device, ['privacy', device.id, 'reset', 'all', appBundleId]); } catch (error) { throw new AppError( 'COMMAND_FAILED', 'iOS simulator blocked direct notifications reset. Fallback reset-all also failed.', { - deviceId, + deviceId: device.id, appBundleId, hint: 'Use reinstall to force a fresh notifications prompt, or reset simulator content and settings.', }, @@ -607,12 +621,13 @@ function isNotificationsOperationNotPermitted(error: unknown): boolean { ); } -async function getSimctlPrivacyServices(): Promise> { - const currentPath = process.env.PATH; - if (cachedSimctlPrivacyServices && cachedSimctlPrivacyServicesPath === currentPath) { +async function getSimctlPrivacyServices(device: DeviceInfo): Promise> { + const simulatorSetPath = resolveIosSimulatorDeviceSetPath(device.simulatorSetPath); + const currentCacheKey = `${process.env.PATH ?? ''}::${simulatorSetPath ?? ''}`; + if (cachedSimctlPrivacyServices && cachedSimctlPrivacyServicesCacheKey === currentCacheKey) { return cachedSimctlPrivacyServices; } - const result = await runCmd('xcrun', ['simctl', 'privacy', 'help'], { allowFailure: true }); + const result = await runSimctl(device, ['privacy', 'help'], { allowFailure: true }); const services = parseSimctlPrivacyServices(`${result.stdout}\n${result.stderr}`); if (services.size === 0) { throw new AppError('COMMAND_FAILED', 'Unable to determine supported simctl privacy services', { @@ -623,7 +638,7 @@ async function getSimctlPrivacyServices(): Promise> { }); } cachedSimctlPrivacyServices = services; - cachedSimctlPrivacyServicesPath = currentPath; + cachedSimctlPrivacyServicesCacheKey = currentCacheKey; return services; } @@ -695,18 +710,19 @@ function parseBiometricAction( } async function runIosBiometricSimctlCommand( - deviceId: string, + device: DeviceInfo, action: IosBiometricAction, options: { settingName: IosBiometricSetting; label: 'Face ID' | 'Touch ID'; modalityAliases: string[] }, ): Promise { - const attempts = biometricCommandAttempts(deviceId, action, options.modalityAliases); + const attempts = biometricCommandAttempts(device.id, action, options.modalityAliases); const failures: Array<{ args: string[]; stderr: string; stdout: string; exitCode: number }> = []; for (const args of attempts) { - const result = await runCmd('xcrun', args, { allowFailure: true }); + const commandArgs = simctlArgs(device, args); + const result = await runCmd('xcrun', commandArgs, { allowFailure: true }); if (result.exitCode === 0) return; failures.push({ - args, + args: commandArgs, stderr: result.stderr, stdout: result.stdout, exitCode: result.exitCode, @@ -726,7 +742,7 @@ async function runIosBiometricSimctlCommand( 'UNSUPPORTED_OPERATION', `${options.label} simulation is not supported on this simulator runtime.`, { - deviceId, + deviceId: device.id, action, setting: options.settingName, attempts: attemptsPayload, @@ -734,7 +750,7 @@ async function runIosBiometricSimctlCommand( ); } throw new AppError('COMMAND_FAILED', `Failed to simulate ${options.settingName}.`, { - deviceId, + deviceId: device.id, action, setting: options.settingName, attempts: attemptsPayload, @@ -750,29 +766,29 @@ function biometricCommandAttempts( switch (action) { case 'match': return modalities.flatMap((modality) => [ - ['simctl', 'biometric', deviceId, 'match', modality], - ['simctl', 'biometric', 'match', deviceId, modality], + ['biometric', deviceId, 'match', modality], + ['biometric', 'match', deviceId, modality], ]); case 'nonmatch': return modalities.flatMap((modality) => [ - ['simctl', 'biometric', deviceId, 'nonmatch', modality], - ['simctl', 'biometric', deviceId, 'nomatch', modality], - ['simctl', 'biometric', 'nonmatch', deviceId, modality], - ['simctl', 'biometric', 'nomatch', deviceId, modality], + ['biometric', deviceId, 'nonmatch', modality], + ['biometric', deviceId, 'nomatch', modality], + ['biometric', 'nonmatch', deviceId, modality], + ['biometric', 'nomatch', deviceId, modality], ]); case 'enroll': return [ - ['simctl', 'biometric', deviceId, 'enroll', 'yes'], - ['simctl', 'biometric', deviceId, 'enroll', '1'], - ['simctl', 'biometric', 'enroll', deviceId, 'yes'], - ['simctl', 'biometric', 'enroll', deviceId, '1'], + ['biometric', deviceId, 'enroll', 'yes'], + ['biometric', deviceId, 'enroll', '1'], + ['biometric', 'enroll', deviceId, 'yes'], + ['biometric', 'enroll', deviceId, '1'], ]; case 'unenroll': return [ - ['simctl', 'biometric', deviceId, 'enroll', 'no'], - ['simctl', 'biometric', deviceId, 'enroll', '0'], - ['simctl', 'biometric', 'enroll', deviceId, 'no'], - ['simctl', 'biometric', 'enroll', deviceId, '0'], + ['biometric', deviceId, 'enroll', 'no'], + ['biometric', deviceId, 'enroll', '0'], + ['biometric', 'enroll', deviceId, 'no'], + ['biometric', 'enroll', deviceId, '0'], ]; } } @@ -815,14 +831,15 @@ async function launchIosSimulatorApp(device: DeviceInfo, bundleId: string): Prom }); } - const result = await runCmd('xcrun', ['simctl', 'launch', device.id, bundleId], { + const launchArgs = simctlArgs(device, ['launch', device.id, bundleId]); + const result = await runCmd('xcrun', launchArgs, { allowFailure: true, }); if (result.exitCode === 0) return; throw new AppError('COMMAND_FAILED', `xcrun exited with code ${result.exitCode}`, { cmd: 'xcrun', - args: ['simctl', 'launch', device.id, bundleId], + args: launchArgs, stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode, diff --git a/src/platforms/ios/devices.ts b/src/platforms/ios/devices.ts index 376d38ff45..37d7793c41 100644 --- a/src/platforms/ios/devices.ts +++ b/src/platforms/ios/devices.ts @@ -5,6 +5,8 @@ import { runCmd, whichCmd } from '../../utils/exec.ts'; import { AppError } from '../../utils/errors.ts'; import type { DeviceInfo, DeviceTarget } from '../../utils/device.ts'; import { resolveTimeoutMs } from '../../utils/timeouts.ts'; +import { resolveIosSimulatorDeviceSetPath } from '../../utils/device-isolation.ts'; +import { buildSimctlArgs } from './simctl.ts'; const IOS_DEVICECTL_LIST_TIMEOUT_MS = resolveTimeoutMs( process.env.AGENT_DEVICE_IOS_DEVICECTL_LIST_TIMEOUT_MS, @@ -40,6 +42,10 @@ type DevicectlListDevicesPayload = { }; }; +type IosDeviceDiscoveryOptions = { + simulatorSetPath?: string; +}; + function normalizeAppleDescriptor(value: string | undefined): string { return (value ?? '').trim().toLowerCase(); } @@ -106,7 +112,7 @@ export function isSupportedAppleDevicectlDevice(device: DevicectlAppleDevice): b return resolveDevicectlAppleLabels(device).some(isAppleTvLabel); } -export async function listIosDevices(): Promise { +export async function listIosDevices(options: IosDeviceDiscoveryOptions = {}): Promise { if (process.platform !== 'darwin') { throw new AppError('UNSUPPORTED_PLATFORM', 'iOS tools are only available on macOS'); } @@ -117,8 +123,9 @@ export async function listIosDevices(): Promise { } const devices: DeviceInfo[] = []; + const simulatorSetPath = resolveIosSimulatorDeviceSetPath(options.simulatorSetPath); - const simResult = await runCmd('xcrun', ['simctl', 'list', 'devices', '-j']); + const simResult = await runCmd('xcrun', buildSimctlArgs(['list', 'devices', '-j'], { simulatorSetPath })); try { const payload = JSON.parse(simResult.stdout as string) as SimctlListDevicesPayload; for (const [runtime, runtimes] of Object.entries(payload.devices)) { @@ -132,6 +139,7 @@ export async function listIosDevices(): Promise { kind: 'simulator', target: resolveAppleTargetFromRuntime(runtime), booted: device.state === 'Booted', + ...(simulatorSetPath ? { simulatorSetPath } : {}), }); } } @@ -139,6 +147,12 @@ export async function listIosDevices(): Promise { throw new AppError('COMMAND_FAILED', 'Failed to parse simctl devices JSON', undefined, err); } + // When a simulator set is configured, keep discovery strictly scoped to that set. + // Do not enumerate host-global physical devices via devicectl. + if (simulatorSetPath) { + return devices; + } + let jsonPath: string | null = null; try { jsonPath = path.join( diff --git a/src/platforms/ios/runner-client.ts b/src/platforms/ios/runner-client.ts index 9638dde673..0358c0ee2b 100644 --- a/src/platforms/ios/runner-client.ts +++ b/src/platforms/ios/runner-client.ts @@ -12,6 +12,7 @@ import net from 'node:net'; import { bootFailureHint, classifyBootFailure } from '../boot-diagnostics.ts'; import { resolveTimeoutMs, resolveTimeoutSeconds } from '../../utils/timeouts.ts'; import { isRequestCanceled } from '../../daemon/request-cancel.ts'; +import { buildSimctlArgsForDevice } from './simctl.ts'; const iosRunnerContainerBundleIds = [ process.env.AGENT_DEVICE_IOS_RUNNER_CONTAINER_BUNDLE_ID, @@ -314,8 +315,8 @@ async function stopRunnerSessionInternal(deviceId: string, sessionOverride?: Run } } -async function ensureBooted(udid: string): Promise { - await runCmd('xcrun', ['simctl', 'bootstatus', udid, '-b'], { +async function ensureBooted(device: DeviceInfo): Promise { + await runCmd('xcrun', buildSimctlArgsForDevice(device, ['bootstatus', device.id, '-b']), { allowFailure: true, timeoutMs: RUNNER_STARTUP_TIMEOUT_MS, }); @@ -551,7 +552,7 @@ function ensureBootedIfNeeded(device: DeviceInfo): Promise { if (device.kind !== 'simulator') { return Promise.resolve(); } - return ensureBooted(device.id); + return ensureBooted(device); } function validateRunnerDevice(device: DeviceInfo): void { @@ -844,7 +845,7 @@ async function waitForRunner( if (remainingMs <= 0) { throw buildRunnerConnectError({ port, endpoints, logPath, lastError }); } - const simResponse = await postCommandViaSimulator(device.id, port, command, remainingMs); + const simResponse = await postCommandViaSimulator(device, port, command, remainingMs); return new Response(simResponse.body, { status: simResponse.status }); } @@ -936,28 +937,28 @@ async function resolveDeviceTunnelIp(deviceId: string, timeoutBudgetMs?: number) } async function postCommandViaSimulator( - udid: string, + device: DeviceInfo, port: number, command: RunnerCommand, timeoutMs: number, ): Promise<{ status: number; body: string }> { const payload = JSON.stringify(command); + const args = buildSimctlArgsForDevice(device, [ + 'spawn', + device.id, + '/usr/bin/curl', + '-s', + '-X', + 'POST', + '-H', + 'Content-Type: application/json', + '--data', + payload, + `http://127.0.0.1:${port}/command`, + ]); const result = await runCmd( 'xcrun', - [ - 'simctl', - 'spawn', - udid, - '/usr/bin/curl', - '-s', - '-X', - 'POST', - '-H', - 'Content-Type: application/json', - '--data', - payload, - `http://127.0.0.1:${port}/command`, - ], + args, { allowFailure: true, timeoutMs }, ); const body = result.stdout as string; diff --git a/src/platforms/ios/simctl.ts b/src/platforms/ios/simctl.ts new file mode 100644 index 0000000000..927eea7dac --- /dev/null +++ b/src/platforms/ios/simctl.ts @@ -0,0 +1,25 @@ +import type { DeviceInfo } from '../../utils/device.ts'; +import { resolveIosSimulatorDeviceSetPath } from '../../utils/device-isolation.ts'; + +type SimctlArgsOptions = { + simulatorSetPath?: string; +}; + +export function buildSimctlArgs( + args: string[], + options: SimctlArgsOptions = {}, +): string[] { + const simulatorSetPath = resolveIosSimulatorDeviceSetPath(options.simulatorSetPath); + if (!simulatorSetPath) return ['simctl', ...args]; + return ['simctl', '--set', simulatorSetPath, ...args]; +} + +export function buildSimctlArgsForDevice( + device: DeviceInfo, + args: string[], +): string[] { + if (device.platform !== 'ios' || device.kind !== 'simulator') { + return ['simctl', ...args]; + } + return buildSimctlArgs(args, { simulatorSetPath: device.simulatorSetPath }); +} diff --git a/src/platforms/ios/simulator.ts b/src/platforms/ios/simulator.ts index 9a41d7d140..8f6700f435 100644 --- a/src/platforms/ios/simulator.ts +++ b/src/platforms/ios/simulator.ts @@ -5,6 +5,7 @@ import { Deadline, retryWithPolicy } from '../../utils/retry.ts'; import { bootFailureHint, classifyBootFailure } from '../boot-diagnostics.ts'; import { IOS_BOOT_TIMEOUT_MS, IOS_SIMCTL_LIST_TIMEOUT_MS } from './config.ts'; +import { buildSimctlArgs, buildSimctlArgsForDevice } from './simctl.ts'; export function ensureSimulator(device: DeviceInfo, command: string): void { if (device.kind !== 'simulator') { @@ -15,7 +16,7 @@ export function ensureSimulator(device: DeviceInfo, command: string): void { export async function ensureBootedSimulator(device: DeviceInfo): Promise { if (device.kind !== 'simulator') return; - const state = await getSimulatorState(device.id); + const state = await getSimulatorState(device); if (state === 'Booted') return; const deadline = Deadline.fromTimeoutMs(IOS_BOOT_TIMEOUT_MS); @@ -44,7 +45,7 @@ export async function ensureBootedSimulator(device: DeviceInfo): Promise { } const remainingMs = Math.max(1_000, attemptDeadline?.remainingMs() ?? IOS_BOOT_TIMEOUT_MS); - const boot = await runCmd('xcrun', ['simctl', 'boot', device.id], { + const boot = await runCmd('xcrun', buildSimctlArgsForDevice(device, ['boot', device.id]), { allowFailure: true, timeoutMs: remainingMs, }); @@ -66,7 +67,7 @@ export async function ensureBootedSimulator(device: DeviceInfo): Promise { }); } - const bootStatus = await runCmd('xcrun', ['simctl', 'bootstatus', device.id, '-b'], { + const bootStatus = await runCmd('xcrun', buildSimctlArgsForDevice(device, ['bootstatus', device.id, '-b']), { allowFailure: true, timeoutMs: remainingMs, }); @@ -84,7 +85,7 @@ export async function ensureBootedSimulator(device: DeviceInfo): Promise { }); } - const nextState = await getSimulatorState(device.id); + const nextState = await getSimulatorState(device); if (nextState !== 'Booted') { throw new AppError('COMMAND_FAILED', 'Simulator is still booting', { state: nextState }); } @@ -137,8 +138,12 @@ export async function ensureBootedSimulator(device: DeviceInfo): Promise { } } -export async function getSimulatorState(udid: string): Promise { - const result = await runCmd('xcrun', ['simctl', 'list', 'devices', '-j'], { +export async function getSimulatorState(deviceOrUdid: DeviceInfo | string): Promise { + const udid = typeof deviceOrUdid === 'string' ? deviceOrUdid : deviceOrUdid.id; + const simctlArgs = typeof deviceOrUdid === 'string' + ? buildSimctlArgs(['list', 'devices', '-j']) + : buildSimctlArgsForDevice(deviceOrUdid, ['list', 'devices', '-j']); + const result = await runCmd('xcrun', simctlArgs, { allowFailure: true, timeoutMs: IOS_SIMCTL_LIST_TIMEOUT_MS, }); diff --git a/src/utils/__tests__/args.test.ts b/src/utils/__tests__/args.test.ts index d5e5663ebc..c8f923f3e6 100644 --- a/src/utils/__tests__/args.test.ts +++ b/src/utils/__tests__/args.test.ts @@ -34,6 +34,22 @@ test('parseArgs recognizes --platform apple alias', () => { assert.equal(parsed.flags.target, 'tv'); }); +test('parseArgs recognizes device isolation flags', () => { + const parsed = parseArgs([ + 'devices', + '--platform', + 'ios', + '--ios-simulator-device-set', + '/tmp/tenant-a/simulators', + '--android-device-allowlist', + 'emulator-5554,device-1234', + ], { strictFlags: true }); + assert.equal(parsed.command, 'devices'); + assert.equal(parsed.flags.platform, 'ios'); + assert.equal(parsed.flags.iosSimulatorDeviceSet, '/tmp/tenant-a/simulators'); + assert.equal(parsed.flags.androidDeviceAllowlist, 'emulator-5554,device-1234'); +}); + test('parseArgs recognizes logs clear --restart', () => { const parsed = parseArgs(['logs', 'clear', '--restart'], { strictFlags: true }); assert.equal(parsed.command, 'logs'); @@ -281,6 +297,8 @@ test('usage includes --relaunch flag', () => { assert.match(usage(), /--relaunch/); assert.match(usage(), /--restart/); assert.match(usage(), /--target mobile\|tv/); + assert.match(usage(), /--ios-simulator-device-set /); + assert.match(usage(), /--android-device-allowlist /); assert.match(usage(), /--fps /); assert.match(usage(), /network dump/); assert.match(usage(), /--save-script \[path\]/); diff --git a/src/utils/__tests__/device-isolation.test.ts b/src/utils/__tests__/device-isolation.test.ts new file mode 100644 index 0000000000..21caea6dba --- /dev/null +++ b/src/utils/__tests__/device-isolation.test.ts @@ -0,0 +1,38 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { + parseSerialAllowlist, + resolveAndroidSerialAllowlist, + resolveIosSimulatorDeviceSetPath, +} from '../device-isolation.ts'; + +test('resolveIosSimulatorDeviceSetPath prefers CLI flag over env', () => { + const value = resolveIosSimulatorDeviceSetPath('/tmp/flag-set', { + AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET: '/tmp/agent-set', + IOS_SIMULATOR_DEVICE_SET: '/tmp/compat-set', + }); + assert.equal(value, '/tmp/flag-set'); +}); + +test('resolveIosSimulatorDeviceSetPath falls back to AGENT_DEVICE env first', () => { + const value = resolveIosSimulatorDeviceSetPath(undefined, { + AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET: '/tmp/agent-set', + IOS_SIMULATOR_DEVICE_SET: '/tmp/compat-set', + }); + assert.equal(value, '/tmp/agent-set'); +}); + +test('parseSerialAllowlist splits comma and whitespace separators', () => { + const parsed = parseSerialAllowlist('emulator-5554, device-1234\nemulator-7777'); + assert.deepEqual(Array.from(parsed).sort(), ['device-1234', 'emulator-5554', 'emulator-7777']); +}); + +test('resolveAndroidSerialAllowlist resolves from CLI and env', () => { + const flag = resolveAndroidSerialAllowlist(' emulator-5554 , device-1234 '); + assert.deepEqual(Array.from(flag ?? []).sort(), ['device-1234', 'emulator-5554']); + + const env = resolveAndroidSerialAllowlist(undefined, { + AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST: 'emulator-7777', + }); + assert.deepEqual(Array.from(env ?? []), ['emulator-7777']); +}); diff --git a/src/utils/command-schema.ts b/src/utils/command-schema.ts index 8bb0c07ab0..57ecc7a1ba 100644 --- a/src/utils/command-schema.ts +++ b/src/utils/command-schema.ts @@ -14,6 +14,8 @@ export type CliFlags = { device?: string; udid?: string; serial?: string; + iosSimulatorDeviceSet?: string; + androidDeviceAllowlist?: string; out?: string; session?: string; verbose?: boolean; @@ -189,6 +191,20 @@ const FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageLabel: '--headless', usageDescription: 'Boot: launch Android emulator without a GUI window', }, + { + key: 'iosSimulatorDeviceSet', + names: ['--ios-simulator-device-set'], + type: 'string', + usageLabel: '--ios-simulator-device-set ', + usageDescription: 'Scope iOS simulator discovery/commands to this simulator device set', + }, + { + key: 'androidDeviceAllowlist', + names: ['--android-device-allowlist'], + type: 'string', + usageLabel: '--android-device-allowlist ', + usageDescription: 'Comma/space separated Android serial allowlist for discovery/selection', + }, { key: 'activity', names: ['--activity'], @@ -444,6 +460,8 @@ export const GLOBAL_FLAG_KEYS = new Set([ 'device', 'udid', 'serial', + 'iosSimulatorDeviceSet', + 'androidDeviceAllowlist', 'session', 'noRecord', ]); diff --git a/src/utils/device-isolation.ts b/src/utils/device-isolation.ts new file mode 100644 index 0000000000..0a7b07792f --- /dev/null +++ b/src/utils/device-isolation.ts @@ -0,0 +1,52 @@ +const IOS_SIMULATOR_DEVICE_SET_ENV_KEYS = [ + 'AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET', + 'IOS_SIMULATOR_DEVICE_SET', +] as const; + +const ANDROID_DEVICE_ALLOWLIST_ENV_KEYS = [ + 'AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST', + 'ANDROID_DEVICE_ALLOWLIST', +] as const; + +function normalizeNonEmpty(value: string | undefined): string | undefined { + const trimmed = value?.trim(); + return trimmed ? trimmed : undefined; +} + +function resolveFirstEnv( + keys: readonly string[], + env: NodeJS.ProcessEnv, +): string | undefined { + for (const key of keys) { + const value = normalizeNonEmpty(env[key]); + if (value) return value; + } + return undefined; +} + +export function resolveIosSimulatorDeviceSetPath( + flagValue: string | undefined, + env: NodeJS.ProcessEnv = process.env, +): string | undefined { + return normalizeNonEmpty(flagValue) ?? resolveFirstEnv(IOS_SIMULATOR_DEVICE_SET_ENV_KEYS, env); +} + +export function parseSerialAllowlist(value: string): Set { + return new Set( + value + .split(/[\s,]+/) + .map((entry) => entry.trim()) + .filter(Boolean), + ); +} + +export function resolveAndroidSerialAllowlist( + flagValue: string | undefined, + env: NodeJS.ProcessEnv = process.env, +): ReadonlySet | undefined { + const configured = + normalizeNonEmpty(flagValue) + ?? resolveFirstEnv(ANDROID_DEVICE_ALLOWLIST_ENV_KEYS, env); + if (!configured) return undefined; + return parseSerialAllowlist(configured); +} diff --git a/src/utils/device.ts b/src/utils/device.ts index cf7e3d5de6..31a4f9d8ec 100644 --- a/src/utils/device.ts +++ b/src/utils/device.ts @@ -14,6 +14,7 @@ export type DeviceInfo = { kind: DeviceKind; target?: DeviceTarget; booted?: boolean; + simulatorSetPath?: string; }; type DeviceSelector = { diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index af8b4653af..2b3c10c0cd 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -38,6 +38,22 @@ agent-device open "https://example.com" --platform ios # open link in agent-device open MyApp "myapp://screen/to" --platform ios # open deep link to MyApp ``` +## Device isolation scopes + +```bash +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 +``` + +- `--ios-simulator-device-set ` constrains simulator discovery and simulator command execution via `xcrun simctl --set ...`. +- `--android-device-allowlist ` constrains Android discovery/selection to comma or space separated serials. +- Scope is applied before selectors (`--device`, `--udid`, `--serial`), so out-of-scope selectors fail with `DEVICE_NOT_FOUND`. +- With iOS simulator-set scope enabled, iOS physical devices are not enumerated. +- Environment equivalents: + - iOS: `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET` (compat: `IOS_SIMULATOR_DEVICE_SET`) + - Android: `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST` (compat: `ANDROID_DEVICE_ALLOWLIST`) +- CLI scope flags override environment values. + ## TV targets ```bash