Skip to content

Commit 62f5434

Browse files
thymikeeclaude
andcommitted
fix(daemon-client): type the remote daemon refusal with its dispatch fact
Both remote-send health probes refused a command with the same sentence and no typed reason, so a caller could only detect the case by comparing message text. The refusal now carries details.reason remote_daemon_unavailable and dispatched: no, which states that nothing was sent, so resending even a UI action is safe. Both throw sites build the error through one constructor, loaded on the refusal. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ddbfc85 commit 62f5434

7 files changed

Lines changed: 174 additions & 5 deletions

File tree

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// A remote connection probes GET /health before it sends anything. When that probe answers nothing
2+
// usable, the refusal is the typed one: the request never left the client, so a caller branches on
3+
// `details.reason` and `details.dispatched` instead of comparing the message.
4+
5+
import assert from 'node:assert/strict';
6+
import http from 'node:http';
7+
import { test } from 'vitest';
8+
import {
9+
closeLoopbackServer,
10+
listenOnLoopback,
11+
skipWhenLoopbackUnavailable,
12+
} from '@agent-device/test-kit';
13+
import { AppError } from '@agent-device/kernel/errors';
14+
import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog';
15+
import { REMOTE_DAEMON_UNAVAILABLE_REASON } from '../daemon-lifecycle-errors.ts';
16+
import { sendToDaemon } from '../index.ts';
17+
18+
// A press, so the refusal states the fact a caller needs before resending a mutating command.
19+
function remotePress(baseUrl: string) {
20+
return {
21+
session: 'default',
22+
command: PUBLIC_COMMANDS.press,
23+
positionals: ['@e1'],
24+
flags: { daemonBaseUrl: baseUrl },
25+
meta: { requestId: 'req-remote-health-refusal' },
26+
};
27+
}
28+
29+
/** A remote daemon that answers `/health` with `healthStatus` and counts the RPCs it receives. */
30+
function remoteWithHealthStatus(healthStatus: number): {
31+
handler: http.Server;
32+
rpcSends: () => number;
33+
} {
34+
let rpcSends = 0;
35+
const handler = http.createServer((req, res) => {
36+
req.resume();
37+
req.on('end', () => {
38+
if (req.url?.endsWith('/health')) {
39+
res.statusCode = healthStatus;
40+
res.end();
41+
return;
42+
}
43+
rpcSends += 1;
44+
res.statusCode = 500;
45+
res.end();
46+
});
47+
});
48+
return { handler, rpcSends: () => rpcSends };
49+
}
50+
51+
test('a remote press whose health probe answers 5xx refuses with the typed reason and dispatched no', async (t) => {
52+
if (await skipWhenLoopbackUnavailable(t)) return;
53+
const { handler, rpcSends } = remoteWithHealthStatus(503);
54+
const port = await listenOnLoopback(handler);
55+
const baseUrl = `http://127.0.0.1:${port}`;
56+
try {
57+
await assert.rejects(sendToDaemon(remotePress(baseUrl)), (error: unknown) => {
58+
assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`);
59+
assert.equal(error.code, 'COMMAND_FAILED');
60+
assert.equal(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON);
61+
assert.equal(error.details?.dispatched, 'no');
62+
assert.equal(error.details?.daemonBaseUrl, baseUrl);
63+
return true;
64+
});
65+
assert.equal(rpcSends(), 0, 'an unreachable remote daemon receives no RPC');
66+
} finally {
67+
await closeLoopbackServer(handler);
68+
}
69+
});
70+
71+
// The closest negative: a probe that answers 4xx counts as reachable, so the press is sent and the
72+
// unavailable refusal is never stamped on a request that left the client.
73+
test('a remote press whose health probe answers 4xx is sent and is not the unavailable refusal', async (t) => {
74+
if (await skipWhenLoopbackUnavailable(t)) return;
75+
const { handler, rpcSends } = remoteWithHealthStatus(404);
76+
const port = await listenOnLoopback(handler);
77+
try {
78+
await assert.rejects(
79+
sendToDaemon(remotePress(`http://127.0.0.1:${port}`)),
80+
(error: unknown) => {
81+
assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`);
82+
assert.notEqual(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON);
83+
return true;
84+
},
85+
);
86+
assert.equal(rpcSends(), 1);
87+
} finally {
88+
await closeLoopbackServer(handler);
89+
}
90+
});

‎packages/daemon-client/src/__tests__/daemon-client-transport.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import {
2727
isDaemonTransportUnavailableError,
2828
sendRequest,
2929
} from '../daemon-client-transport.ts';
30+
import { REMOTE_DAEMON_UNAVAILABLE_REASON } from '../daemon-lifecycle-errors.ts';
3031
import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution';
3132
import { createDaemonProxyServer } from '@agent-device/proxy';
3233

@@ -360,6 +361,8 @@ async function assertRestartProbeFailureReportsUnavailable(
360361
await assert.rejects(sendWithStaleInstance(port, 150), (error: unknown) => {
361362
assert.ok(error instanceof AppError);
362363
assert.equal(error.message, 'Remote daemon is unavailable');
364+
assert.equal(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON);
365+
assert.equal(error.details?.dispatched, 'no');
363366
assert.equal(error.details?.daemonBaseUrl, `http://127.0.0.1:${port}`);
364367
assert.notEqual(error.details?.reason, 'daemon_transport_timeout');
365368
return true;

‎packages/daemon-client/src/daemon-client-lifecycle.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -258,9 +258,11 @@ async function ensureRemoteDaemon(settings: DaemonClientSettings): Promise<Ensur
258258
remoteInfo.remoteUpstreamInstanceId = health.upstream?.instanceId;
259259
return { info: remoteInfo, startedByClient: false };
260260
}
261-
throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', {
261+
// Loaded on the refusal: this error module is not part of what every CLI start pays for.
262+
const { remoteDaemonUnavailableError } = await import('./daemon-lifecycle-errors.ts');
263+
throw remoteDaemonUnavailableError({
262264
daemonBaseUrl: settings.remoteBaseUrl,
263-
hint: 'Verify AGENT_DEVICE_DAEMON_BASE_URL points to a reachable daemon with GET /health and POST /rpc. If this CLI was connected with connect proxy, run agent-device disconnect to return to the local daemon.',
265+
hint: 'Fix or unset --daemon-base-url or AGENT_DEVICE_DAEMON_BASE_URL so the client targets a reachable daemon or the local one. If this CLI was connected with connect proxy, run agent-device disconnect to clear the saved connection and return to the local daemon.',
264266
});
265267
}
266268

‎packages/daemon-client/src/daemon-client-transport.ts‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -495,9 +495,8 @@ async function retryAfterRemoteInstanceMismatch(
495495
health.timedOut ? probeTimeoutMs : undefined,
496496
);
497497
if (!health.reachable) {
498-
throw new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', {
499-
daemonBaseUrl: info.baseUrl,
500-
});
498+
const { remoteDaemonUnavailableError } = await import('./daemon-lifecycle-errors.ts');
499+
throw remoteDaemonUnavailableError({ daemonBaseUrl: info.baseUrl });
501500
}
502501
info.remoteInstanceId = health.instanceId;
503502
info.remoteUpstreamInstanceId = health.upstream?.instanceId;

‎packages/daemon-client/src/daemon-lifecycle-errors.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,35 @@ export function daemonStopCommand(stateDir: string): string {
5151
return `agent-device daemon stop --state-dir ${shellQuoteIfNeeded(stateDir)}`;
5252
}
5353

54+
/**
55+
* The reason a remote connection answers when the `GET /health` probe that gates its send found no
56+
* daemon to hand the request to. Recovery is what the reason's meaning is: make the daemon at
57+
* `daemonBaseUrl` reachable, or return to the local daemon, then resend.
58+
*/
59+
export const REMOTE_DAEMON_UNAVAILABLE_REASON = 'remote_daemon_unavailable';
60+
61+
/**
62+
* The refusal both remote-send gates answer with: the probe before the first send
63+
* (`ensureRemoteDaemon`) and the probe a restart retry runs after the daemon instance changed under
64+
* the request. Before the first send, the request never leaves the client. On the restart retry, the
65+
* first request did reach the daemon, but it refused it with the instance-mismatch precondition
66+
* before running it, and the retry is withheld. So `dispatched: 'no'` states that the command did
67+
* not run — what makes a resend safe, for a UI action as much as for a read — and a caller branches
68+
* on the reason instead of comparing the message.
69+
*/
70+
export function remoteDaemonUnavailableError(params: {
71+
daemonBaseUrl: string | undefined;
72+
hint?: string;
73+
}): AppError {
74+
const { daemonBaseUrl, hint } = params;
75+
return new AppError('COMMAND_FAILED', 'Remote daemon is unavailable', {
76+
reason: REMOTE_DAEMON_UNAVAILABLE_REASON,
77+
dispatched: 'no',
78+
daemonBaseUrl,
79+
...(hint !== undefined ? { hint } : {}),
80+
});
81+
}
82+
5483
/** A daemon won a startup race that this caller may not settle by retiring it. */
5584
export const DAEMON_CONTENDED_REASON = 'daemon-contended';
5685

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// A remote daemon that answers nothing stops the CLI before its request is sent. This runs the real
2+
// CLI against a base URL with no listener, so what it reads is the `--json` failure envelope a
3+
// caller branches on: the typed reason, and the fact that nothing was dispatched.
4+
5+
import http from 'node:http';
6+
import assert from 'node:assert/strict';
7+
import { test } from 'vitest';
8+
import { runCliCapture } from './cli-capture.ts';
9+
10+
/** An ephemeral loopback port with no listener: bind 127.0.0.1:0, read the port, close it. */
11+
async function reserveUnusedLoopbackPort(): Promise<number> {
12+
const server = http.createServer();
13+
try {
14+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
15+
const address = server.address();
16+
if (address === null || typeof address === 'string') {
17+
throw new Error('Expected a TCP port on the loopback listener');
18+
}
19+
return address.port;
20+
} finally {
21+
await new Promise<void>((resolve, reject) =>
22+
server.close((error) => (error ? reject(error) : resolve())),
23+
);
24+
}
25+
}
26+
27+
test('--json carries the remote daemon refusal reason and its non-dispatch', async () => {
28+
const port = await reserveUnusedLoopbackPort();
29+
const result = await runCliCapture(['devices', '--json'], {
30+
useRealDaemonClient: true,
31+
env: { AGENT_DEVICE_DAEMON_BASE_URL: `http://127.0.0.1:${port}` },
32+
});
33+
34+
assert.equal(result.code, 1);
35+
const payload = JSON.parse(result.stdout) as {
36+
success: boolean;
37+
error: { code: string; message: string; details?: Record<string, unknown> };
38+
};
39+
assert.equal(payload.success, false);
40+
assert.equal(payload.error.code, 'COMMAND_FAILED');
41+
assert.equal(payload.error.message, 'Remote daemon is unavailable');
42+
// The published wire values a --json consumer branches on, asserted as the strings themselves.
43+
assert.equal(payload.error.details?.reason, 'remote_daemon_unavailable');
44+
assert.equal(payload.error.details?.dispatched, 'no');
45+
});

‎website/docs/docs/commands.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -592,6 +592,7 @@ These refusals carry `dispatched: no` and a typed `error.details.reason`, so bra
592592
- `session_app_required`: a per-app setting was requested but the session binds no app and none was named. Run `open <app>`, or name the app on the request for a setting that takes one (`settings clear-app-state com.example.app`).
593593
- `app_not_installed`: the named app resolves to no installed app on the target. Run `apps --all` for the exact bundle id or package, or install the app, then retry.
594594
- `malformed_request`: the local socket transport refused the request envelope before any handler read it, for example a positional that is not a string. Fix the client that built the request; resending it unchanged fails the same way.
595+
- `remote_daemon_unavailable`: the client's `GET /health` probe of the remote daemon answered nothing usable, so the command did not run, and `details.daemonBaseUrl` names the daemon that failed the probe. The probe before the first send refuses it outright; the probe a restart retry runs after the daemon instance changed refuses it too — there the first request reached the daemon but was refused before execution, so nothing ran either way. Make that daemon reachable, or clear or override `--daemon-base-url` or `AGENT_DEVICE_DAEMON_BASE_URL`; for a saved `connect` connection, run `disconnect` to return to the local daemon, then resend the same command.
595596
- `webdriver_route_unsupported`: on a WebDriver-backed device cloud, the driver does not implement the route; the limit is the cloud's driver, not the device. A command with a second route (`orientation` has two) tries it before failing. After an ambiguous failure on that transport, only read-only requests are resent.
596597
597598
## Find (semantic)

0 commit comments

Comments
 (0)