diff --git a/scripts/__tests__/help-conformance-sample-producers.ts b/scripts/__tests__/help-conformance-sample-producers.ts index 6cc0c78469..587ac727d8 100644 --- a/scripts/__tests__/help-conformance-sample-producers.ts +++ b/scripts/__tests__/help-conformance-sample-producers.ts @@ -498,7 +498,8 @@ export const SAMPLE_PRODUCERS: SampleProducer[] = [ } satisfies ConnectVerification; return renderConnectSuccess({ state, - readiness: presentConnectReadiness(state, facts), + readiness: presentConnectReadiness(state, facts, process.env), + env: process.env, }); } finally { restoreEnv('AGENT_DEVICE_HOME', previousHome); diff --git a/src/__tests__/remote-connection.test.ts b/src/__tests__/remote-connection.test.ts index f1444be18e..3713a3ff26 100644 --- a/src/__tests__/remote-connection.test.ts +++ b/src/__tests__/remote-connection.test.ts @@ -1321,74 +1321,6 @@ test('deferred materialization allocates pending lease for devices', async () => fs.rmSync(tempRoot, { recursive: true, force: true }); }); -test('deferred provider materialization forwards provider profile fields to lease allocation', async () => { - const { tempRoot, stateDir } = connectionWorkspace('agent-device-provider-lease-flags-'); - const remoteConfigPath = path.join(tempRoot, 'browserstack.json'); - fs.writeFileSync( - remoteConfigPath, - JSON.stringify({ - tenant: 'browserstack', - runId: 'browserstack-run', - leaseProvider: 'browserstack', - leaseBackend: 'android-instance', - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: '/tmp/WikipediaSample.apk', - providerProject: 'agent-device', - providerBuild: 'live-smoke', - }), - ); - seedConnectionState({ - stateDir, - state: { - session: 'adc-browserstack', - remoteConfigPath, - tenant: 'browserstack', - runId: 'browserstack-run', - leaseBackend: 'android-instance', - leaseProvider: 'browserstack', - platform: 'android', - }, - }); - const allocate = recordedLeaseAllocate({ - leaseId: 'lease-browserstack', - backend: 'android-instance', - }); - - const materialized = await materializeRemoteConnectionForCommand({ - command: 'open', - flags: { - json: true, - help: false, - version: false, - stateDir, - remoteConfig: remoteConfigPath, - tenant: 'browserstack', - runId: 'browserstack-run', - session: 'adc-browserstack', - leaseBackend: 'android-instance', - platform: 'android', - device: 'Google Pixel 8', - providerOsVersion: '14.0', - providerApp: '/tmp/WikipediaSample.apk', - providerProject: 'agent-device', - providerBuild: 'live-smoke', - }, - client: createTestClient({ allocate: allocate.stub }), - }); - - assert.equal(materialized.flags.leaseId, 'lease-browserstack'); - assert.equal(allocate.request?.platform, 'android'); - assert.equal(allocate.request?.device, 'Google Pixel 8'); - assert.equal(allocate.request?.providerApp, '/tmp/WikipediaSample.apk'); - assert.equal(allocate.request?.providerOsVersion, '14.0'); - assert.equal(allocate.request?.providerProject, 'agent-device'); - assert.equal(allocate.request?.providerBuild, 'live-smoke'); - - fs.rmSync(tempRoot, { recursive: true, force: true }); -}); - test('deferred materialization reallocates when the persisted lease is inactive', async () => { const { tempRoot, stateDir, remoteConfigPath } = connectionWorkspace( 'agent-device-connect-stale-lease-', diff --git a/src/cli/commands/connection-lease-policy.test.ts b/src/cli/commands/connection-lease-policy.test.ts index 825f1e41bf..1212b4860a 100644 --- a/src/cli/commands/connection-lease-policy.test.ts +++ b/src/cli/commands/connection-lease-policy.test.ts @@ -33,7 +33,7 @@ vi.mock('../connection/provider-policy.ts', () => ({ function ttlFor(leaseProvider: string): number | undefined { const state = { leaseProvider } as RemoteConnectionState; - return connectionLeasePolicyForState(state).ttlMs(state); + return connectionLeasePolicyForState(state, {}).ttlMs(state, {}); } test.each([ diff --git a/src/cli/commands/connection-lease-policy.ts b/src/cli/commands/connection-lease-policy.ts index 569cd8c4be..fca756c4fe 100644 --- a/src/cli/commands/connection-lease-policy.ts +++ b/src/cli/commands/connection-lease-policy.ts @@ -19,8 +19,11 @@ const leaseDeferredCommands = new Set([ 'session', 'shutdown', ]); -function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined { - const capabilities = connectionProviderCapabilities(state.leaseProvider); +function remoteLeaseTtlMs( + state: RemoteConnectionState, + env: NodeJS.ProcessEnv, +): number | undefined { + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); return capabilities.leaseKind === 'proxy' || capabilities.usesCloudWebDriverLease || capabilities.holdsCloudDevice === true @@ -30,7 +33,7 @@ function remoteLeaseTtlMs(state: RemoteConnectionState): number | undefined { export type ConnectionLeasePolicy = { shouldAllocate(command: string): boolean; - ttlMs(state: RemoteConnectionState): number | undefined; + ttlMs(state: RemoteConnectionState, env: NodeJS.ProcessEnv): number | undefined; /** The id this client names a new lease with; without it the daemon mints one. */ newLeaseId?(): string; resolveLeaseState(options: { @@ -42,9 +45,12 @@ export type ConnectionLeasePolicy = { }): Promise; }; -export function connectionLeasePolicyForState(state: RemoteConnectionState): ConnectionLeasePolicy { +export function connectionLeasePolicyForState( + state: RemoteConnectionState, + env: NodeJS.ProcessEnv, +): ConnectionLeasePolicy { if (state.leaseBackend === 'macos-app') return MACOS_APP_CONNECTION_LEASE_POLICY; - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); if (capabilities.leaseKind === 'proxy') { return PROXY_CONNECTION_LEASE_POLICY; } diff --git a/src/cli/commands/connection-lease-transaction.ts b/src/cli/commands/connection-lease-transaction.ts index 322524aea9..a303567481 100644 --- a/src/cli/commands/connection-lease-transaction.ts +++ b/src/cli/commands/connection-lease-transaction.ts @@ -114,15 +114,17 @@ export async function acquireConnectionLease(options: { nextFlags: CliFlags; positionals?: string[]; leaseLedger: LeaseLedger; + env: NodeJS.ProcessEnv; }): Promise<{ state: RemoteConnectionState; changed: boolean }> { const { command, client, state, nextFlags, leaseLedger } = options; const deferredAppSelection = connectionProviderCapabilities( state.leaseProvider, + options.env, ).supportsDeferredAppSelection; const initialApp = deferredAppSelection && command === PUBLIC_COMMANDS.open ? options.positionals?.[0] : undefined; if (deferredAppSelection) delete nextFlags.providerApp; - const leasePolicy = connectionLeasePolicyForState(state); + const leasePolicy = connectionLeasePolicyForState(state, options.env); let nextState = state; let changed = false; if (leasePolicy.shouldAllocate(command)) { @@ -135,6 +137,7 @@ export async function acquireConnectionLease(options: { initialApp, policy: leasePolicy, leaseLedger, + env: options.env, }); nextState = materialized.state; changed = materialized.changed; @@ -184,6 +187,7 @@ async function materializeLeaseForCommand(options: { initialApp?: string; policy: ConnectionLeasePolicy; leaseLedger: LeaseLedger; + env: NodeJS.ProcessEnv; }): Promise<{ state: RemoteConnectionState; changed: boolean }> { const { command, client, state, nextFlags, policy, leaseLedger } = options; const preliminaryLeaseBackend = state.leaseBackend ?? resolveRequestedLeaseBackend(nextFlags); @@ -218,6 +222,7 @@ async function materializeLeaseForCommand(options: { options.initialApp, resolvedLeaseState.allocateBySpec, leaseLedger, + options.env, ); if (resolvedLeaseState.allocateBySpec) { const bound = await bindLeaseNamedDevice({ @@ -237,6 +242,7 @@ async function materializeLeaseForCommand(options: { options.initialApp, undefined, leaseLedger, + options.env, ), }); nextState = bound.state; @@ -357,6 +363,7 @@ async function allocateOrReuseLease( initialApp: string | undefined, allocateBySpec: boolean | undefined, leaseLedger: LeaseLedger, + env: NodeJS.ProcessEnv, ): Promise<{ lease: Lease; acquired: boolean }> { const connection = buildRemoteConnectionRequestMetadata(state); if (state.leaseId && state.leaseBackend === leaseBackend) { @@ -365,7 +372,7 @@ async function allocateOrReuseLease( runId: state.runId, leaseBackend, ...connection, - ttlMs: policy.ttlMs(state), + ttlMs: policy.ttlMs(state, env), }); if (existing) return { lease: existing, acquired: false }; } @@ -386,7 +393,7 @@ async function allocateOrReuseLease( leaseBackend, ...connection, ...(allocateBySpec ? { deviceKey: undefined } : {}), - ttlMs: policy.ttlMs(state), + ttlMs: policy.ttlMs(state, env), ...providerFlags, platform: state.platform ?? flags.platform, target: state.target ?? flags.target, diff --git a/src/cli/commands/connection-plugin-admission.test.ts b/src/cli/commands/connection-plugin-admission.test.ts new file mode 100644 index 0000000000..47d00a1e63 --- /dev/null +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -0,0 +1,172 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { runCli } from '../../cli.ts'; +import { runCliCapture } from '../../__tests__/cli-capture.ts'; +import { + hashRemoteConfigFile, + readRemoteConnectionState, + writeRemoteConnectionState, +} from '@agent-device/remote/remote-connection-state'; +import { + beginStdoutCapture, + pluginHome, + selectV2Plugin, + v2RegistrationSource, +} from '@agent-device/test-kit'; + +const provider = 'browserstack'; +const packageName = '@agent-device/browserstack'; +const capabilities = { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: false, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, +}; + +afterEach(() => vi.unstubAllEnvs()); + +function fixture(home: string, leaseProvider = provider) { + const stateDir = path.join(home, 'state'); + const remoteConfigPath = path.join(home, 'remote.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'team', + runId: 'run-1', + leaseProvider, + leaseBackend: 'android-instance', + platform: 'android', + ...(leaseProvider === 'ordinary-remote' + ? { daemonBaseUrl: 'https://daemon.example.test' } + : {}), + }), + ); + return { stateDir, remoteConfigPath }; +} + +function seedState(f: ReturnType, leaseProvider = provider) { + const now = new Date().toISOString(); + writeRemoteConnectionState({ + stateDir: f.stateDir, + state: { + version: 1, + session: 'default', + remoteConfigPath: f.remoteConfigPath, + remoteConfigHash: hashRemoteConfigFile(f.remoteConfigPath), + tenant: 'team', + runId: 'run-1', + leaseProvider, + leaseBackend: 'android-instance', + platform: 'android', + connectedAt: now, + updatedAt: now, + }, + }); +} + +test.each(['missing', 'failed'] as const)( + 'routed %s vetted plugin fails before capability-based actions', + async (kind) => { + const { home, env } = pluginHome(); + if (kind === 'failed') + selectV2Plugin(home, packageName, 'throw new Error("registration failed")'); + const f = fixture(home); + const opts = { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }; + const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; + const connect = await runCliCapture( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + opts, + ); + seedState(f); + const status = await runCliCapture( + ['connection', 'status', '--state-dir', f.stateDir, '--json'], + opts, + ); + const snapshot = await runCliCapture( + ['snapshot', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + opts, + ); + const disconnected = await runCliCapture( + ['disconnect', '--state-dir', f.stateDir, '--json'], + opts, + ); + assert.equal(disconnected.code, null); + assert.equal(readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' }), null); + for (const result of [connect, status, snapshot]) { + const parsed = JSON.parse(result.stdout); + assert.equal(result.code, 1, result.stdout); + assert.equal(parsed.error?.code, 'UNSUPPORTED_OPERATION', result.stdout); + assert.equal(parsed.error?.details?.reason, expected, result.stdout); + assert.deepEqual(result.calls, []); + assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); + } + }, +); + +test('a generic remote profile remains connectable without a plugin', async () => { + const { home, env } = pluginHome(); + const f = fixture(home, 'ordinary-remote'); + const result = await runCliCapture( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }, + ); + assert.equal(result.code, null); + assert.equal( + readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider, + 'ordinary-remote', + ); +}); + +test('routed status uses capabilities from the supplied host store rather than the process store', async () => { + const { home } = pluginHome(); + const ambient = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', ambient.home); + selectV2Plugin( + home, + packageName, + v2RegistrationSource(provider, { + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() { return { provider: 'browserstack', service: 'BrowserStack', verificationMessage: 'verified' }; } },`, + }), + ); + const f = fixture(home); + const capture = beginStdoutCapture(); + const sendToDaemon = vi.fn(async () => { + throw new Error('unexpected daemon access'); + }); + try { + const suppliedHost = { + cwd: home, + env: { + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + AGENT_DEVICE_SESSION: 'default', + }, + }; + await runCli( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir], + { sendToDaemon }, + suppliedHost, + ); + assert.equal( + readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider, + provider, + ); + const statusOutputStart = capture.read().length; + await runCli( + ['connection', 'status', '--state-dir', f.stateDir], + { sendToDaemon }, + suppliedHost, + ); + const statusOutput = capture.read().slice(statusOutputStart); + assert.match(statusOutput, /The first device command shown below will allocate one/); + assert.doesNotMatch(statusOutput, /install-from-source/); + assert.equal(sendToDaemon.mock.calls.length, 0); + } finally { + capture.restore(); + } +}); diff --git a/src/cli/commands/connection-presentation.ts b/src/cli/commands/connection-presentation.ts index c46349794f..9ff359b9a6 100644 --- a/src/cli/commands/connection-presentation.ts +++ b/src/cli/commands/connection-presentation.ts @@ -31,15 +31,16 @@ export type PreviousLeaseReleaseNotice = { export function buildLeasePreparationNotice( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): LeasePreparationNotice | undefined { if (state.leaseId) return undefined; - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); const leaseKind = capabilities.leaseKind; if (leaseKind === 'proxy') { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. Run devices to inspect inventory without allocating, then open when ready.', }; @@ -47,7 +48,7 @@ export function buildLeasePreparationNotice( if (capabilities.supportsDeferredAppSelection) { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. Run apps to inspect uploaded assets without allocating; open creates the instance.', }; @@ -55,7 +56,7 @@ export function buildLeasePreparationNotice( if (leaseKind === 'direct-device-provider') { return { status: 'deferred', - nextSteps: buildConnectWorkflow(state, verification).nextSteps, + nextSteps: buildConnectWorkflow(state, verification, env).nextSteps, message: 'No live device session has been created. The first device command shown below will allocate one.', }; @@ -81,13 +82,14 @@ export function buildLeasePreparationNotice( export function presentConnectReadiness( state: RemoteConnectionState, verification: ConnectVerification, + env: NodeJS.ProcessEnv, ): ConnectReadiness { return { ...verification, preparationMessage: - buildLeasePreparationNotice(state, verification)?.message ?? + buildLeasePreparationNotice(state, verification, env)?.message ?? 'No live device session has been created.', - ...buildConnectWorkflow(state, verification), + ...buildConnectWorkflow(state, verification, env), }; } @@ -96,10 +98,11 @@ export function renderConnectSuccess(options: { readiness?: ConnectReadiness; runtimePreparation?: RuntimePreparationNotice; previousLeaseNotice?: PreviousLeaseReleaseNotice; + env: NodeJS.ProcessEnv; }): string { - const { state, readiness, runtimePreparation, previousLeaseNotice } = options; + const { state, readiness, runtimePreparation, previousLeaseNotice, env } = options; if (!readiness) { - const leasePreparation = buildLeasePreparationNotice(state); + const leasePreparation = buildLeasePreparationNotice(state, undefined, env); return [ `Configured remote session "${state.session}" tenant "${state.tenant}" run "${state.runId}"${state.leaseId ? ` lease ${state.leaseId}` : ''}.`, leasePreparation?.message, @@ -118,7 +121,7 @@ export function renderConnectSuccess(options: { lines.push(`Project: ${readiness.project.name ?? readiness.project.reference} — verified`); } if (readiness.device) lines.push(renderDevice(readiness.device)); - if (readiness.app) lines.push(renderApp(state, readiness.app)); + if (readiness.app) lines.push(renderApp(state, readiness.app, env)); lines.push(readiness.preparationMessage); lines.push('Next:'); lines.push(...readiness.nextSteps.map((step) => ` ${step}`)); @@ -133,9 +136,10 @@ export function serializeConnectionState(options: { runtimePreparation?: RuntimePreparationNotice; readiness?: ConnectReadiness; previousLeaseNotice?: PreviousLeaseReleaseNotice; + env: NodeJS.ProcessEnv; }): Record { - const { state, runtimePreparation, readiness, previousLeaseNotice } = options; - const leasePreparation = buildLeasePreparationNotice(state, readiness); + const { state, runtimePreparation, readiness, previousLeaseNotice, env } = options; + const leasePreparation = buildLeasePreparationNotice(state, readiness, env); return { connected: true, session: state.session, @@ -212,9 +216,10 @@ function renderDevice(device: NonNullable): string { function renderApp( state: RemoteConnectionState, app: NonNullable, + env: NodeJS.ProcessEnv, ): string { if (app.status === 'missing') { - return `App: ${missingAppLabel(state)} — ${app.message ?? 'Install or attach an app before open.'}`; + return `App: ${missingAppLabel(state, env)} — ${app.message ?? 'Install or attach an app before open.'}`; } const label = app.name ?? app.reference ?? 'configured app'; const suffix = app.status === 'verified' ? 'verified' : (app.message ?? 'configured'); @@ -223,17 +228,19 @@ function renderApp( function buildConnectWorkflow( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): Pick { - const workflow = buildUnscopedConnectWorkflow(state, verification); + const workflow = buildUnscopedConnectWorkflow(state, verification, env); return { ...workflow, nextSteps: scopeNextSteps(state, workflow.nextSteps) }; } function buildUnscopedConnectWorkflow( state: RemoteConnectionState, - verification?: ConnectVerification, + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, ): Pick { - const capabilities = connectionProviderCapabilities(state.leaseProvider); + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); const leaseKind = capabilities.leaseKind; if (leaseKind === 'proxy') { return { @@ -246,7 +253,7 @@ function buildUnscopedConnectWorkflow( if (!verification && leaseKind === 'direct-device-provider') { return { nextSteps: defaultDirectProviderLifecycle() }; } - if (connectionProviderCapabilities(verification?.provider).supportsDeferredAppSelection) { + if (connectionProviderCapabilities(verification?.provider, env).supportsDeferredAppSelection) { return { nextSteps: ['agent-device apps', 'agent-device open '], }; @@ -256,7 +263,7 @@ function buildUnscopedConnectWorkflow( nextSteps: requiresInstall(verification) ? installThenOpenWorkflow(state) : [...missingAttachedAppRecovery(verification), ...openWorkflow(state).nextSteps], - ...(supportsProviderArtifacts(verification) + ...(supportsProviderArtifacts(verification, env) ? { notes: providerArtifactNotes(state, !appMissing) } : {}), }; @@ -266,8 +273,11 @@ function requiresInstall(verification?: ConnectVerification): boolean { return verification?.app?.status === 'missing' && verification.device?.status === 'deferred'; } -function supportsProviderArtifacts(verification?: ConnectVerification): boolean { - return connectionProviderCapabilities(verification?.provider).supportsArtifacts; +function supportsProviderArtifacts( + verification: ConnectVerification | undefined, + env: NodeJS.ProcessEnv, +): boolean { + return connectionProviderCapabilities(verification?.provider, env).supportsArtifacts; } function missingAttachedAppRecovery(verification?: ConnectVerification): string[] { @@ -345,8 +355,8 @@ function appIdPlaceholder(platform: RemoteConnectionState['platform']): string { return platform === 'ios' ? '' : ''; } -function missingAppLabel(state: RemoteConnectionState): string { - const capabilities = connectionProviderCapabilities(state.leaseProvider); +function missingAppLabel(state: RemoteConnectionState, env: NodeJS.ProcessEnv): string { + const capabilities = connectionProviderCapabilities(state.leaseProvider, env); if (capabilities.requiresAppAttachment) return 'not attached'; if (capabilities.supportsDeferredAppSelection) { return 'not installed yet'; diff --git a/src/cli/commands/connection-runtime-direct-host.test.ts b/src/cli/commands/connection-runtime-direct-host.test.ts new file mode 100644 index 0000000000..01c6609ffd --- /dev/null +++ b/src/cli/commands/connection-runtime-direct-host.test.ts @@ -0,0 +1,87 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import { afterEach, test, vi } from 'vitest'; +import { createAgentDeviceClient } from '@agent-device/client'; +import { REMOTE_LEASE_IDLE_TTL_MS } from '@agent-device/contracts/lease-scope'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { materializeRemoteConnectionForCommand } from './connection-runtime.ts'; + +const capabilities = { + leaseKind: 'direct-device-provider', + requiresAppAttachment: false, + requiresRemoteDaemon: false, + supportsArtifacts: true, + supportsDeferredAppSelection: false, + supportsDirectPortReverse: false, + usesCloudWebDriverLease: true, +}; + +afterEach(() => vi.unstubAllEnvs()); + +test('direct materialization uses supplied host store without an ambient command host', async () => { + const { home } = pluginHome(); + const ambient = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', ambient.home); + selectV2Plugin( + home, + 'example-v2', + v2RegistrationSource('example-v2', { + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() {} },`, + }), + ); + const remoteConfigPath = path.join(home, 'remote.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'team', + runId: 'run-1', + leaseProvider: 'example-v2', + leaseBackend: 'android-instance', + platform: 'android', + }), + ); + const host = { cwd: home, env: { AGENT_DEVICE_HOME: home } }; + const requests: Array<{ command: string; meta?: { leaseTtlMs?: number } }> = []; + const client = createAgentDeviceClient( + {}, + { + host, + transport: async (request) => { + requests.push(request); + if (request.command === 'lease_allocate') + return { + ok: true, + data: { + lease: { + leaseId: 'lease-1', + tenantId: 'team', + runId: 'run-1', + backend: 'android-instance', + created: true, + }, + }, + }; + throw new Error(`unexpected daemon request: ${request.command}`); + }, + }, + ); + const result = await materializeRemoteConnectionForCommand({ + host, + command: 'snapshot', + client, + flags: { + json: true, + help: false, + version: false, + stateDir: path.join(home, 'state'), + remoteConfig: remoteConfigPath, + session: 'plugin-direct', + platform: 'android', + }, + }); + assert.equal(result.flags.leaseId, 'lease-1'); + assert.equal(requests.length, 1); + assert.equal(requests[0]?.command, 'lease_allocate'); + assert.equal(requests[0]?.meta?.leaseTtlMs, REMOTE_LEASE_IDLE_TTL_MS); +}); diff --git a/src/cli/commands/connection-runtime-provider.test.ts b/src/cli/commands/connection-runtime-provider.test.ts new file mode 100644 index 0000000000..3f75b9bedf --- /dev/null +++ b/src/cli/commands/connection-runtime-provider.test.ts @@ -0,0 +1,92 @@ +import { afterEach, test, vi } from 'vitest'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import path from 'node:path'; +import browserstack from '@agent-device/browserstack'; +import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; +import { + connectionWorkspace, + createTestClient, + recordedLeaseAllocate, + seedConnectionState, +} from '../../__tests__/remote-connection.fixtures.ts'; +import { materializeRemoteConnectionForCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; + +afterEach(() => vi.unstubAllEnvs()); + +test('deferred provider materialization forwards provider profile fields to lease allocation', async () => { + const { home } = pluginHome(); + vi.stubEnv('AGENT_DEVICE_HOME', home); + selectV2Plugin( + home, + '@agent-device/browserstack', + v2RegistrationSource('browserstack', { + extra: `connection: { capabilities: ${JSON.stringify(browserstack().connection?.capabilities)}, resolve() {}, verify() {} },`, + }), + ); + const { tempRoot, stateDir } = connectionWorkspace('agent-device-provider-lease-flags-'); + const remoteConfigPath = path.join(tempRoot, 'browserstack.json'); + fs.writeFileSync( + remoteConfigPath, + JSON.stringify({ + tenant: 'browserstack', + runId: 'browserstack-run', + leaseProvider: 'browserstack', + leaseBackend: 'android-instance', + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: '/tmp/WikipediaSample.apk', + providerProject: 'agent-device', + providerBuild: 'live-smoke', + }), + ); + seedConnectionState({ + stateDir, + state: { + session: 'adc-browserstack', + remoteConfigPath, + tenant: 'browserstack', + runId: 'browserstack-run', + leaseBackend: 'android-instance', + leaseProvider: 'browserstack', + platform: 'android', + }, + }); + const allocate = recordedLeaseAllocate({ + leaseId: 'lease-browserstack', + backend: 'android-instance', + }); + + const materialized = await materializeRemoteConnectionForCommand({ + command: 'open', + flags: { + json: true, + help: false, + version: false, + stateDir, + remoteConfig: remoteConfigPath, + tenant: 'browserstack', + runId: 'browserstack-run', + session: 'adc-browserstack', + leaseBackend: 'android-instance', + platform: 'android', + device: 'Google Pixel 8', + providerOsVersion: '14.0', + providerApp: '/tmp/WikipediaSample.apk', + providerProject: 'agent-device', + providerBuild: 'live-smoke', + }, + client: createTestClient({ allocate: allocate.stub }), + }); + + assert.equal(materialized.flags.leaseId, 'lease-browserstack'); + assert.equal(allocate.request?.platform, 'android'); + assert.equal(allocate.request?.device, 'Google Pixel 8'); + assert.equal(allocate.request?.providerApp, '/tmp/WikipediaSample.apk'); + assert.equal(allocate.request?.providerOsVersion, '14.0'); + assert.equal(allocate.request?.providerProject, 'agent-device'); + assert.equal(allocate.request?.providerBuild, 'live-smoke'); + + fs.rmSync(tempRoot, { recursive: true, force: true }); +}); diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0c687dc05c..4285f74e2c 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -85,13 +85,14 @@ export async function materializeRemoteConnectionForCommand(options: { ); } - await primeProviderConnection(providerOf(existingState, remoteConfig.profile)); + await primeProviderConnection(providerOf(existingState, remoteConfig.profile), host.env); const state = existingState ?? createRemoteConnectionStateFromFlags( mergedFlags, remoteConfig.resolvedPath, remoteConfig.profile, + host.env, ); const nextFlags = { ...mergedFlags, session: state.session }; let nextRuntime = selectCompatibleRuntime(state.runtime, nextFlags.platform) ?? options.runtime; @@ -109,6 +110,7 @@ export async function materializeRemoteConnectionForCommand(options: { nextFlags, positionals: options.positionals, leaseLedger, + env: host.env, }); nextState = acquired.state; changed = changed || acquired.changed; @@ -194,7 +196,8 @@ function createRemoteConnectionStateFromFlags( remoteConfigPath: string, profile: Partial< Pick - > = {}, + >, + env: NodeJS.ProcessEnv, ): RemoteConnectionState { const session = flags.session ?? 'default'; const scope = sessionLeaseScope( @@ -218,7 +221,7 @@ function createRemoteConnectionStateFromFlags( } if ( !flags.daemonBaseUrl && - connectionProviderCapabilities(profile.leaseProvider).requiresRemoteDaemon + connectionProviderCapabilities(profile.leaseProvider, env).requiresRemoteDaemon ) { throw new AppError( 'INVALID_ARGS', diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 9ebcafac2a..7124d610f8 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -81,7 +81,7 @@ export const connectCommand: ClientCommandHandler = async ({ resolved, host, ); - const scope = readRequiredConnectScope(connectFlags, connectionMetadata); + const scope = readRequiredConnectScope(connectFlags, connectionMetadata, host.env); const context = resolveConnectContext({ stateDir, flags: connectFlags, @@ -113,12 +113,25 @@ export const connectCommand: ClientCommandHandler = async ({ host, ); const runtimePreparation = buildRuntimePreparationNotice(connectFlags, state, host); - const readiness = presentConnectReadiness(state, verification); + const readiness = presentConnectReadiness(state, verification, host.env); await writeCommandOutput( connectFlags, - serializeConnectionState({ state, runtimePreparation, readiness, previousLeaseNotice }), - () => renderConnectSuccess({ state, runtimePreparation, readiness, previousLeaseNotice }), + serializeConnectionState({ + state, + runtimePreparation, + readiness, + previousLeaseNotice, + env: host.env, + }), + () => + renderConnectSuccess({ + state, + runtimePreparation, + readiness, + previousLeaseNotice, + env: host.env, + }), ); return true; }; @@ -134,6 +147,7 @@ function assertConnectProviderUsage(provider: ConnectProvider | undefined, flags function readRequiredConnectScope( flags: CliFlags, connectionMetadata: RemoteConnectionRequestMetadata | undefined, + env: NodeJS.ProcessEnv, ): { tenant: string; runId: string } { if (!flags.tenant) { throw new AppError( @@ -149,7 +163,7 @@ function readRequiredConnectScope( } if ( !flags.daemonBaseUrl && - connectionProviderCapabilities(connectionMetadata?.leaseProvider).requiresRemoteDaemon + connectionProviderCapabilities(connectionMetadata?.leaseProvider, env).requiresRemoteDaemon ) { throw new AppError( 'INVALID_ARGS', @@ -395,20 +409,23 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla await writeNoRemoteConnectionOutput(flags, session); return true; } - await primeProviderConnection(state.leaseProvider); - const leasePreparation = buildLeasePreparationNotice(state); + await primeProviderConnection(state.leaseProvider, host.env); + const leasePreparation = buildLeasePreparationNotice(state, undefined, host.env); const runtimePreparation = buildRuntimePreparationNoticeFromState(state, host); - await writeCommandOutput(flags, serializeConnectionState({ state, runtimePreparation }), () => - [ - `Configured remote session "${state.session}".`, - `tenant=${state.tenant} runId=${state.runId} leaseId=${state.leaseId ?? 'pending'} backend=${state.leaseBackend ?? 'pending'}`, - `remoteConfig=${state.remoteConfigPath}`, - state.runtime ? 'metro=prepared' : 'metro=not-prepared', - leasePreparation?.message, - runtimePreparation?.message, - ] - .filter((line): line is string => Boolean(line)) - .join('\n'), + await writeCommandOutput( + flags, + serializeConnectionState({ state, runtimePreparation, env: host.env }), + () => + [ + `Configured remote session "${state.session}".`, + `tenant=${state.tenant} runId=${state.runId} leaseId=${state.leaseId ?? 'pending'} backend=${state.leaseBackend ?? 'pending'}`, + `remoteConfig=${state.remoteConfigPath}`, + state.runtime ? 'metro=prepared' : 'metro=not-prepared', + leasePreparation?.message, + runtimePreparation?.message, + ] + .filter((line): line is string => Boolean(line)) + .join('\n'), ); return true; }; diff --git a/src/cli/connection/provider-policy.test.ts b/src/cli/connection/provider-policy.test.ts index 9bef132122..7201b85dee 100644 --- a/src/cli/connection/provider-policy.test.ts +++ b/src/cli/connection/provider-policy.test.ts @@ -14,7 +14,7 @@ import { import { pluginHome, selectV2Plugin, v2RegistrationSource } from '@agent-device/test-kit'; test('provider policy projects provider identity into semantic capabilities', () => { - assert.deepEqual(connectionProviderCapabilities('limrun'), { + assert.deepEqual(connectionProviderCapabilities('limrun', {}), { leaseKind: 'direct-device-provider', requiresAppAttachment: false, requiresRemoteDaemon: false, @@ -26,9 +26,12 @@ test('provider policy projects provider identity into semantic capabilities', () forgetsEndedConnectionLease: true, }); // BrowserStack is a plugin: without an installed one nothing declares its capabilities. - assert.equal(connectionProviderCapabilities('browserstack').leaseKind, 'remote-provider'); - assert.equal(connectionProviderCapabilities('aws-device-farm').requiresAppAttachment, true); - assert.equal(connectionProviderCapabilities('proxy').leaseKind, 'proxy'); + assert.equal( + connectionProviderCapabilities('browserstack', pluginHome().env).leaseKind, + 'remote-provider', + ); + assert.equal(connectionProviderCapabilities('aws-device-farm', {}).requiresAppAttachment, true); + assert.equal(connectionProviderCapabilities('proxy', {}).leaseKind, 'proxy'); }); test('a manifest connection on a store package supplies no capabilities', async () => { diff --git a/src/cli/connection/provider-policy.ts b/src/cli/connection/provider-policy.ts index 8327ae2866..d77a4efb11 100644 --- a/src/cli/connection/provider-policy.ts +++ b/src/cli/connection/provider-policy.ts @@ -41,6 +41,9 @@ export async function primeProviderConnection( ): Promise { if (provider === undefined || BUILTIN_CONNECT_PROVIDER_IDS.includes(provider)) return; await primePluginConnections(env, BUILTIN_PROVIDER_IDS); + if (pluginConnectionCapabilities(provider, env) !== undefined) return; + const unavailable = unavailableConnectPluginError(provider, env); + if (unavailable) throw unavailable; } export function isConnectProviderName( @@ -104,11 +107,13 @@ export function unavailableConnectPluginError( /** Bundled and installed providers declare their capabilities; the rest is the daemon's own routing. */ export function connectionProviderCapabilities( provider: string | undefined, - env: NodeJS.ProcessEnv = process.env, + env: NodeJS.ProcessEnv, ): ConnectionProviderCapabilities { if (provider === 'proxy') return remoteDaemonConnection('proxy'); const declared = builtinConnectionCapabilities(provider) ?? - (provider === 'cloud' ? undefined : pluginConnectionCapabilities(provider, env)); + (provider === undefined || provider === 'cloud' + ? undefined + : pluginConnectionCapabilities(provider, env)); return declared ?? remoteDaemonConnection('remote-provider'); }