Skip to content
3 changes: 2 additions & 1 deletion scripts/__tests__/help-conformance-sample-producers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
68 changes: 0 additions & 68 deletions src/__tests__/remote-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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-',
Expand Down
2 changes: 1 addition & 1 deletion src/cli/commands/connection-lease-policy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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([
Expand Down
16 changes: 11 additions & 5 deletions src/cli/commands/connection-lease-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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: {
Expand All @@ -42,9 +45,12 @@ export type ConnectionLeasePolicy = {
}): Promise<ResolvedLeaseState>;
};

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;
}
Expand Down
13 changes: 10 additions & 3 deletions src/cli/commands/connection-lease-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -135,6 +137,7 @@ export async function acquireConnectionLease(options: {
initialApp,
policy: leasePolicy,
leaseLedger,
env: options.env,
});
nextState = materialized.state;
changed = materialized.changed;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -218,6 +222,7 @@ async function materializeLeaseForCommand(options: {
options.initialApp,
resolvedLeaseState.allocateBySpec,
leaseLedger,
options.env,
);
if (resolvedLeaseState.allocateBySpec) {
const bound = await bindLeaseNamedDevice({
Expand All @@ -237,6 +242,7 @@ async function materializeLeaseForCommand(options: {
options.initialApp,
undefined,
leaseLedger,
options.env,
),
});
nextState = bound.state;
Expand Down Expand Up @@ -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) {
Expand All @@ -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 };
}
Expand All @@ -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,
Expand Down
172 changes: 172 additions & 0 deletions src/cli/commands/connection-plugin-admission.test.ts
Original file line number Diff line number Diff line change
@@ -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<typeof fixture>, 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();
}
});
Loading
Loading