diff --git a/src/__tests__/cli-leased-session.test.ts b/src/__tests__/cli-leased-session.test.ts index 5ddd9e9fda..2582d17953 100644 --- a/src/__tests__/cli-leased-session.test.ts +++ b/src/__tests__/cli-leased-session.test.ts @@ -2,7 +2,8 @@ import { test, vi } from 'vitest'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; -import { makeTempWorkspace } from '@agent-device/test-kit'; +import { installFakeManagedAgentBrowser, makeTempWorkspace } from '@agent-device/test-kit'; +import { withCommandExecutorOverride } from '@agent-device/host-kit/command'; import { createAgentDeviceClient } from '@agent-device/client'; import type { DaemonResponse } from '@agent-device/daemon-client'; import { @@ -361,18 +362,68 @@ test('a command that takes no session runs while a leased connection is active', // The active leased connection still makes a connection command name its session... assertSessionRequired(await runAgentCommand(solo, ['snapshot'])); - // ...but `auth` runs on no connection, and `--session` is not one of its flags. + // ...but `auth` and `web` run on no connection, and `--session` is not one of their flags. + const install = await installFakeManagedAgentBrowser(solo.stateDir); const environments: Record[] = [{}, { AGENT_DEVICE_SESSION: 'demo' }]; for (const env of environments) { - const result = await runAgentCommand(solo, ['auth', 'status'], env); - assert.equal(result.code, null, result.stdout); - assert.equal(JSON.parse(result.stdout).data.authenticated, false); - assert.deepEqual(result.calls, []); + const auth = await runAgentCommand(solo, ['auth', 'status'], env); + assert.equal(auth.code, null, auth.stdout); + assert.equal(JSON.parse(auth.stdout).data.authenticated, false); + assert.deepEqual(auth.calls, []); + + const doctor = await withCommandExecutorOverride( + async () => ({ stdout: 'ok', stderr: '', exitCode: 0 }), + async () => await runAgentCommand(solo, ['web', 'doctor'], env), + ); + // `web` ends through process.exit, which the capture throws, so the report is the first document. + assert.match(doctor.stdout, /^\{\n {2}"success": true,/, doctor.stdout); + assert.ok(doctor.stdout.includes(JSON.stringify(install.binaryPath)), doctor.stdout); + assert.deepEqual(doctor.calls, []); } fs.rmSync(solo.root, { recursive: true, force: true }); }); +test('a command that takes no session never leases through a remote config', async () => { + const solo = workspace(); + const remoteConfig = path.join(solo.project, 'generic.remote.json'); + fs.writeFileSync( + remoteConfig, + JSON.stringify({ + daemonBaseUrl: PROXY_URL, + tenant: 'acme', + runId: 'run-generic', + leaseBackend: 'android-instance', + platform: 'android', + }), + ); + + // A profile that names a lease provider asks for no session either: `auth` cannot take one. + for (const profile of [remoteConfig, writeLeasedProfile(solo)]) { + const auth = await runAgentCommand(solo, ['auth', 'status', '--remote-config', profile]); + assert.equal(auth.code, null, auth.stdout); + assert.equal(JSON.parse(auth.stdout).data.authenticated, false); + assert.deepEqual(auth.calls, []); + assert.equal(readRemoteConnectionState({ stateDir: solo.stateDir, session: 'default' }), null); + } + + // The same profile does lease for a command that takes a session. + const open = await runAgentCommand(solo, [ + 'open', + 'com.example', + '--remote-config', + remoteConfig, + ]); + assert.equal(open.code, null, open.stdout); + assert.ok( + open.calls.some((call) => call.command === 'lease_allocate'), + open.stdout, + ); + assert.notEqual(readRemoteConnectionState({ stateDir: solo.stateDir, session: 'default' }), null); + + fs.rmSync(solo.root, { recursive: true, force: true }); +}); + function writeLeasedProfile(workspace: Workspace): string { const remoteConfig = path.join(workspace.project, 'shared.remote.json'); fs.writeFileSync( diff --git a/src/cli-command-dispatch.test.ts b/src/cli-command-dispatch.test.ts index c969225ad2..1900a3ad62 100644 --- a/src/cli-command-dispatch.test.ts +++ b/src/cli-command-dispatch.test.ts @@ -10,20 +10,15 @@ test('cli.ts command dispatch checks are recognized by parser-level unknown-comm // The exact set, so a reader that collects nothing, or stops collecting, fails here instead // of passing over an empty loop. assert.deepEqual([...commands].sort(), [ - 'auth', 'batch', 'cdp', 'close', 'connect', 'connection', - 'daemon', - 'device', 'disconnect', 'help', 'mcp', 'open', - 'plugins', - 'proxy', 'react-devtools', 'runtime', 'test', diff --git a/src/cli.ts b/src/cli.ts index 20b0d78ea6..86fb9c4715 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -130,12 +130,8 @@ const REMOTE_MATERIALIZATION_DEFERRED_COMMANDS = new Set([ 'connect', 'connection', 'close', - 'daemon', - 'plugins', - 'device', 'disconnect', 'metro', - 'proxy', 'session', 'takeover', ]); @@ -407,8 +403,10 @@ async function resolveRunContextOrExit( }); // A leased remote config, or a connect without one (it always leases through a provider), needs // an explicit session before anything is resolved or leased (#3931). + const leasedRemoteConfig = + parsed.remoteConfigLeaseProvider && runsOnRemoteConnection(base.command); const leasedConnect = base.command === 'connect' && !flags.remoteConfig; - if (flags.session === undefined && (parsed.remoteConfigLeaseProvider || leasedConnect)) { + if (flags.session === undefined && (leasedRemoteConfig || leasedConnect)) { throw remoteSessionRequiredError(parsed.remoteConfigLeaseProvider); } const daemonPaths = resolveDaemonPaths(flags.stateDir, { @@ -788,9 +786,7 @@ function resolveActiveConnectionDefaults(options: { if ( options.command === 'connect' || options.command === 'connection' || - // A command that cannot take a session (`auth`, `daemon`, `plugins`, `device`, `proxy`) runs - // on no connection. Reading the active one would refuse it for a session it cannot name. - !isFlagSupportedForCommand('session', options.command) + !runsOnRemoteConnection(options.command) ) { return null; } @@ -805,19 +801,19 @@ function resolveActiveConnectionDefaults(options: { return defaults; } +// A command that cannot take a session runs on no remote connection. Reading, authenticating or +// leasing one would act for a session the command cannot name. +function runsOnRemoteConnection(command: string): boolean { + return isFlagSupportedForCommand('session', command); +} + function shouldMaterializeRemoteConnection(command: string): boolean { - return !REMOTE_MATERIALIZATION_DEFERRED_COMMANDS.has(command); + return runsOnRemoteConnection(command) && !REMOTE_MATERIALIZATION_DEFERRED_COMMANDS.has(command); } function shouldResolveRemoteAuth(command: string): boolean { - return ( - command !== 'auth' && - command !== 'connection' && - command !== 'daemon' && - command !== 'plugins' && - command !== 'device' && - command !== 'proxy' - ); + // `connection status` reports the stored record and sends no daemon request. + return runsOnRemoteConnection(command) && command !== 'connection'; } function shouldWarnOpenMayMissRemoteRuntime(options: { diff --git a/src/commands/schema/cli-help.ts b/src/commands/schema/cli-help.ts index 847b6988e2..ff8a0fc57d 100644 --- a/src/commands/schema/cli-help.ts +++ b/src/commands/schema/cli-help.ts @@ -503,7 +503,7 @@ Direct proxy flow for a remote Mac/simulator: agent-device close agent-device disconnect -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, from connect to disconnect, names its session with --session , AGENT_DEVICE_SESSION, or a config session. Without one, it 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. +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. diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index e0fa89a950..0466477c2f 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -2304,7 +2304,7 @@ agent-device disconnect --remote-config ./agent-device.remote.json - `connect` fetches the cloud connection profile; `connect --remote-config ` uses a local profile with the host, tenant/run, and optional session, platform, lease backend, and Metro settings. Both save connection state and defer the device lease and Metro preparation until a command needs them (including a `batch` step that opens an app). Direct-provider profiles need their provider credentials when `connect` runs. Cloud profiles must be a JSON object at `connection.remoteConfigProfile`; the older `connection.remoteConfig` string is rejected. - Cloud auth: `connect` refreshes a stored CLI session into a short-lived `adc_agent_...` token. Without a session, interactive shells start login; CI and non-interactive shells fail with API-token setup instructions. `--no-login` disables implicit login. Use `adc_live_...` service tokens for CI. Manage the CLI session with `agent-device auth status`, `auth login`, and `auth logout`; login never stores an `adc_live_...` token. - `AGENT_DEVICE_CLOUD_BASE_URL` is the bridge/control-plane API origin, not necessarily the dashboard; its `/api-keys` route may redirect to the dashboard. -- Every command on a connection with a lease provider (the cloud, `connect proxy`, a device cloud, or a `leaseProvider` in the profile), including `connect`, must name its session with `--session`, `AGENT_DEVICE_SESSION`, or config, or it fails with `REMOTE_SESSION_REQUIRED`. Each session on such a profile leases under its own client and run, derived from the session name, unless the profile names a lease the host issued. For any other profile, `connect` without `--session` creates a fresh remote session and prints the generated `--session`, and commands without one fall back to the most recent connection on the machine, which is safe only for one sequential workflow. To replace a connection, pass `--session --force`. +- Every command that takes a session on a connection with a lease provider (the cloud, `connect proxy`, a device cloud, or a `leaseProvider` in the profile), including `connect`, must name it with `--session`, `AGENT_DEVICE_SESSION`, or config, or it fails with `REMOTE_SESSION_REQUIRED`. Each session on such a profile leases under its own client and run, derived from the session name, unless the profile names a lease the host issued. For any other profile, `connect` without `--session` creates a fresh remote session and prints the generated `--session`, and commands without one fall back to the most recent connection on the machine, which is safe only for one sequential workflow. To replace a connection, pass `--session --force`. - After `connect`, normal commands (`install-from-source`, `open`, `snapshot`, `press`, `screenshot`, and others) reuse the connection state. `connection status` shows `leaseId=pending` until the first platform-bound command allocates the lease. Explicit flags override connected defaults; `open` with explicit remote flags but no saved runtime hints warns that React Native apps may launch without Metro hints. - End with `disconnect` (or `disconnect --remote-config `) to release the lease and stop the Metro companion owned by the connection. It also removes the profile that `connect ` generated, once no other session uses it. It does not stop your Metro server. - If `disconnect` cannot release the lease, it still removes the local connection state and prints the lease id, tenant, run, and the configured endpoint when available, so you can release the lease manually. It also keeps the generated profile. `disconnect --json` reports this case as `leaseId` and `releaseError`. diff --git a/website/docs/docs/device-clouds.md b/website/docs/docs/device-clouds.md index 99566acfae..b54d2be5b8 100644 --- a/website/docs/docs/device-clouds.md +++ b/website/docs/docs/device-clouds.md @@ -36,7 +36,7 @@ Every provider follows the same steps: 4. Follow the printed next command to install or open the app. 5. Run normal device commands, then `agent-device close` and `agent-device disconnect`. -Every command on a provider connection must name its session, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, before it leases anything, instead of using the connection that another agent or job on the same machine saved last. This includes `connect` itself. +Every command on a provider connection that takes a session must name it, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, before it leases anything, instead of using the connection that another agent or job on the same machine saved last. This includes `connect` itself. Each provider accepts only its own provider flags (`--provider-*` and `--aws-*`). A flag the provider does not use fails with `INVALID_ARGS` naming the flag, whether you pass it to `connect`, `client.leases.allocate()`, or a remote-config profile, so no setting is silently dropped. diff --git a/website/docs/docs/remote-proxy.md b/website/docs/docs/remote-proxy.md index 3a9f20248a..8685cee553 100644 --- a/website/docs/docs/remote-proxy.md +++ b/website/docs/docs/remote-proxy.md @@ -44,7 +44,7 @@ agent-device close agent-device disconnect ``` -Every command on a proxy connection must name its session, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. The same applies to every device-cloud connection. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, and sends nothing to the proxy. It never falls back to the connection that another agent on the same machine saved last. This includes `connect proxy` and `open --remote-config ` with a proxy profile. The client and run that the proxy leases under come from the session name, so two agents with different names never share a lease. +Every command on a proxy connection that takes a session must name it, with `AGENT_DEVICE_SESSION`, `--session `, or a `session` in your config. The same applies to every device-cloud connection. A command that names none fails with `INVALID_ARGS` and `details.reason: "REMOTE_SESSION_REQUIRED"`, and sends nothing to the proxy. It never falls back to the connection that another agent on the same machine saved last. This includes `connect proxy` and `open --remote-config ` with a proxy profile. The client and run that the proxy leases under come from the session name, so two agents with different names never share a lease. `--daemon-auth-token ` works instead of the environment variable, but it authenticates only the command you pass it to. Later commands need the token again through the environment variable, a `daemonAuthToken` entry in your remote config profile, or the flag on each command.