|
| 1 | +import fs from 'node:fs'; |
| 2 | +import { afterEach, expect, test, vi } from 'vitest'; |
| 3 | +import { resolveDaemonPaths } from '@agent-device/daemon-contracts/daemon-resolution'; |
| 4 | +import { mkdtempForTestSync } from '@agent-device/test-kit/tmp-dir'; |
| 5 | + |
| 6 | +// The HTTP server hands a `/rpc` flow rejection it answered itself to `onUnownedRequestFailure`, |
| 7 | +// because that event has no request scope to be recorded in — the request's own scope opens later, |
| 8 | +// inside the handler. The runtime owns the pair every other out-of-request daemon event uses, so |
| 9 | +// this boots the real runtime and checks both halves of what `openDaemonServers` wires: the |
| 10 | +// injected error stream and the daemon log. The daemon's own HTTP route drives it, so a flow that |
| 11 | +// stops answering shows up as a refused call rather than a hung one. |
| 12 | +const requestProbe = vi.hoisted(() => ({ |
| 13 | + failNextDispatch: false, |
| 14 | +})); |
| 15 | + |
| 16 | +vi.mock('../../../daemon/request-router.ts', async (importOriginal) => { |
| 17 | + const actual = await importOriginal<typeof import('../../../daemon/request-router.ts')>(); |
| 18 | + return { |
| 19 | + ...actual, |
| 20 | + createRequestHandler: (...args: Parameters<typeof actual.createRequestHandler>) => { |
| 21 | + const dispatch = actual.createRequestHandler(...args); |
| 22 | + return async (request: Parameters<typeof dispatch>[0]) => { |
| 23 | + if (requestProbe.failNextDispatch) { |
| 24 | + requestProbe.failNextDispatch = false; |
| 25 | + throw unwrappableReason(); |
| 26 | + } |
| 27 | + return await dispatch(request); |
| 28 | + }; |
| 29 | + }, |
| 30 | + }; |
| 31 | +}); |
| 32 | + |
| 33 | +vi.mock('../../../provider-device-runtimes.ts', () => ({ |
| 34 | + DEFAULT_PROVIDER_RUNTIME_REQUIRED_IDS: [], |
| 35 | + createDaemonProviderRuntimeComposition: async () => ({ runtimes: [], platformModules: [] }), |
| 36 | +})); |
| 37 | + |
| 38 | +import { startDaemonRuntimeFixture } from '../daemon-runtime-fixture.ts'; |
| 39 | + |
| 40 | +afterEach(() => { |
| 41 | + requestProbe.failNextDispatch = false; |
| 42 | +}); |
| 43 | + |
| 44 | +test('a /rpc flow failure the server refused itself reaches the runtime stderr and daemon log', async () => { |
| 45 | + const stateDir = mkdtempForTestSync('agent-device-daemon-rpc-flow-failure-'); |
| 46 | + const paths = resolveDaemonPaths(stateDir); |
| 47 | + const stderrLines: string[] = []; |
| 48 | + // Records the reason without inspecting it: this one throws on the property read an assertion |
| 49 | + // would perform. |
| 50 | + const rejections: unknown[] = []; |
| 51 | + const observeRejection = (reason: unknown) => { |
| 52 | + rejections.push(reason); |
| 53 | + }; |
| 54 | + process.on('unhandledRejection', observeRejection); |
| 55 | + let exitCode: number | undefined; |
| 56 | + try { |
| 57 | + const runtime = await startDaemonRuntimeFixture({ |
| 58 | + env: { |
| 59 | + ...process.env, |
| 60 | + AGENT_DEVICE_STATE_DIR: stateDir, |
| 61 | + AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS: '0', |
| 62 | + AGENT_DEVICE_DAEMON_SERVER_MODE: 'http', |
| 63 | + }, |
| 64 | + exit: (code) => { |
| 65 | + exitCode = code; |
| 66 | + }, |
| 67 | + registerProcessHandlers: false, |
| 68 | + stderr: { write: (chunk: string) => void stderrLines.push(chunk) }, |
| 69 | + stdout: { write: () => {} }, |
| 70 | + }); |
| 71 | + expect(runtime).not.toBeNull(); |
| 72 | + const { httpPort, token } = JSON.parse(fs.readFileSync(paths.infoPath, 'utf8')) as { |
| 73 | + httpPort: number; |
| 74 | + token: string; |
| 75 | + }; |
| 76 | + |
| 77 | + requestProbe.failNextDispatch = true; |
| 78 | + const refused = await postRpc(httpPort, token, { |
| 79 | + jsonrpc: '2.0', |
| 80 | + id: 'req-flow-failure', |
| 81 | + method: 'agent_device.command', |
| 82 | + params: { command: 'session_list', meta: { requestId: 'req-flow-failure' } }, |
| 83 | + }); |
| 84 | + expect(refused.status).toBe(500); |
| 85 | + expect(refused.body.id).toBeNull(); |
| 86 | + expect(refused.body.error?.code).toBe(-32000); |
| 87 | + |
| 88 | + // The refusal is answered synchronously while its record is written by the detached report the |
| 89 | + // server was handed, so the log line follows the answer by a turn. |
| 90 | + const events = await waitForDaemonLogEvent(paths.logPath, 'daemon_rpc_request_flow_failed'); |
| 91 | + expect(events).toHaveLength(1); |
| 92 | + expect(events[0]?.data).toEqual({ code: 'UNKNOWN', message: 'Unknown error' }); |
| 93 | + // The runtime's injected stream and not the process's: this is the channel the |
| 94 | + // `unhandledRejection` handler uses, and a daemon-level event belongs on that one. |
| 95 | + expect(stderrLines.filter((line) => line.startsWith('Daemon error:'))).toEqual([ |
| 96 | + 'Daemon error: Unknown error\n', |
| 97 | + ]); |
| 98 | + |
| 99 | + const next = await postRpc(httpPort, token, 'null'); |
| 100 | + expect(next.status).toBe(400); |
| 101 | + expect(next.body.error?.code).toBe(-32600); |
| 102 | + expect(rejections).toEqual([]); |
| 103 | + expect(exitCode).toBeUndefined(); |
| 104 | + } finally { |
| 105 | + process.off('unhandledRejection', observeRejection); |
| 106 | + await fs.promises.rm(stateDir, { recursive: true, force: true }); |
| 107 | + } |
| 108 | +}); |
| 109 | + |
| 110 | +async function postRpc( |
| 111 | + httpPort: number, |
| 112 | + token: string, |
| 113 | + body: unknown, |
| 114 | +): Promise<{ status: number; body: { id?: unknown; error?: { code?: number } } }> { |
| 115 | + const response = await fetch(`http://127.0.0.1:${httpPort}/rpc`, { |
| 116 | + method: 'POST', |
| 117 | + headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, |
| 118 | + body: typeof body === 'string' ? body : JSON.stringify(body), |
| 119 | + }); |
| 120 | + return { status: response.status, body: (await response.json()) as never }; |
| 121 | +} |
| 122 | + |
| 123 | +async function waitForDaemonLogEvent( |
| 124 | + logPath: string, |
| 125 | + phase: string, |
| 126 | +): Promise<Array<{ phase: string; data?: Record<string, unknown> }>> { |
| 127 | + const deadline = Date.now() + 2_000; |
| 128 | + for (;;) { |
| 129 | + const events = readDaemonLogEvents(logPath); |
| 130 | + if (events.some((event) => event.phase === phase) || Date.now() >= deadline) return events; |
| 131 | + await new Promise((resolve) => setTimeout(resolve, 10)); |
| 132 | + } |
| 133 | +} |
| 134 | + |
| 135 | +function readDaemonLogEvents( |
| 136 | + logPath: string, |
| 137 | +): Array<{ phase: string; data?: Record<string, unknown> }> { |
| 138 | + if (!fs.existsSync(logPath)) return []; |
| 139 | + return fs |
| 140 | + .readFileSync(logPath, 'utf8') |
| 141 | + .trim() |
| 142 | + .split('\n') |
| 143 | + .filter(Boolean) |
| 144 | + .map((line) => JSON.parse(line) as { phase: string; data?: Record<string, unknown> }); |
| 145 | +} |
| 146 | + |
| 147 | +/** |
| 148 | + * A rejection reason that cannot be inspected: the one property `normalizeError` must read to |
| 149 | + * redact its diagnostics throws the reason itself, so the flow's own catches fail while computing |
| 150 | + * their answer and the failure reaches the runtime's sink unreadable — the shape a daemon-level |
| 151 | + * record has to survive. It stays printable, so a run without the guard reports the escaped |
| 152 | + * rejection instead of failing to format it. |
| 153 | + */ |
| 154 | +function unwrappableReason(): Record<string, unknown> { |
| 155 | + const hostile: Record<string, unknown> = {}; |
| 156 | + Object.defineProperty(hostile, 'details', { |
| 157 | + enumerable: true, |
| 158 | + get(): never { |
| 159 | + throw hostile; |
| 160 | + }, |
| 161 | + }); |
| 162 | + return hostile; |
| 163 | +} |
0 commit comments