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 Beeper JSON response reads (#7176)

[._.]/ Adam Eivya8e3d20b8460
diff --git a/server/services/beeperClient.js b/server/services/beeperClient.js
index 4a1918d334..a4bfaee6db 100644
--- a/server/services/beeperClient.js
+++ b/server/services/beeperClient.js
@@ -282,37 +282,49 @@ 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;
+
let response;
+ let data;
try {
- response = await fetchWithTimeout(`${resolved.baseUrl}${path}`, {
- method,
- headers: reqHeaders,
- redirect: 'error',
- body: body === undefined ? undefined : JSON.stringify(body),
- }, timeoutMs, allowRetry ? READ_RETRY : {});
- } catch (err) {
- const description = describeFetchError(err);
- // AbortController firing (the timeout above, or a caller-supplied
- // `signal`) 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). Node/undici's own AbortError always carries "abort" in
- // its name or message; `describeFetchError` folds both into this string.
- 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,
- });
- }
+ 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,
+ });
+ }
- if (response.status === 204) {
+ if (!response.ok) throw mapBeeperResponseError(response.status, data, { isAssetEndpoint, retryEligible: allowRetry });
noteSuccess();
- return null;
+ return data;
+ } finally {
+ if (deadlineId !== null) clearTimeout(deadlineId);
}
- const data = await readResponseJson(response, { fallback: (text) => ({ message: text }) });
- if (!response.ok) throw mapBeeperResponseError(response.status, data, { isAssetEndpoint, retryEligible: allowRetry });
- noteSuccess();
- return data;
}
// ---------------------------------------------------------------------------
diff --git a/server/services/beeperClient.test.js b/server/services/beeperClient.test.js
index 72cf017655..ffe77d0575 100644
--- a/server/services/beeperClient.test.js
+++ b/server/services/beeperClient.test.js
@@ -366,6 +366,20 @@ describe('beeperClient', () => {
// -------------------------------------------------------------------------
describe('timeout behavior (fake timers)', () => {
+ function bodyThatRejectsOnAbort(status, signal, { trickle = false } = {}) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ text: () => new Promise((_resolve, reject) => {
+ const trickleId = trickle ? setInterval(() => {}, 5) : null;
+ signal.addEventListener('abort', () => {
+ if (trickleId !== null) clearInterval(trickleId);
+ reject(new DOMException('aborted while reading body', 'AbortError'));
+ }, { once: true });
+ }),
+ };
+ }
+
// Fork issue #61, decision 7: 1s proved too tight for a briefly-busy Beeper
// Desktop, so the cap moved to 3s.
it('probeBeeperInfo caps at 3s and resolves reachable:false/timedOut:true without throwing, and without a real sleep', async () => {
@@ -414,6 +428,94 @@ describe('beeperClient', () => {
}
});
+ it.each([200, 500])('bounds a stalled JSON body after immediate HTTP %s headers', async (status) => {
+ vi.useFakeTimers();
+ try {
+ let requestSignal;
+ const fetchMock = vi.fn().mockImplementation((_url, opts) => {
+ requestSignal = opts.signal;
+ return Promise.resolve(bodyThatRejectsOnAbort(status, requestSignal));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const request = getInfo({ baseUrl: DEFAULT_BASE_URL, timeoutMs: 25 });
+ const rejection = expect(request).rejects.toMatchObject({
+ code: 'NETWORK_ERROR',
+ context: { details: { timedOut: true } },
+ });
+ await vi.advanceTimersByTimeAsync(25);
+
+ await rejection;
+ expect(requestSignal.aborted).toBe(true);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps one total deadline when a JSON body keeps trickling data', async () => {
+ vi.useFakeTimers();
+ try {
+ let requestSignal;
+ vi.stubGlobal('fetch', vi.fn().mockImplementation((_url, opts) => {
+ requestSignal = opts.signal;
+ return Promise.resolve(bodyThatRejectsOnAbort(200, requestSignal, { trickle: true }));
+ }));
+
+ const request = getInfo({ baseUrl: DEFAULT_BASE_URL, timeoutMs: 30 });
+ const rejection = expect(request).rejects.toMatchObject({
+ code: 'NETWORK_ERROR',
+ context: { details: { timedOut: true } },
+ });
+ await vi.advanceTimersByTimeAsync(30);
+
+ await rejection;
+ expect(requestSignal.aborted).toBe(true);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('clears the total deadline after a successful JSON read', async () => {
+ vi.useFakeTimers();
+ try {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(jsonResponse(200, {
+ app: { name: 'Beeper' }, server: { status: 'running' },
+ })));
+
+ await expect(getInfo({ baseUrl: DEFAULT_BASE_URL, timeoutMs: 50 })).resolves.toMatchObject({
+ app: { name: 'Beeper' },
+ });
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('aborts a stalled send body after one POST without retrying it', async () => {
+ vi.useFakeTimers();
+ try {
+ let requestSignal;
+ const fetchMock = vi.fn().mockImplementation((_url, opts) => {
+ requestSignal = opts.signal;
+ return Promise.resolve(bodyThatRejectsOnAbort(200, requestSignal));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const request = sendMessage('chat1', { text: 'hi' }, {
+ baseUrl: DEFAULT_BASE_URL, token: 't', timeoutMs: 25,
+ });
+ const rejection = expect(request).rejects.toMatchObject({ code: 'NETWORK_ERROR', retryable: false });
+ await vi.advanceTimersByTimeAsync(25);
+
+ await rejection;
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock.mock.calls[0][1].method).toBe('POST');
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it('getInfo does not retry (unauthenticated probe, no allowRetry) — a connection error surfaces immediately', async () => {
const fetchMock = vi.fn().mockRejectedValue(Object.assign(new TypeError('fetch failed'), { cause: { code: 'ECONNREFUSED' } }));
vi.stubGlobal('fetch', fetchMock);