From 547b40627040416e31a668088eec04ade8f5618c Mon Sep 17 00:00:00 2001 From: parbez Date: Thu, 26 Nov 2026 19:39:03 +0530 Subject: [PATCH] fix(daemon-client): clear remote URL and token on timeout once response starts or /health answers --- .../daemon-client-timeout-route.test.ts | 291 +++++++++++++++++- .../__tests__/daemon-client-timeout.test.ts | 107 +++++++ .../src/daemon-client-timeout.ts | 171 +++++++++- .../src/daemon-client-transport-reasons.ts | 2 + .../src/daemon-client-transport.ts | 44 ++- website/docs/docs/error-reasons.md | 2 +- 6 files changed, 566 insertions(+), 51 deletions(-) diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts index 6862b44038..b1cb8dbb9f 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout-route.test.ts @@ -39,6 +39,7 @@ vi.mock('@agent-device/host-kit/command', async () => { import { AppError } from '@agent-device/kernel/errors'; import { isProcessAlive } from '@agent-device/host-kit/process'; import { PUBLIC_COMMANDS } from '@agent-device/command-registry/catalog'; +import { DAEMON_HTTP_INSTANCE_MISMATCH_HEADER } from '@agent-device/contracts/daemon-http'; import { sendRequest } from '../daemon-client-transport.ts'; import type { DaemonInfo } from '../daemon-client-metadata.ts'; import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; @@ -129,6 +130,7 @@ function buildRequest( command: string, platform: 'android' | 'ios' | undefined, positionals: readonly string[] = [], + requestProgress?: 'command' | 'replay-test', ): DaemonWireRequest { return { token: 'test-token', @@ -136,16 +138,18 @@ function buildRequest( command, positionals: [...positionals], flags: platform ? { platform } : {}, - meta: { requestId: 'req-timeout-route' }, + meta: { + requestId: 'req-timeout-route', + ...(requestProgress ? { requestProgress } : {}), + }, }; } /** - * A daemon stand-in whose FIRST connection (the RPC) is accepted and never answered, so the - * client's own envelope cuts the round trip off, and whose LATER connections — the timeout - * handler's fresh probe — either answer like a live daemon (`answer`) or are destroyed - * unanswered (`refuse`, the wedged daemon the reset path is built for: fails the probe fast - * instead of spending its window). + * A daemon stand-in whose FIRST connection (the RPC) is accepted and never answered (or opens a + * stalled stream according to `firstResponse`), so the client's own envelope cuts the round trip + * off, and whose LATER connections — the timeout handler's fresh probe — answer according to + * `afterFirst`. * * `connections` counts accepted TCP connections, NOT requests: the probe's whole claim is that it * asks on a FRESH connection, so an HTTP request counter — which an RPC kept alive by keep-alive @@ -153,9 +157,28 @@ function buildRequest( * answers `/health` on a connection after the first, so a row that reaches its kept-alive hint is * simultaneously proving a fresh connection carried a health request. */ +type StandInAnswer = + | 'answer' + | 'refuse' + | 'answer-late' + | 'not-found' + | 'named-daemon' + | 'named-proxy' + | 'foreign-service' + | 'hold'; + +type StandInFirstResponse = 'silent' | 'stream-200' | 'stream-500' | 'html-200'; + +const NAMED_HEALTH_SERVICES: Partial> = { + 'named-daemon': 'agent-device-daemon', + 'named-proxy': 'agent-device-proxy', + 'foreign-service': 'web-server', +}; + async function startStandIn( transport: 'http' | 'socket', - afterFirst: 'answer' | 'refuse' | 'answer-late', + afterFirst: StandInAnswer, + firstResponse: StandInFirstResponse = 'silent', ): Promise<{ server: LoopbackServer; port: number; connections: () => number }> { let connections = 0; // The TCP ordinal lives on the socket the request arrived on, so two requests sharing one @@ -171,11 +194,52 @@ async function startStandIn( res.end('{}'); return; } + // A non-2xx status must still reject `/health` even if the body names a daemon service. + if (connection > 1 && afterFirst === 'not-found') { + res.statusCode = 404; + res.end(JSON.stringify({ service: 'agent-device-daemon' })); + return; + } + // A success that names a service: the contract's daemon/proxy, or a foreign server. + const service = NAMED_HEALTH_SERVICES[afterFirst]; + if (connection > 1 && service) { + res.statusCode = 200; + res.end(JSON.stringify({ service })); + return; + } + // Holds the probe's connection open without an answer. + if (connection > 1 && afterFirst === 'hold') { + res.on('error', () => {}); + return; + } if (connection > 1) { res.destroy(); return; } res.on('error', () => {}); + if (firstResponse === 'stream-200') { + res.writeHead(200, { 'content-type': 'application/x-ndjson' }); + res.write( + `${JSON.stringify({ + type: 'progress', + event: { + type: 'command', + status: 'progress', + message: 'Starting XCTest runner...', + }, + })}\n`, + ); + return; + } + if (firstResponse === 'stream-500') { + res.writeHead(500, { 'content-type': 'application/x-ndjson' }); + res.flushHeaders(); + return; + } + if (firstResponse === 'html-200') { + res.writeHead(200, { 'content-type': 'text/html' }); + res.write(''); + } }) : net.createServer((socket) => { const connection = ++connections; @@ -244,8 +308,14 @@ type RouteRow = Readonly<{ command: string; platform: 'android' | 'ios' | undefined; positionals?: readonly string[]; - afterFirst: 'answer' | 'refuse' | 'answer-late'; + requestProgress?: 'command' | 'replay-test'; + firstResponse?: StandInFirstResponse; + afterFirst: StandInAnswer; hintPattern: RegExp; + /** `details.remoteResponseStarted`: set only for a sent remote request. */ + remoteResponseStarted?: boolean; + /** `details.remoteHealthAnswered`: set only when a sent remote request checked `/health`. */ + remoteHealthAnswered?: boolean; // The connections the stand-in must observe: 1 = the RPC only (route never probed), // 2 = RPC + the probe that answered, 3 = RPC + a missed probe + the one that answered, // 4 = RPC + every probe of the unresponsive verdict. @@ -329,14 +399,137 @@ const ROUTE_ROWS: readonly RouteRow[] = [ resets: false, }, { - // A remote client cannot reset anything on the daemon's host: no probe window, no sweep. - name: 'keeps a remote timeout declarative', + // A streamed CLI request that already opened a 2xx progress stream proves both URL and token + // directly, so the client skips `/health` entirely even if a second connect would fail (#5004). + name: 'clears the URL and token without probing /health once a remote progress stream started', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + requestProgress: 'command', + firstResponse: 'stream-200', + afterFirst: 'refuse', + hintPattern: + /already started answering this request, so its URL and auth token are not the cause.*builds and starts the XCTest runner.*running it again is safe/s, + remoteResponseStarted: true, + connections: 1, + resets: false, + }, + { + // A local HTTP stream must never leak remote response flags onto local timeout recovery. + name: 'leaves local HTTP timeout details free of remote stream flags', + transport: 'http', + command: RESET_POLICY_COMMAND, + platform: 'ios', + requestProgress: 'command', + firstResponse: 'stream-200', + afterFirst: 'answer', + hintPattern: /The timed-out open request was canceled; the daemon was kept alive/, + connections: 2, + resets: false, + }, + { + // Non-2xx progress headers are not proof that the daemon admitted the request. + name: 'does not treat a non-2xx NDJSON stream as a started remote response', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + requestProgress: 'command', + firstResponse: 'stream-500', + afterFirst: 'refuse', + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, + resets: false, + }, + { + // A non-daemon web server at the wrong URL streaming 200 text/html must not clear the URL. + name: 'does not treat a non-NDJSON 200 response as a started remote progress stream', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + requestProgress: 'command', + firstResponse: 'html-200', + afterFirst: 'not-found', + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, + resets: false, + }, + { + // Non-streaming callers (`--json`, MCP, SDK) and unstarted streams fall back to `/health` once. + name: 'clears the URL and token of a remote daemon whose /health names the daemon service', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + afterFirst: 'named-daemon', + hintPattern: + /still answers \/health, so its URL and auth token are not the cause.*builds and starts the XCTest runner.*running it again is safe/s, + remoteResponseStarted: false, + remoteHealthAnswered: true, + connections: 2, + resets: false, + }, + { + // #5058 forwards client disconnects through the proxy, so proxy and direct share one retry hint. + name: 'clears the URL and token of a remote proxy whose /health names the proxy service', transport: 'remote', command: RESET_POLICY_COMMAND, platform: 'android', + afterFirst: 'named-proxy', + hintPattern: /still answers \/health.*running it again is safe even if the app launched\.$/s, + remoteResponseStarted: false, + remoteHealthAnswered: true, + connections: 2, + resets: false, + }, + { + name: 'keeps the URL and token hint when a /health success names no daemon service', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', afterFirst: 'answer', - hintPattern: /Verify the remote daemon URL, auth token, and remote host logs/, - connections: 1, + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, + resets: false, + }, + { + name: 'keeps the URL and token hint when a /health success names a foreign service', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + afterFirst: 'foreign-service', + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, + resets: false, + }, + { + name: 'keeps the URL and token hint when the remote URL answers /health with no success', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + afterFirst: 'not-found', + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, + resets: false, + }, + { + name: 'keeps the URL and token hint for a remote daemon that no longer answers', + transport: 'remote', + command: RESET_POLICY_COMMAND, + platform: 'ios', + afterFirst: 'refuse', + hintPattern: /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + remoteResponseStarted: false, + remoteHealthAnswered: false, + connections: 2, resets: false, }, ]; @@ -357,6 +550,7 @@ for (const row of ROUTE_ROWS) { const daemon = await startStandIn( row.transport === 'remote' ? 'http' : row.transport, row.afterFirst, + row.firstResponse, ); // Preserved rows retain seeded metadata. Reset rows acquire a real child-owned registration. const statePaths = dummyStatePaths(); @@ -373,7 +567,7 @@ for (const row of ROUTE_ROWS) { const error = await expectRouteError( sendRequest( info, - buildRequest(row.command, row.platform, row.positionals), + buildRequest(row.command, row.platform, row.positionals, row.requestProgress), row.transport === 'remote' ? 'http' : row.transport, statePaths, TIMEOUT_MS, @@ -384,6 +578,8 @@ for (const row of ROUTE_ROWS) { // The hint is printed as the Next step; a failure that already wrote its log never asks for // a --debug rerun. assert.equal(/--debug/.test(String(error.details?.hint)), false); + assert.equal(error.details?.remoteResponseStarted, row.remoteResponseStarted); + assert.equal(error.details?.remoteHealthAnswered, row.remoteHealthAnswered); assert.equal(daemon.connections(), row.connections, 'probe-vs-skip is a route decision'); assert.equal( fs.existsSync(statePaths.infoPath), @@ -401,6 +597,75 @@ for (const row of ROUTE_ROWS) { }); } +test('request-timeout route: a held remote /health answers nothing within the probe bound', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + // The probe only picks the hint, so a daemon that holds `/health` open must cost the caller about + // one second past the request window, not the full remote health-check window. + const daemon = await startStandIn('http', 'hold'); + const startedAt = performance.now(); + try { + const error = await expectRouteError( + sendRequest( + { token: 'test-token', pid: process.pid, baseUrl: `http://127.0.0.1:${daemon.port}` }, + buildRequest(RESET_POLICY_COMMAND, 'ios'), + 'http', + dummyStatePaths(), + TIMEOUT_MS, + { host: createTestHostEnvironment() }, + ), + /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + ); + assert.equal(error.details?.remoteResponseStarted, false); + assert.equal(error.details?.remoteHealthAnswered, false); + assert.ok(performance.now() - startedAt < 2_000, 'the probe stays within its 1 s bound'); + } finally { + (daemon.server as http.Server).closeAllConnections(); + await closeLoopbackServer(daemon.server); + } +}); + +test('request-timeout route: a remote request that never left the client does not ask /health again', async (t) => { + if (await skipWhenLoopbackUnavailable(t)) return; + // The RPC is refused as an instance change, and the retry's own `/health` read hangs until the + // budget ends, so the timeout lands before the request was resent. A later `/health` would + // answer, but nothing reached the daemon, so it cannot clear the token or promise a cancel. The + // window is wide enough that the 409 always lands before it, so the timeout is the retry's. + const windowMs = 500; + let healthReads = 0; + const server = http.createServer((req, res) => { + if (req.url === '/rpc') { + res.writeHead(409, { [DAEMON_HTTP_INSTANCE_MISMATCH_HEADER]: 'true' }); + res.end(); + return; + } + healthReads += 1; + if (healthReads === 1) return; + res.statusCode = 200; + res.end(JSON.stringify({ service: 'agent-device-daemon' })); + }); + const port = await listenOnLoopback(server); + try { + const error = await expectRouteError( + sendRequest( + { token: 'test-token', pid: process.pid, baseUrl: `http://127.0.0.1:${port}` }, + buildRequest(RESET_POLICY_COMMAND, 'ios'), + 'http', + dummyStatePaths(), + windowMs, + { host: createTestHostEnvironment() }, + ), + /^Verify the remote daemon URL, auth token, and remote host logs\.$/, + ); + assert.equal(error.details?.daemonRequestSent, false); + assert.equal(error.details?.remoteResponseStarted, undefined); + assert.equal(error.details?.remoteHealthAnswered, undefined); + assert.equal(healthReads, 1, 'no post-timeout /health probe runs for an unsent request'); + } finally { + server.closeAllConnections(); + await closeLoopbackServer(server); + } +}); + test('request-timeout route: a reset never deletes a registration a replacement daemon published', async (t) => { if (await skipWhenLoopbackUnavailable(t)) return; // The probe window is exactly when another client can start a replacement daemon and publish diff --git a/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts b/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts index 400336adc4..fe3395ee1d 100644 --- a/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts +++ b/packages/daemon-client/src/__tests__/daemon-client-timeout.test.ts @@ -4,6 +4,7 @@ import assert from 'node:assert/strict'; import { test } from 'vitest'; +import { AppError, normalizeError } from '@agent-device/kernel/errors'; import { resolveRequestTimeoutHint } from '../daemon-client-timeout.ts'; test('request timeout hint names an Apple runner only on a declared Apple platform', () => { @@ -68,6 +69,112 @@ test('request timeout hint names an Apple runner only on a declared Apple platfo ); }); +test('a remote timeout clears the URL and token once the response started or /health answered', () => { + const started = + 'The remote daemon already started answering this request, so its URL and auth token are not the cause.'; + const reachable = + 'The remote daemon still answers /health, so its URL and auth token are not the cause.'; + // The CLI prints "Run snapshot to check the screen before you retry." first, because the open + // may have launched the app, so the retry is stated as safe whatever that check shows. + const retry = + 'The daemon canceled this open, so running it again is safe even if the app launched.'; + // A streamed first Apple open that started responding before timing out (#5004). + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted: true, + resetDaemon: false, + command: 'open', + applePlatformDeclared: true, + }), + `${started} A first Apple open can outlast the request window while the host builds and starts the XCTest runner. ${retry} For a longer startup window, run agent-device prepare ios-runner with the same --platform first.`, + ); + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted: true, + resetDaemon: false, + command: 'open', + applePlatformDeclared: false, + }), + `${started} ${retry}`, + ); + // If both flags are set, the started response is the stronger proof and chooses the lead wording. + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted: true, + remoteHealthAnswered: true, + resetDaemon: false, + command: 'press', + applePlatformDeclared: true, + }), + `${started} Read the remote host logs for the timed-out press step.`, + ); + // A non-streaming caller whose `/health` probe answered gets the same recovery guidance. + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted: false, + remoteHealthAnswered: true, + resetDaemon: false, + command: 'open', + applePlatformDeclared: true, + }), + `${reachable} A first Apple open can outlast the request window while the host builds and starts the XCTest runner. ${retry} For a longer startup window, run agent-device prepare ios-runner with the same --platform first.`, + ); + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteHealthAnswered: true, + resetDaemon: false, + command: 'open', + applePlatformDeclared: false, + }), + `${reachable} ${retry}`, + ); + // Another command may have acted before the window closed, so no retry is promised. + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteHealthAnswered: true, + resetDaemon: false, + command: undefined, + applePlatformDeclared: true, + }), + `${reachable} Read the remote host logs for the timed-out request step.`, + ); + // The error's details are capped when normalized, and a cut hint loses its last step. + for (const applePlatformDeclared of [true, false]) { + for (const remoteResponseStarted of [true, false]) { + const hint = resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted, + remoteHealthAnswered: !remoteResponseStarted, + resetDaemon: false, + command: 'open', + applePlatformDeclared, + }); + assert.equal( + normalizeError(new AppError('COMMAND_FAILED', 'timed out', { hint })).hint, + hint, + ); + } + } + // The closest negative: neither a started response nor a healthy daemon keeps the old hint. + assert.equal( + resolveRequestTimeoutHint({ + remote: true, + remoteResponseStarted: false, + remoteHealthAnswered: false, + resetDaemon: false, + command: 'open', + applePlatformDeclared: true, + }), + 'Verify the remote daemon URL, auth token, and remote host logs.', + ); +}); + test('a timed-out record stop on a surviving daemon names the retry that returns the export', () => { // A remote client never touches the daemon's host, so its daemon survives by construction. assert.equal( diff --git a/packages/daemon-client/src/daemon-client-timeout.ts b/packages/daemon-client/src/daemon-client-timeout.ts index 14ccf4563f..142f26019b 100644 --- a/packages/daemon-client/src/daemon-client-timeout.ts +++ b/packages/daemon-client/src/daemon-client-timeout.ts @@ -8,6 +8,7 @@ import type { DaemonPaths } from '@agent-device/daemon-contracts/daemon-resoluti import type { PlatformSelector } from '@agent-device/kernel/device'; import { observedDaemonIdentityOf, type DaemonInfo } from './daemon-client-metadata.ts'; import type { DaemonProbeVerdict } from './daemon-client-loopback-probe.ts'; +import type { RemoteDaemonHealth } from './daemon-client-transport.ts'; // Recovery for a timed-out request is scoped to that request or to nothing. The daemon owns // request-scoped recovery (#3177): destroying the timed-out connection cancels exactly that @@ -40,19 +41,89 @@ export async function handleRequestTimeout( action?: string; /** Whether the request left this process before the window expired. */ requestSent: boolean; + /** Whether the remote daemon had already opened a 2xx progress stream before the timeout. */ + responseStarted: boolean; + /** Reads the remote daemon's `/health` within a budget. The transport owns the request. */ + readRemoteHealth: (budgetMs: number) => Promise; }>, ): Promise { - const { info, statePaths, remote, retireUnresponsive, timeoutMs, requestId, command, session } = - params; + const { + info, + statePaths, + remote, + retireUnresponsive, + timeoutMs, + requestId, + command, + session, + requestSent, + responseStarted, + readRemoteHealth, + } = params; // The command's declared policy (`timeoutPolicy.onTimeout`, ADR 0008) decides whether a local // timed-out request is RESET-ELIGIBLE; the liveness probe decides whether the eligibility runs. // A remote client cannot reach the host's process table or the daemon's state dir, so a remote // timeout stays purely declarative here. const resetEligible = !remote && shouldResetDaemonAfterRequestTimeout(command); const liveness = resetEligible ? await probeDaemonLiveness(info, session) : undefined; + const remoteProof = await resolveRemoteTimeoutProof({ + remote, + requestSent, + responseStarted, + readRemoteHealth, + }); const recovery = await recoverFromTimeout({ info, statePaths, liveness, retireUnresponsive }); - emitTimeoutDiagnostic({ timeoutMs, requestId, command, remote, info, liveness, recovery }); - return await timeoutFailure({ params, statePaths, liveness, recovery }); + emitTimeoutDiagnostic({ + timeoutMs, + requestId, + command, + remote, + info, + liveness, + remoteProof, + recovery, + }); + return await timeoutFailure({ params, statePaths, liveness, remoteProof, recovery }); +} + +// The answer only picks the hint, so a probe that misses costs the old wording, not a recovery, and +// it must not add the full health-check window to every remote timeout. +const REMOTE_TIMEOUT_HEALTH_PROBE_MS = 1_000; + +/** What a sent remote request proved about the daemon URL and auth token before or after timeout. */ +type RemoteTimeoutProof = Readonly<{ + /** Set for a sent remote request: whether a 2xx progress stream had opened before the timeout. */ + responseStarted?: boolean; + /** Set when no progress stream had opened and `/health` was checked instead. */ + healthAnswered?: boolean; +}>; + +/** + * Whether a sent remote request already proved that the URL and auth token were fine. + * A 2xx progress stream proves both without another round trip. Non-streaming callers (`--json`, + * MCP, SDK) and streams that emitted no progress before the timeout ask `/health` once (1 s cap) + * and require a 2xx with a contract daemon or proxy `service`; `/health` checks no token, but + * `/rpc` refuses a wrong one at once, so a timed-out request had already passed it. + */ +async function resolveRemoteTimeoutProof( + params: Readonly<{ + remote: boolean; + requestSent: boolean; + responseStarted: boolean; + readRemoteHealth: (budgetMs: number) => Promise; + }>, +): Promise { + if (!params.remote || !params.requestSent) return {}; + if (params.responseStarted) return { responseStarted: true }; + const health = await params.readRemoteHealth(REMOTE_TIMEOUT_HEALTH_PROBE_MS); + return { + responseStarted: false, + healthAnswered: + health.reachable && + health.statusCode !== undefined && + health.statusCode < 300 && + health.service !== undefined, + }; } /** @@ -117,10 +188,11 @@ function emitTimeoutDiagnostic( remote: boolean; info: DaemonInfo; liveness: DaemonProbeVerdict | undefined; + remoteProof: RemoteTimeoutProof; recovery: TimeoutRecovery; }>, ): void { - const { timeoutMs, requestId, command, remote, info, liveness, recovery } = params; + const { timeoutMs, requestId, command, remote, info, liveness, remoteProof, recovery } = params; const { retirement } = recovery; const resetDaemon = retirement?.status === 'retired'; const preserved = @@ -138,6 +210,8 @@ function emitTimeoutDiagnostic( daemonPreservedAfterTimeout: preserved || (!remote && !recovery.mayRetire), daemonLivenessProbeAnswered: liveness?.reachable, daemonLivenessConnectDenied: liveness?.denial, + remoteResponseStarted: remoteProof.responseStarted, + remoteHealthAnswered: remoteProof.healthAnswered, daemonBaseUrl: info.baseUrl, }, }); @@ -155,10 +229,11 @@ async function timeoutFailure( params: Parameters[0]; statePaths: DaemonPaths; liveness: DaemonProbeVerdict | undefined; + remoteProof: RemoteTimeoutProof; recovery: TimeoutRecovery; }>, ): Promise { - const { params: request, statePaths, liveness, recovery } = params; + const { params: request, statePaths, liveness, remoteProof, recovery } = params; const { timeoutMs, requestId, requestSent } = request; const { retirement } = recovery; if (liveness?.denial) { @@ -180,8 +255,14 @@ async function timeoutFailure( requestId, reason: DAEMON_TRANSPORT_REASONS.timeout.reason, daemonRequestSent: requestSent, + ...(remoteProof.responseStarted !== undefined + ? { remoteResponseStarted: remoteProof.responseStarted } + : {}), + ...(remoteProof.healthAnswered !== undefined + ? { remoteHealthAnswered: remoteProof.healthAnswered } + : {}), ...(retirement ? { retirement, stateDir: statePaths.baseDir } : {}), - hint: resolveTimeoutHint({ request, recovery, stateDir: statePaths.baseDir }), + hint: resolveTimeoutHint({ request, remoteProof, recovery, stateDir: statePaths.baseDir }), }); } @@ -192,17 +273,20 @@ async function timeoutFailure( function resolveTimeoutHint( params: Readonly<{ request: Parameters[0]; + remoteProof: RemoteTimeoutProof; recovery: TimeoutRecovery; stateDir: string; }>, ): string { - const { request, recovery, stateDir } = params; + const { request, remoteProof, recovery, stateDir } = params; const { retirement } = recovery; if (retirement?.status === 'retained') { return `The daemon could not be safely retired. State was retained at ${stateDir}. ${retirement.error?.hint ?? 'Read the request log and daemon.log in that directory before you retry.'}`; } return resolveRequestTimeoutHint({ remote: request.remote, + remoteResponseStarted: remoteProof.responseStarted, + remoteHealthAnswered: remoteProof.healthAnswered, resetDaemon: retirement?.status === 'retired', stopCommand: recovery.stopCommand, command: request.command, @@ -251,6 +335,9 @@ function isAffirmativelyApplePlatform(platform: PlatformSelector | undefined): b return platform !== undefined && AFFIRMATIVE_APPLE_PLATFORM_SELECTORS.has(platform); } +/** The step that runs Apple runner startup under `prepare`'s own envelope. */ +const PREPARE_RUNNER_STEP = 'run agent-device prepare ios-runner with the same --platform'; + // Exported for direct hint-matrix testing: handleRequestTimeout also runs the real liveness probe // and process-kill side effects, so its wording is verified through this pure sub-function // (see also the production-seam route tests in @@ -259,6 +346,10 @@ function isAffirmativelyApplePlatform(platform: PlatformSelector | undefined): b // cannot reach). export function resolveRequestTimeoutHint(params: { remote: boolean; + /** Whether a remote daemon had already opened a 2xx progress stream before the timeout. */ + remoteResponseStarted?: boolean; + /** Whether a remote daemon answered `/health` after the timeout. */ + remoteHealthAnswered?: boolean; resetDaemon: boolean; /** Set when the daemon answered nothing and this caller is not allowed to retire it. */ stopCommand?: string; @@ -269,8 +360,17 @@ export function resolveRequestTimeoutHint(params: { action?: string; session?: string; }): string { - const { remote, resetDaemon, stopCommand, command, applePlatformDeclared, session, action } = - params; + const { + remote, + remoteResponseStarted, + remoteHealthAnswered, + resetDaemon, + stopCommand, + command, + applePlatformDeclared, + session, + action, + } = params; // A daemon that survives this client window may still be exporting a `record stop` that ran out // of time — a stop still queued for the device lock is dropped before any export starts, hence // "may" — and a finished file stays retrievable by asking again. This holds whether the daemon @@ -282,7 +382,12 @@ export function resolveRequestTimeoutHint(params: { } again to wait for that export and receive the completed recording.`; } if (remote) { - return 'Verify the remote daemon URL, auth token, and remote host logs.'; + return resolveRemoteTimeoutHint({ + command, + applePlatformDeclared, + remoteResponseStarted, + remoteHealthAnswered, + }); } if (resetDaemon) { // The reset SIGKILLs the daemon pid only; child processes it owned (Apple runners included) @@ -294,7 +399,7 @@ export function resolveRequestTimeoutHint(params: { } const iosPrepareHint = applePlatformDeclared && command === PUBLIC_COMMANDS.snapshot - ? ' If this was the first Apple-platform snapshot on the device, run agent-device prepare ios-runner with the same --platform before snapshot/test so runner startup is handled explicitly.' + ? ` If this was the first Apple-platform snapshot on the device, ${PREPARE_RUNNER_STEP} before snapshot/test so runner startup is handled explicitly.` : ''; // The daemon canceled the request when this client's connection was destroyed, and stayed // reachable (the probe answered, or the command's policy forbids the reset), so the session @@ -304,6 +409,48 @@ export function resolveRequestTimeoutHint(params: { } request was canceled; the daemon was kept alive so the session can still be closed or inspected. Read the request log for the timed-out step.${iosPrepareHint}`; } +function resolveRemoteTimeoutHint( + params: Readonly<{ + command: string | undefined; + applePlatformDeclared: boolean; + remoteResponseStarted?: boolean; + remoteHealthAnswered?: boolean; + }>, +): string { + const { command, applePlatformDeclared, remoteResponseStarted, remoteHealthAnswered } = params; + if (remoteResponseStarted) { + return resolveReachableRemoteTimeoutHint(command, applePlatformDeclared, 'response-started'); + } + if (remoteHealthAnswered) { + return resolveReachableRemoteTimeoutHint(command, applePlatformDeclared, 'health'); + } + return 'Verify the remote daemon URL, auth token, and remote host logs.'; +} + +// The daemon cancels a request whose connection closed (directly and through agent-device-proxy, +// #5058), so a timed-out `open` leaves nothing that a retry could race. The CLI prints the +// observe-first step before this hint, since the open may have launched the app, so the retry is +// stated as safe whatever that check shows. A first Apple open can spend the default envelope +// building and starting the XCTest runner (#5004); `prepare` runs that startup under its own +// longer envelope. +function resolveReachableRemoteTimeoutHint( + command: string | undefined, + applePlatformDeclared: boolean, + proof: 'response-started' | 'health', +): string { + const reachable = + proof === 'response-started' + ? 'The remote daemon already started answering this request, so its URL and auth token are not the cause.' + : 'The remote daemon still answers /health, so its URL and auth token are not the cause.'; + if (command !== PUBLIC_COMMANDS.open) { + return `${reachable} Read the remote host logs for the timed-out ${command ?? 'request'} step.`; + } + const retry = + 'The daemon canceled this open, so running it again is safe even if the app launched.'; + if (!applePlatformDeclared) return `${reachable} ${retry}`; + return `${reachable} A first Apple open can outlast the request window while the host builds and starts the XCTest runner. ${retry} For a longer startup window, ${PREPARE_RUNNER_STEP} first.`; +} + function daemonWasForceKilled(retirement: DaemonRetirementResult | undefined): boolean { if (!retirement || retirement.status === 'absent') return false; const termination = retirement.termination; diff --git a/packages/daemon-client/src/daemon-client-transport-reasons.ts b/packages/daemon-client/src/daemon-client-transport-reasons.ts index 40415aeb88..e83a128723 100644 --- a/packages/daemon-client/src/daemon-client-transport-reasons.ts +++ b/packages/daemon-client/src/daemon-client-transport-reasons.ts @@ -8,6 +8,8 @@ export const DAEMON_TRANSPORT_REASONS = { // The connection to the daemon broke; `details.daemonRequestSent` says whether the request was written. failure: { reason: 'daemon_transport_failure' }, // The daemon did not answer within the request's budget; `details.timeoutMs` is that budget. + // For a sent remote request, `details.remoteResponseStarted` says whether a progress stream had + // already begun, and `details.remoteHealthAnswered` says whether `/health` answered when it had not. timeout: { reason: 'daemon_transport_timeout' }, // A message the daemon sent is not a daemon response envelope; `details.line`, when present, // carries what arrived. diff --git a/packages/daemon-client/src/daemon-client-transport.ts b/packages/daemon-client/src/daemon-client-transport.ts index 1d1483e725..397cea0767 100644 --- a/packages/daemon-client/src/daemon-client-transport.ts +++ b/packages/daemon-client/src/daemon-client-transport.ts @@ -439,9 +439,17 @@ async function recoverFromTimeout( return await handleRequestTimeout({ info, statePaths, + remote: isRemoteDaemon(info), retireUnresponsive: options.timeoutRecovery !== 'none', + timeoutMs: expiredBudget, + requestId: req.meta?.requestId, + command: req.command, + platform: req.flags?.platform, + session: req.session, + action: req.positionals?.[0], requestSent: error.details.daemonRequestSent !== false, - ...timeoutRequestContext(req, isRemoteDaemon(info), expiredBudget), + responseStarted: error.details.remoteResponseStarted === true, + readRemoteHealth: (budgetMs) => readDaemonHttpHealth(info, budgetMs, options.signal), }); } @@ -772,38 +780,17 @@ function requestTimeoutError( timeoutMs: number, requestId: string | undefined, daemonRequestSent: boolean, + remoteResponseStarted?: boolean, ): AppError { return new AppError('COMMAND_FAILED', 'Daemon request timed out', { reason: DAEMON_TRANSPORT_REASONS.timeout.reason, timeoutMs, requestId, daemonRequestSent, + ...(remoteResponseStarted ? { remoteResponseStarted: true } : {}), }); } -// The fields a timed-out request is described by, read once so a socket and an HTTP timeout cannot -// describe the same request differently. -type TimeoutRequestFields = Omit< - Parameters[0], - 'info' | 'statePaths' | 'retireUnresponsive' | 'requestSent' ->; - -function timeoutRequestContext( - req: DaemonWireRequest, - remote: boolean, - timeoutMs: number, -): TimeoutRequestFields { - return { - remote, - timeoutMs, - requestId: req.meta?.requestId, - command: req.command, - platform: req.flags?.platform, - session: req.session, - action: req.positionals?.[0], - }; -} - function buildRemoteInstancePreconditionHeaders(info: DaemonInfo): Record { return { ...(info.remoteInstanceId ? { [DAEMON_HTTP_INSTANCE_HEADER]: info.remoteInstanceId } : {}), @@ -848,6 +835,8 @@ async function sendHttpRequest( let settled = false; // Set when the request was handed to the OS (`finish`), never for a connection that failed first. let requestSent = false; + // Set when a 2xx progress stream opened on `/rpc`, proving the remote URL and auth token. + let responseStarted = false; const detachCallerAbort = (): void => { if (callerSignal) callerSignal.removeEventListener('abort', onCallerAbort); }; @@ -895,6 +884,9 @@ async function sendHttpRequest( return; } if (shouldReadDaemonProgressStream(req, res.headers?.['content-type'])) { + if (res.statusCode !== undefined && res.statusCode >= 200 && res.statusCode < 300) { + responseStarted = true; + } readDaemonHttpProgressResponse(res, { req, onProgress: options.onProgress, @@ -933,7 +925,9 @@ async function sendHttpRequest( const timeoutHandle = typeof timeoutMs === 'number' ? setTimeout(() => { - rejectOnce(requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent)); + rejectOnce( + requestTimeoutError(timeoutMs, req.meta?.requestId, requestSent, responseStarted), + ); request.destroy(); }, timeoutMs) : undefined; diff --git a/website/docs/docs/error-reasons.md b/website/docs/docs/error-reasons.md index ffb9930286..8bf47bdb18 100644 --- a/website/docs/docs/error-reasons.md +++ b/website/docs/docs/error-reasons.md @@ -641,7 +641,7 @@ These reasons can come from more than one command. | --- | --- | | `daemon_endpoint_unavailable` | The daemon's socket or HTTP endpoint is unreachable; `details.transport` names the one tried. | | `daemon_transport_failure` | The connection to the daemon broke; `details.daemonRequestSent` says whether the request was written. | -| `daemon_transport_timeout` | The daemon did not answer within the request's budget; `details.timeoutMs` is that budget. | +| `daemon_transport_timeout` | The daemon did not answer within the request's budget; `details.timeoutMs` is that budget. For a sent remote request, `details.remoteResponseStarted` says whether a progress stream had already begun, and `details.remoteHealthAnswered` says whether `/health` answered when it had not. | | `daemon_response_invalid` | A message the daemon sent is not a daemon response envelope; `details.line`, when present, carries what arrived. | | `daemon_response_read_failure` | The response body could not be read before the connection ended. | | `daemon_request_too_large` | The serialized request passes `DAEMON_REQUEST_MAX_BYTES`, so it was refused before being sent. |