Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
d71e7f0
feat(cli): replace cloud connection profiles with hosted session leases
thymikee Nov 24, 2026
3c26055
fix(cli): fence hosted health and artifact requests
thymikee Nov 24, 2026
4ec1414
fix(cli): refuse broker credential echoes in attachment URLs
thymikee Nov 24, 2026
349eaf8
fix(cli): report cloud record I/O codes safely
thymikee Nov 24, 2026
88d79e6
fix(cli): omit scoped credentials from viewer links
thymikee Nov 24, 2026
64913f2
chore(gates): acknowledge client-local daemon admission changes
thymikee Nov 24, 2026
4915252
test(cli): cover conflicted hosted session release
thymikee Nov 24, 2026
3858907
fix(cli): refuse dispatch during cloud allocation
thymikee Nov 24, 2026
c9ac750
test(cli): keep direct connect coverage beside legacy admission
thymikee Nov 24, 2026
05def9a
fix(cli): refuse disconnect during a contended cloud allocation
thymikee Nov 24, 2026
aaad938
fix(cli): fence hosted handoffs and protect teardown credentials
thymikee Nov 25, 2026
9f0c335
fix(cli): refuse contention during hosted connection setup
thymikee Nov 25, 2026
779fa98
fix(cli): avoid waiting for ended lease bookkeeping
thymikee Nov 25, 2026
657c17a
fix(cli): protect hosted handoffs and legacy lease recovery
thymikee Nov 25, 2026
faf7820
chore(gates): record compatible upload handoffs
thymikee Nov 25, 2026
e7d4d30
fix(cli): normalize teardown inputs and finish request handoffs
thymikee Nov 25, 2026
5efa384
chore(gates): record compatible request handoff timing
thymikee Nov 25, 2026
00e4e6d
fix(cli): address hosted session review follow-ups
thymikee Nov 25, 2026
4d90c49
chore(gates): record client admission deadlines
thymikee Nov 25, 2026
cf19331
fix(remote): finish diagnostics cleanup before reporting timeout
thymikee Nov 25, 2026
44cd162
fix(remote): finalize compatible diagnostics cleanup
thymikee Nov 25, 2026
684c867
refactor(cli): narrow hosted admission inputs
thymikee Nov 25, 2026
08e66f6
fix(remote): admit each artifact GET at send time
thymikee Nov 25, 2026
0d6af48
fix(daemon-client): load artifact admission on demand
thymikee Nov 25, 2026
0a0baf4
fix(remote): hold artifact admission through header writes
thymikee Nov 25, 2026
6b4c493
fix(remote): preserve artifacts when admission refuses a download
thymikee Nov 25, 2026
9bb90e4
test(provision): acknowledge SOCKS tunnels after relay setup
thymikee Nov 25, 2026
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
4 changes: 3 additions & 1 deletion docs/adr/0007-remote-device-leases.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ Hosted devices can continue to incur charges after their daemon stops.

A remote device lease gives one client logical ownership of a selected device for a connection provider.
The daemon is authoritative for admission, ownership, and session lifetime.
`connect` establishes client identity and a connection profile. Allocation is lazy, when the device, backend, and provider are known.
`connect` establishes client identity and a connection profile for direct providers. Allocation is lazy, when the device, backend, and provider are known.
`open` is the natural acquisition point.
Runner and process locks remain separate backend guards.

For `connect cloud`, the hosted session API owns the device rental and enforces the rental deadline. The CLI asks the API to allocate during connect and receives a scoped attachment. The CLI records the allocation identity before attaching. It can recover an interrupted allocation or end the rental without a live daemon. The daemon retains authority over its session lifetime and the requests it receives.

The proxy token authenticates the host, not the client: every client of one proxy can hold the same token.
The lease id is the credential that proves ownership of a leased session.
A request on a session that holds a lease must send that lease's id. The daemon refuses a request that omits it with `LEASE_SESSION_MISMATCH` and never fills it from the session.
Expand Down
1 change: 1 addition & 0 deletions packages/client/src/lease-client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ export function createLeaseClient(
const data = await execute(INTERNAL_COMMANDS.leaseRelease, [], options);
return {
released: data.released === true,
...(data.absent === true ? { absent: true } : {}),
provider: isRecord(data.provider) ? data.provider : undefined,
};
},
Expand Down
40 changes: 40 additions & 0 deletions packages/command-registry/src/flag-definitions-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,46 @@ export const CONNECTION_FLAG_DEFINITIONS: readonly FlagDefinition[] = [
projectConfig: true,
recorded: false,
},
{
key: 'vendor',
names: ['--vendor'],
type: 'string',
usageLabel: '--vendor <id>',
usageDescription: 'Connect cloud: choose a device vendor',
projectConfig: false,
recorded: false,
},
{
key: 'maxMinutes',
names: ['--max-minutes'],
type: 'int',
min: 1,
max: Number.MAX_SAFE_INTEGER,
usageLabel: '--max-minutes <minutes>',
usageDescription: 'Connect cloud: request a maximum session duration in minutes',
projectConfig: false,
recorded: false,
},

