Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix(ai): stop undici's 300s ceiling from preempting a run's stall bound
Adam Eivyd82320e8eb50
diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex be3dd99577..0494ff679a 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -37,6 +37,8 @@ Inheritance mirrors `withGatewayApiKey`: a gateway-backed wrapper with no policy- **Stall bound** = `timeout || provider.timeout || DEFAULT_API_RUN_TIMEOUT_MS`, re-armed by every `reader.read()` that yields bytes. It is the hang detector, and it cuts a silent provider off at exactly the moment the single timer did — reinterpreting the field this way costs no protection, because catching a hung provider is the only job that timer ever actually did.- **Absolute cap** = `Math.max(DEFAULT_API_RUN_MAX_RUNTIME_MS, stallBound)`, never extended, so a provider trickling one byte per minute still cannot hold its `activeRuns` slot forever. The `Math.max` is load-bearing: an install that deliberately raised `provider.timeout` past the default cap must keep running as long as it asked to, never be clamped DOWN by a ceiling it never configured.+**A THIRD ceiling lives under both of them, and it is not PortOS's.** undici — the client behind Node's built-in `fetch` — arms its own `headersTimeout` and `bodyTimeout` on every request, both defaulting to 300000ms: the same number as `DEFAULT_API_RUN_TIMEOUT_MS`, one layer closer to the socket. The transport sees a byte before the read loop does, so its timer re-armed fractionally earlier and fired fractionally first, and it won every race the two bounds above were meant to decide. A provider that opened the stream and went quiet finalized as `network-error` ("Check network connectivity and provider endpoint URL") with no `timeoutBound` stamped — so the bench decision never saw the stall it exists to catch — and a `provider.timeout` raised past five minutes was silently capped at undici's. An NVIDIA NIM nemotron persistent-mind run died that way at 419.9s with `terminated: UND_ERR_INFO: HTTP/2: "stream timeout after 300000"`. The streaming fetch now carries the dispatcher from `internal/streamTransport.js`, which disables both (`0` = no timer) and leaves the run's declared bounds authoritative. That module is also where the **undici-major split** is decided: Node 26 bundles undici 8 and takes the bare Agent, Node 22/24/25 bundle undici 6/7 and need `Dispatcher1Wrapper` (a bare undici-8 dispatcher is rejected there with `UND_ERR_INVALID_ARG`). The split is not cosmetic — the wrapper forces `allowH2: false`, and HTTP/1.1 has no `GOAWAY`, the one frame `internal/preHeaderRetry.js` may replay against a billable provider. Each runtime keeps exactly the wire protocol its own fetch already negotiated; only the timeouts change.+Only the STREAMING path reads the field this way. `aiProvider.js`, `askService.js` and `services/runner.js` are non-streaming and keep reading it as a wall clock, which is correct there — no persisted field changed shape, so no migration and no schema parity work is owed.Both numbers and the `Math.max` live in `internal/runTimeouts.js`, a leaf module with no imports, because **a host that wraps `executeApiRun` in its own backstop timer must arm it against the ABSOLUTE bound** — which `apiRunAbsoluteTimeoutMs(stallBound)` exists to answer, and which a host reached by hundreds of suites must be able to import without dragging `runner.js`'s `fs`/`child_process` closure (server/AGENTS.md → Import scoping). `promptRunner.js` armed its backstop at `provider.timeout + 2s` and so killed every healthy streaming run at the old ceiling, making the 30-minute cap unreachable and reinstating precisely what #7560 removed. Worse, that backstop kills via `stopRun`, so the run finalized as a USER CANCEL: `onRunFailed` never fired (no bench, no investigation task) and `isRunCanceledError` callers skipped the fallback cascade — a productive run silently produced nothing. Sixteen NVIDIA NIM nemotron persistent-mind runs died that way at exactly 302s in the two days after #7560 merged, and none before (#7665). Derive the number from the exported helper rather than restating the `Math.max`, so the two cannot drift apart again.diff --git a/server/lib/aiToolkit/internal/streamTransport.js b/server/lib/aiToolkit/internal/streamTransport.jsnew file mode 100644index 0000000000..982cf2815c--- /dev/null+++ b/server/lib/aiToolkit/internal/streamTransport.js@@ -0,0 +1,90 @@+/**+ * The dispatcher a STREAMING provider run fetches through.+ *+ * undici — the HTTP client behind Node's built-in `fetch` — arms its OWN+ * no-progress ceilings on every request: `headersTimeout` and `bodyTimeout`,+ * both 300000ms by default. A streaming API run therefore carried a THIRD+ * bound nobody declared, exactly equal to `DEFAULT_API_RUN_TIMEOUT_MS`, and+ * armed one layer below the two in `runTimeouts.js` — the transport sees a byte+ * before the read loop does, so undici's timer re-arms fractionally earlier and+ * fires fractionally first. It won every race:+ *+ * - A provider that opened the stream and went quiet finalized as+ * `network-error` ("Check network connectivity and provider endpoint URL")+ * instead of the stall TIMEOUT it is, so `metadata.timeoutBound` — the+ * field that tells a quiet provider (bench candidate) from a slow but+ * productive one — was never stamped, and the run escalated as a+ * connectivity fault. An NVIDIA NIM `nemotron` persistent-mind run died+ * that way at 419.9s with `terminated: UND_ERR_INFO: HTTP/2: "stream+ * timeout after 300000"`.+ * - `provider.timeout` above 300000 was silently capped: an install that+ * deliberately widened the stall bound for a slow reasoning model still+ * lost the stream at undici's five minutes.+ *+ * `executeApiRun` arms both of its own bounds around this fetch and aborts the+ * controller the request carries, so the transport ceilings are pure+ * duplication — disabled here (`0` = no timer, in undici's h1 parser and its h2+ * stream alike) and the run's declared bounds are authoritative again.+ * `connectTimeout` is untouched: it bounds the pre-request dial, which no run+ * timer covers.+ *+ * ## Why the dispatcher is sometimes wrapped+ *+ * Node's built-in `fetch` drives a dispatcher with whichever request-handler+ * contract the undici version BUNDLED IN THAT NODE speaks, and we hand it an+ * Agent from the undici in `node_modules`:+ *+ * - Node 26+ bundles undici 8, the same contract — hand it the bare Agent.+ * - Node 22/24/25 bundle undici 6/7, whose handler shape undici 8 dropped; a+ * bare undici-8 Agent is rejected there with `UND_ERR_INVALID_ARG`+ * ("invalid onRequestStart method") and the request never leaves.+ * `Dispatcher1Wrapper` is undici's adapter for exactly that.+ *+ * The wrapper is not free, which is why it is not simply used everywhere: it+ * forces `allowH2: false` ("Legacy (v1) consumers do not support HTTP/2"), and+ * forcing HTTP/1.1 would cost the run its `GOAWAY` frames — the one transport+ * failure `preHeaderRetry.js` may replay against a billable provider, because+ * only HTTP/2 §6.8 guarantees the request was never processed. NVIDIA NIM+ * recycles idle pooled connections on its own schedule, so that replay is load+ * bearing.+ *+ * Splitting on the bundled major keeps the wire protocol exactly as each+ * runtime already chose it: Node ≤25's built-in fetch offers only `http/1.1`+ * over ALPN and gets HTTP/1.1 through the wrapper; Node 26's offers `h2` and+ * gets HTTP/2 through the bare Agent. Only the timeouts change.+ */++import { Agent, Dispatcher1Wrapper } from 'undici';++// Both of undici's per-request no-progress ceilings, disabled. `0` is undici's+// documented "no timer" (`if (delay)` guards the h1 parser's timer, and the h2+// stream arms none when both are falsy) — not "expire immediately".+export const STREAM_TRANSPORT_TIMEOUTS = { headersTimeout: 0, bodyTimeout: 0 };++/**+ * Does this runtime's built-in fetch speak undici's pre-8 handler contract?+ * An unreadable version reads as "yes": the wrapper is accepted by BOTH+ * contracts, so an unknown runtime degrades to HTTP/1.1 rather than to a+ * dispatcher the runtime refuses.+ */+export function needsDispatcher1Wrapper(undiciVersion) {+ const major = Number(String(undiciVersion || '').split('.')[0]);+ return !(major >= 8);+}++let cached = null;++/**+ * The shared dispatcher for provider streaming requests. One Agent for the+ * process, so connection pooling and keep-alive behave as they did under the+ * runtime's global dispatcher.+ */+export function streamTransportDispatcher() {+ if (!cached) {+ // Spread: undici keeps the options object, and the exported constant is+ // read by the tests — never hand the same reference to both.+ const agent = new Agent({ ...STREAM_TRANSPORT_TIMEOUTS });+ cached = needsDispatcher1Wrapper(process.versions.undici) ? new Dispatcher1Wrapper(agent) : agent;+ }+ return cached;+}diff --git a/server/lib/aiToolkit/internal/streamTransport.test.js b/server/lib/aiToolkit/internal/streamTransport.test.jsnew file mode 100644index 0000000000..ae2420b713--- /dev/null+++ b/server/lib/aiToolkit/internal/streamTransport.test.js@@ -0,0 +1,76 @@+import { describe, it, expect, afterAll } from 'vitest';+import { createServer } from 'node:http';+import { Agent, Dispatcher1Wrapper } from 'undici';++import { STREAM_TRANSPORT_TIMEOUTS, needsDispatcher1Wrapper, streamTransportDispatcher } from './streamTransport.js';++// Longer than the control dispatcher's body ceiling below (undici rounds a+// short body timeout up to its ~500ms fast-timer tick, so the gap is wide+// enough that the control fails deterministically), short enough to keep the+// suite quick.+const QUIET_MS = 1500;+const CONTROL_BODY_TIMEOUT_MS = 100;++// A provider that opens the stream, sends one frame, then goes quiet before+// finishing: the exact shape that made undici's transport ceiling — not the+// run's own stall bound — end an NVIDIA NIM streaming run.+const server = createServer((_req, res) => {+ res.writeHead(200, { 'content-type': 'text/event-stream' });+ res.write('data: first\n\n');+ const quiet = setTimeout(() => res.end('data: [DONE]\n\n'), QUIET_MS);+ res.on('close', () => clearTimeout(quiet));+});+await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));+const url = `http://127.0.0.1:${server.address().port}/`;++// The dispatcher is a process-wide keep-alive pool; close it so its idle+// sockets can't hold the runner open past this file.+afterAll(async () => {+ await streamTransportDispatcher().close();+ server.close();+});++// Same wrapping rule as the module under test, so the control differs from it+// in the timeouts ALONE — including on a runtime whose built-in fetch refuses+// an unwrapped undici-8 dispatcher.+const controlDispatcher = () => {+ const agent = new Agent({ headersTimeout: 0, bodyTimeout: CONTROL_BODY_TIMEOUT_MS });+ return needsDispatcher1Wrapper(process.versions.undici) ? new Dispatcher1Wrapper(agent) : agent;+};++const readAll = (dispatcher) => fetch(url, { dispatcher }).then((res) => res.text());++describe('streaming transport dispatcher', () => {+ it('lets a stream go quiet past a ceiling that would otherwise cut it', async () => {+ const control = controlDispatcher();+ // The ceiling is real and this plumbing reaches it: with a body timeout+ // configured, the quiet window kills the request.+ await expect(readAll(control)).rejects.toThrow();+ await control.close();++ // With `0` (undici's "no timer", not "expire immediately") the same quiet+ // window is survived, leaving `executeApiRun`'s stall and absolute bounds+ // as the only ceilings on the run — so a provider that goes silent is+ // classified as the stall TIMEOUT it is (with `timeoutBound` stamped for+ // the bench decision) instead of a `network-error`, and a `provider.timeout`+ // raised past undici's default 300s is no longer silently capped.+ await expect(readAll(streamTransportDispatcher())).resolves.toContain('[DONE]');+ });++ it('wraps the dispatcher only for runtimes bundling undici < 8', () => {+ // Node 22/24/25 bundle undici 6/7, whose handler contract undici 8 dropped:+ // a bare undici-8 Agent is rejected there (`UND_ERR_INVALID_ARG`).+ expect(needsDispatcher1Wrapper('6.22.0')).toBe(true);+ expect(needsDispatcher1Wrapper('7.24.4')).toBe(true);+ // Node 26+ bundles undici 8 and its built-in fetch negotiates HTTP/2. The+ // wrapper forces `allowH2: false`, which would cost the run the GOAWAY+ // frames `preHeaderRetry.js` replays against a billable provider.+ expect(needsDispatcher1Wrapper('8.0.2')).toBe(false);+ // Unreadable version → the wrapper, which BOTH contracts accept.+ expect(needsDispatcher1Wrapper(undefined)).toBe(true);+ });++ it('disables both of undici\'s per-request no-progress ceilings', () => {+ expect(STREAM_TRANSPORT_TIMEOUTS).toEqual({ headersTimeout: 0, bodyTimeout: 0 });+ });+});diff --git a/server/lib/aiToolkit/runner.js b/server/lib/aiToolkit/runner.jsindex c143ea2456..471b170e68 100644--- a/server/lib/aiToolkit/runner.js+++ b/server/lib/aiToolkit/runner.js@@ -12,6 +12,10 @@ import { describeTransportError, fetchWithPreHeaderRetry, isReplaySafeLocalReque// a leaf module so a host's own backstop timer can read the absolute bound// without dragging this file's fs/child_process closure with it.import { DEFAULT_API_RUN_TIMEOUT_MS, apiRunAbsoluteTimeoutMs } from './internal/runTimeouts.js';+// undici arms its own 300s header/body ceilings under every fetch, which raced+// — and beat — the two above. The streaming request goes through a dispatcher+// with those disabled so the run's declared bounds are the only ones.+import { streamTransportDispatcher } from './internal/streamTransport.js';// npm-installed CLI providers (claude, codex, opencode, …) are .cmd/.bat// shims on Windows; Node's spawn() can't execute those without going through@@ -834,6 +838,10 @@ export function createRunnerService(config = {}) {method: 'POST',headers,signal: controller.signal,+ // Hands the request undici's ceilings disabled, leaving `stallTimeout`+ // / `absoluteTimeout` above as the run's only bounds — see+ // ./internal/streamTransport.js for what fired first without it.+ dispatcher: streamTransportDispatcher(),body: JSON.stringify({model: model || provider.defaultModel,messages: [{ role: 'user', content: messageContent }],diff --git a/server/lib/aiToolkit/runner.test.js b/server/lib/aiToolkit/runner.test.jsindex e37c568677..6676587c88 100644--- a/server/lib/aiToolkit/runner.test.js+++ b/server/lib/aiToolkit/runner.test.js@@ -22,6 +22,7 @@ vi.mock('child_process', async (importOriginal) => {const { spawn } = await import('child_process');const { createRunnerService } = await import('./runner.js');+const { streamTransportDispatcher } = await import('./internal/streamTransport.js');describe('AI Toolkit runner service', () => {const tempDirs = [];@@ -639,6 +640,46 @@ describe('AI Toolkit runner service', () => {expect(metadata.error).toMatch(/no stream progress/i);});+ // Those two bounds are only authoritative if nothing UNDERNEATH them expires+ // first. undici arms its own `headersTimeout`/`bodyTimeout` on every fetch —+ // both 300000ms, the same number as the default stall bound — one layer+ // closer to the socket, so it won every race: a provider that went quiet+ // finalized as `network-error` with no `timeoutBound` stamped for the bench+ // decision, and a `provider.timeout` raised past five minutes was silently+ // capped. The streaming request has to go out on the dispatcher that+ // disables them (./internal/streamTransport.js).+ it('sends the streaming request through the ceiling-free transport dispatcher', async () => {+ const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));+ tempDirs.push(dataDir);++ const fetch = vi.fn(async () => ({+ ok: true,+ body: { getReader: () => ({ read: async () => ({ done: true }), cancel: async () => {} }) }+ }));+ vi.stubGlobal('fetch', fetch);++ const runner = createRunnerService({+ dataDir,+ hooks: { ensureProviderReady: async () => ({ success: true }) }+ });++ let done;+ const completed = new Promise((resolve) => { done = resolve; });+ await runner.executeApiRun({+ runId: 'run-dispatcher',+ provider: runReady(),+ model: null,+ prompt: 'hi',+ workspacePath: process.cwd(),+ screenshots: [],+ onData: undefined,+ onComplete: (m) => done(m)+ });+ await completed;++ expect(fetch.mock.calls[0][1].dispatcher).toBe(streamTransportDispatcher());+ });+it('bounds a run whose provider-readiness hook never resolves (fetch never reached)', async () => {const dataDir = await mkdtemp(join(tmpdir(), 'ai-toolkit-runner-'));tempDirs.push(dataDir);