diff --git a/packages/command-registry/src/registry.ts b/packages/command-registry/src/registry.ts index 8d97dd08a1..e35ae00ed5 100644 --- a/packages/command-registry/src/registry.ts +++ b/packages/command-registry/src/registry.ts @@ -712,6 +712,23 @@ const COMMAND_DESCRIPTOR_BY_NAME: ReadonlyMap< CommandDescriptor & { standaloneCommandProjection: StandaloneCommandProjection | undefined } > = new Map(commandDescriptors.map((descriptor) => [descriptor.name, descriptor])); +const DAEMON_COMMAND_BY_SERVED_PUBLIC_COMMAND: ReadonlyMap = new Map( + (commandDescriptors as readonly CommandDescriptor[]).flatMap(({ name, catalog }) => + catalog.group === 'internal' && catalog.servesPublicCommand + ? [[catalog.servesPublicCommand, name] as const] + : [], + ), +); + +/** + * The name the daemon runs a command under: the internal command that declares it serves this public + * command (`install-from-source` runs as `install_source`), or else the name itself. Daemon traits + * are declared under this name. + */ +export function resolveDaemonCommandName(command: string): string { + return DAEMON_COMMAND_BY_SERVED_PUBLIC_COMMAND.get(command) ?? command; +} + /** * Whether the daemon admits this command's request against the lease it names (ADR 0007). A name * outside the registry, or a command exempt from lease admission, never meets lease admission. diff --git a/packages/daemon/docs/remote-device-lease-contracts.md b/packages/daemon/docs/remote-device-lease-contracts.md index eee4ed0627..ffa9926173 100644 --- a/packages/daemon/docs/remote-device-lease-contracts.md +++ b/packages/daemon/docs/remote-device-lease-contracts.md @@ -99,16 +99,17 @@ These commands keep the heartbeat: - A command on a host-allocated `macos-app` lease. - A command on a lease whose provider has a runtime. A heartbeat runs its lifecycle hooks, such as the Limrun instance liveness check. - A command exempt from lease admission. -- `install`, `reinstall`, and `install-from-source`, which can upload a local artifact before admission. +- `install` and `reinstall`, which can upload a local artifact before admission. +- `install-from-source` without an http(s) URL. With such a URL, the daemon downloads the artifact after admission, so this item does not apply. The other items in this list still apply. - A command with `--save-script`. - `batch`, `replay`, and `test`, which read local scripts while they build the request. A script path can be a pipe. - `fill --text-stdin`, so that a refusal comes before the CLI reads the pipe. - A command that prepares a Metro runtime, which registers remote work under the lease before the command. - A command whose daemon URL, tenant, run, lease backend, or device key differs from the saved connection, or that has no saved connection. - A command whose stored lease id is not canonical lower-case hex. -- A by-spec `open` that allocates fresh: the connection names no device, or the request names a device spec or a device selector. +- A by-spec allocation (`open`, `install`, `reinstall`, `uninstall`, or `install-from-source` through a proxy) that allocates fresh: the connection names no device, or the request names a device spec or a device selector. -A by-spec `open` that names no spec or selector reuses the stored device without a heartbeat. +A by-spec allocation that names no spec or selector reuses the stored device without a heartbeat, unless another item in this list applies. ## Admitted request work diff --git a/src/__tests__/cli-lease-admission-proxy.test.ts b/src/__tests__/cli-lease-admission-proxy.test.ts index aafabca1a3..3a82cf0089 100644 --- a/src/__tests__/cli-lease-admission-proxy.test.ts +++ b/src/__tests__/cli-lease-admission-proxy.test.ts @@ -32,34 +32,43 @@ const LEASE_SCOPE = { deviceKey: 'android:mobile:emulator-9999', } as const; -test('a lease the daemon dropped is reallocated through the proxy without a heartbeat', async (t) => { - if (await skipWhenLoopbackUnavailable(t)) return; - await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => { - const client = createAgentDeviceClient({ - daemonBaseUrl: baseUrl, - daemonAuthToken: 'client-secret', - daemonTransport: 'http', - }); - const lease = await client.leases.allocate({ ...LEASE_SCOPE, leaseId: 'b'.repeat(32) }); - writeConnection(stateDir, project, baseUrl, lease.leaseId); - await client.leases.release({ ...LEASE_SCOPE, leaseId: lease.leaseId }); - upstream.length = 0; +test.for<[string, string[], string | undefined]>([ + ['snapshot', ['snapshot'], LEASE_SCOPE.leaseProvider], + // A `proxy` provider connection reallocates an install by spec, and this daemon has no device to + // grant. The URL is a loopback port with no listener, so a download never leaves the host. + ['install_source', ['install-from-source', 'http://127.0.0.1:1/app.apk'], undefined], +])( + 'a dropped lease is reallocated for %s through the proxy without a heartbeat', + async ([command, argv, leaseProvider], t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => { + const client = createAgentDeviceClient({ + daemonBaseUrl: baseUrl, + daemonAuthToken: 'client-secret', + daemonTransport: 'http', + }); + const scope = { ...LEASE_SCOPE, leaseProvider }; + const lease = await client.leases.allocate({ ...scope, leaseId: 'b'.repeat(32) }); + writeConnection(stateDir, project, baseUrl, lease.leaseId, leaseProvider); + await client.leases.release({ ...scope, leaseId: lease.leaseId }); + upstream.length = 0; - const result = await cli(['snapshot']); + const result = await cli(argv); - const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId; - assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout); - // The setup above already cached `/health` for this endpoint in this process, so only RPCs show. - assert.deepEqual( - upstream.filter((route) => route.startsWith('/rpc')), - ['/rpc snapshot', '/rpc agent_device.lease.allocate', '/rpc snapshot'], - ); - // The resent command passed admission: whatever it answered, it was not the lease refusal. - if (result.code !== null) { - assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND'); - } - }); -}); + const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId; + assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout); + // The setup above already cached `/health` for this endpoint in this process, so only RPCs show. + assert.deepEqual( + upstream.filter((route) => route.startsWith('/rpc')), + [`/rpc ${command}`, '/rpc agent_device.lease.allocate', `/rpc ${command}`], + ); + // The resent command passed admission: whatever it answered, it was not the lease refusal. + if (result.code !== null) { + assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND'); + } + }); + }, +); // A reused lease on the connection does not move a command that checks no lease off the checked route. test('a checked connection sends a command that checks no lease as its one checked request', async (t) => { @@ -149,7 +158,13 @@ async function describe(request: Request): Promise { return `${route} ${body.method === 'agent_device.command' ? body.params?.command : body.method}`; } -function writeConnection(stateDir: string, project: string, baseUrl: string, leaseId: string) { +function writeConnection( + stateDir: string, + project: string, + baseUrl: string, + leaseId: string, + leaseProvider: string | undefined, +) { const remoteConfigPath = path.join(project, 'agent.remote.json'); fs.writeFileSync(remoteConfigPath, JSON.stringify({})); const now = new Date().toISOString(); @@ -165,7 +180,7 @@ function writeConnection(stateDir: string, project: string, baseUrl: string, lea runId: LEASE_SCOPE.runId, leaseId, leaseBackend: LEASE_SCOPE.leaseBackend, - leaseProvider: LEASE_SCOPE.leaseProvider, + leaseProvider, clientId: LEASE_SCOPE.clientId, deviceKey: LEASE_SCOPE.deviceKey, platform: 'android', diff --git a/src/__tests__/cli-lease-admission.test.ts b/src/__tests__/cli-lease-admission.test.ts index 9b5f6a0ccf..e3c2cf7665 100644 --- a/src/__tests__/cli-lease-admission.test.ts +++ b/src/__tests__/cli-lease-admission.test.ts @@ -112,6 +112,9 @@ function transportTo(daemon: Daemon) { } if (daemon.refusal && scopeOf(req, 'leaseId') === STORED_LEASE) throw daemon.refusal(); if (req.command === 'open') return { ok: true, data: { session: req.session } }; + if (req.command === 'install_source') { + return { ok: true, data: { launchTarget: 'com.example' } }; + } return { ok: true, data: { nodes: [], truncated: false } }; }; } @@ -151,6 +154,11 @@ function markedOf(result: Awaited>): boolean[] { test.each([ ['snapshot -i', ['snapshot', '-i'], 'snapshot'], ['a proxy open on the stored device', ['open', 'com.example'], 'open'], + [ + 'an install from a URL the daemon downloads', + ['install-from-source', 'https://example.com/app.apk'], + 'install_source', + ], ])('%s reaches a lease-admission daemon without a heartbeat', async (_name, argv, command) => { const ws = workspace(); const result = await run(ws, argv, transportTo({ leaseAdmission: true })); @@ -288,7 +296,7 @@ test.each<[string, string[], Partial]>([ { leaseProvider: 'limrun' }, ], ['an install that uploads a local artifact first', ['install', 'com.example', 'app.apk'], {}], - ['an install from a source', ['install-from-source', 'https://example.com/app.apk'], {}], + ['an install-from-source naming a local path', ['install-from-source', 'app.apk'], {}], [ 'a stored lease id that is not canonical', ['snapshot'], @@ -317,6 +325,18 @@ test.each<[string, string[], Partial]>([ fs.rmSync(ws.root, { recursive: true, force: true }); }); +// Without its own backend, nothing says the stored lease is on the one this command asks for. +test('a stored lease with no backend of its own is not left to admission', async () => { + const ws = workspace({ leaseBackend: undefined }); + const result = await run(ws, ['snapshot'], transportTo({ leaseAdmission: true })); + + assert.equal(result.code, null, result.stdout); + assert.deepEqual(commandsOf(result), ['lease_allocate', 'snapshot']); + assert.deepEqual(markedOf(result), [false, false]); + + fs.rmSync(ws.root, { recursive: true, force: true }); +}); + // Metro preparation registers the companion tunnel under the connection's lease before the command, // so the lease is checked first and the tunnel and the app share the live one. test('an open that prepares Metro replaces an ended lease before the bridge setup', async () => { diff --git a/src/cli/commands/__tests__/proxy-lease-device-spec.test.ts b/src/cli/commands/__tests__/proxy-lease-device-spec.test.ts index eadb8cf9e7..89a428a6fd 100644 --- a/src/cli/commands/__tests__/proxy-lease-device-spec.test.ts +++ b/src/cli/commands/__tests__/proxy-lease-device-spec.test.ts @@ -640,6 +640,32 @@ test('a new spec lease for another device than the requested --udid is released fs.rmSync(tempRoot, { recursive: true, force: true }); }); +test('install-from-source on a proxy connection with no lease allocates one by spec', async () => { + const { tempRoot, stateDir, flags } = proxyWorkspace('agent-device-proxy-install-source-'); + const requests: LeaseAllocateRequest[] = []; + + const materialized = await materializeRemoteConnectionForCommand({ + host: createTestHostEnvironment(), + command: 'install-from-source', + positionals: ['https://example.com/app.apk'], + flags, + client: createTestClient({ + listDevices: unexpectedCommandCall, + allocate: async (request) => { + requests.push(request); + return grantedLease(request, { deviceKey: REMOTE_DEVICE_KEY }); + }, + release: unexpectedCommandCall, + }), + }); + + assert.equal(requests.length, 1); + assert.equal(requests[0]?.deviceKey, undefined); + assert.equal(materialized.flags.udid, 'SIM-REMOTE'); + assert.equal(readRemoteConnectionState({ stateDir, session: 'adc-proxy' })?.leaseId, 'lease-1'); + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); + test('a lease re-allocated by its stored device for a non-allocating command does not carry the spec', async () => { const { tempRoot, flags } = proxyWorkspace('agent-device-proxy-device-spec-snapshot-', { leaseId: 'lease-1', diff --git a/src/cli/commands/connection-lease-admission.ts b/src/cli/commands/connection-lease-admission.ts index d9270615a9..3865b6aa4e 100644 --- a/src/cli/commands/connection-lease-admission.ts +++ b/src/cli/commands/connection-lease-admission.ts @@ -1,6 +1,8 @@ +import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog'; import { commandMeetsLeaseAdmission, isDelegatingCompositeCommand, + resolveDaemonCommandName, } from '@agent-device/command-registry/registry'; import { isUndispatchedInactiveLeaseRefusal, @@ -46,7 +48,8 @@ export type AdmissionCheckedLease = Readonly<{ * - a host-allocated `macos-app` lease has its own refusal; * - a provider with a runtime runs lifecycle hooks on a heartbeat, such as an instance liveness check; * - a command exempt from lease admission is never checked there; - * - an upload of a local artifact runs before admission, under the lease; + * - an upload of a local artifact runs before admission, under the lease. Of the commands that can + * upload, only an `install_source` of an http(s) URL uploads nothing: the daemon downloads it; * - Metro preparation registers remote work under the lease before the command; * - a composite (`batch`, `replay`, `test`) reads local scripts while it builds its request, and * `fill --text-stdin` reads a pipe: a refusal must come before either, and a rerun could not read @@ -61,6 +64,7 @@ export type AdmissionCheckedLease = Readonly<{ export function leaseCheckedByAdmission( options: Readonly<{ command: string; + positionals: readonly string[] | undefined; state: RemoteConnectionState; /** The stored connection record, absent while the connection is still built from flags. */ savedState: RemoteConnectionState | undefined; @@ -73,6 +77,7 @@ export function leaseCheckedByAdmission( }>, ): AdmissionCheckedLease | undefined { const { state, flags, check } = options; + const command = resolveDaemonCommandName(options.command); if ( !check?.byAdmission || !state.leaseId || @@ -80,10 +85,10 @@ export function leaseCheckedByAdmission( state.leaseBackend !== options.leaseBackend || state.leaseBackend === 'macos-app' || leaseProviderRequiringRuntime({ leaseProvider: state.leaseProvider }) !== undefined || - !commandMeetsLeaseAdmission(options.command) || - requestUploadsArtifacts({ command: options.command }) || + !commandMeetsLeaseAdmission(command) || + uploadsBeforeAdmission(command, options.positionals) || options.preparesRuntime || - isDelegatingCompositeCommand({ command: options.command, positionals: [] }) || + isDelegatingCompositeCommand({ command, positionals: [] }) || flags.textStdin === true || flags.saveScript !== undefined || !namesSavedConnection(options.savedState, state, flags) || @@ -95,6 +100,17 @@ export function leaseCheckedByAdmission( return { leaseId: state.leaseId, ...(leaseTtlMs === undefined ? {} : { leaseTtlMs }) }; } +/** Whether sending the command may upload a local artifact first. */ +function uploadsBeforeAdmission( + command: string, + positionals: readonly string[] | undefined, +): boolean { + if (!requestUploadsArtifacts({ command })) return false; + if (command !== INTERNAL_COMMANDS.installSource) return true; + const protocol = URL.parse(positionals?.[0] ?? '')?.protocol; + return protocol !== 'http:' && protocol !== 'https:'; +} + /** Whether the command goes to the saved connection's daemon, under its owner scope. */ function namesSavedConnection( saved: RemoteConnectionState | undefined, diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index ffb6540683..a788c43683 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -151,6 +151,7 @@ export async function acquireConnectionLease(options: { if (leasePolicy.shouldAllocate(command)) { const materialized = await materializeLeaseForCommand({ command, + positionals: options.positionals, client, state, nextState, @@ -204,6 +205,7 @@ function carriedConnectionPlatform( async function materializeLeaseForCommand(options: { command: string; + positionals?: string[]; client: AgentDeviceClient; state: RemoteConnectionState; nextState: RemoteConnectionState; @@ -245,6 +247,7 @@ async function materializeLeaseForCommand(options: { nextFlags.platform = platform; const admissionCheckedLease = leaseCheckedByAdmission({ command, + positionals: options.positionals, state: nextState, flags: nextFlags, leaseBackend, diff --git a/src/cli/commands/proxy-lease-device.ts b/src/cli/commands/proxy-lease-device.ts index 2eb61965d1..3c5e3565f5 100644 --- a/src/cli/commands/proxy-lease-device.ts +++ b/src/cli/commands/proxy-lease-device.ts @@ -24,8 +24,9 @@ import type { CliFlags } from '@agent-device/contracts/command'; import type { AgentDeviceClient } from '@agent-device/command-surface'; import type { LeaseLedger } from './connection-lease-transaction.ts'; import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import { resolveDaemonCommandName } from '@agent-device/command-registry/registry'; -const proxyLeaseAllocatingCommands: ReadonlySet = new Set([ +const proxyLeaseAllocatingDaemonCommands: ReadonlySet = new Set([ PUBLIC_COMMANDS.open, PUBLIC_COMMANDS.install, PUBLIC_COMMANDS.reinstall, @@ -62,7 +63,7 @@ export async function resolveProxyLeaseState(options: { flags: CliFlags; leaseBackend?: LeaseBackend; }): Promise { - if (!proxyLeaseAllocatingCommands.has(options.command)) { + if (!proxyLeaseAllocatingDaemonCommands.has(resolveDaemonCommandName(options.command))) { if (options.state.leaseId && options.state.deviceKey) return { state: options.state }; throw new AppError( 'INVALID_ARGS', diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index c562f2edcb..165b187607 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -512,7 +512,7 @@ Direct proxy flow for a remote Mac/simulator: Leased sessions: a connection from connect proxy, connect (cloud), another connect provider, or a remote config that sets leaseProvider leases its device for one agent. Every command on it that takes a session, from connect to disconnect, names its session with --session , AGENT_DEVICE_SESSION, or a config session. A command that takes no session, such as auth, daemon, device, plugins, proxy, or web, runs on no connection. It never reads the active connection or leases a device through a remote config. Without a session, a command that takes one fails with INVALID_ARGS, reason REMOTE_SESSION_REQUIRED, before anything is leased, and never falls back to the connection another agent on the machine saved last. Set AGENT_DEVICE_SESSION once per agent or CI job before connect. Proxy lease by device spec: - Without --udid or --serial, open, install, reinstall, and uninstall through connect proxy send --platform, --target, and --device on the lease allocate, and the backend in front of the daemon picks the device. --os , --image-tag , --device-mode , --device-baseline , and --physical add a device spec to that request. A non-blank osVersion, imageTag, deviceMode or deviceBaseline and physical: true name a spec key, sent as given; the backend validates its value (for example, Android --os is an API level, --device-mode full asks for an unslimmed iOS simulator, and --device-baseline names a saved device state the backend restores; it is unrelated to diff screenshot --baseline ). A blank string and physical: false name nothing, from the CLI, the SDK, or MCP. A value of another type fails with INVALID_ARGS, reason device-spec-invalid. connect proxy stores the spec keys it names as defaults like --platform and --device. + Without --udid or --serial, open, install, reinstall, uninstall, and install-from-source through connect proxy send --platform, --target, and --device on the lease allocate, and the backend in front of the daemon picks the device. On open, install, reinstall, and uninstall, --os , --image-tag , --device-mode , --device-baseline , and --physical add a device spec to that request. install-from-source takes no spec flags. A non-blank osVersion, imageTag, deviceMode or deviceBaseline and physical: true name a spec key, sent as given; the backend validates its value (for example, Android --os is an API level, --device-mode full asks for an unslimmed iOS simulator, and --device-baseline names a saved device state the backend restores; it is unrelated to diff screenshot --baseline ). A blank string and physical: false name nothing, from the CLI, the SDK, or MCP. A value of another type fails with INVALID_ARGS, reason device-spec-invalid. connect proxy stores the spec keys it names as defaults like --platform and --device. agent-device open MyApp --platform ios --device "iPhone 17 Pro" --os ">=26" agent-device open MyApp --platform android --os 34 --image-tag google_apis_playstore A backend that honours the spec returns the granted device as lease.device (model, osVersion, imageTag, physical, deviceMode when it reports one, and baseline {name, version} when one was restored); open --json prints it. A lease that reports no deviceMode is accepted without confirming the mode. A daemon, local or behind agent-device proxy, refuses a request that names a spec key with UNSUPPORTED_OPERATION, reason device-spec-unsupported, and details.keys, and records no lease. When the backend returns a lease without lease.device, with deviceMode slim for a full request, or without baseline.name equal to the requested --device-baseline, the CLI releases that lease, unless the allocation explicitly reports reuse (created: false). The command then fails with UNSUPPORTED_OPERATION, reason device-spec-unsupported, and details.released reports whether a release it attempted succeeded. A live lease serves a later command only when every spec key the command names equals the one the lease was allocated by; otherwise the command fails with reason CONNECTION_DEVICE_CONFLICT. Run connect --force to lease by another spec. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index c755b5b827..3198f394ad 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -62,7 +62,7 @@ config, an explicit `--config` file, or protected CI environment variables. ## Lease by device spec -A service in front of the daemon, such as simlock, can also pick the device by OS version, Android image tag, iOS simulator mode, saved device state (baseline), and physical or virtual class. Pass `--os `, `--image-tag `, `--device-mode `, `--device-baseline `, or `--physical` to `open`, `install`, `reinstall`, or `uninstall`, and the CLI sends them with `--platform`, `--target`, and `--device` on the lease request. A non-blank `osVersion`, `imageTag`, `deviceMode` or `deviceBaseline` and `physical: true` name a spec key and are sent as given. An empty or blank string and `physical: false` name nothing, from the CLI, the SDK, or MCP. A value of another type (for example `physical: "yes"`) fails with `INVALID_ARGS` and `details.reason: "device-spec-invalid"`. The service validates the values themselves (for example, Android `--os` is an API level). `connect proxy` stores the spec keys it names as defaults like `--platform` and `--device`. `--target` stays the device class selector. +A service in front of the daemon, such as simlock, can also pick the device by OS version, Android image tag, iOS simulator mode, saved device state (baseline), and physical or virtual class. Pass `--os `, `--image-tag `, `--device-mode `, `--device-baseline `, or `--physical` to `open`, `install`, `reinstall`, or `uninstall`, and the CLI sends them with `--platform`, `--target`, and `--device` on the lease request. A non-blank `osVersion`, `imageTag`, `deviceMode` or `deviceBaseline` and `physical: true` name a spec key and are sent as given. An empty or blank string and `physical: false` name nothing, from the CLI, the SDK, or MCP. A value of another type (for example `physical: "yes"`) fails with `INVALID_ARGS` and `details.reason: "device-spec-invalid"`. The service validates the values themselves (for example, Android `--os` is an API level). `connect proxy` stores the spec keys it names as defaults like `--platform` and `--device`. `install-from-source` also allocates through the proxy, but takes no spec flags. `--target` stays the device class selector. ```bash agent-device open MyApp --platform ios --device "iPhone 17 Pro" --os ">=26"