Skip to content

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

fix: bound fetchWithTimeout through the response body, not just the headers (#7236)

[._.]/ Adam Eivy1f12badbc8ae
diff --git a/server/lib/fetchWithTimeout.js b/server/lib/fetchWithTimeout.js
index 187522fc2d..863d8d060e 100644
--- a/server/lib/fetchWithTimeout.js
+++ b/server/lib/fetchWithTimeout.js
@@ -2,6 +2,21 @@
* Fetch wrapper with AbortController timeout, and an opt-in retry for
* connection-level failures.
*
+ * `timeoutMs` bounds the WHOLE exchange — headers AND body. A server that
+ * answers `200 OK` and then stalls mid-body is the failure this helper exists
+ * to catch, so the abort timer stays armed past `fetch()` resolving and is
+ * cleared only once the body is fully read, cancelled, or the request rejects.
+ * Before that was true the argument was a lie at every call site: `fal.js`
+ * passed a constant literally named `FAL_DOWNLOAD_TIMEOUT_MS` that bounded only
+ * the headers, leaving the multi-MB download itself with no ceiling at all.
+ *
+ * `timeoutMs <= 0` still means "no deadline" (multi-GB Ollama pulls and the
+ * Hugging Face import rely on that — the stream is their lifecycle). A caller
+ * that genuinely holds a body open longer than its header budget, and bounds
+ * that body some other way, opts out with `{ bodyDeadline: false }` — Beeper's
+ * asset proxy is the one such caller, since its mirror applies its own
+ * per-chunk idle abort.
+ *
* The retry exists because undici reports a retired pooled connection (notably
* an HTTP/2 GOAWAY) as a request-level rejection, so a perfectly good request
* dies as a bare `TypeError: fetch failed`. The same request succeeds on a fresh
@@ -19,8 +34,11 @@
*
* @param {string} url
* @param {RequestInit} [options]
- * @param {number} [timeoutMs=15000] - Timeout in milliseconds
- * @param {object} [retry] - Opt-in retry policy; omit for the historical no-retry behavior
+ * @param {number} [timeoutMs=15000] - Deadline in milliseconds covering headers AND body
+ * @param {object} [retry] - PortOS-owned options bag (never forwarded to `fetch`);
+ * omit for the historical no-retry behavior
+ * @param {boolean} [retry.bodyDeadline=true] - Keep the deadline armed through body
+ * consumption; set false for a caller that bounds its own stream
* @param {number} [retry.retries=0] - Extra attempts after the first
* @param {number} [retry.retryDelayMs=250] - Pause between attempts, so the replay
* opens a new connection rather than racing the pool's teardown of the old one
@@ -29,11 +47,11 @@
* @returns {Promise<Response>}
*/
export function fetchWithTimeout(url, options = {}, timeoutMs = 15000, retry = {}) {
- const { retries = 0, retryDelayMs = 250, shouldRetry } = retry;
+ const { retries = 0, retryDelayMs = 250, shouldRetry, bodyDeadline = true } = retry;
// Each attempt re-enters fetchOnce, so a replay builds a FRESH
// AbortController and gets a full timeout budget rather than inheriting the
// exhausted one.
- return fetchOnce(url, options, timeoutMs).catch((err) => {
+ return fetchOnce(url, options, timeoutMs, bodyDeadline).catch((err) => {
if (retries < 1 || typeof shouldRetry !== 'function' || !shouldRetry(err)) throw err;
return waitForRetry(retryDelayMs, options.signal)
.then(() => fetchWithTimeout(url, options, timeoutMs, { ...retry, retries: retries - 1 }));
@@ -66,7 +84,7 @@ function waitForRetry(delayMs, signal) {
* One attempt: fetch with an AbortController timeout, honoring a caller signal.
* @returns {Promise<Response>}
*/
-async function fetchOnce(url, options = {}, timeoutMs = 15000) {
+async function fetchOnce(url, options = {}, timeoutMs = 15000, bodyDeadline = true) {
const controller = new AbortController();
const hasTimeout = Number.isFinite(timeoutMs) && timeoutMs > 0;
const timeoutId = hasTimeout ? setTimeout(() => controller.abort(), timeoutMs) : null;
@@ -86,13 +104,139 @@ async function fetchOnce(url, options = {}, timeoutMs = 15000) {
}
}
- try {
- const response = await fetch(url, { ...options, signal });
- return response;
- } finally {
+ // Idempotent, because the body wrapper can reach it from several directions
+ // (a reader method, the stream closing, a cancel) and the caller-signal
+ // listener must be removed exactly once.
+ let released = false;
+ const releaseDeadline = () => {
+ if (released) return;
+ released = true;
if (timeoutId !== null) clearTimeout(timeoutId);
if (options.signal && abortHandler) {
options.signal.removeEventListener('abort', abortHandler);
}
+ };
+
+ let response;
+ try {
+ response = await fetch(url, { ...options, signal });
+ } catch (err) {
+ releaseDeadline();
+ throw err;
+ }
+
+ // Nothing left to bound: no timer armed, the caller opted out, or the
+ // response has no body to wait on.
+ if (timeoutId === null || !bodyDeadline || !response || typeof response !== 'object' || isBodyless(response)) {
+ releaseDeadline();
+ return response;
}
+
+ // A body nobody ever reads would otherwise hold the event loop open for the
+ // rest of the budget; unref lets the process exit while the abort still fires
+ // on time if it is still running.
+ if (typeof timeoutId.unref === 'function') timeoutId.unref();
+ return withBodyDeadline(response, releaseDeadline);
+}
+
+// Response methods that consume the whole body, so the deadline is satisfied
+// the moment their promise settles.
+const BODY_CONSUMERS = ['json', 'text', 'arrayBuffer', 'blob', 'formData', 'bytes'];
+
+/**
+ * Is there anything left for the deadline to cover?
+ *
+ * A real `Response` with a null body genuinely has nothing left to read —
+ * 204/304, a HEAD, and `safeUrlFetch`'s manual-redirect hop — so it is released
+ * on the spot rather than leaving a timer armed against a body that will never
+ * arrive. A hand-rolled double exposes no `body` either but still resolves
+ * `text()`/`json()` later, and that read is precisely what has to stay bounded,
+ * so those keep the deadline. A double with neither is inert and passes
+ * through untouched, identity intact.
+ */
+function isBodyless(response) {
+ if (response.body != null) return false;
+ if (typeof Response !== 'undefined' && response instanceof Response) return true;
+ return !BODY_CONSUMERS.some((name) => typeof response[name] === 'function');
+}
+
+/**
+ * Wrap a `Response` so the abort deadline is released once its body is drained.
+ *
+ * A Proxy rather than a rebuilt Response: callers pass these straight to
+ * `Readable.fromWeb`, `instanceof` checks and their own error mappers, so the
+ * object has to stay the real thing. Getters are read with `target` as the
+ * receiver because `ok`/`status`/`headers` are branded accessors that throw on
+ * a foreign `this`.
+ */
+function withBodyDeadline(response, release) {
+ let wrappedBody;
+ return new Proxy(response, {
+ get(target, prop) {
+ if (prop === 'body') {
+ const raw = Reflect.get(target, prop, target);
+ // Not a web stream (a test double, or a runtime without one) — there is
+ // no close/cancel hook to hang the release on.
+ if (!raw || typeof raw.getReader !== 'function') return raw;
+ wrappedBody ||= watchStream(raw, release);
+ return wrappedBody;
+ }
+
+ const value = Reflect.get(target, prop, target);
+ if (typeof value !== 'function') return value;
+
+ if (BODY_CONSUMERS.includes(prop)) {
+ return (...args) => {
+ const result = Reflect.apply(value, target, args);
+ if (!result || typeof result.then !== 'function') {
+ release();
+ return result;
+ }
+ return result.then(
+ (resolved) => { release(); return resolved; },
+ (err) => { release(); throw err; },
+ );
+ };
+ }
+
+ // A clone shares one deadline: whichever copy is drained first satisfies it.
+ if (prop === 'clone') {
+ return (...args) => withBodyDeadline(Reflect.apply(value, target, args), release);
+ }
+
+ return value.bind(target);
+ },
+ });
+}
+
+/**
+ * Mirror a body stream, releasing the deadline when it ends, errors, or is
+ * cancelled. `highWaterMark: 0` is load-bearing: the default strategy would
+ * pull — and therefore LOCK the underlying body — the instant the wrapper is
+ * constructed, breaking the common `if (!res.body) … await res.json()` shape
+ * where `.body` is only touched as a truthiness check.
+ */
+function watchStream(stream, release) {
+ let reader = null;
+ return new ReadableStream({
+ async pull(controller) {
+ reader ||= stream.getReader();
+ try {
+ const { done, value } = await reader.read();
+ if (done) {
+ release();
+ controller.close();
+ return;
+ }
+ controller.enqueue(value);
+ } catch (err) {
+ release();
+ controller.error(err);
+ }
+ },
+ async cancel(reason) {
+ release();
+ await Promise.resolve(reader ? reader.cancel(reason) : stream.cancel(reason)).catch(() => {});
+ },
+ }, { highWaterMark: 0 });
}
diff --git a/server/lib/fetchWithTimeout.test.js b/server/lib/fetchWithTimeout.test.js
index 80afa5e6cf..d0e4a6f656 100644
--- a/server/lib/fetchWithTimeout.test.js
+++ b/server/lib/fetchWithTimeout.test.js
@@ -30,6 +30,7 @@ describe('fetchWithTimeout', () => {
await expect(promise).rejects.toThrow('aborted');
} finally {
+ vi.restoreAllMocks();
vi.useRealTimers();
}
});
@@ -58,6 +59,11 @@ describe('fetchWithTimeout', () => {
// pending this would cause an unhandled abort on a resolved promise.
vi.advanceTimersByTime(6000);
} finally {
+ // Restore spies BEFORE leaving fake-timer mode: a spy installed while the
+ // fakes were active captured the FAKE timer function as its "original",
+ // so restoring it afterwards would reinstall that fake globally and
+ // silently freeze every real-timer test that runs later in this file.
+ vi.restoreAllMocks();
vi.useRealTimers();
}
});
@@ -95,6 +101,8 @@ describe('fetchWithTimeout', () => {
// setTimeout should not have been called for the abort timer
expect(setTimeoutSpy).not.toHaveBeenCalled();
} finally {
+ // See the note above — restore spies while the fakes are still installed.
+ vi.restoreAllMocks();
vi.useRealTimers();
}
});
@@ -126,4 +134,112 @@ describe('fetchWithTimeout', () => {
}
}
});
+// --- Body deadline (#7236) -------------------------------------------------
+ //
+ // These drive REAL streams rather than plain-object doubles, because the whole
+ // point is what happens between "headers resolved" and "last byte read" — a
+ // double that resolves `json()` instantly cannot observe it.
+
+ /** A Response whose headers have landed but whose body never produces a byte. */
+ function stallingResponse(signal) {
+ const body = new ReadableStream({
+ start(controller) {
+ signal.addEventListener('abort', () => controller.error(new DOMException('aborted', 'AbortError')), { once: true });
+ },
+ });
+ return new Response(body, { status: 200, headers: { 'Content-Type': 'application/json' } });
+ }
+
+ it('aborts a body that stalls after headers land', async () => {
+ vi.stubGlobal('fetch', vi.fn((_url, opts) => Promise.resolve(stallingResponse(opts.signal))));
+
+ const started = Date.now();
+ const res = await fetchWithTimeout('http://example.com', {}, 60);
+ // Headers resolved fine — the old helper cleared its timer right here and
+ // left the read below unbounded forever.
+ expect(res.status).toBe(200);
+ await expect(res.text()).rejects.toThrow(/abort/i);
+ expect(Date.now() - started).toBeLessThan(60 * 2 + 500);
+ });
+
+ it('aborts a stalled body read through the raw stream too', async () => {
+ vi.stubGlobal('fetch', vi.fn((_url, opts) => Promise.resolve(stallingResponse(opts.signal))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 60);
+ const reader = res.body.getReader();
+ await expect(reader.read()).rejects.toThrow(/abort/i);
+ });
+
+ it('does not arm a body deadline when timeoutMs is 0', async () => {
+ vi.stubGlobal('fetch', vi.fn((_url, opts) => Promise.resolve(stallingResponse(opts.signal))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 0);
+ const settled = await Promise.race([
+ res.text().then(() => 'read', () => 'aborted'),
+ new Promise((resolve) => setTimeout(() => resolve('still-open'), 150)),
+ ]);
+ expect(settled).toBe('still-open');
+ });
+
+ it('honors bodyDeadline: false for a caller that bounds its own stream', async () => {
+ vi.stubGlobal('fetch', vi.fn((_url, opts) => Promise.resolve(stallingResponse(opts.signal))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 60, { bodyDeadline: false });
+ const settled = await Promise.race([
+ res.text().then(() => 'read', () => 'aborted'),
+ new Promise((resolve) => setTimeout(() => resolve('still-open'), 200)),
+ ]);
+ expect(settled).toBe('still-open');
+ });
+
+ it('releases the deadline once the body is fully read', async () => {
+ const clearSpy = vi.spyOn(global, 'clearTimeout');
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response('{"ok":true}', { status: 200 }))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 5000);
+ expect(clearSpy).not.toHaveBeenCalled(); // still armed while the body is unread
+ expect(await res.json()).toEqual({ ok: true });
+ expect(clearSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases the deadline when the body is cancelled instead of read', async () => {
+ const clearSpy = vi.spyOn(global, 'clearTimeout');
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response('payload', { status: 500 }))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 5000);
+ await res.body.cancel();
+ expect(clearSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('releases the deadline immediately for a bodyless response', async () => {
+ const clearSpy = vi.spyOn(global, 'clearTimeout');
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response(null, { status: 204 }))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 5000);
+ expect(res.status).toBe(204);
+ expect(clearSpy).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps branded Response accessors and instanceof working through the wrapper', async () => {
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(
+ new Response('hi', { status: 201, statusText: 'Created', headers: { 'X-Trace': 'abc' } })
+ )));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 5000);
+ expect(res).toBeInstanceOf(Response);
+ expect(res.ok).toBe(true);
+ expect(res.status).toBe(201);
+ expect(res.headers.get('x-trace')).toBe('abc');
+ expect(await res.text()).toBe('hi');
+ });
+
+ it('does not lock the body when .body is only read as a truthiness check', async () => {
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response('{"a":1}', { status: 200 }))));
+
+ const res = await fetchWithTimeout('http://example.com', {}, 5000);
+ expect(res.body).toBeTruthy();
+ // The wrapper must not have drained/locked the real body just by being asked for.
+ expect(await res.json()).toEqual({ a: 1 });
+ });
});
+
diff --git a/server/services/beeperClient.js b/server/services/beeperClient.js
index a4bfaee6db..d702e46cf4 100644
--- a/server/services/beeperClient.js
+++ b/server/services/beeperClient.js
@@ -282,49 +282,50 @@ async function beeperRequest(path, {
const reqHeaders = { 'Content-Type': 'application/json', ...headers };
if (resolved.token) reqHeaders.Authorization = `Bearer ${resolved.token}`;
- // fetchWithTimeout owns the deadline only until response headers arrive. Keep
- // a caller-owned signal alive through body consumption as well, so a local
- // bridge cannot hold a request open indefinitely after answering headers.
- const requestController = new AbortController();
- const hasDeadline = Number.isFinite(timeoutMs) && timeoutMs > 0;
- const deadlineId = hasDeadline ? setTimeout(() => requestController.abort(), timeoutMs) : null;
+ // `timeoutMs` covers headers AND body consumption inside `fetchWithTimeout`
+ // (#7236), so there is no second body deadline to keep here. What that helper
+ // deliberately does NOT bound is a whole retry SEQUENCE — each replay gets a
+ // fresh budget — so a read that may replay carries a caller-owned signal as
+ // the TOTAL deadline, which is exactly the hook `waitForRetry` honors. A
+ // Beeper that keeps dropping connections therefore cannot stretch one logical
+ // request across unbounded backoffs.
+ const totalDeadline = allowRetry && Number.isFinite(timeoutMs) && timeoutMs > 0 ? new AbortController() : null;
+ const totalDeadlineId = totalDeadline ? setTimeout(() => totalDeadline.abort(), timeoutMs) : null;
let response;
let data;
try {
- try {
- response = await fetchWithTimeout(`${resolved.baseUrl}${path}`, {
- method,
- headers: reqHeaders,
- redirect: 'error',
- body: body === undefined ? undefined : JSON.stringify(body),
- signal: requestController.signal,
- }, timeoutMs, allowRetry ? READ_RETRY : {});
-
- if (response.status === 204) {
- noteSuccess();
- return null;
- }
- data = await readResponseJson(response, { fallback: (text) => ({ message: text }) });
- } catch (err) {
- const description = describeFetchError(err);
- // AbortController firing (during headers OR body consumption) is the one
- // network failure that means "no answer arrived in time" rather than
- // "nothing is listening" — the distinction `probeBeeperInfo` needs to
- // tell `slow` from `unreachable` (fork issue #61, decision 7).
- const timedOut = /\babort/i.test(description);
- throw new BeeperApiError(`Beeper request failed: ${description}`, {
- status: 0, code: 'NETWORK_ERROR', retryable: allowRetry && isReplayableConnectionError(err),
- details: timedOut ? { timedOut: true } : undefined,
- });
+ response = await fetchWithTimeout(`${resolved.baseUrl}${path}`, {
+ method,
+ headers: reqHeaders,
+ redirect: 'error',
+ body: body === undefined ? undefined : JSON.stringify(body),
+ ...(totalDeadline ? { signal: totalDeadline.signal } : {}),
+ }, timeoutMs, allowRetry ? READ_RETRY : {});
+
+ if (response.status === 204) {
+ noteSuccess();
+ return null;
}
-
- if (!response.ok) throw mapBeeperResponseError(response.status, data, { isAssetEndpoint, retryEligible: allowRetry });
- noteSuccess();
- return data;
+ data = await readResponseJson(response, { fallback: (text) => ({ message: text }) });
+ } catch (err) {
+ const description = describeFetchError(err);
+ // AbortController firing (during headers OR body consumption) is the one
+ // network failure that means "no answer arrived in time" rather than
+ // "nothing is listening" — the distinction `probeBeeperInfo` needs to
+ // tell `slow` from `unreachable` (fork issue #61, decision 7).
+ const timedOut = /\babort/i.test(description);
+ throw new BeeperApiError(`Beeper request failed: ${description}`, {
+ status: 0, code: 'NETWORK_ERROR', retryable: allowRetry && isReplayableConnectionError(err),
+ details: timedOut ? { timedOut: true } : undefined,
+ });
} finally {
- if (deadlineId !== null) clearTimeout(deadlineId);
+ if (totalDeadlineId !== null) clearTimeout(totalDeadlineId);
}
+
+ if (!response.ok) throw mapBeeperResponseError(response.status, data, { isAssetEndpoint, retryEligible: allowRetry });
+ noteSuccess();
+ return data;
}
// ---------------------------------------------------------------------------
@@ -727,13 +728,14 @@ export async function downloadAsset(url, { baseUrl, token, timeoutMs } = {}) {
* ordinarily-retryable `UPSTREAM_ERROR` a generic "5xx is transient" policy
* would loop on forever.
*/
-// Time to the RESPONSE HEADERS, not to the last byte: `fetchWithTimeout` clears
-// its abort timer once `fetch` resolves, which is the moment the headers land.
+// Time to the RESPONSE HEADERS, not to the last byte — which is why this is the
+// one call site that opts out of `fetchWithTimeout`'s body deadline below.
// Generous rather than the 15s a JSON call gets, because Beeper may have to
// pull the media off the network before it can answer at all. The BODY is
// bounded separately by the mirror's own idle-abort (`STREAM_IDLE_TIMEOUT_MS`
// in `beeperAttachments.js`), which is what a caller passing `signal` here is
-// usually doing.
+// usually doing — a whole-transfer ceiling here would instead kill a large
+// attachment that is streaming along perfectly happily.
const ASSET_REQUEST_TIMEOUT_MS = 60_000;
function assetErrorFrom(response) {
@@ -762,7 +764,7 @@ async function assetRequest(mxcId, { method, baseUrl, token, timeoutMs = ASSET_R
headers: { Authorization: `Bearer ${resolved.token}` },
redirect: 'error',
signal,
- }, timeoutMs).catch((err) => {
+ }, timeoutMs, { bodyDeadline: false }).catch((err) => {
throw new BeeperApiError(`Beeper asset request failed: ${describeFetchError(err)}`, {
status: 0, code: 'NETWORK_ERROR', retryable: false,
});
diff --git a/server/services/videoGen/fal.js b/server/services/videoGen/fal.js
index 10d65ff64c..e154d3dac9 100644
--- a/server/services/videoGen/fal.js
+++ b/server/services/videoGen/fal.js
@@ -47,7 +47,13 @@ export const FAL_DEFAULT_IMAGE_MODEL = 'fal-ai/minimax/hailuo-02/standard/image-
const FAL_SUBMIT_TIMEOUT_MS = 30_000;
const FAL_POLL_TIMEOUT_MS = 15_000;
const FAL_POLL_INTERVAL_MS = 3000;
-const FAL_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
+// Bounds the WHOLE download — headers and every byte of the video — now that
+// `fetchWithTimeout` holds its deadline through body consumption. It used to
+// bound only the headers, which left the multi-MB transfer itself with no
+// ceiling: a stalled body pinned the media job in `running` until the queue
+// watchdog reaped it 30 minutes later. Ten minutes is far more than a finished
+// render takes to transfer and still well inside that watchdog.
+const FAL_DOWNLOAD_TIMEOUT_MS = 10 * 60 * 1000;
// A cloud queue render can sit behind other tenants' jobs before it starts —
// generously bounded, same order of magnitude as grok's image-first cap.
const FAL_RENDER_TIMEOUT_MS = (() => {