diff --git a/README.md b/README.md index 6c701dee03..573c963e6c 100644 --- a/README.md +++ b/README.md @@ -349,6 +349,7 @@ Navigation helpers: - `install`/`reinstall` accept package/bundle id style app names and support `~` in paths. - `install-from-source` supports `--retain-paths` and `--retention-ms ` when callers need retained materialized artifact paths after the install. - When `AGENT_DEVICE_DAEMON_BASE_URL` targets a remote daemon, local `.apk`/`.aab`/`.ipa` files and `.app` bundles are uploaded automatically before `install`/`reinstall`. +- `metro prepare --public-base-url ` starts or reuses a local Metro server for sandbox/client flows and prints runtime JSON to stdout. `--json` wraps the same payload in the standard `{ success, data }` envelope. Pass `--proxy-base-url ` plus `AGENT_DEVICE_PROXY_TOKEN` (preferred) or `--bearer-token ` when the runtime must be bridged through `agent-device-proxy`, and `--runtime-file ` only when a persisted artifact is needed. - Remote daemon clients can persist session-scoped runtime hints with `runtime set` before `open`; Android launches write React Native dev prefs, and iOS simulator launches write React Native bundle defaults before app start. Example: `agent-device runtime set --session my-session --platform android --metro-host 10.0.0.10 --metro-port 8081 --launch-url "myapp://dev"`. - Remote daemon screenshots and recordings are materialized back to the caller path instead of returning host-local daemon paths. - To force a daemon-side path instead of uploading a local file, prefix it with `remote:`, for example `remote:/srv/builds/MyApp.app`. @@ -567,6 +568,7 @@ Environment selectors: - `AGENT_DEVICE_DAEMON_BASE_URL=http(s)://host:port[/base-path]` connect directly to a remote HTTP daemon and skip local daemon metadata/startup. - Remote daemon installs upload local artifacts through `POST /upload`; use a `remote:` path prefix when you need the daemon to read an existing server-side artifact path as-is. - `AGENT_DEVICE_DAEMON_AUTH_TOKEN=` auth token for remote HTTP daemon mode; sent in both the JSON-RPC request token and HTTP auth headers (`Authorization: Bearer` and `x-agent-device-token`). +- `AGENT_DEVICE_PROXY_TOKEN=` preferred bearer token for `metro prepare --proxy-base-url ` so the proxy secret does not need to be passed on the command line. `AGENT_DEVICE_METRO_BEARER_TOKEN` is also supported. - `AGENT_DEVICE_DAEMON_SERVER_MODE=socket|http|dual` daemon server mode. `http` and `dual` expose JSON-RPC 2.0 at `POST /rpc` (`GET /health` available for liveness). - `AGENT_DEVICE_DAEMON_TRANSPORT=auto|socket|http` client preference when connecting to daemon metadata. - `AGENT_DEVICE_HTTP_AUTH_HOOK=` optional HTTP auth hook module path for JSON-RPC server mode. diff --git a/src/__tests__/cli-client-commands.test.ts b/src/__tests__/cli-client-commands.test.ts index be2d4d9a6b..c0c6449cf4 100644 --- a/src/__tests__/cli-client-commands.test.ts +++ b/src/__tests__/cli-client-commands.test.ts @@ -1,7 +1,11 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import { tryRunClientBackedCommand } from '../cli-client-commands.ts'; -import type { AgentDeviceClient, AppInstallFromSourceOptions } from '../client.ts'; +import type { + AgentDeviceClient, + AppInstallFromSourceOptions, + MetroPrepareOptions, +} from '../client.ts'; import { AppError } from '../utils/errors.ts'; test('install-from-source forwards URL and repeated headers to client.apps.installFromSource', async () => { @@ -73,8 +77,129 @@ test('install-from-source rejects malformed header syntax', async () => { ); }); +test('metro prepare forwards normalized options to client.metro.prepare', async () => { + let observed: MetroPrepareOptions | undefined; + const client = createStubClient({ + installFromSource: async () => { + throw new Error('unexpected install call'); + }, + prepareMetro: async (options) => { + observed = options; + return { + projectRoot: '/tmp/project', + kind: 'react-native', + dependenciesInstalled: false, + packageManager: null, + started: false, + reused: true, + pid: 0, + logPath: '/tmp/project/.agent-device/metro.log', + statusUrl: 'http://127.0.0.1:8081/status', + runtimeFilePath: null, + iosRuntime: { + platform: 'ios', + bundleUrl: 'https://sandbox.example.test/index.bundle?platform=ios', + }, + androidRuntime: { + platform: 'android', + bundleUrl: 'https://sandbox.example.test/index.bundle?platform=android', + }, + bridge: null, + }; + }, + }); + + const stdout = await captureStdout(async () => { + const handled = await tryRunClientBackedCommand({ + command: 'metro', + positionals: ['prepare'], + flags: { + json: false, + help: false, + version: false, + metroProjectRoot: './apps/demo', + metroPublicBaseUrl: 'https://sandbox.example.test', + metroProxyBaseUrl: 'https://proxy.example.test', + metroBearerToken: 'secret', + metroPreparePort: 9090, + metroKind: 'expo', + metroRuntimeFile: './.agent-device/metro-runtime.json', + metroNoReuseExisting: true, + metroNoInstallDeps: true, + }, + client, + }); + assert.equal(handled, true); + }); + const payload = JSON.parse(stdout); + + assert.deepEqual(observed, { + projectRoot: './apps/demo', + publicBaseUrl: 'https://sandbox.example.test', + proxyBaseUrl: 'https://proxy.example.test', + bearerToken: 'secret', + port: 9090, + kind: 'expo', + runtimeFilePath: './.agent-device/metro-runtime.json', + reuseExisting: false, + installDependenciesIfNeeded: false, + listenHost: undefined, + statusHost: undefined, + startupTimeoutMs: undefined, + probeTimeoutMs: undefined, + }); + assert.equal(payload.kind, 'react-native'); + assert.equal(payload.runtimeFilePath, null); +}); + +test('metro prepare wraps output in the standard success envelope for --json', async () => { + const client = createStubClient({ + installFromSource: async () => { + throw new Error('unexpected install call'); + }, + }); + + const stdout = await captureStdout(async () => { + const handled = await tryRunClientBackedCommand({ + command: 'metro', + positionals: ['prepare'], + flags: { + json: true, + help: false, + version: false, + metroPublicBaseUrl: 'https://sandbox.example.test', + }, + client, + }); + assert.equal(handled, true); + }); + + const payload = JSON.parse(stdout); + assert.equal(payload.success, true); + assert.equal(payload.data.kind, 'react-native'); + assert.equal(payload.data.iosRuntime.platform, 'ios'); +}); + +async function captureStdout(run: () => Promise): Promise { + let stdout = ''; + const originalWrite = process.stdout.write.bind(process.stdout); + (process.stdout as any).write = ((chunk: unknown) => { + stdout += String(chunk); + return true; + }) as typeof process.stdout.write; + + try { + await run(); + } finally { + process.stdout.write = originalWrite; + } + + return stdout; +} + function createStubClient(params: { installFromSource: AgentDeviceClient['apps']['installFromSource']; + prepareMetro?: AgentDeviceClient['metro']['prepare']; }): AgentDeviceClient { return { devices: { @@ -140,6 +265,31 @@ function createStubClient(params: { identifiers: { session: 'default' }, }), }, + metro: { + prepare: + params.prepareMetro ?? + (async () => ({ + projectRoot: '/tmp/project', + kind: 'react-native', + dependenciesInstalled: false, + packageManager: null, + started: false, + reused: true, + pid: 0, + logPath: '/tmp/project/.agent-device/metro.log', + statusUrl: 'http://127.0.0.1:8081/status', + runtimeFilePath: null, + iosRuntime: { + platform: 'ios', + bundleUrl: 'https://sandbox.example.test/index.bundle?platform=ios', + }, + androidRuntime: { + platform: 'android', + bundleUrl: 'https://sandbox.example.test/index.bundle?platform=android', + }, + bridge: null, + })), + }, capture: { snapshot: async () => ({ nodes: [], diff --git a/src/__tests__/client-metro.test.ts b/src/__tests__/client-metro.test.ts new file mode 100644 index 0000000000..eb6eeb1c28 --- /dev/null +++ b/src/__tests__/client-metro.test.ts @@ -0,0 +1,244 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { once } from 'node:events'; +import { randomUUID } from 'node:crypto'; +import { chmodSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +import type { Socket } from 'node:net'; +import net from 'node:net'; +import os from 'node:os'; +import path from 'node:path'; +import { prepareMetroRuntime } from '../client-metro.ts'; +import { AppError } from '../utils/errors.ts'; + +const TEST_TOKEN = 'agent-device-proxy-test-token'; + +test('prepareMetroRuntime starts Metro, bridges through proxy, and writes runtime file when requested', async () => { + const tempRoot = path.join(os.tmpdir(), `agent-device-metro-${randomUUID()}`); + const projectRoot = path.join(tempRoot, 'project'); + const binDir = path.join(tempRoot, 'bin'); + const runtimeFilePath = path.join(projectRoot, '.agent-device', 'metro-runtime.json'); + const metroPort = await findFreePort(); + const proxyPort = await findFreePort(); + const requests: string[] = []; + const proxySockets = new Set(); + + mkdirSync(projectRoot, { recursive: true }); + mkdirSync(binDir, { recursive: true }); + writeFileSync( + path.join(projectRoot, 'package.json'), + JSON.stringify({ + name: 'metro-runtime-test', + private: true, + dependencies: { + 'react-native': '0.0.0-test', + }, + }), + ); + writeFakeNpx(binDir); + + const proxyServer = createServer(async (req, res) => { + if (req.headers.authorization !== `Bearer ${TEST_TOKEN}`) { + res.statusCode = 401; + res.end(JSON.stringify({ ok: false, error: 'unauthorized' })); + return; + } + + requests.push(req.url || ''); + const chunks: Buffer[] = []; + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { + ios_runtime?: { metro_bundle_url?: string }; + }; + assert.match(body.ios_runtime?.metro_bundle_url ?? '', /index\.bundle\?platform=ios/); + + res.statusCode = 200; + res.setHeader('content-type', 'application/json'); + if (req.url === '/api/metro/bridge') { + res.end( + JSON.stringify({ + ok: true, + data: { + enabled: true, + base_url: 'http://127.0.0.1:8081', + status_url: 'http://127.0.0.1:8081/status', + bundle_url: 'http://127.0.0.1:8081/index.bundle?platform=ios&dev=true&minify=false', + ios_runtime: { + metro_host: '127.0.0.1', + metro_port: 8081, + metro_bundle_url: + 'http://127.0.0.1:8081/index.bundle?platform=ios&dev=true&minify=false', + }, + android_runtime: { + metro_host: '10.0.2.2', + metro_port: 8081, + metro_bundle_url: + 'http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false', + }, + upstream: { + bundle_url: `http://127.0.0.1:${metroPort}/index.bundle?platform=ios&dev=true&minify=false`, + host: '127.0.0.1', + port: metroPort, + status_url: `http://127.0.0.1:${metroPort}/status`, + }, + probe: { + reachable: true, + status_code: 200, + latency_ms: 3, + detail: 'ok', + }, + }, + }), + ); + return; + } + + res.statusCode = 404; + res.end(JSON.stringify({ ok: false, error: 'not found' })); + }); + proxyServer.on('connection', (socket) => { + proxySockets.add(socket); + socket.on('close', () => proxySockets.delete(socket)); + }); + proxyServer.listen(proxyPort, '127.0.0.1'); + proxyServer.unref(); + await once(proxyServer, 'listening'); + + let pid = 0; + + try { + const result = await prepareMetroRuntime({ + projectRoot, + publicBaseUrl: `http://127.0.0.1:${metroPort}`, + proxyBaseUrl: `http://127.0.0.1:${proxyPort}`, + proxyBearerToken: TEST_TOKEN, + metroPort, + reuseExisting: false, + installDependenciesIfNeeded: false, + runtimeFilePath, + env: { + ...process.env, + PATH: `${binDir}:${process.env.PATH || ''}`, + }, + }); + + pid = result.pid; + assert.equal(result.kind, 'react-native'); + assert.equal(result.started, true); + assert.equal(result.reused, false); + assert.equal(result.bridge?.enabled, true); + assert.equal(result.iosRuntime.metroHost, '127.0.0.1'); + assert.equal(result.iosRuntime.platform, 'ios'); + assert.equal(result.androidRuntime.metroHost, '10.0.2.2'); + assert.equal(result.androidRuntime.platform, 'android'); + assert.deepEqual(requests, ['/api/metro/bridge']); + + const written = JSON.parse(readFileSync(runtimeFilePath, 'utf8')) as { + iosRuntime: { metroHost?: string; metroPort?: number; platform?: string }; + androidRuntime: { metroHost?: string; metroPort?: number; platform?: string }; + runtimeFilePath?: string; + }; + assert.equal(written.iosRuntime.metroHost, '127.0.0.1'); + assert.equal(written.iosRuntime.metroPort, 8081); + assert.equal(written.iosRuntime.platform, 'ios'); + assert.equal(written.androidRuntime.metroHost, '10.0.2.2'); + assert.equal(written.androidRuntime.platform, 'android'); + assert.equal(written.runtimeFilePath, runtimeFilePath); + } finally { + for (const socket of proxySockets) { + socket.destroy(); + } + await closeServer(proxyServer); + if (pid) { + try { + process.kill(pid); + } catch {} + } + rmSync(tempRoot, { recursive: true, force: true }); + } +}); + +test('prepareMetroRuntime rejects incomplete proxy configuration', async () => { + await assert.rejects( + () => + prepareMetroRuntime({ + publicBaseUrl: 'https://sandbox.example.test', + proxyBaseUrl: 'https://proxy.example.test', + }), + (error) => + error instanceof AppError && + error.code === 'INVALID_ARGS' && + error.message.includes('AGENT_DEVICE_PROXY_TOKEN'), + ); +}); + +function writeFakeNpx(binDir: string): void { + const filePath = path.join(binDir, 'npx'); + writeFileSync( + filePath, + `#!/usr/bin/env node +const http = require("node:http") +const args = process.argv.slice(2) +const portIndex = args.indexOf("--port") +const hostIndex = args.indexOf("--host") +const port = portIndex === -1 ? 8081 : Number(args[portIndex + 1] || "8081") +const host = hostIndex === -1 ? "0.0.0.0" : String(args[hostIndex + 1] || "0.0.0.0") +const server = http.createServer((req, res) => { + if (req.url === "/status") { + res.statusCode = 200 + res.end("packager-status:running") + return + } + if (req.url && req.url.startsWith("/index.bundle")) { + res.statusCode = 200 + res.setHeader("content-type", "application/javascript") + res.end("console.log('metro-runtime-test')") + return + } + res.statusCode = 404 + res.end("not found") +}) +server.listen(port, host) +setInterval(() => {}, 1000) +`, + ); + chmodSync(filePath, 0o755); +} + +async function findFreePort(): Promise { + return await new Promise((resolve, reject) => { + const server = net.createServer(); + server.once('error', reject); + server.listen(0, '127.0.0.1', () => { + const address = server.address(); + if (!address || typeof address === 'string') { + reject(new Error('Failed to allocate free port')); + return; + } + const port = address.port; + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(port); + }); + }); + }); +} + +async function closeServer(server: ReturnType): Promise { + server.closeIdleConnections?.(); + server.closeAllConnections?.(); + await new Promise((resolve, reject) => { + server.close((error) => { + if (error) { + reject(error); + return; + } + resolve(); + }); + }); +} diff --git a/src/cli-client-commands.ts b/src/cli-client-commands.ts index a8037fc455..f462196e2d 100644 --- a/src/cli-client-commands.ts +++ b/src/cli-client-commands.ts @@ -104,6 +104,34 @@ const clientCommandHandlers: Partial> = { } return false; }, + metro: async ({ positionals, flags, client }) => { + const action = (positionals[0] ?? '').toLowerCase(); + if (action !== 'prepare') { + throw new AppError('INVALID_ARGS', 'metro only supports prepare'); + } + if (!flags.metroPublicBaseUrl) { + throw new AppError('INVALID_ARGS', 'metro prepare requires --public-base-url .'); + } + + const result = await client.metro.prepare({ + projectRoot: flags.metroProjectRoot, + kind: flags.metroKind, + port: flags.metroPreparePort, + listenHost: flags.metroListenHost, + statusHost: flags.metroStatusHost, + publicBaseUrl: flags.metroPublicBaseUrl, + proxyBaseUrl: flags.metroProxyBaseUrl, + bearerToken: flags.metroBearerToken, + startupTimeoutMs: flags.metroStartupTimeoutMs, + probeTimeoutMs: flags.metroProbeTimeoutMs, + reuseExisting: flags.metroNoReuseExisting ? false : undefined, + installDependenciesIfNeeded: flags.metroNoInstallDeps ? false : undefined, + runtimeFilePath: flags.metroRuntimeFile, + }); + + writeMetroPrepareResult(result, flags); + return true; + }, install: async ({ positionals, flags, client }) => { const result = await runDeployCommand('install', positionals, flags, client); if (flags.json) printJson({ success: true, data: serializeDeployResult(result) }); @@ -309,6 +337,14 @@ function writeRuntimeResult(result: RuntimeResult, flags: CliFlags): void { } } +function writeMetroPrepareResult(result: unknown, flags: CliFlags): void { + if (flags.json) { + printJson({ success: true, data: result }); + } else { + process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); + } +} + function buildSelectionOptions(flags: CliFlags): { platform?: CliFlags['platform']; target?: CliFlags['target']; diff --git a/src/client-metro.ts b/src/client-metro.ts new file mode 100644 index 0000000000..4da7f66073 --- /dev/null +++ b/src/client-metro.ts @@ -0,0 +1,592 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { AppError } from './utils/errors.ts'; +import { runCmdSync } from './utils/exec.ts'; +import { resolveUserPath } from './utils/path-resolution.ts'; + +export type MetroPrepareKind = 'auto' | 'react-native' | 'expo'; +type ResolvedMetroKind = Exclude; +type EnvSource = NodeJS.ProcessEnv | Record; + +type PackageJsonShape = { + dependencies?: Record; + devDependencies?: Record; +}; + +type PackageManagerConfig = { + command: string; + installArgs: string[]; +}; + +type MetroProcessResult = { + pid: number; +}; + +type ProxyMetroRuntimeHints = { + metro_host?: string; + metro_port?: number; + metro_bundle_url?: string; + launch_url?: string; +}; + +type ProxyMetroBridgeResponse = { + enabled: boolean; + base_url: string; + status_url: string; + bundle_url: string; + ios_runtime: ProxyMetroRuntimeHints; + android_runtime: ProxyMetroRuntimeHints; + upstream: { + bundle_url: string; + host: string; + port: number; + status_url: string; + }; + probe: { + reachable: boolean; + status_code: number; + latency_ms: number; + detail: string; + }; +}; + +export type MetroRuntimeHints = { + platform?: 'ios' | 'android'; + metroHost?: string; + metroPort?: number; + bundleUrl?: string; + launchUrl?: string; +}; + +export type MetroBridgeResult = { + enabled: boolean; + baseUrl: string; + statusUrl: string; + bundleUrl: string; + iosRuntime: MetroRuntimeHints; + androidRuntime: MetroRuntimeHints; + upstream: { + bundleUrl: string; + host: string; + port: number; + statusUrl: string; + }; + probe: { + reachable: boolean; + statusCode: number; + latencyMs: number; + detail: string; + }; +}; + +export type PrepareMetroRuntimeOptions = { + projectRoot?: string; + kind?: MetroPrepareKind; + metroPort?: number | string; + listenHost?: string; + statusHost?: string; + publicBaseUrl?: string; + proxyBaseUrl?: string; + proxyBearerToken?: string; + startupTimeoutMs?: number | string; + probeTimeoutMs?: number | string; + reuseExisting?: boolean; + installDependenciesIfNeeded?: boolean; + runtimeFilePath?: string; + logPath?: string; + env?: EnvSource; +}; + +export type PrepareMetroRuntimeResult = { + projectRoot: string; + kind: ResolvedMetroKind; + dependenciesInstalled: boolean; + packageManager: string | null; + started: boolean; + reused: boolean; + pid: number; + logPath: string; + statusUrl: string; + runtimeFilePath: string | null; + iosRuntime: MetroRuntimeHints; + androidRuntime: MetroRuntimeHints; + bridge: MetroBridgeResult | null; +}; + +type ProxyBridgeRequestOptions = { + baseUrl: string; + bearerToken: string; + runtime: ProxyMetroRuntimeHints; + timeoutMs: number; +}; + +function normalizeBaseUrl(input: string): string { + return input.replace(/\/+$/, ''); +} + +function normalizeOptionalBaseUrl(input: unknown): string { + return typeof input === 'string' && input.trim() ? normalizeBaseUrl(input.trim()) : ''; +} + +function normalizeOptionalString(input: unknown): string | undefined { + return typeof input === 'string' && input.trim() ? input.trim() : undefined; +} + +function resolvePath(inputPath: string, env: EnvSource, cwd: string): string { + return resolveUserPath(inputPath, { env, cwd }); +} + +function buildBundleUrl(baseUrl: string, platform: 'ios' | 'android'): string { + const url = new URL(`${normalizeBaseUrl(baseUrl)}/index.bundle`); + url.searchParams.set('platform', platform); + url.searchParams.set('dev', 'true'); + url.searchParams.set('minify', 'false'); + return url.toString(); +} + +function fileExists(filePath: string): boolean { + try { + fs.accessSync(filePath, fs.constants.F_OK); + return true; + } catch { + return false; + } +} + +function directoryExists(dirPath: string): boolean { + try { + return fs.statSync(dirPath).isDirectory(); + } catch { + return false; + } +} + +function readPackageJson(projectRoot: string): PackageJsonShape { + const packageJsonPath = path.join(projectRoot, 'package.json'); + if (!fileExists(packageJsonPath)) { + throw new AppError('INVALID_ARGS', `package.json not found at ${packageJsonPath}`); + } + + return JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) as PackageJsonShape; +} + +function detectPackageManager(projectRoot: string): PackageManagerConfig { + if (fileExists(path.join(projectRoot, 'pnpm-lock.yaml'))) { + return { command: 'pnpm', installArgs: ['install'] }; + } + if (fileExists(path.join(projectRoot, 'yarn.lock'))) { + return { command: 'yarn', installArgs: ['install'] }; + } + return { command: 'npm', installArgs: ['install'] }; +} + +function detectMetroKind(projectRoot: string, requestedKind: MetroPrepareKind): ResolvedMetroKind { + if (requestedKind !== 'auto') { + return requestedKind; + } + + const packageJson = readPackageJson(projectRoot); + const dependencies = { + ...(packageJson.dependencies ?? {}), + ...(packageJson.devDependencies ?? {}), + }; + + return typeof dependencies.expo === 'string' ? 'expo' : 'react-native'; +} + +function parseTimeout( + value: number | string | undefined, + fallback: number, + minimum: number, +): number { + if (value === undefined || value === null || value === '') { + return fallback; + } + const parsed = Number.parseInt(String(value), 10); + if (!Number.isInteger(parsed)) { + return fallback; + } + return Math.max(parsed, minimum); +} + +function parsePort(value: number | string | undefined, fallback: number): number { + if (value === undefined || value === null || value === '') { + return fallback; + } + const parsed = Number.parseInt(String(value), 10); + if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) { + throw new AppError('INVALID_ARGS', `Invalid Metro port: ${String(value)}. Use 1-65535.`); + } + return parsed; +} + +function buildPublicRuntime(baseUrl: string, platform: 'ios' | 'android'): MetroRuntimeHints { + return { + platform, + bundleUrl: buildBundleUrl(baseUrl, platform), + }; +} + +function normalizeProxyRuntimeHints( + value: ProxyMetroRuntimeHints | undefined, + platform: 'ios' | 'android', +): MetroRuntimeHints { + return { + platform, + metroHost: normalizeOptionalString(value?.metro_host), + metroPort: value?.metro_port, + bundleUrl: normalizeOptionalString(value?.metro_bundle_url), + launchUrl: normalizeOptionalString(value?.launch_url), + }; +} + +function shellQuote(value: string): string { + return `'${value.replace(/'/g, `'\"'\"'`)}'`; +} + +function installDependenciesIfNeeded( + projectRoot: string, + env: EnvSource, +): { installed: boolean; packageManager?: string } { + if (directoryExists(path.join(projectRoot, 'node_modules'))) { + return { installed: false }; + } + + const packageManager = detectPackageManager(projectRoot); + runCmdSync(packageManager.command, packageManager.installArgs, { + cwd: projectRoot, + env: env as NodeJS.ProcessEnv, + }); + return { installed: true, packageManager: packageManager.command }; +} + +async function wait(ms: number): Promise { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function fetchText( + url: string, + timeoutMs: number, + extraHeaders: Record = {}, +): Promise<{ ok: boolean; status: number; body: string }> { + try { + const response = await fetch(url, { + headers: extraHeaders, + signal: AbortSignal.timeout(timeoutMs), + }); + return { + ok: response.ok, + status: response.status, + body: await response.text(), + }; + } catch (error) { + if (error instanceof Error && error.name === 'TimeoutError') { + throw new Error(`Timed out fetching ${url} after ${timeoutMs}ms`); + } + throw error; + } +} + +async function isMetroReady(statusUrl: string, timeoutMs: number): Promise { + try { + const response = await fetchText(statusUrl, timeoutMs); + return response.ok && response.body.includes('packager-status:running'); + } catch { + return false; + } +} + +function buildMetroCommand( + kind: ResolvedMetroKind, + port: number, + listenHost: string, +): PackageManagerConfig { + if (kind === 'expo') { + return { + command: 'npx', + installArgs: ['expo', 'start', '--host', 'lan', '--port', String(port)], + }; + } + + return { + command: 'npx', + installArgs: ['react-native', 'start', '--host', listenHost, '--port', String(port)], + }; +} + +function startMetroProcess( + projectRoot: string, + kind: ResolvedMetroKind, + port: number, + listenHost: string, + logPath: string, + env: EnvSource, +): MetroProcessResult { + const metro = buildMetroCommand(kind, port, listenHost); + fs.mkdirSync(path.dirname(logPath), { recursive: true }); + const command = [shellQuote(metro.command), ...metro.installArgs.map(shellQuote)].join(' '); + const launchScript = `nohup ${command} >> ${shellQuote(logPath)} 2>&1 < /dev/null & echo $!`; + const result = runCmdSync('/bin/sh', ['-c', launchScript], { + cwd: projectRoot, + env: env as NodeJS.ProcessEnv, + }); + const pid = Number.parseInt(result.stdout.trim(), 10); + + if (!Number.isInteger(pid) || pid <= 0) { + throw new Error( + `Failed to start Metro. Expected a child PID in stdout, got "${result.stdout.trim()}".`, + ); + } + + return { + pid, + }; +} + +function createProxyHeaders(baseUrl: string, bearerToken: string): Record { + return { + Authorization: `Bearer ${bearerToken}`, + 'Content-Type': 'application/json', + ...(baseUrl.includes('ngrok') ? { 'ngrok-skip-browser-warning': '1' } : {}), + }; +} + +async function configureMetroBridge(input: ProxyBridgeRequestOptions): Promise { + let response: Response; + + try { + response = await fetch(`${input.baseUrl}/api/metro/bridge`, { + method: 'POST', + headers: createProxyHeaders(input.baseUrl, input.bearerToken), + body: JSON.stringify({ + ios_runtime: input.runtime, + timeout_ms: input.timeoutMs, + }), + signal: AbortSignal.timeout(input.timeoutMs), + }); + } catch (error) { + if (error instanceof Error && error.name === 'TimeoutError') { + throw new Error( + `/api/metro/bridge timed out after ${input.timeoutMs}ms calling ${input.baseUrl}/api/metro/bridge`, + ); + } + throw error; + } + + const responseText = await response.text(); + const responsePayload = responseText ? JSON.parse(responseText) : {}; + + if (!response.ok) { + throw new Error( + `/api/metro/bridge failed (${response.status}): ${JSON.stringify(responsePayload)}`, + ); + } + + return normalizeBridgeResponse( + (responsePayload.data ?? responsePayload) as ProxyMetroBridgeResponse, + ); +} + +function normalizeBridgeResponse(response: ProxyMetroBridgeResponse): MetroBridgeResult { + return { + enabled: response.enabled, + baseUrl: response.base_url, + statusUrl: response.status_url, + bundleUrl: response.bundle_url, + iosRuntime: normalizeProxyRuntimeHints(response.ios_runtime, 'ios'), + androidRuntime: normalizeProxyRuntimeHints(response.android_runtime, 'android'), + upstream: { + bundleUrl: response.upstream.bundle_url, + host: response.upstream.host, + port: response.upstream.port, + statusUrl: response.upstream.status_url, + }, + probe: { + reachable: response.probe.reachable, + statusCode: response.probe.status_code, + latencyMs: response.probe.latency_ms, + detail: response.probe.detail, + }, + }; +} + +function describeBridgeFailure( + baseUrl: string, + bridgeError: string | null, + bridge: MetroBridgeResult | null, +): string { + const parts = [ + `Metro bridge is required for this run but could not be configured via ${baseUrl}/api/metro/bridge.`, + ]; + + if (bridgeError) { + parts.push(`bridgeError=${bridgeError}`); + } + if (bridge?.probe.reachable === false) { + parts.push( + `bridgeProbe=${bridge.probe.detail || `unreachable (status ${bridge.probe.statusCode || 0})`}`, + ); + } + + return parts.join(' '); +} + +function resolveProxySettings( + proxyBaseUrl: string, + proxyBearerToken: string, +): { + proxyEnabled: boolean; + proxyBaseUrl: string; + proxyBearerToken: string; +} { + if (proxyBaseUrl && !proxyBearerToken) { + throw new AppError( + 'INVALID_ARGS', + 'metro prepare requires proxy auth when --proxy-base-url is provided. Pass --bearer-token or set AGENT_DEVICE_PROXY_TOKEN.', + ); + } + if (!proxyBaseUrl && proxyBearerToken) { + throw new AppError( + 'INVALID_ARGS', + 'metro prepare requires --proxy-base-url when proxy auth is provided.', + ); + } + return { + proxyEnabled: Boolean(proxyBaseUrl && proxyBearerToken), + proxyBaseUrl, + proxyBearerToken, + }; +} + +async function waitForMetroReady( + statusUrl: string, + startupTimeoutMs: number, + probeTimeoutMs: number, +): Promise { + const deadline = Date.now() + startupTimeoutMs; + while (Date.now() < deadline) { + const remainingMs = deadline - Date.now(); + const requestTimeoutMs = Math.min(probeTimeoutMs, Math.max(remainingMs, 1)); + if (await isMetroReady(statusUrl, requestTimeoutMs)) { + return true; + } + const sleepMs = Math.min(500, Math.max(deadline - Date.now(), 0)); + if (sleepMs > 0) { + await wait(sleepMs); + } + } + return false; +} + +export async function prepareMetroRuntime( + input: PrepareMetroRuntimeOptions = {}, +): Promise { + const env = input.env ?? process.env; + const cwd = process.cwd(); + const projectRoot = resolvePath(input.projectRoot ?? cwd, env, cwd); + const kind = detectMetroKind(projectRoot, input.kind ?? 'auto'); + const metroPort = parsePort(input.metroPort ?? 8081, 8081); + const listenHost = normalizeOptionalString(input.listenHost) ?? '0.0.0.0'; + const statusHost = normalizeOptionalString(input.statusHost) ?? '127.0.0.1'; + const publicBaseUrl = normalizeOptionalBaseUrl(input.publicBaseUrl); + const startupTimeoutMs = parseTimeout(input.startupTimeoutMs, 180_000, 30_000); + const probeTimeoutMs = parseTimeout(input.probeTimeoutMs, 10_000, 1_000); + const reuseExisting = input.reuseExisting ?? true; + const installProjectDeps = input.installDependenciesIfNeeded ?? true; + const runtimeFilePath = input.runtimeFilePath + ? resolvePath(input.runtimeFilePath, env, cwd) + : null; + const logPath = resolvePath( + input.logPath ?? path.join(projectRoot, '.agent-device', 'metro.log'), + env, + cwd, + ); + + if (!publicBaseUrl) { + throw new AppError('INVALID_ARGS', 'metro prepare requires --public-base-url .'); + } + + const { proxyEnabled, proxyBaseUrl, proxyBearerToken } = resolveProxySettings( + normalizeOptionalBaseUrl(input.proxyBaseUrl), + normalizeOptionalString(input.proxyBearerToken) ?? '', + ); + + const dependencyInstall = installProjectDeps + ? installDependenciesIfNeeded(projectRoot, env) + : { installed: false as const }; + const statusUrl = `http://${statusHost}:${metroPort}/status`; + + let started = false; + let reused = false; + let pid = 0; + if (reuseExisting && (await isMetroReady(statusUrl, probeTimeoutMs))) { + reused = true; + } else { + const startedProcess = startMetroProcess( + projectRoot, + kind, + metroPort, + listenHost, + logPath, + env, + ); + started = true; + pid = startedProcess.pid; + + if (!(await waitForMetroReady(statusUrl, startupTimeoutMs, probeTimeoutMs))) { + throw new Error( + `Metro did not become ready at ${statusUrl} within ${startupTimeoutMs}ms. Check ${logPath}.`, + ); + } + } + + const publicIosRuntime = buildPublicRuntime(publicBaseUrl, 'ios'); + const publicAndroidRuntime = buildPublicRuntime(publicBaseUrl, 'android'); + + let bridge: MetroBridgeResult | null = null; + let bridgeError: string | null = null; + + if (proxyEnabled) { + try { + bridge = await configureMetroBridge({ + baseUrl: proxyBaseUrl, + bearerToken: proxyBearerToken, + runtime: { + metro_bundle_url: publicIosRuntime.bundleUrl, + }, + timeoutMs: probeTimeoutMs, + }); + } catch (error) { + bridgeError = error instanceof Error ? error.message : String(error); + } + } + + if (proxyEnabled && (!bridge || bridge.probe.reachable === false)) { + throw new Error(describeBridgeFailure(proxyBaseUrl, bridgeError, bridge)); + } + + const iosRuntime = bridge?.iosRuntime ?? publicIosRuntime; + const androidRuntime = bridge?.androidRuntime ?? publicAndroidRuntime; + const result: PrepareMetroRuntimeResult = { + projectRoot, + kind, + dependenciesInstalled: dependencyInstall.installed, + packageManager: dependencyInstall.packageManager ?? null, + started, + reused, + pid, + logPath, + statusUrl, + runtimeFilePath, + iosRuntime, + androidRuntime, + bridge, + }; + + if (runtimeFilePath) { + fs.mkdirSync(path.dirname(runtimeFilePath), { recursive: true }); + fs.writeFileSync(runtimeFilePath, JSON.stringify(result, null, 2)); + } + + return result; +} diff --git a/src/client-types.ts b/src/client-types.ts index b0fb278ae3..29cda284b7 100644 --- a/src/client-types.ts +++ b/src/client-types.ts @@ -7,6 +7,7 @@ import type { } from './daemon/types.ts'; import type { DeviceKind, DeviceTarget, Platform, PlatformSelector } from './utils/device.ts'; import type { SnapshotNode } from './utils/snapshot.ts'; +import type { MetroPrepareKind, PrepareMetroRuntimeResult } from './client-metro.ts'; type DaemonTransportMode = 'auto' | 'socket' | 'http'; type DaemonServerMode = 'socket' | 'http' | 'dual'; @@ -237,6 +238,25 @@ export type RuntimeResult = { identifiers: AgentDeviceIdentifiers; }; +export type MetroPrepareOptions = { + projectRoot?: string; + kind?: MetroPrepareKind; + publicBaseUrl: string; + proxyBaseUrl?: string; + bearerToken?: string; + port?: number; + listenHost?: string; + statusHost?: string; + startupTimeoutMs?: number; + probeTimeoutMs?: number; + reuseExisting?: boolean; + installDependenciesIfNeeded?: boolean; + runtimeFilePath?: string; + logPath?: string; +}; + +export type MetroPrepareResult = PrepareMetroRuntimeResult; + export type CaptureSnapshotOptions = AgentDeviceRequestOverrides & AgentDeviceSelectionOptions & { interactiveOnly?: boolean; @@ -320,6 +340,9 @@ export type AgentDeviceClient = { set: (options: RuntimeSetOptions) => Promise; show: (options?: RuntimeShowOptions) => Promise; }; + metro: { + prepare: (options: MetroPrepareOptions) => Promise; + }; capture: { snapshot: (options?: CaptureSnapshotOptions) => Promise; screenshot: (options?: CaptureScreenshotOptions) => Promise; diff --git a/src/client.ts b/src/client.ts index e33b735722..3f6d145c57 100644 --- a/src/client.ts +++ b/src/client.ts @@ -1,4 +1,5 @@ import { sendToDaemon } from './daemon-client.ts'; +import { prepareMetroRuntime } from './client-metro.ts'; import { AppError } from './utils/errors.ts'; import { buildFlags, @@ -31,6 +32,7 @@ import type { EnsureSimulatorOptions, InternalRequestOptions, MaterializationReleaseOptions, + MetroPrepareOptions, RuntimeSetOptions, RuntimeShowOptions, } from './client-types.ts'; @@ -203,6 +205,25 @@ export function createAgentDeviceClient( resolveSessionName(config.session, options.session), ), }, + metro: { + prepare: async (options: MetroPrepareOptions) => + await prepareMetroRuntime({ + projectRoot: options.projectRoot ?? config.cwd, + kind: options.kind, + publicBaseUrl: options.publicBaseUrl, + proxyBaseUrl: options.proxyBaseUrl, + proxyBearerToken: options.bearerToken, + metroPort: options.port, + listenHost: options.listenHost, + statusHost: options.statusHost, + startupTimeoutMs: options.startupTimeoutMs, + probeTimeoutMs: options.probeTimeoutMs, + reuseExisting: options.reuseExisting, + installDependenciesIfNeeded: options.installDependenciesIfNeeded, + runtimeFilePath: options.runtimeFilePath, + logPath: options.logPath, + }), + }, capture: { snapshot: async (options: CaptureSnapshotOptions = {}) => { const session = resolveSessionName(config.session, options.session); @@ -258,6 +279,8 @@ export type { EnsureSimulatorResult, MaterializationReleaseOptions, MaterializationReleaseResult, + MetroPrepareOptions, + MetroPrepareResult, RuntimeResult, RuntimeSetOptions, RuntimeShowOptions, diff --git a/src/index.ts b/src/index.ts index 28d975acc2..a0b483973a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,6 +23,8 @@ export { type EnsureSimulatorResult, type MaterializationReleaseOptions, type MaterializationReleaseResult, + type MetroPrepareOptions, + type MetroPrepareResult, type RuntimeResult, type RuntimeSetOptions, type RuntimeShowOptions, @@ -30,5 +32,6 @@ export { type StartupPerfSample, } from './client.ts'; export { AppError, type NormalizedError } from './utils/errors.ts'; +export type { MetroPrepareKind, MetroRuntimeHints } from './client-metro.ts'; export type { SessionRuntimeHints } from './daemon/types.ts'; export type { SnapshotNode } from './utils/snapshot.ts'; diff --git a/src/utils/__tests__/args.test.ts b/src/utils/__tests__/args.test.ts index fef3aea192..ef87bc370b 100644 --- a/src/utils/__tests__/args.test.ts +++ b/src/utils/__tests__/args.test.ts @@ -129,6 +129,44 @@ test('parseArgs accepts install-from-source url and repeated headers', () => { assert.equal(parsed.flags.retentionMs, 60000); }); +test('parseArgs accepts metro prepare arguments', () => { + const parsed = parseArgs( + [ + 'metro', + 'prepare', + '--project-root', + './apps/demo', + '--public-base-url', + 'https://sandbox.example.test', + '--proxy-base-url', + 'https://proxy.example.test', + '--bearer-token', + 'secret', + '--port', + '9090', + '--kind', + 'expo', + '--runtime-file', + './.agent-device/metro-runtime.json', + '--no-reuse-existing', + '--no-install-deps', + ], + { strictFlags: true }, + ); + + assert.equal(parsed.command, 'metro'); + assert.deepEqual(parsed.positionals, ['prepare']); + assert.equal(parsed.flags.metroProjectRoot, './apps/demo'); + assert.equal(parsed.flags.metroPublicBaseUrl, 'https://sandbox.example.test'); + assert.equal(parsed.flags.metroProxyBaseUrl, 'https://proxy.example.test'); + assert.equal(parsed.flags.metroBearerToken, 'secret'); + assert.equal(parsed.flags.metroPreparePort, 9090); + assert.equal(parsed.flags.metroKind, 'expo'); + assert.equal(parsed.flags.metroRuntimeFile, './.agent-device/metro-runtime.json'); + assert.equal(parsed.flags.metroNoReuseExisting, true); + assert.equal(parsed.flags.metroNoInstallDeps, true); +}); + test('parseArgs accepts clipboard subcommands', () => { const read = parseArgs(['clipboard', 'read'], { strictFlags: true }); assert.equal(read.command, 'clipboard'); @@ -421,7 +459,9 @@ test('parseArgs rejects invalid swipe pattern', () => { test('usage includes --relaunch flag', () => { assert.match(usage(), /--relaunch/); assert.match(usage(), /install-from-source /); + assert.match(usage(), /metro prepare/); assert.match(usage(), /--header /); + assert.match(usage(), /--public-base-url /); assert.match(usage(), /--restart/); assert.match(usage(), /--target mobile\|tv/); assert.match(usage(), /--ios-simulator-device-set /); diff --git a/src/utils/__tests__/cli-option-schema.test.ts b/src/utils/__tests__/cli-option-schema.test.ts index d64b7a27eb..a4dff8c920 100644 --- a/src/utils/__tests__/cli-option-schema.test.ts +++ b/src/utils/__tests__/cli-option-schema.test.ts @@ -33,6 +33,13 @@ test('option schema exposes legacy env aliases and command scoping', () => { assert.ok(snapshotDepth); assert.equal(snapshotDepth.supportsCommand('snapshot'), true); assert.equal(snapshotDepth.supportsCommand('open'), false); + + const metroBearerToken = getOptionSpec('metroBearerToken'); + assert.ok(metroBearerToken); + assert.deepEqual(metroBearerToken.env.names, [ + 'AGENT_DEVICE_METRO_BEARER_TOKEN', + 'AGENT_DEVICE_PROXY_TOKEN', + ]); }); test('configurable option specs are filtered by command support', () => { diff --git a/src/utils/cli-option-schema.ts b/src/utils/cli-option-schema.ts index 5e17bf4c63..414345e61e 100644 --- a/src/utils/cli-option-schema.ts +++ b/src/utils/cli-option-schema.ts @@ -27,6 +27,7 @@ const CONFIG_EXCLUDED_FLAG_KEYS = new Set(['config', 'help', 'version', const LEGACY_ENV_VAR_NAMES: Partial> = { iosSimulatorDeviceSet: ['IOS_SIMULATOR_DEVICE_SET'], androidDeviceAllowlist: ['ANDROID_DEVICE_ALLOWLIST'], + metroBearerToken: ['AGENT_DEVICE_PROXY_TOKEN'], }; const BOOLEAN_TRUE_VALUES = new Set(['1', 'true', 'yes', 'on']); diff --git a/src/utils/command-schema.ts b/src/utils/command-schema.ts index 4861b9d809..3cf64188ab 100644 --- a/src/utils/command-schema.ts +++ b/src/utils/command-schema.ts @@ -27,6 +27,19 @@ export type CliFlags = { runtime?: string; metroHost?: string; metroPort?: number; + metroProjectRoot?: string; + metroKind?: 'auto' | 'react-native' | 'expo'; + metroPublicBaseUrl?: string; + metroProxyBaseUrl?: string; + metroBearerToken?: string; + metroPreparePort?: number; + metroListenHost?: string; + metroStatusHost?: string; + metroStartupTimeoutMs?: number; + metroProbeTimeoutMs?: number; + metroRuntimeFile?: string; + metroNoReuseExisting?: boolean; + metroNoInstallDeps?: boolean; bundleUrl?: string; launchUrl?: string; boot?: boolean; @@ -280,6 +293,103 @@ const FLAG_DEFINITIONS: readonly FlagDefinition[] = [ usageLabel: '--metro-port ', usageDescription: 'runtime set: session-scoped Metro/debug port hint', }, + { + key: 'metroProjectRoot', + names: ['--project-root'], + type: 'string', + usageLabel: '--project-root ', + usageDescription: 'metro prepare: React Native project root (default: cwd)', + }, + { + key: 'metroKind', + names: ['--kind'], + type: 'enum', + enumValues: ['auto', 'react-native', 'expo'], + usageLabel: '--kind auto|react-native|expo', + usageDescription: 'metro prepare: detect or force the Metro launcher kind', + }, + { + key: 'metroPublicBaseUrl', + names: ['--public-base-url'], + type: 'string', + usageLabel: '--public-base-url ', + usageDescription: 'metro prepare: public base URL used to build bundle hints', + }, + { + key: 'metroProxyBaseUrl', + names: ['--proxy-base-url'], + type: 'string', + usageLabel: '--proxy-base-url ', + usageDescription: 'metro prepare: optional agent-device-proxy base URL for Metro bridging', + }, + { + key: 'metroBearerToken', + names: ['--bearer-token'], + type: 'string', + usageLabel: '--bearer-token ', + usageDescription: + 'metro prepare: proxy bearer token (prefer AGENT_DEVICE_PROXY_TOKEN or AGENT_DEVICE_METRO_BEARER_TOKEN)', + }, + { + key: 'metroPreparePort', + names: ['--port'], + type: 'int', + min: 1, + max: 65535, + usageLabel: '--port ', + usageDescription: 'metro prepare: local Metro port (default: 8081)', + }, + { + key: 'metroListenHost', + names: ['--listen-host'], + type: 'string', + usageLabel: '--listen-host ', + usageDescription: 'metro prepare: host Metro listens on (default: 0.0.0.0)', + }, + { + key: 'metroStatusHost', + names: ['--status-host'], + type: 'string', + usageLabel: '--status-host ', + usageDescription: 'metro prepare: host used for local /status polling (default: 127.0.0.1)', + }, + { + key: 'metroStartupTimeoutMs', + names: ['--startup-timeout-ms'], + type: 'int', + min: 1, + usageLabel: '--startup-timeout-ms ', + usageDescription: 'metro prepare: timeout while waiting for Metro to become ready', + }, + { + key: 'metroProbeTimeoutMs', + names: ['--probe-timeout-ms'], + type: 'int', + min: 1, + usageLabel: '--probe-timeout-ms ', + usageDescription: 'metro prepare: timeout for /status and proxy bridge calls', + }, + { + key: 'metroRuntimeFile', + names: ['--runtime-file'], + type: 'string', + usageLabel: '--runtime-file ', + usageDescription: 'metro prepare: optional file path to persist the JSON result', + }, + { + key: 'metroNoReuseExisting', + names: ['--no-reuse-existing'], + type: 'boolean', + usageLabel: '--no-reuse-existing', + usageDescription: 'metro prepare: always start a fresh Metro process', + }, + { + key: 'metroNoInstallDeps', + names: ['--no-install-deps'], + type: 'boolean', + usageLabel: '--no-install-deps', + usageDescription: 'metro prepare: skip package-manager install when node_modules is missing', + }, { key: 'bundleUrl', names: ['--bundle-url'], @@ -712,6 +822,29 @@ const COMMAND_SCHEMAS: Record = { allowedFlags: ['metroHost', 'metroPort', 'bundleUrl', 'launchUrl'], skipCapabilityCheck: true, }, + metro: { + usageOverride: + 'metro prepare --public-base-url [--project-root ] [--port ] [--kind auto|react-native|expo]', + description: + 'Prepare a local Metro runtime and optionally bridge it through agent-device-proxy', + positionalArgs: ['prepare'], + allowedFlags: [ + 'metroProjectRoot', + 'metroKind', + 'metroPublicBaseUrl', + 'metroProxyBaseUrl', + 'metroBearerToken', + 'metroPreparePort', + 'metroListenHost', + 'metroStatusHost', + 'metroStartupTimeoutMs', + 'metroProbeTimeoutMs', + 'metroRuntimeFile', + 'metroNoReuseExisting', + 'metroNoInstallDeps', + ], + skipCapabilityCheck: true, + }, clipboard: { usageOverride: 'clipboard read | clipboard write ', description: 'Read or write device clipboard text', diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index 3aa32d281d..c4738e115d 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -42,6 +42,7 @@ agent-device app-switcher - Tenant-scoped daemon runs can pass `--tenant`, `--session-isolation tenant`, `--run-id`, and `--lease-id` to enforce lease admission. - Remote daemon clients can pass `--daemon-base-url http(s)://host:port[/base-path]` to skip local daemon discovery/startup and call a remote HTTP daemon directly. - Use `--daemon-auth-token ` (or `AGENT_DEVICE_DAEMON_AUTH_TOKEN`) when the remote daemon expects the shared daemon token over HTTP; the client sends it in both the JSON-RPC request token and HTTP auth headers. +- `metro prepare` starts or reuses a local Metro instance for sandbox/client flows and prints runtime JSON to stdout. `--json` wraps the same payload in the standard `{ success, data }` envelope. Pass `--proxy-base-url ` plus `AGENT_DEVICE_PROXY_TOKEN` (preferred) or `--bearer-token ` when the runtime must be bridged through `agent-device-proxy`; add `--runtime-file ` only when a persisted artifact is required. - `runtime set|show|clear` manages session-scoped runtime hints for remote/native daemon flows. Supported hints include `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url`. Typed daemon clients can also pass `runtime: { ... }` on `open` to replace the stored session runtime atomically for that launch. Android applies Metro hints through React Native dev prefs before `open`, and iOS simulators apply them through app defaults before launch. - Android React Native relaunch flows require an installed package name for `open --relaunch`; install/reinstall the APK first, then relaunch by package. `open --relaunch` is rejected because runtime hints are written through the installed app sandbox. - Remote daemon screenshots and recordings are downloaded back to the caller path, so `screenshot page.png` and `record start session.mp4` remain usable when the daemon runs on another host. @@ -485,11 +486,14 @@ agent-device trace stop session.trace ```bash agent-device runtime show +agent-device metro prepare --public-base-url "https://sandbox.example.test" --proxy-base-url "https://proxy.example.test" --bearer-token "$TOKEN" agent-device runtime set --session my-session --platform android --metro-host 10.0.0.10 --metro-port 8081 agent-device runtime set --session my-session --platform ios --bundle-url "http://10.0.0.10:8081/index.bundle?platform=ios" agent-device runtime clear ``` +- `metro prepare` emits JSON runtime hints to stdout and does not mutate session runtime state by itself. +- Add `--runtime-file ` when callers need the same JSON payload written to disk for later steps. - `runtime show` prints the current session-scoped runtime hints. - `runtime set` updates supported hints: `--metro-host`, `--metro-port`, `--bundle-url`, and `--launch-url`. - `runtime clear` removes previously configured hints for the active session.