Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions packages/command-registry/src/registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -712,6 +712,23 @@ const COMMAND_DESCRIPTOR_BY_NAME: ReadonlyMap<
CommandDescriptor & { standaloneCommandProjection: StandaloneCommandProjection | undefined }
> = new Map(commandDescriptors.map((descriptor) => [descriptor.name, descriptor]));

const DAEMON_COMMAND_BY_SERVED_PUBLIC_COMMAND: ReadonlyMap<string, string> = new Map(
(commandDescriptors as readonly CommandDescriptor[]).flatMap(({ name, catalog }) =>
catalog.group === 'internal' && catalog.servesPublicCommand
? [[catalog.servesPublicCommand, name] as const]
: [],
),
);

/**
* The name the daemon runs a command under: the internal command that declares it serves this public
* command (`install-from-source` runs as `install_source`), or else the name itself. Daemon traits
* are declared under this name.
*/
export function resolveDaemonCommandName(command: string): string {
return DAEMON_COMMAND_BY_SERVED_PUBLIC_COMMAND.get(command) ?? command;
}

/**
* Whether the daemon admits this command's request against the lease it names (ADR 0007). A name
* outside the registry, or a command exempt from lease admission, never meets lease admission.
Expand Down
7 changes: 4 additions & 3 deletions packages/daemon/docs/remote-device-lease-contracts.md
Original file line number Diff line number Diff line change
Expand Up @@ -99,16 +99,17 @@ These commands keep the heartbeat:
- A command on a host-allocated `macos-app` lease.
- A command on a lease whose provider has a runtime. A heartbeat runs its lifecycle hooks, such as the Limrun instance liveness check.
- A command exempt from lease admission.
- `install`, `reinstall`, and `install-from-source`, which can upload a local artifact before admission.
- `install` and `reinstall`, which can upload a local artifact before admission.
- `install-from-source` without an http(s) URL. With such a URL, the daemon downloads the artifact after admission, so this item does not apply. The other items in this list still apply.
- A command with `--save-script`.
- `batch`, `replay`, and `test`, which read local scripts while they build the request. A script path can be a pipe.
- `fill --text-stdin`, so that a refusal comes before the CLI reads the pipe.
- A command that prepares a Metro runtime, which registers remote work under the lease before the command.
- A command whose daemon URL, tenant, run, lease backend, or device key differs from the saved connection, or that has no saved connection.
- A command whose stored lease id is not canonical lower-case hex.
- A by-spec `open` that allocates fresh: the connection names no device, or the request names a device spec or a device selector.
- A by-spec allocation (`open`, `install`, `reinstall`, `uninstall`, or `install-from-source` through a proxy) that allocates fresh: the connection names no device, or the request names a device spec or a device selector.

A by-spec `open` that names no spec or selector reuses the stored device without a heartbeat.
A by-spec allocation that names no spec or selector reuses the stored device without a heartbeat, unless another item in this list applies.

## Admitted request work

Expand Down
71 changes: 43 additions & 28 deletions src/__tests__/cli-lease-admission-proxy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,34 +32,43 @@ const LEASE_SCOPE = {
deviceKey: 'android:mobile:emulator-9999',
} as const;

test('a lease the daemon dropped is reallocated through the proxy without a heartbeat', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => {
const client = createAgentDeviceClient({
daemonBaseUrl: baseUrl,
daemonAuthToken: 'client-secret',
daemonTransport: 'http',
});
const lease = await client.leases.allocate({ ...LEASE_SCOPE, leaseId: 'b'.repeat(32) });
writeConnection(stateDir, project, baseUrl, lease.leaseId);
await client.leases.release({ ...LEASE_SCOPE, leaseId: lease.leaseId });
upstream.length = 0;
test.for<[string, string[], string | undefined]>([
['snapshot', ['snapshot'], LEASE_SCOPE.leaseProvider],
// A `proxy` provider connection reallocates an install by spec, and this daemon has no device to
// grant. The URL is a loopback port with no listener, so a download never leaves the host.
['install_source', ['install-from-source', 'http://127.0.0.1:1/app.apk'], undefined],
])(
'a dropped lease is reallocated for %s through the proxy without a heartbeat',
async ([command, argv, leaseProvider], t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
await withProxiedDaemon(async ({ baseUrl, project, stateDir, upstream, cli }) => {
const client = createAgentDeviceClient({
daemonBaseUrl: baseUrl,
daemonAuthToken: 'client-secret',
daemonTransport: 'http',
});
const scope = { ...LEASE_SCOPE, leaseProvider };
const lease = await client.leases.allocate({ ...scope, leaseId: 'b'.repeat(32) });
writeConnection(stateDir, project, baseUrl, lease.leaseId, leaseProvider);
await client.leases.release({ ...scope, leaseId: lease.leaseId });
upstream.length = 0;

const result = await cli(['snapshot']);
const result = await cli(argv);

const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId;
assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout);
// The setup above already cached `/health` for this endpoint in this process, so only RPCs show.
assert.deepEqual(
upstream.filter((route) => route.startsWith('/rpc')),
['/rpc snapshot', '/rpc agent_device.lease.allocate', '/rpc snapshot'],
);
// The resent command passed admission: whatever it answered, it was not the lease refusal.
if (result.code !== null) {
assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND');
}
});
});
const reallocated = readRemoteConnectionState({ stateDir, session: 'agent' })?.leaseId;
assert.ok(reallocated && reallocated !== lease.leaseId, result.stdout);
// The setup above already cached `/health` for this endpoint in this process, so only RPCs show.
assert.deepEqual(
upstream.filter((route) => route.startsWith('/rpc')),
[`/rpc ${command}`, '/rpc agent_device.lease.allocate', `/rpc ${command}`],
);
// The resent command passed admission: whatever it answered, it was not the lease refusal.
if (result.code !== null) {
assert.notEqual(JSON.parse(result.stdout).error.details?.reason, 'LEASE_NOT_FOUND');
}
});
},
);

// A reused lease on the connection does not move a command that checks no lease off the checked route.
test('a checked connection sends a command that checks no lease as its one checked request', async (t) => {
Expand Down Expand Up @@ -149,7 +158,13 @@ async function describe(request: Request): Promise<string> {
return `${route} ${body.method === 'agent_device.command' ? body.params?.command : body.method}`;
}

function writeConnection(stateDir: string, project: string, baseUrl: string, leaseId: string) {
function writeConnection(
stateDir: string,
project: string,
baseUrl: string,
leaseId: string,
leaseProvider: string | undefined,
) {
const remoteConfigPath = path.join(project, 'agent.remote.json');
fs.writeFileSync(remoteConfigPath, JSON.stringify({}));
const now = new Date().toISOString();
Expand All @@ -165,7 +180,7 @@ function writeConnection(stateDir: string, project: string, baseUrl: string, lea
runId: LEASE_SCOPE.runId,
leaseId,
leaseBackend: LEASE_SCOPE.leaseBackend,
leaseProvider: LEASE_SCOPE.leaseProvider,
leaseProvider,
clientId: LEASE_SCOPE.clientId,
deviceKey: LEASE_SCOPE.deviceKey,
platform: 'android',
Expand Down
22 changes: 21 additions & 1 deletion src/__tests__/cli-lease-admission.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,9 @@ function transportTo(daemon: Daemon) {
}
if (daemon.refusal && scopeOf(req, 'leaseId') === STORED_LEASE) throw daemon.refusal();
if (req.command === 'open') return { ok: true, data: { session: req.session } };
if (req.command === 'install_source') {
return { ok: true, data: { launchTarget: 'com.example' } };
}
return { ok: true, data: { nodes: [], truncated: false } };
};
}
Expand Down Expand Up @@ -151,6 +154,11 @@ function markedOf(result: Awaited<ReturnType<typeof run>>): boolean[] {
test.each([
['snapshot -i', ['snapshot', '-i'], 'snapshot'],
['a proxy open on the stored device', ['open', 'com.example'], 'open'],
[
'an install from a URL the daemon downloads',
['install-from-source', 'https://example.com/app.apk'],
'install_source',
],
])('%s reaches a lease-admission daemon without a heartbeat', async (_name, argv, command) => {
const ws = workspace();
const result = await run(ws, argv, transportTo({ leaseAdmission: true }));
Expand Down Expand Up @@ -288,7 +296,7 @@ test.each<[string, string[], Partial<RemoteConnectionState>]>([
{ leaseProvider: 'limrun' },
],
['an install that uploads a local artifact first', ['install', 'com.example', 'app.apk'], {}],
['an install from a source', ['install-from-source', 'https://example.com/app.apk'], {}],
['an install-from-source naming a local path', ['install-from-source', 'app.apk'], {}],
[
'a stored lease id that is not canonical',
['snapshot'],
Expand Down Expand Up @@ -317,6 +325,18 @@ test.each<[string, string[], Partial<RemoteConnectionState>]>([
fs.rmSync(ws.root, { recursive: true, force: true });
});

// Without its own backend, nothing says the stored lease is on the one this command asks for.
test('a stored lease with no backend of its own is not left to admission', async () => {
const ws = workspace({ leaseBackend: undefined });
const result = await run(ws, ['snapshot'], transportTo({ leaseAdmission: true }));

assert.equal(result.code, null, result.stdout);
assert.deepEqual(commandsOf(result), ['lease_allocate', 'snapshot']);
assert.deepEqual(markedOf(result), [false, false]);

fs.rmSync(ws.root, { recursive: true, force: true });
});

// Metro preparation registers the companion tunnel under the connection's lease before the command,
// so the lease is checked first and the tunnel and the app share the live one.
test('an open that prepares Metro replaces an ended lease before the bridge setup', async () => {
Expand Down
26 changes: 26 additions & 0 deletions src/cli/commands/__tests__/proxy-lease-device-spec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -640,6 +640,32 @@ test('a new spec lease for another device than the requested --udid is released
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test('install-from-source on a proxy connection with no lease allocates one by spec', async () => {
const { tempRoot, stateDir, flags } = proxyWorkspace('agent-device-proxy-install-source-');
const requests: LeaseAllocateRequest[] = [];

const materialized = await materializeRemoteConnectionForCommand({
host: createTestHostEnvironment(),
command: 'install-from-source',
positionals: ['https://example.com/app.apk'],
flags,
client: createTestClient({
listDevices: unexpectedCommandCall,
allocate: async (request) => {
requests.push(request);
return grantedLease(request, { deviceKey: REMOTE_DEVICE_KEY });
},
release: unexpectedCommandCall,
}),
});

assert.equal(requests.length, 1);
assert.equal(requests[0]?.deviceKey, undefined);
assert.equal(materialized.flags.udid, 'SIM-REMOTE');
assert.equal(readRemoteConnectionState({ stateDir, session: 'adc-proxy' })?.leaseId, 'lease-1');
fs.rmSync(tempRoot, { recursive: true, force: true });
});

test('a lease re-allocated by its stored device for a non-allocating command does not carry the spec', async () => {
const { tempRoot, flags } = proxyWorkspace('agent-device-proxy-device-spec-snapshot-', {
leaseId: 'lease-1',
Expand Down
24 changes: 20 additions & 4 deletions src/cli/commands/connection-lease-admission.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { INTERNAL_COMMANDS } from '@agent-device/command-registry/catalog';
import {
commandMeetsLeaseAdmission,
isDelegatingCompositeCommand,
resolveDaemonCommandName,
} from '@agent-device/command-registry/registry';
import {
isUndispatchedInactiveLeaseRefusal,
Expand Down Expand Up @@ -46,7 +48,8 @@ export type AdmissionCheckedLease = Readonly<{
* - a host-allocated `macos-app` lease has its own refusal;
* - a provider with a runtime runs lifecycle hooks on a heartbeat, such as an instance liveness check;
* - a command exempt from lease admission is never checked there;
* - an upload of a local artifact runs before admission, under the lease;
* - an upload of a local artifact runs before admission, under the lease. Of the commands that can
* upload, only an `install_source` of an http(s) URL uploads nothing: the daemon downloads it;
* - Metro preparation registers remote work under the lease before the command;
* - a composite (`batch`, `replay`, `test`) reads local scripts while it builds its request, and
* `fill --text-stdin` reads a pipe: a refusal must come before either, and a rerun could not read
Expand All @@ -61,6 +64,7 @@ export type AdmissionCheckedLease = Readonly<{
export function leaseCheckedByAdmission(
options: Readonly<{
command: string;
positionals: readonly string[] | undefined;
state: RemoteConnectionState;
/** The stored connection record, absent while the connection is still built from flags. */
savedState: RemoteConnectionState | undefined;
Expand All @@ -73,17 +77,18 @@ export function leaseCheckedByAdmission(
}>,
): AdmissionCheckedLease | undefined {
const { state, flags, check } = options;
const command = resolveDaemonCommandName(options.command);
if (
!check?.byAdmission ||
!state.leaseId ||
normalizeLeaseId(state.leaseId) !== state.leaseId ||
state.leaseBackend !== options.leaseBackend ||
state.leaseBackend === 'macos-app' ||
leaseProviderRequiringRuntime({ leaseProvider: state.leaseProvider }) !== undefined ||
!commandMeetsLeaseAdmission(options.command) ||
requestUploadsArtifacts({ command: options.command }) ||
!commandMeetsLeaseAdmission(command) ||
uploadsBeforeAdmission(command, options.positionals) ||
options.preparesRuntime ||
isDelegatingCompositeCommand({ command: options.command, positionals: [] }) ||
isDelegatingCompositeCommand({ command, positionals: [] }) ||
flags.textStdin === true ||
flags.saveScript !== undefined ||
!namesSavedConnection(options.savedState, state, flags) ||
Expand All @@ -95,6 +100,17 @@ export function leaseCheckedByAdmission(
return { leaseId: state.leaseId, ...(leaseTtlMs === undefined ? {} : { leaseTtlMs }) };
}

/** Whether sending the command may upload a local artifact first. */
function uploadsBeforeAdmission(
command: string,
positionals: readonly string[] | undefined,
): boolean {
if (!requestUploadsArtifacts({ command })) return false;
if (command !== INTERNAL_COMMANDS.installSource) return true;
const protocol = URL.parse(positionals?.[0] ?? '')?.protocol;
return protocol !== 'http:' && protocol !== 'https:';
}

/** Whether the command goes to the saved connection's daemon, under its owner scope. */
function namesSavedConnection(
saved: RemoteConnectionState | undefined,
Expand Down
3 changes: 3 additions & 0 deletions src/cli/commands/connection-lease-transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ export async function acquireConnectionLease(options: {
if (leasePolicy.shouldAllocate(command)) {
const materialized = await materializeLeaseForCommand({
command,
positionals: options.positionals,
client,
state,
nextState,
Expand Down Expand Up @@ -204,6 +205,7 @@ function carriedConnectionPlatform(

async function materializeLeaseForCommand(options: {
command: string;
positionals?: string[];
client: AgentDeviceClient;
state: RemoteConnectionState;
nextState: RemoteConnectionState;
Expand Down Expand Up @@ -245,6 +247,7 @@ async function materializeLeaseForCommand(options: {
nextFlags.platform = platform;
const admissionCheckedLease = leaseCheckedByAdmission({
command,
positionals: options.positionals,
state: nextState,
flags: nextFlags,
leaseBackend,
Expand Down
5 changes: 3 additions & 2 deletions src/cli/commands/proxy-lease-device.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,9 @@ import type { CliFlags } from '@agent-device/contracts/command';
import type { AgentDeviceClient } from '@agent-device/command-surface';
import type { LeaseLedger } from './connection-lease-transaction.ts';
import { INTERNAL_COMMANDS, PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
import { resolveDaemonCommandName } from '@agent-device/command-registry/registry';

const proxyLeaseAllocatingCommands: ReadonlySet<string> = new Set([
const proxyLeaseAllocatingDaemonCommands: ReadonlySet<string> = new Set([
PUBLIC_COMMANDS.open,
PUBLIC_COMMANDS.install,
PUBLIC_COMMANDS.reinstall,
Expand Down Expand Up @@ -62,7 +63,7 @@ export async function resolveProxyLeaseState(options: {
flags: CliFlags;
leaseBackend?: LeaseBackend;
}): Promise<ResolvedLeaseState> {
if (!proxyLeaseAllocatingCommands.has(options.command)) {
if (!proxyLeaseAllocatingDaemonCommands.has(resolveDaemonCommandName(options.command))) {
if (options.state.leaseId && options.state.deviceKey) return { state: options.state };
throw new AppError(
'INVALID_ARGS',
Comment thread
thymikee marked this conversation as resolved.
Resolved
Expand Down
Loading
Loading