diff --git a/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts new file mode 100644 index 0000000000..9d8948baa1 --- /dev/null +++ b/packages/daemon-client/src/__tests__/daemon-client-lifecycle-remote-health.test.ts @@ -0,0 +1,90 @@ +// A remote connection probes GET /health before it sends anything. When that probe answers nothing +// usable, the refusal is the typed one: the request never left the client, so a caller branches on +// `details.reason` and `details.dispatched` instead of comparing the message. + +import assert from 'node:assert/strict'; +import http from 'node:http'; +import { test } from 'vitest'; +import { + closeLoopbackServer, + listenOnLoopback, + skipWhenLoopbackUnavailable, +} from '@agent-device/test-kit'; +import { AppError } from '@agent-device/kernel/errors'; +import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import { REMOTE_DAEMON_UNAVAILABLE_REASON } from '../daemon-lifecycle-errors.ts'; +import { sendToDaemon } from '../index.ts'; + +// A press, so the refusal states the fact a caller needs before resending a mutating command. +function remotePress(baseUrl: string) { + return { + session: 'default', + command: PUBLIC_COMMANDS.press, + positionals: ['@e1'], + flags: { daemonBaseUrl: baseUrl }, + meta: { requestId: 'req-remote-health-refusal' }, + }; +} + +/** A remote daemon that answers `/health` with `healthStatus` and counts the RPCs it receives. */ +function remoteWithHealthStatus(healthStatus: number): { + handler: http.Server; + rpcSends: () => number; +} { + let rpcSends = 0; + const handler = http.createServer((req, res) => { + req.resume(); + req.on('end', () => { + if (req.url?.endsWith('/health')) { + res.statusCode = healthStatus; + res.end(); + return; + } + rpcSends += 1; + res.statusCode = 500; + res.end(); + }); + }); + return { handler, rpcSends: () => rpcSends }; +} + +test('a remote press whose health probe answers 5xx refuses with the typed reason and dispatched no', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { handler, rpcSends } = remoteWithHealthStatus(503); + const port = await listenOnLoopback(handler); + const baseUrl = `http://127.0.0.1:${port}`; + try { + await assert.rejects(sendToDaemon(remotePress(baseUrl)), (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.equal(error.code, 'COMMAND_FAILED'); + assert.equal(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON); + assert.equal(error.details?.dispatched, 'no'); + assert.equal(error.details?.daemonBaseUrl, baseUrl); + return true; + }); + assert.equal(rpcSends(), 0, 'an unreachable remote daemon receives no RPC'); + } finally { + await closeLoopbackServer(handler); + } +}); + +// The closest negative: a probe that answers 4xx counts as reachable, so the press is sent and the +// unavailable refusal is never stamped on a request that left the client. +test('a remote press whose health probe answers 4xx is sent and is not the unavailable refusal', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + const { handler, rpcSends } = remoteWithHealthStatus(404); + const port = await listenOnLoopback(handler); + try { + await assert.rejects( + sendToDaemon(remotePress(`http://127.0.0.1:${port}`)), + (error: unknown) => { + assert.ok(error instanceof AppError, `unexpected failure: ${String(error)}`); + assert.notEqual(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON); + return true; + }, + ); + assert.equal(rpcSends(), 1); + } finally { + await closeLoopbackServer(handler); + } +}); diff --git a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts index e7ed735183..4061079136 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-transport.test.ts @@ -27,6 +27,7 @@ import { isDaemonTransportUnavailableError, sendRequest, } from '../daemon-client-transport.ts'; +import { REMOTE_DAEMON_UNAVAILABLE_REASON } from '../daemon-lifecycle-errors.ts'; import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; import { createDaemonProxyServer } from '@agent-device/proxy'; @@ -360,6 +361,8 @@ async function assertRestartProbeFailureReportsUnavailable( await assert.rejects(sendWithStaleInstance(port, 150), (error: unknown) => { assert.ok(error instanceof AppError); assert.equal(error.message, 'Remote daemon is unavailable'); + assert.equal(error.details?.reason, REMOTE_DAEMON_UNAVAILABLE_REASON); + assert.equal(error.details?.dispatched, 'no'); assert.equal(error.details?.daemonBaseUrl, `http://127.0.0.1:${port}`); assert.notEqual(error.details?.reason, 'daemon_transport_timeout'); return true; diff --git a/packages/daemon-client/src/daemon-client-lifecycle.ts b/packages/daemon-client/src/daemon-client-lifecycle.ts index bbf0f40ff0..b68845aafd 100644 --- a/packages/daemon-client/src/daemon-client-lifecycle.ts +++ b/packages/daemon-client/src/daemon-client-lifecycle.ts @@ -258,9 +258,11 @@ async function ensureRemoteDaemon(settings: DaemonClientSettings): Promise { + const server = http.createServer(); + try { + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + const address = server.address(); + if (address === null || typeof address === 'string') { + throw new Error('Expected a TCP port on the loopback listener'); + } + return address.port; + } finally { + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } +} + +test('--json carries the remote daemon refusal reason and its non-dispatch', async () => { + const port = await reserveUnusedLoopbackPort(); + const result = await runCliCapture(['devices', '--json'], { + useRealDaemonClient: true, + env: { AGENT_DEVICE_DAEMON_BASE_URL: `http://127.0.0.1:${port}` }, + }); + + assert.equal(result.code, 1); + const payload = JSON.parse(result.stdout) as { + success: boolean; + error: { code: string; message: string; details?: Record }; + }; + assert.equal(payload.success, false); + assert.equal(payload.error.code, 'COMMAND_FAILED'); + assert.equal(payload.error.message, 'Remote daemon is unavailable'); + // The published wire values a --json consumer branches on, asserted as the strings themselves. + assert.equal(payload.error.details?.reason, 'remote_daemon_unavailable'); + assert.equal(payload.error.details?.dispatched, 'no'); +}); diff --git a/website/docs/docs/commands.md b/website/docs/docs/commands.md index a93e539340..c13b007f6a 100644 --- a/website/docs/docs/commands.md +++ b/website/docs/docs/commands.md @@ -592,6 +592,7 @@ These refusals carry `dispatched: no` and a typed `error.details.reason`, so bra - `session_app_required`: a per-app setting was requested but the session binds no app and none was named. Run `open `, or name the app on the request for a setting that takes one (`settings clear-app-state com.example.app`). - `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. - `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. +- `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. - `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. ## Find (semantic)