From 9cd79cc9c966fa19f18240f590d7935927d18d50 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 10:56:43 +0100 Subject: [PATCH 1/8] fix(plugins): admit connection providers from their host registry --- src/cli/commands/connection-runtime.ts | 2 +- src/cli/commands/connection.ts | 2 +- src/cli/connection/provider-policy.ts | 10 ++++++++-- 3 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index 0c687dc05c..f10d88ecb4 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -85,7 +85,7 @@ export async function materializeRemoteConnectionForCommand(options: { ); } - await primeProviderConnection(providerOf(existingState, remoteConfig.profile)); + await primeProviderConnection(providerOf(existingState, remoteConfig.profile), host.env); const state = existingState ?? createRemoteConnectionStateFromFlags( diff --git a/src/cli/commands/connection.ts b/src/cli/commands/connection.ts index 9ebcafac2a..bbdfb5affe 100644 --- a/src/cli/commands/connection.ts +++ b/src/cli/commands/connection.ts @@ -395,7 +395,7 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla await writeNoRemoteConnectionOutput(flags, session); return true; } - await primeProviderConnection(state.leaseProvider); + await primeProviderConnection(state.leaseProvider, host.env); const leasePreparation = buildLeasePreparationNotice(state); const runtimePreparation = buildRuntimePreparationNoticeFromState(state, host); await writeCommandOutput(flags, serializeConnectionState({ state, runtimePreparation }), () => diff --git a/src/cli/connection/provider-policy.ts b/src/cli/connection/provider-policy.ts index 8327ae2866..f3e4ab3209 100644 --- a/src/cli/connection/provider-policy.ts +++ b/src/cli/connection/provider-policy.ts @@ -1,3 +1,4 @@ +import { commandHostEnvironment } from '@agent-device/host-kit/command'; import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import { pluginConnectionInventory, @@ -41,6 +42,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 +108,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 ?? commandHostEnvironment().env)); return declared ?? remoteDaemonConnection('remote-provider'); } From bcae7ab102f10fff34c2c668d531e1ad16444704 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 10:56:43 +0100 Subject: [PATCH 2/8] test(plugins): cover routed connection admission --- .../connection-plugin-admission.test.ts | 111 ++++++++++++++++++ src/cli/connection/provider-policy.test.ts | 2 +- 2 files changed, 112 insertions(+), 1 deletion(-) create mode 100644 src/cli/commands/connection-plugin-admission.test.ts 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..d90e59fe7f --- /dev/null +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -0,0 +1,111 @@ +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 profile, status and materialization reject a %s vetted plugin before dispatch', + 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 }; + const connect = await runCliCapture(['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], opts); + const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; + assert.equal(connect.code, 1); + assert.equal(JSON.parse(connect.stdout).error.details.reason, expected); + assert.deepEqual(connect.calls, []); + assert.equal(readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' }), null); + seedState(f); + for (const argv of [ + ['connection', 'status', '--state-dir', f.stateDir, '--json'], + ['snapshot', '--state-dir', f.stateDir, '--json'], + ]) { + const result = await runCliCapture(argv, opts); + assert.equal(result.code, 1); + assert.equal(JSON.parse(result.stdout).error.details.reason, expected); + assert.deepEqual(result.calls, []); + assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); + } + 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); + }, +); + +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 }); + 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() {} },`, + })); + const f = fixture(home); + seedState(f); + const capture = beginStdoutCapture(); + const sendToDaemon = vi.fn(async () => { throw new Error('unexpected daemon access'); }); + try { + await runCli(['connection', 'status', '--state-dir', f.stateDir], { sendToDaemon }, { + cwd: home, env: { AGENT_DEVICE_HOME: home, AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1' }, + }); + assert.match(capture.read(), /The first device command shown below will allocate one/); + assert.doesNotMatch(capture.read(), /install-from-source/); + assert.equal(sendToDaemon.mock.calls.length, 0); + } finally { + capture.restore(); + } +}); diff --git a/src/cli/connection/provider-policy.test.ts b/src/cli/connection/provider-policy.test.ts index 9bef132122..5dd8fac19f 100644 --- a/src/cli/connection/provider-policy.test.ts +++ b/src/cli/connection/provider-policy.test.ts @@ -26,7 +26,7 @@ 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('browserstack', pluginHome().env).leaseKind, 'remote-provider'); assert.equal(connectionProviderCapabilities('aws-device-farm').requiresAppAttachment, true); assert.equal(connectionProviderCapabilities('proxy').leaseKind, 'proxy'); }); From 37d97a3792f85087be988ee9437edd3c82f8a22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 12:30:03 +0100 Subject: [PATCH 3/8] test(plugins): use explicit remote session fixtures --- .../connection-plugin-admission.test.ts | 92 ++++++++++++++----- src/cli/connection/provider-policy.test.ts | 5 +- 2 files changed, 74 insertions(+), 23 deletions(-) diff --git a/src/cli/commands/connection-plugin-admission.test.ts b/src/cli/commands/connection-plugin-admission.test.ts index d90e59fe7f..f0884a6723 100644 --- a/src/cli/commands/connection-plugin-admission.test.ts +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -33,30 +33,54 @@ 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' } : {}), - })); + 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, - } }); + 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 profile, status and materialization reject a %s vetted plugin before dispatch', async (kind) => { const { home, env } = pluginHome(); - if (kind === 'failed') selectV2Plugin(home, packageName, 'throw new Error("registration failed")'); + if (kind === 'failed') + selectV2Plugin(home, packageName, 'throw new Error("registration failed")'); const f = fixture(home); - const opts = { cwd: home, env }; - const connect = await runCliCapture(['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], opts); + const opts = { cwd: home, env: { ...env, AGENT_DEVICE_SESSION: 'default' } }; + const connect = await runCliCapture( + ['connect', '--remote-config', f.remoteConfigPath, '--state-dir', f.stateDir, '--json'], + opts, + ); const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; assert.equal(connect.code, 1); assert.equal(JSON.parse(connect.stdout).error.details.reason, expected); @@ -73,7 +97,10 @@ test.each(['missing', 'failed'] as const)( assert.deepEqual(result.calls, []); assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); } - const disconnected = await runCliCapture(['disconnect', '--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); }, @@ -82,26 +109,47 @@ test.each(['missing', 'failed'] as const)( 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 }); + 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'); + 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() {} },`, - })); + selectV2Plugin( + home, + packageName, + v2RegistrationSource(provider, { + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() {} },`, + }), + ); const f = fixture(home); seedState(f); const capture = beginStdoutCapture(); - const sendToDaemon = vi.fn(async () => { throw new Error('unexpected daemon access'); }); + const sendToDaemon = vi.fn(async () => { + throw new Error('unexpected daemon access'); + }); try { - await runCli(['connection', 'status', '--state-dir', f.stateDir], { sendToDaemon }, { - cwd: home, env: { AGENT_DEVICE_HOME: home, AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1' }, - }); + await runCli( + ['connection', 'status', '--state-dir', f.stateDir], + { sendToDaemon }, + { + cwd: home, + env: { + AGENT_DEVICE_HOME: home, + AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', + AGENT_DEVICE_SESSION: 'default', + }, + }, + ); assert.match(capture.read(), /The first device command shown below will allocate one/); assert.doesNotMatch(capture.read(), /install-from-source/); assert.equal(sendToDaemon.mock.calls.length, 0); diff --git a/src/cli/connection/provider-policy.test.ts b/src/cli/connection/provider-policy.test.ts index 5dd8fac19f..715643d317 100644 --- a/src/cli/connection/provider-policy.test.ts +++ b/src/cli/connection/provider-policy.test.ts @@ -26,7 +26,10 @@ 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', pluginHome().env).leaseKind, 'remote-provider'); + assert.equal( + connectionProviderCapabilities('browserstack', pluginHome().env).leaseKind, + 'remote-provider', + ); assert.equal(connectionProviderCapabilities('aws-device-farm').requiresAppAttachment, true); assert.equal(connectionProviderCapabilities('proxy').leaseKind, 'proxy'); }); From 9ee56ebdd78b92739259380f0a0ab458f9b55d92 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 13:38:08 +0100 Subject: [PATCH 4/8] test(plugins): verify routed admission and cleanup --- .../connection-plugin-admission.test.ts | 32 ++++++++++--------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/cli/commands/connection-plugin-admission.test.ts b/src/cli/commands/connection-plugin-admission.test.ts index f0884a6723..3fb0c888fb 100644 --- a/src/cli/commands/connection-plugin-admission.test.ts +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -70,39 +70,41 @@ function seedState(f: ReturnType, leaseProvider = provider) { } test.each(['missing', 'failed'] as const)( - 'routed profile, status and materialization reject a %s vetted plugin before dispatch', + '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, ); - const expected = kind === 'missing' ? 'plugin-not-installed' : 'plugin-unavailable'; - assert.equal(connect.code, 1); - assert.equal(JSON.parse(connect.stdout).error.details.reason, expected); - assert.deepEqual(connect.calls, []); - assert.equal(readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' }), null); seedState(f); - for (const argv of [ + const status = await runCliCapture( ['connection', 'status', '--state-dir', f.stateDir, '--json'], - ['snapshot', '--state-dir', f.stateDir, '--json'], - ]) { - const result = await runCliCapture(argv, opts); - assert.equal(result.code, 1); - assert.equal(JSON.parse(result.stdout).error.details.reason, expected); - assert.deepEqual(result.calls, []); - assert.doesNotMatch(result.stdout, /install-from-source|leaseId.*pending/); - } + 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/); + } }, ); From 55a444ff4bbe48e8224513bdbc920bf4cf287410 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 13:50:04 +0100 Subject: [PATCH 5/8] fix(connection): pass host environment through capability decisions --- .../help-conformance-sample-producers.ts | 3 +- .../commands/connection-lease-policy.test.ts | 2 +- src/cli/commands/connection-lease-policy.ts | 16 ++-- .../commands/connection-lease-transaction.ts | 13 ++- .../connection-plugin-admission.test.ts | 29 ++++--- src/cli/commands/connection-presentation.ts | 56 +++++++----- .../connection-runtime-direct-host.test.ts | 87 +++++++++++++++++++ src/cli/commands/connection-runtime.ts | 7 +- src/cli/commands/connection.ts | 51 +++++++---- src/cli/connection/provider-policy.test.ts | 6 +- src/cli/connection/provider-policy.ts | 5 +- 11 files changed, 207 insertions(+), 68 deletions(-) create mode 100644 src/cli/commands/connection-runtime-direct-host.test.ts 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/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 index 3fb0c888fb..63f58cf106 100644 --- a/src/cli/commands/connection-plugin-admission.test.ts +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -130,27 +130,36 @@ test('routed status uses capabilities from the supplied host store rather than t home, packageName, v2RegistrationSource(provider, { - extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() {} },`, + extra: `connection: { capabilities: ${JSON.stringify(capabilities)}, resolve() {}, verify() { return { provider: 'browserstack', service: 'BrowserStack', verificationMessage: 'verified' }; } },`, }), ); const f = fixture(home); - seedState(f); 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, + ); await runCli( ['connection', 'status', '--state-dir', f.stateDir], { sendToDaemon }, - { - cwd: home, - env: { - AGENT_DEVICE_HOME: home, - AGENT_DEVICE_NO_UPDATE_NOTIFIER: '1', - AGENT_DEVICE_SESSION: 'default', - }, - }, + suppliedHost, ); assert.match(capture.read(), /The first device command shown below will allocate one/); assert.doesNotMatch(capture.read(), /install-from-source/); 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..c1197b980f --- /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; flags?: Record }> = []; + 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]?.flags?.ttlMs, REMOTE_LEASE_IDLE_TTL_MS); +}); diff --git a/src/cli/commands/connection-runtime.ts b/src/cli/commands/connection-runtime.ts index f10d88ecb4..4285f74e2c 100644 --- a/src/cli/commands/connection-runtime.ts +++ b/src/cli/commands/connection-runtime.ts @@ -92,6 +92,7 @@ export async function materializeRemoteConnectionForCommand(options: { 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 bbdfb5affe..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', @@ -396,19 +410,22 @@ export const connectionCommand: ClientCommandHandler = async ({ positionals, fla return true; } await primeProviderConnection(state.leaseProvider, host.env); - const leasePreparation = buildLeasePreparationNotice(state); + 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 715643d317..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, @@ -30,8 +30,8 @@ test('provider policy projects provider identity into semantic capabilities', () connectionProviderCapabilities('browserstack', pluginHome().env).leaseKind, 'remote-provider', ); - assert.equal(connectionProviderCapabilities('aws-device-farm').requiresAppAttachment, true); - assert.equal(connectionProviderCapabilities('proxy').leaseKind, 'proxy'); + 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 f3e4ab3209..d77a4efb11 100644 --- a/src/cli/connection/provider-policy.ts +++ b/src/cli/connection/provider-policy.ts @@ -1,4 +1,3 @@ -import { commandHostEnvironment } from '@agent-device/host-kit/command'; import type { ConnectionProviderCapabilities } from '@agent-device/contracts/remote'; import { pluginConnectionInventory, @@ -108,13 +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, + env: NodeJS.ProcessEnv, ): ConnectionProviderCapabilities { if (provider === 'proxy') return remoteDaemonConnection('proxy'); const declared = builtinConnectionCapabilities(provider) ?? (provider === undefined || provider === 'cloud' ? undefined - : pluginConnectionCapabilities(provider, env ?? commandHostEnvironment().env)); + : pluginConnectionCapabilities(provider, env)); return declared ?? remoteDaemonConnection('remote-provider'); } From 4e9140f8d5980e8ddc2de47dc5e45b765c779d59 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 13:57:45 +0100 Subject: [PATCH 6/8] test(connection): isolate stored status output assertions --- src/cli/commands/connection-plugin-admission.test.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cli/commands/connection-plugin-admission.test.ts b/src/cli/commands/connection-plugin-admission.test.ts index 63f58cf106..47d00a1e63 100644 --- a/src/cli/commands/connection-plugin-admission.test.ts +++ b/src/cli/commands/connection-plugin-admission.test.ts @@ -156,13 +156,15 @@ test('routed status uses capabilities from the supplied host store rather than t readRemoteConnectionState({ stateDir: f.stateDir, session: 'default' })?.leaseProvider, provider, ); + const statusOutputStart = capture.read().length; await runCli( ['connection', 'status', '--state-dir', f.stateDir], { sendToDaemon }, suppliedHost, ); - assert.match(capture.read(), /The first device command shown below will allocate one/); - assert.doesNotMatch(capture.read(), /install-from-source/); + 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(); From f8df9a55d7ccfdbd4d70ffddb0245d519f7e001c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 14:02:07 +0100 Subject: [PATCH 7/8] test(connection): register providers in lease fixtures --- .../remote-connection-provider.test.ts | 92 +++++++++++++++++++ src/__tests__/remote-connection.test.ts | 68 -------------- .../connection-runtime-direct-host.test.ts | 4 +- 3 files changed, 94 insertions(+), 70 deletions(-) create mode 100644 src/__tests__/remote-connection-provider.test.ts diff --git a/src/__tests__/remote-connection-provider.test.ts b/src/__tests__/remote-connection-provider.test.ts new file mode 100644 index 0000000000..103b4ebdad --- /dev/null +++ b/src/__tests__/remote-connection-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 './remote-connection.fixtures.ts'; +import { materializeRemoteConnectionForCommand } from './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/__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-runtime-direct-host.test.ts b/src/cli/commands/connection-runtime-direct-host.test.ts index c1197b980f..01c6609ffd 100644 --- a/src/cli/commands/connection-runtime-direct-host.test.ts +++ b/src/cli/commands/connection-runtime-direct-host.test.ts @@ -42,7 +42,7 @@ test('direct materialization uses supplied host store without an ambient command }), ); const host = { cwd: home, env: { AGENT_DEVICE_HOME: home } }; - const requests: Array<{ command: string; flags?: Record }> = []; + const requests: Array<{ command: string; meta?: { leaseTtlMs?: number } }> = []; const client = createAgentDeviceClient( {}, { @@ -83,5 +83,5 @@ test('direct materialization uses supplied host store without an ambient command assert.equal(result.flags.leaseId, 'lease-1'); assert.equal(requests.length, 1); assert.equal(requests[0]?.command, 'lease_allocate'); - assert.equal(requests[0]?.flags?.ttlMs, REMOTE_LEASE_IDLE_TTL_MS); + assert.equal(requests[0]?.meta?.leaseTtlMs, REMOTE_LEASE_IDLE_TTL_MS); }); From d2f18cff2110e81c8a7b0b391dd02a32a10fe870 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Pierzcha=C5=82a?= Date: Tue, 17 Nov 2026 14:07:31 +0100 Subject: [PATCH 8/8] test(connection): colocate provider lease fixture --- .../commands/connection-runtime-provider.test.ts} | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) rename src/{__tests__/remote-connection-provider.test.ts => cli/commands/connection-runtime-provider.test.ts} (94%) diff --git a/src/__tests__/remote-connection-provider.test.ts b/src/cli/commands/connection-runtime-provider.test.ts similarity index 94% rename from src/__tests__/remote-connection-provider.test.ts rename to src/cli/commands/connection-runtime-provider.test.ts index 103b4ebdad..3f75b9bedf 100644 --- a/src/__tests__/remote-connection-provider.test.ts +++ b/src/cli/commands/connection-runtime-provider.test.ts @@ -9,8 +9,8 @@ import { createTestClient, recordedLeaseAllocate, seedConnectionState, -} from './remote-connection.fixtures.ts'; -import { materializeRemoteConnectionForCommand } from './test-utils/host-bound-commands.ts'; +} from '../../__tests__/remote-connection.fixtures.ts'; +import { materializeRemoteConnectionForCommand } from '../../__tests__/test-utils/host-bound-commands.ts'; afterEach(() => vi.unstubAllEnvs());