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
8 changes: 8 additions & 0 deletions skills/agent-device/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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 <name>` is required (e.g. `"iPhone 16 Pro"`). `--runtime <id>` 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).
Expand Down
14 changes: 14 additions & 0 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | 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<string, unknown> | undefined;
const pathOut = typeof data?.path === 'string' ? data.path : '';
Expand Down
3 changes: 2 additions & 1 deletion src/daemon.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
52 changes: 51 additions & 1 deletion src/daemon/handlers/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }>;
Expand Down Expand Up @@ -99,12 +100,17 @@ function buildOpenResult(params: {
appName?: string;
appBundleId?: string;
startup?: StartupPerfSample;
device?: DeviceInfo;
}): Record<string, unknown> {
const { sessionName, appName, appBundleId, startup } = params;
const { sessionName, appName, appBundleId, startup, device } = params;
const result: Record<string, unknown> = { 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;
}

Expand Down Expand Up @@ -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,
},
};
}
Expand Down Expand Up @@ -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 <name>' } };
}
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[] = [];
Expand Down Expand Up @@ -1127,6 +1175,7 @@ export async function handleSessionCommands(params: {
appName: openTarget,
appBundleId,
startup: startupSample,
device: session.device,
});
sessionStore.recordAction(nextSession, {
command,
Expand Down Expand Up @@ -1205,6 +1254,7 @@ export async function handleSessionCommands(params: {
appName: openTarget,
appBundleId,
startup: startupSample,
device,
});
sessionStore.recordAction(session, {
command,
Expand Down
177 changes: 177 additions & 0 deletions src/platforms/ios/ensure-simulator.ts
Original file line number Diff line number Diff line change
@@ -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<string, SimctlDeviceRecord[]>;
};

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<void>;
};

export async function ensureSimulatorExists(options: EnsureSimulatorOptions): Promise<EnsureSimulatorResult> {
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<string> {
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, '');
}
30 changes: 30 additions & 0 deletions src/utils/command-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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 <id>',
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'],
Expand Down Expand Up @@ -508,6 +532,12 @@ const COMMAND_SCHEMAS: Record<string, CommandSchema> = {
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: [],
Expand Down
Loading
Loading