Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,8 @@ Flags:
- `--device <name>`
- `--udid <udid>` (iOS)
- `--serial <serial>` (Android)
- `--ios-simulator-device-set <path>` constrain iOS simulator discovery/commands to one simulator set (`xcrun simctl --set`)
- `--android-device-allowlist <serials>` constrain Android discovery/selection to comma/space-separated serials
- `--activity <component>` (Android app launch only; package/Activity or package/.Activity; not for URL opens)
- `--session <name>`
- `--state-dir <path>` daemon state directory override (default: `~/.agent-device`)
Expand All @@ -232,6 +234,11 @@ Flags:
- `--on-error stop` batch: stop when a step fails
- `--max-steps <n>` 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).
Expand Down Expand Up @@ -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=<udid>`
- `AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET=<path>` (or `IOS_SIMULATOR_DEVICE_SET=<path>`) to scope all iOS simulator discovery/commands to one simulator set.
- `AGENT_DEVICE_ANDROID_DEVICE_ALLOWLIST=<serials>` (or `ANDROID_DEVICE_ALLOWLIST=<serials>`) 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=<ms>` to adjust iOS simulator boot timeout (default: `120000`, minimum: `5000`).
- `AGENT_DEVICE_DAEMON_TIMEOUT_MS=<ms>` to override daemon request timeout (default `90000`). Increase for slow physical-device setup (for example `120000`).
- `AGENT_DEVICE_STATE_DIR=<path>` override daemon state directory (metadata, logs, session artifacts).
Expand Down
11 changes: 11 additions & 0 deletions skills/agent-device/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ Use this skill as a router, not a full manual.
- Debug/crash: `open <app>` -> `logs clear --restart` -> reproduce -> `network dump` -> `logs path` -> targeted `grep`
- Replay drift: `replay -u <path>` -> 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

Expand Down Expand Up @@ -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]
Expand All @@ -103,6 +106,12 @@ For Android emulators by AVD name, use `boot --platform android --device <avd-na
For Android emulators without GUI, add `--headless`.
Use `--target mobile|tv` with `--platform` (required) to pick phone/tablet vs TV targets (AndroidTV/tvOS).

Isolation scoping quick reference:
- `--ios-simulator-device-set <path>` scopes iOS simulator discovery + command execution to one simulator set.
- `--android-device-allowlist <serials>` 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).
Expand Down Expand Up @@ -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

Expand Down
16 changes: 16 additions & 0 deletions skills/agent-device/references/session-management.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 7 additions & 4 deletions src/core/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -41,6 +42,8 @@ export type CommandFlags = Omit<CliFlags, 'json' | 'help' | 'version' | 'batchSt

export async function resolveTargetDevice(flags: CommandFlags): Promise<DeviceInfo> {
const normalizedPlatform = normalizePlatformSelector(flags.platform);
const iosSimulatorSetPath = resolveIosSimulatorDeviceSetPath(flags.iosSimulatorDeviceSet);
const androidSerialAllowlist = resolveAndroidSerialAllowlist(flags.androidDeviceAllowlist);
return await withDiagnosticTimer(
'resolve_target_device',
async () => {
Expand All @@ -60,23 +63,23 @@ export async function resolveTargetDevice(flags: CommandFlags): Promise<DeviceIn

if (selector.platform === 'android') {
await ensureAdb();
const devices = await listAndroidDevices();
const devices = await listAndroidDevices({ serialAllowlist: androidSerialAllowlist });
return await selectDevice(devices, selector);
}

if (selector.platform === 'ios') {
const devices = await listIosDevices();
const devices = await listIosDevices({ simulatorSetPath: iosSimulatorSetPath });
return await selectDevice(devices, selector);
}

const devices: DeviceInfo[] = [];
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
}
Expand Down
28 changes: 28 additions & 0 deletions src/daemon/__tests__/session-selector.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,31 @@ test('rejects mismatched device selector', () => {
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'),
);
});
3 changes: 2 additions & 1 deletion src/daemon/handlers/record-trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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 };
Expand Down
14 changes: 9 additions & 5 deletions src/daemon/handlers/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -516,31 +517,34 @@ 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
}
}
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 } };
Expand Down
20 changes: 20 additions & 0 deletions src/daemon/session-selector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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(
Expand Down
14 changes: 12 additions & 2 deletions src/platforms/android/devices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-';
Expand All @@ -16,6 +17,10 @@ const ANDROID_TV_FEATURES = [
'android.hardware.type.television',
] as const;

type AndroidDeviceDiscoveryOptions = {
serialAllowlist?: ReadonlySet<string>;
};

function commandOutput(result: ExecResult): string {
return `${result.stdout}\n${result.stderr}`;
}
Expand Down Expand Up @@ -136,15 +141,20 @@ async function resolveAndroidTarget(serial: string): Promise<'mobile' | 'tv'> {
return 'mobile';
}

export async function listAndroidDevices(): Promise<DeviceInfo[]> {
export async function listAndroidDevices(options: AndroidDeviceDiscoveryOptions = {}): Promise<DeviceInfo[]> {
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),
Expand Down
35 changes: 35 additions & 0 deletions src/platforms/ios/__tests__/simctl.test.ts
Original file line number Diff line number Diff line change
@@ -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']);
});
Loading
Loading