{
key: 'needs',
names: ['--needs'],
type: 'string',
usageLabel: '--needs <capability,...>',
usageDescription: 'Connect cloud: require each of these comma-separated capabilities',
projectConfig: false,
recorded: false,
},

{
key: 'showViewer',
names: ['--show-viewer'],
type: 'boolean',
usageLabel: '--show-viewer',
usageDescription: 'Connect cloud: open the live viewer in the browser',
projectConfig: false,
recorded: false,
},
{
key: 'live',
names: ['--live'],
Expand Down
2 changes: 1 addition & 1 deletion packages/command-surface/src/client-port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -187,7 +187,7 @@ export type AgentDeviceClient = {
heartbeat: (options: LeaseScopedOptions) => Promise<Lease>;
release: (
options: LeaseScopedOptions,
) => Promise<{ released: boolean; provider?: CloudProviderSessionResult }>;
) => Promise<{ released: boolean; absent?: true; provider?: CloudProviderSessionResult }>;
humanControl: {
list: (options?: AgentDeviceRequestOverrides) => Promise<HumanControlHold[]>;
put: (
Expand Down
11 changes: 8 additions & 3 deletions packages/command-surface/src/schema/command-overrides.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ const CONNECT_ALLOWED_FLAGS = [
...LEASE_DEVICE_SPEC_FLAGS,
'force',
'noLogin',
'vendor',
'maxMinutes',
'needs',
'showViewer',
] as const;

const CONNECT_SUPPORTED_FLAGS = [
'stateDir',
'daemonAuthToken',
Expand Down Expand Up @@ -124,10 +129,10 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
text: {
summary: 'Configure remote or provider state',
description:
'List cloud offerings with a CLI login or AGENT_DEVICE_CLOUD_API_KEY. For a custom catalog, set AGENT_DEVICE_CLOUD_API_KEY_ORIGIN to the same origin as AGENT_DEVICE_CLOUD_BASE_URL. Use AGENT_DEVICE_DAEMON_AUTH_TOKEN for remote connection setup. Direct providers validate credentials and resources before saving state and print any preparation needed before open.',
'List cloud offerings or start a hosted session with a CLI login or AGENT_DEVICE_CLOUD_API_KEY. For a custom cloud API, set AGENT_DEVICE_CLOUD_API_KEY_ORIGIN to the same origin as AGENT_DEVICE_CLOUD_BASE_URL. Use AGENT_DEVICE_DAEMON_AUTH_TOKEN for direct remote daemon connections. Direct providers validate credentials and resources before saving state and print any preparation needed before open.',
},
usageOverride:
'connect [cloud] list [--live] [--json] | connect [provider] [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login]',
'connect [cloud] list [--live] [--json] | connect cloud --platform ios|android [--vendor <id>] [--max-minutes <minutes>] [--needs <capability,...>] [--device <model>] [--os <version>] [--show-viewer] | connect [provider] [--remote-config <path>] [--daemon-base-url <url>] [--tenant <id>] [--run-id <id>] [--lease-id <id>] [--lease-backend <backend>] [--force] [--no-login]',
usageFlags: [],
listUsageOverride: 'connect',
positionalArgs: ['provider?|list'],
Expand All @@ -151,7 +156,7 @@ const SCHEMA_ONLY_CLI_COMMAND_SCHEMAS = {
},
listUsageOverride: 'disconnect',
allowedFlags: ['shutdown'],
supportedFlags: ['remoteConfig', 'stateDir', 'session'],
supportedFlags: ['remoteConfig', 'stateDir', 'session', 'daemonAuthToken'],
},
mcp: {
text: {
Expand Down
4 changes: 4 additions & 0 deletions packages/contracts/src/cli-flags.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export type CliFlags = CloudProviderProfileFields &
force?: boolean;
clean?: boolean;
noLogin?: boolean;
vendor?: string;
maxMinutes?: number;
needs?: string;
showViewer?: boolean;
live?: boolean;
kind?: string;
perfTemplate?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,42 @@ test('concurrent first requests share one ensure through the CLI and MCP transpo
}
});

test('a failed attach checks admission again before restarting the daemon', async () => {
const { stateDir } = stateDirAndPaths();
let admitted = false;
let closing = false;
const ensure = vi.spyOn(ensureModule, 'ensureDaemon').mockImplementation(async () => {
assert.equal(admitted, true);
return undefined as never;
});
const send = vi.fn(async () => {
assert.equal(admitted, false);
closing = true;
throw daemonNotRunningError(stateDir);
});
const ensuring = withEnsuredDaemon(send, {
admit: async (start) => {
if (closing) {
throw new AppError('COMMAND_FAILED', 'Connection closed.', { reason: 'connection_closed' });
}
admitted = true;
try {
return await start();
} finally {
admitted = false;
}
},
});

await assert.rejects(ensuring(request('open', { stateDir })), (error: unknown) => {
assert.ok(error instanceof AppError);
assert.equal(error.details?.reason, 'connection_closed');
return true;
});
assert.equal(ensure.mock.calls.length, 1);
assert.equal(send.mock.calls.length, 1);
});

test('a request canceled before it starts does not start a daemon', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { stateDir, paths } = stateDirAndPaths();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,3 +204,30 @@ test('an aborted or budgetless health caller sends no probe', async (t) => {
await closeLoopbackServer(remote.handler);
}
});

test.for([1, 2])(
'does not send an authenticated remote health probe after handoff %i is refused',
async (refused, t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const { handler, healthProbes, rpcSends } = remoteWithHealthStatus(503, 200);
const port = await listenOnLoopback(handler);
const closed = new AppError('COMMAND_FAILED', 'The saved session changed.');
let handoffs = 0;
try {
await assert.rejects(
sendToDaemon(remotePress(`http://127.0.0.1:${port}`), {
authToken: 'test-scoped-token',
dispatch: async (send) => {
if (++handoffs === refused) throw closed;
return await send();
},
}),
(error: unknown) => error === closed,
);
assert.equal(healthProbes(), refused - 1);
assert.equal(rpcSends(), 0);
} finally {
await closeLoopbackServer(handler);
}
},
);
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import { sendToDaemon } from '../index.ts';
import {
canConnect,
isDaemonTransportUnavailableError,
readRemoteDaemonHealth,
sendRequest,
} from '../daemon-client-transport.ts';
import { DAEMON_UNAVAILABLE_REASONS } from '../daemon-lifecycle-errors.ts';
Expand Down Expand Up @@ -54,6 +55,30 @@ function sendWithStaleInstance(port: number, timeoutMs: number) {
);
}

test('remote health stops waiting when canceled during admission', async () => {
const controller = new AbortController();
let release!: () => void;
const held = new Promise<void>((resolve) => {
release = resolve;
});
try {
const result = await readRemoteDaemonHealth(
{ baseUrl: 'http://127.0.0.1:1', token: 'fixture-token', pid: 1 },
1000,
controller.signal,
async (send) => {
controller.abort();
await held;
return await send();
},
);
assert.equal(controller.signal.aborted, true);
assert.equal(result.reachable, false);
} finally {
release();
}
});

test('auto health probing reserves time for a healthy fallback when HTTP hangs', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const httpServer = http.createServer(() => {});
Expand Down Expand Up @@ -661,3 +686,68 @@ test('a transport failure invalidates cached health for a remote daemon only', a
await closeLoopbackServer(server);
}
});

test('refuses a follow-up artifact download after the admission closes', async (t) => {
if (await skipWhenLoopbackUnavailable(t)) return;
const root = mkdtempForTestSync('daemon-admitted-artifact-');
const calls: string[] = [];
const server = http.createServer((request, response) => {
calls.push(request.url ?? '');
request.resume();
if (request.url === '/health') {
response.end('{}');
} else if (request.url === '/rpc') {
response.end(
JSON.stringify({
jsonrpc: '2.0',
id: 'test',
result: {
ok: true,
data: {
artifacts: [
{
artifactId: 'fixture-artifact',
field: 'path',
artifactType: 'screenshot',
path: '/server/fixture.png',
fileName: 'fixture.png',
},
],
},
},
}),
);
} else {
response.end('unexpected artifact bytes');
}
});
let handoffs = 0;
try {
const port = await listenOnLoopback(server);
await assert.rejects(
sendToDaemon(
{
command: 'screenshot',
session: 'fixture',
positionals: [],
flags: { daemonBaseUrl: `http://127.0.0.1:${port}` },
meta: { cwd: root },
},
{
authToken: 'test-scoped-token',
dispatch: async (send) => {
// The health probe and RPC send are admitted before the artifact download.
if (++handoffs === 3)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: The handoffs === 3 cutoff hardcodes how many dispatch handoffs run before artifact materialization (health probe, RPC send, then materialize). Any added or removed handoff would make this test fail or pass for the wrong reason. Add a comment naming the materialize handoff, or assert on the materialize call directly.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At packages/daemon-client/src/__tests__/daemon-client-transport.test.ts, line 714:

<comment>The `handoffs === 3` cutoff hardcodes how many dispatch handoffs run before artifact materialization (health probe, RPC send, then materialize). Any added or removed handoff would make this test fail or pass for the wrong reason. Add a comment naming the materialize handoff, or assert on the materialize call directly.</comment>

<file context>
@@ -661,3 +661,67 @@ test('a transport failure invalidates cached health for a remote daemon only', a
+        {
+          authToken: 'test-scoped-token',
+          dispatch: async (send) => {
+            if (++handoffs === 3)
+              throw new AppError('COMMAND_FAILED', 'The saved session changed.');
+            return await send();
</file context>

throw new AppError('COMMAND_FAILED', 'The saved session changed.');
return await send();
},
},
),
{ message: 'The saved session changed.' },
);
assert.deepEqual(calls, ['/health', '/rpc']);
assert.deepEqual(fs.readdirSync(root), []);
} finally {
await closeLoopbackServer(server);
}
});
Loading
Loading