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([shared-tolerant-fetch-json-helper]): address multi-reviewer findings on malformed-body handling

[._.]/ Adam Eivyff33aee8a2f1
diff --git a/PLAN.md b/PLAN.md
index cf8b825e3a..2155a48845 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -6,7 +6,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel
Claimable, well-specified, no decision needed — `/claim`-able. Unordered.
-- [ ] [tolerant-fetch-json-additional-clients] **Adopt the shared `readResponseJson` helper in the remaining fetch-based clients.** The `[shared-tolerant-fetch-json-helper]` PR promoted `server/lib/readResponseJson.js` and migrated the originally-scoped clients, but a reuse-review sweep surfaced more fetch-based clients with the same unguarded `await response.json()` crash risk (an HTML/non-JSON error body throws `Unexpected token <`): `server/services/memoryClassifier.js:274`, `server/services/calendarApiSync.js:96`, `server/services/messageApiSync.js:74`, `server/services/insightsService.js:197`, and `server/services/localLlmPlayground.js:114` (all unguarded), plus `server/services/codeReview.js:166` which currently uses a `.catch(() => null)` band-aid that silently swallows the real error. Migrate each to `readResponseJson(response)` (object callers) with the appropriate `{ fallback, emptyValue }` for array endpoints; for `codeReview.js`, decide whether to surface the error text via the function-fallback form. Deferred out of the helper PR to keep it within its stated single-file-list scope. Surfaced by /simplify reuse review (2026-06-01).
+- [ ] [tolerant-fetch-json-additional-clients] **Adopt the shared `readResponseJson` helper in the remaining fetch-based clients.** The `[shared-tolerant-fetch-json-helper]` PR promoted `server/lib/readResponseJson.js` and migrated the originally-scoped clients, but a reuse-review sweep surfaced more fetch-based clients with the same unguarded `await response.json()` crash risk (an HTML/non-JSON error body throws `Unexpected token <`): `server/services/memoryClassifier.js:274`, `server/services/calendarApiSync.js:96`, `server/services/messageApiSync.js:74`, `server/services/insightsService.js:197`, `server/services/localLlmPlayground.js:114`, `server/lib/civitai.js:209` and `:347`, and `server/lib/telegramClient.js:31` and `:59` (all unguarded), plus `server/services/codeReview.js:166` which currently uses a `.catch(() => null)` band-aid that silently swallows the real error. Migrate each to `readResponseJson(response)` (object callers) with `{ fallback: [] }` for array endpoints; for `codeReview.js`, decide whether to surface the error text via the function-fallback form. Deferred out of the helper PR to keep it within its stated single-file-list scope. Surfaced by /simplify reuse review + the multi-reviewer pass on PR #614 (2026-06-01).
- [ ] [cos-agent-output-write-amplification] **`appendAgentOutput` write-amplification — already batched via `appendAgentOutputLines`, audit non-runner producers.** CLAUDE.md documents the streaming-producers convention (batched variant + ~250ms debounce + drain on completion); the runner path uses it. Verify every producer that calls `appendAgentOutput` directly (`server/services/cosAgents.js:216`) is human-pace, not a hot loop. If any hot producer is still calling the per-line variant, migrate it. Likely a no-op audit; capture it so the convention doesn't silently drift.
- [ ] [subagent-spawner-top-level-side-effects] **`subAgentSpawner.js` top-level side effects — move init into an explicit `initSpawner()`.** Module-load (`server/services/subAgentSpawner.js:153`) wires event listeners + timers, which interferes with test isolation (each test import re-arms them). Wrap the init block in `export function initSpawner()` and call it from `server/index.js` after dependencies are ready. Treat as a refactor — needs care that no consumer relies on the import-time wiring.
- [ ] [conflict-journal-media-collections] **Conflict journal does not cover media-collection scalar overwrites.** `mergeMediaCollectionsFromSync` (`server/services/mediaCollections.js`) LWW-overwrites scalars (name/description/coverKey/universeId/seriesId) when `remoteWins`; items are union-merged (never lost). v1 hooks only universe + series merges because the whole-record content hash used by `conflictJournal.detectConflict` would false-positive on collections whenever items differ. Doing it right needs scalar-subset hashing that stays consistent with the sender-side base hash. Low value (scalar loss is minor), deferred.
diff --git a/server/lib/aiProvider.js b/server/lib/aiProvider.js
index 0dcbab48ed..3d718000b2 100644
--- a/server/lib/aiProvider.js
+++ b/server/lib/aiProvider.js
@@ -145,7 +145,14 @@ async function postChatCompletion(provider, model, prompt, { temperature, max_to
}
const data = await readResponseJson(response);
- return { text: data.choices?.[0]?.message?.content || '' };
+ // A valid completion always carries `choices`; its absence means the 200 body
+ // wasn't the expected JSON (e.g. a proxy HTML page). Surface that as an error
+ // rather than masquerading a malformed body as an empty-but-successful reply.
+ const content = data.choices?.[0]?.message?.content;
+ if (typeof content !== 'string') {
+ return { error: 'Provider returned a malformed (non-JSON or unexpected) response body' };
+ }
+ return { text: content };
}
/**
diff --git a/server/lib/readResponseJson.js b/server/lib/readResponseJson.js
index c2f8bd04c9..6e36adbb68 100644
--- a/server/lib/readResponseJson.js
+++ b/server/lib/readResponseJson.js
@@ -15,27 +15,47 @@ const PARSE_FAILED = Symbol('parse-failed');
* crashing the Node process. This reads the raw text and parses it tolerantly
* via `safeJSONParse`:
*
- * - a valid JSON body parses normally;
- * - an empty body returns `emptyValue` (default `{}`), distinct from a parse
- * failure, so spreading callers don't pick up a spurious shape;
+ * - a valid JSON object/array body parses normally;
+ * - a blank (empty or whitespace-only) body returns `emptyValue`, distinct
+ * from a parse failure, so spreading callers don't pick up a spurious shape;
* - a non-JSON body returns `fallback` (default `{}`). `fallback` may be a
* function `(rawText) => value` when the fallback needs the body text —
* e.g. surfacing the server's error page as `{ error: rawText }`.
*
+ * `emptyValue` defaults to `fallback` (when `fallback` is a plain value), so an
+ * array caller only needs `{ fallback: [] }` to get `[]` for both empty and
+ * non-JSON. A function `fallback` is for surfacing error text and doesn't apply
+ * to a blank body, so `emptyValue` then defaults to `{}`.
+ *
* Object-shaped callers (the common case — endpoints returning `{ data }`,
* `{ models }`, `{ choices }`, …) need no options: a non-JSON body becomes
* `{}`, so their existing `data.foo || []` defaults take over instead of
- * throwing on `null.foo`. Array-shaped callers pass `{ fallback: [], emptyValue: [] }`.
+ * throwing on `null.foo`. Array-shaped callers pass `{ fallback: [] }`. Callers
+ * with a downstream truthiness contract (e.g. a route that 503s when this is
+ * falsy) pass `{ fallback: null, emptyValue: null }` so a malformed body stays
+ * falsy rather than masquerading as a valid empty value.
+ *
+ * Note: only object/array JSON bodies are recognized; a bare JSON primitive
+ * (`"str"`, `42`, `true`, `null`) is treated as a parse failure and returns the
+ * fallback (it inherits `safeJSONParse`'s structural validation). All current
+ * callers return objects/arrays.
*
- * @param {Response} response - an already-awaited fetch Response
+ * @param {Response} response - a resolved fetch Response (body not yet consumed)
* @param {Object} [opts]
* @param {*|function(string):*} [opts.fallback={}] - value (or text→value fn) for a non-JSON body
- * @param {*} [opts.emptyValue={}] - value for an empty body
+ * @param {*} [opts.emptyValue] - value for a blank body (defaults to `fallback`, or `{}` when `fallback` is a function)
* @returns {Promise<*>} parsed JSON, or the fallback/empty value
*/
-export async function readResponseJson(response, { fallback = {}, emptyValue = {} } = {}) {
+export async function readResponseJson(response, { fallback = {}, emptyValue } = {}) {
+ // A blank body is a distinct "successful but empty" case. It mirrors the
+ // fallback shape so a caller specifies one value; a function fallback (used to
+ // surface error text) can't apply to an empty body, so it falls back to `{}`.
+ const resolvedEmpty = emptyValue !== undefined
+ ? emptyValue
+ : (typeof fallback === 'function' ? {} : fallback);
+
const text = await response.text();
- if (!text) return emptyValue;
+ if (!text.trim()) return resolvedEmpty;
// Parse against the sentinel so a successful parse is distinguishable from a
// parse failure, and the (possibly function) fallback is only materialized
// when the body genuinely isn't JSON — never eagerly on every success.
diff --git a/server/lib/readResponseJson.test.js b/server/lib/readResponseJson.test.js
index 0f2df9442f..18a42fcbf2 100644
--- a/server/lib/readResponseJson.test.js
+++ b/server/lib/readResponseJson.test.js
@@ -10,16 +10,24 @@ describe('readResponseJson', () => {
});
it('parses a valid JSON array body when an array fallback is given', async () => {
- const out = await readResponseJson(res('[1,2,3]'), { fallback: [], emptyValue: [] });
+ const out = await readResponseJson(res('[1,2,3]'), { fallback: [] });
expect(out).toEqual([1, 2, 3]);
});
- it('returns emptyValue ({} by default) for an empty body', async () => {
+ it('returns {} for an empty body by default', async () => {
expect(await readResponseJson(res(''))).toEqual({});
});
- it('honors a custom emptyValue for an empty body', async () => {
- expect(await readResponseJson(res(''), { emptyValue: [] })).toEqual([]);
+ it('defaults emptyValue to a plain-value fallback (array caller gets [] for empty)', async () => {
+ expect(await readResponseJson(res(''), { fallback: [] })).toEqual([]);
+ });
+
+ it('honors an explicit emptyValue distinct from fallback', async () => {
+ expect(await readResponseJson(res(''), { fallback: [], emptyValue: null })).toBeNull();
+ });
+
+ it('treats a whitespace-only body as empty (returns emptyValue, not fallback)', async () => {
+ expect(await readResponseJson(res(' \n '), { fallback: 'NON_JSON', emptyValue: 'EMPTY' })).toBe('EMPTY');
});
it('returns the fallback ({} by default) for a non-JSON body instead of throwing', async () => {
@@ -27,9 +35,12 @@ describe('readResponseJson', () => {
await expect(readResponseJson(res('<!DOCTYPE html><html>500</html>'))).resolves.toEqual({});
});
+ it('returns null fallback for a non-JSON body when a truthiness contract requires it', async () => {
+ expect(await readResponseJson(res('nope'), { fallback: null, emptyValue: null })).toBeNull();
+ });
+
it('returns an array fallback for a non-JSON body when requested', async () => {
- const out = await readResponseJson(res('nope'), { fallback: [], emptyValue: [] });
- expect(out).toEqual([]);
+ expect(await readResponseJson(res('nope'), { fallback: [] })).toEqual([]);
});
it('passes the raw body text to a function fallback', async () => {
diff --git a/server/services/browserService.js b/server/services/browserService.js
index f234f4cdb4..e7a466c805 100644
--- a/server/services/browserService.js
+++ b/server/services/browserService.js
@@ -205,7 +205,7 @@ export async function cdpRequest(path, options = {}) {
export async function listCdpPages() {
const response = await cdpRequest('/json/list', { timeout: HEALTH_TIMEOUT_MS }).catch(() => null);
if (!response || !response.ok) return [];
- return readResponseJson(response, { fallback: [], emptyValue: [] });
+ return readResponseJson(response, { fallback: [] });
}
export async function findOrOpenPage(targetUrl) {
@@ -214,7 +214,8 @@ export async function findOrOpenPage(targetUrl) {
if (existing) return existing;
const response = await cdpRequest(`/json/new?${encodeURIComponent(targetUrl)}`, { method: 'PUT' });
if (!response.ok) return null;
- return readResponseJson(response);
+ // Preserve the null-on-failure contract: a malformed body stays null, not {}.
+ return readResponseJson(response, { fallback: null, emptyValue: null });
}
export function isAuthPage(page) {
@@ -289,7 +290,9 @@ export async function getOpenPages() {
export async function getCdpVersion() {
const response = await cdpRequest('/json/version', { timeout: HEALTH_TIMEOUT_MS }).catch(() => null);
if (!response || !response.ok) return null;
- return readResponseJson(response);
+ // Preserve the null-on-failure contract: the /version route 503s when this is
+ // falsy, so a malformed body must stay null, not become a truthy {}.
+ return readResponseJson(response, { fallback: null, emptyValue: null });
}
// ---------- Downloads ----------
diff --git a/server/services/huggingFaceCatalog.js b/server/services/huggingFaceCatalog.js
index 147246b545..c5b4241868 100644
--- a/server/services/huggingFaceCatalog.js
+++ b/server/services/huggingFaceCatalog.js
@@ -246,7 +246,7 @@ async function fetchModels(search, limit, useGgufFilter) {
const text = await response.text().catch(() => '')
throw new Error(`Hugging Face search failed: ${response.status}${text ? ` — ${text.slice(0, 160)}` : ''}`)
}
- const data = await readResponseJson(response, { fallback: [], emptyValue: [] })
+ const data = await readResponseJson(response, { fallback: [] })
return Array.isArray(data) ? data : []
}