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([tolerant-fetch-json-additional-clients]): guard remaining fetch json() calls with readResponseJson
[._.]/ Adam Eivyaeca21dc822e
diff --git a/server/lib/civitai.js b/server/lib/civitai.jsindex 07bf139f81..5c340720c4 100644--- a/server/lib/civitai.js+++ b/server/lib/civitai.js@@ -17,6 +17,7 @@import { ServerError } from './errorHandler.js';import { RUNNER_FAMILIES } from './runners.js';+import { readResponseJson } from './readResponseJson.js';const CIVITAI_API = 'https://civitai.com/api/v1';const CIVITAI_HOSTS = new Set(['civitai.com', 'civitai.red', 'civitai.green', 'www.civitai.com']);@@ -206,7 +207,7 @@ export const fetchCivitaiModel = async (modelId, { apiKey, fetchImpl = fetch } =}throw new ServerError(`Civitai metadata fetch failed: ${res.status}`, { status: 502, code: 'CIVITAI_FETCH_FAILED' });}- return res.json();+ return readResponseJson(res);};// Apply the auth token to a Civitai download URL. The download endpoint@@ -344,7 +345,7 @@ export const searchCivitaiLoras = async ({ runnerFamily, limit = 12, sort = 'Mos}throw new ServerError(`Civitai search failed: ${res.status}`, { status: 502, code: 'CIVITAI_SEARCH_FAILED' });}- const body = await res.json();+ const body = await readResponseJson(res);return Array.isArray(body?.items) ? body.items : [];};diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex cbeb0d3337..bcefd76101 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -267,7 +267,7 @@ describe('fetchCivitaiModel', () => {calledUrl = url;expect(opts.headers.Accept).toBe('application/json');expect(opts.headers.Authorization).toBe('Bearer k');- return { ok: true, status: 200, json: async () => ({ id: 1, name: 'X' }) };+ return { ok: true, status: 200, text: async () => JSON.stringify({ id: 1, name: 'X' }) };};const out = await fetchCivitaiModel('123', { apiKey: 'k', fetchImpl });expect(calledUrl).toBe('https://civitai.com/api/v1/models/123');@@ -283,7 +283,7 @@ describe('fetchCivitaiModel', () => {});it('rejects non-numeric modelId without hitting the network', async () => {let called = false;- const fetchImpl = async () => { called = true; return { ok: true, status: 200, json: async () => ({}) }; };+ const fetchImpl = async () => { called = true; return { ok: true, status: 200, text: async () => '{}' }; };await expect(fetchCivitaiModel('abc', { fetchImpl })).rejects.toThrow(/Invalid Civitai model id/);expect(called).toBe(false);});diff --git a/server/lib/telegramClient.js b/server/lib/telegramClient.jsindex 6691c10446..3ed6a4ebd5 100644--- a/server/lib/telegramClient.js+++ b/server/lib/telegramClient.js@@ -4,6 +4,7 @@*/import { EventEmitter } from 'events';+import { readResponseJson } from './readResponseJson.js';const BASE_URL = 'https://api.telegram.org/bot';const POLL_TIMEOUT_SEC = 30;@@ -28,7 +29,7 @@ async function apiCall(token, method, body = {}) {body: JSON.stringify(payload),signal: AbortSignal.timeout(API_TIMEOUT_MS)});- const json = await res.json();+ const json = await readResponseJson(res);if (!json.ok) throw new Error(json.description || `Telegram API error: ${method}`);return json.result;}@@ -56,7 +57,7 @@ export function createTelegramBot(token, opts = {}) {body: JSON.stringify({ offset, timeout: POLL_TIMEOUT_SEC, allowed_updates: ['message', 'callback_query'] }),signal: activePollController.signal});- const json = await res.json();+ const json = await readResponseJson(res);if (!json.ok) {// Retry after a delay on API errorsawait new Promise(r => setTimeout(r, RETRY_DELAY_API_ERROR_MS));diff --git a/server/services/calendarApiSync.js b/server/services/calendarApiSync.jsindex d63ca49020..8a5d01bf07 100644--- a/server/services/calendarApiSync.js+++ b/server/services/calendarApiSync.js@@ -1,6 +1,7 @@import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { readResponseJson } from '../lib/readResponseJson.js';import { getToken, clearTokenCache } from './messageTokenExtractor.js';const GRAPH_API_TIMEOUT_MS = 30000;@@ -93,7 +94,7 @@ export async function syncOutlookCalendarApi(account, _cache, io, options = {})return { events: [], status: 'api-error' };}- const data = await response.json();+ const data = await readResponseJson(response);const items = data.value || [];for (const item of items) {diff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.jsindex 5c47204d81..536a959b9a 100644--- a/server/services/civitaiSuggestions.test.js+++ b/server/services/civitaiSuggestions.test.js@@ -33,12 +33,12 @@ describe('getSuggestions', () => {const fetchImpl = async (url) => {// Curated direct fetches go through /models/<id>; search goes through /models?...const m = url.match(/api\/v1\/models\/(\d+)$/);- if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated-${m[1]}`, 'Flux.1 D') };+ if (m) return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated-${m[1]}`, 'Flux.1 D') )};// Search endpoint — return a list with entries matching the requested baseModel.const search = new URL(url);const baseModels = search.searchParams.getAll('baseModels');const items = baseModels.map((bm, i) => buildModel(9000 + i, `Top-${bm}-${i}`, bm));- return { ok: true, status: 200, json: async () => ({ items }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items }) )};};const out = await svc.getSuggestions({ fetchImpl, limit: 5 });expect(Array.isArray(out.curated)).toBe(true);@@ -61,9 +61,9 @@ describe('getSuggestions', () => {calls += 1;// First curated call 404s; rest succeed.if (calls === 1) return { ok: false, status: 404 };- return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Ok-${m[1]}`, 'Flux.1 D') };+ return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Ok-${m[1]}`, 'Flux.1 D') )};}- return { ok: true, status: 200, json: async () => ({ items: [buildModel(9999, 'Search', 'Flux.1 D')] }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: [buildModel(9999, 'Search', 'Flux.1 D')] }) )};};const out = await svc.getSuggestions({ fetchImpl });// The first curated entry was dropped, but we should still have the others.@@ -76,8 +76,8 @@ describe('getSuggestions', () => {const fetchImpl = async (url) => {calls += 1;const m = url.match(/api\/v1\/models\/(\d+)$/);- if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };- return { ok: true, status: 200, json: async () => ({ items: [buildModel(1, 'Cached', 'Flux.1 D')] }) };+ if (m) return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated`, 'Flux.1 D') )};+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: [buildModel(1, 'Cached', 'Flux.1 D')] }) )};};await svc.getSuggestions({ fetchImpl });const callsAfterFirst = calls;@@ -93,9 +93,9 @@ describe('getSuggestions', () => {let fetchCalls = 0;const fetchImpl = async (url) => {const m = url.match(/api\/v1\/models\/(\d+)$/);- if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };+ if (m) return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated`, 'Flux.1 D') )};fetchCalls += 1;- return { ok: true, status: 200, json: async () => ({ items: makeItems(24) }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: makeItems(24) }) )};};// First call uses limit=4 — cache is populated at MAX (24 entries).@@ -117,9 +117,9 @@ describe('getSuggestions', () => {let fetchCalls = 0;const fetchImpl = async (url) => {const m = url.match(/api\/v1\/models\/(\d+)$/);- if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `Curated`, 'Flux.1 D') };+ if (m) return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated`, 'Flux.1 D') )};fetchCalls += 1;- return { ok: true, status: 200, json: async () => ({ items: makeItems(24) }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: makeItems(24) }) )};};// First call: limit=24 — populates cache with 24 cards.@@ -141,8 +141,8 @@ describe('getSuggestions', () => {const fetchImpl = async (url) => {calls += 1;const m = url.match(/api\/v1\/models\/(\d+)$/);- if (m) return { ok: true, status: 200, json: async () => buildModel(Number(m[1]), `C`, 'Flux.1 D') };- return { ok: true, status: 200, json: async () => ({ items: [] }) };+ if (m) return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `C`, 'Flux.1 D') )};+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: [] }) )};};await svc.getSuggestions({ fetchImpl });const callsAfterFirst = calls;@@ -158,7 +158,7 @@ describe('getSuggestions', () => {return {ok: true,status: 200,- json: async () => ({+ text: async () => JSON.stringify(({...buildModel(id, 'Multi', 'Flux.1 D'),modelVersions: [// Most recent (first) per family wins. Two flux2 versions —@@ -171,10 +171,10 @@ describe('getSuggestions', () => {// Unsupported base — shouldn't appear in installs{ id: 50, baseModel: 'SDXL 1.0', files: [{ name: 's.safetensors', primary: true, sizeKB: 500 }] },],- }),+ })),};}- return { ok: true, status: 200, json: async () => ({ items: [] }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: [] }) )};};const out = await svc.getSuggestions({ fetchImpl });const card = out.curated[0];@@ -198,16 +198,16 @@ describe('getSuggestions', () => {return {ok: true,status: 200,- json: async () => ({+ text: async () => JSON.stringify(({...buildModel(id, 'Multi', 'Flux.1 D'),modelVersions: [{ id: id * 10, baseModel: 'Flux.1 D', trainedWords: [], images: [], files: [{ name: 'a.safetensors', primary: true }] },{ id: id * 10 + 1, baseModel: 'Flux.2', trainedWords: [], images: [], files: [{ name: 'b.safetensors', primary: true }] },],- }),+ })),};}- return { ok: true, status: 200, json: async () => ({ items: [] }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ items: [] }) )};};const out = await svc.getSuggestions({ fetchImpl });const card = out.curated[0];diff --git a/server/services/codeReview.js b/server/services/codeReview.jsindex c328529159..b251ad69b0 100644--- a/server/services/codeReview.js+++ b/server/services/codeReview.js@@ -13,6 +13,7 @@*/import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'+import { readResponseJson } from '../lib/readResponseJson.js'import {LOCAL_LLM_REVIEWERS,DEFAULT_REVIEWERS,@@ -163,7 +164,12 @@ export async function runLocalCodeReview({ backend, model, diff, timeoutMs = 120return { ok: false, backend, model, error: `${backend} API error ${response.status}: ${text.slice(0, 300)}` }}- const data = await response.json().catch(() => null)+ // Surface the server's raw error text instead of swallowing a non-JSON body to+ // null — a 200-with-HTML answer used to read as the misleading "no content".+ const data = await readResponseJson(response, { fallback: (raw) => ({ _nonJson: raw }) })+ if (data?._nonJson !== undefined) {+ return { ok: false, backend, model, error: `${backend} returned a non-JSON response: ${data._nonJson.slice(0, 300)}` }+ }const findings = data?.choices?.[0]?.message?.contentif (!findings || typeof findings !== 'string') {return { ok: false, backend, model, error: `${backend} returned no content.` }diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsindex 743f7ac0ee..7574bbc9a1 100644--- a/server/services/codeReview.test.js+++ b/server/services/codeReview.test.js@@ -129,8 +129,7 @@ describe('codeReview helpers', () => {global.fetch = vi.fn().mockResolvedValue({ok: true,status: 200,- json: () => Promise.resolve({ choices: [{ message: { content: 'No findings.' } }] }),- text: () => Promise.resolve(''),+ text: () => Promise.resolve(JSON.stringify({ choices: [{ message: { content: 'No findings.' } }] })),})})@@ -190,11 +189,23 @@ describe('codeReview helpers', () => {global.fetch = vi.fn().mockResolvedValue({ok: true,status: 200,- json: () => Promise.resolve({ choices: [{ message: { content: '' } }] }),+ text: () => Promise.resolve(JSON.stringify({ choices: [{ message: { content: '' } }] })),})const r = await runLocalCodeReview({ backend: 'ollama', model: 'm', diff: 'x' })expect(r.ok).toBe(false)expect(r.error).toMatch(/no content/)})++ it('surfaces a 200-with-non-JSON body instead of masking it as "no content"', async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ text: () => Promise.resolve('<html><body>502 Bad Gateway</body></html>'),+ })+ const r = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: 'x' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/non-JSON response/)+ expect(r.error).toMatch(/502 Bad Gateway/)+ })})})diff --git a/server/services/insightsService.js b/server/services/insightsService.jsindex 84e5a4c5bc..a55daf6206 100644--- a/server/services/insightsService.js+++ b/server/services/insightsService.js@@ -22,6 +22,7 @@ import { getActiveProvider, getProviderById } from './providers.js';import { getCorrelationData } from './appleHealthQuery.js';import { stripCodeFences, parseLLMJSON } from '../lib/aiProvider.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { readResponseJson } from '../lib/readResponseJson.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';const DEFAULT_AI_TIMEOUT_MS = 300000;@@ -194,7 +195,7 @@ async function callProviderAISimple(provider, model, prompt, { temperature = 0.3return { error: `Provider returned ${response.status}: ${errorText}` };}- const data = await response.json();+ const data = await readResponseJson(response);return { text: data.choices?.[0]?.message?.content || '' };}diff --git a/server/services/localLlmPlayground.js b/server/services/localLlmPlayground.jsindex 398b49ce42..337f69c17f 100644--- a/server/services/localLlmPlayground.js+++ b/server/services/localLlmPlayground.js@@ -4,6 +4,7 @@ import { ensureBackendProvider } from './localLlm.js';import { getProviderById } from './providers.js';import { markProviderAvailable } from './providerStatus.js';import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';+import { readResponseJson } from '../lib/readResponseJson.js';const PROVIDER_BY_BACKEND = { ollama: 'ollama', lmstudio: 'lmstudio' };@@ -111,7 +112,7 @@ async function streamChatCompletion({ provider, backend, modelId, prompt, system}if (!response.body?.getReader) {- const data = await response.json();+ const data = await readResponseJson(response);const text = data.choices?.[0]?.message?.content || '';if (text) onChunk(text);return text;diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex a0b9ce1323..27a22a8a65 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -220,7 +220,7 @@ describe('installFromCivitai', () => {const fetchImpl = async (url) => {calls.push(url);if (url.startsWith('https://civitai.com/api/v1/models/2600698')) {- return { ok: true, status: 200, json: async () => FAKE_MODEL };+ return { ok: true, status: 200, text: async () => JSON.stringify(FAKE_MODEL )};}if (url.startsWith('https://civitai.com/api/download/models/7')) {// Return a Web ReadableStream so Readable.fromWeb can consume it.@@ -250,7 +250,7 @@ describe('installFromCivitai', () => {});it('refuses to install non-LoRA model types', async () => {- const fetchImpl = async () => ({ ok: true, status: 200, json: async () => ({ ...FAKE_MODEL, type: 'Checkpoint' }) });+ const fetchImpl = async () => ({ ok: true, status: 200, text: async () => JSON.stringify(({ ...FAKE_MODEL, type: 'Checkpoint' }) )});await expect(lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),).rejects.toThrow(/not a LoRA/);@@ -261,7 +261,7 @@ describe('installFromCivitai', () => {// / lower-case variants are all the same family from diffusers' POV.const fetchImpl = async (url) => {if (url.startsWith('https://civitai.com/api/v1/models/')) {- return { ok: true, status: 200, json: async () => ({ ...FAKE_MODEL, type: 'DoRA' }) };+ return { ok: true, status: 200, text: async () => JSON.stringify(({ ...FAKE_MODEL, type: 'DoRA' }) )};}const stream = new ReadableStream({ start(c) { c.enqueue(new Uint8Array(Buffer.from('w'))); c.close(); } });return { ok: true, status: 200, body: stream };@@ -275,7 +275,7 @@ describe('installFromCivitai', () => {await fs.mkdir(tmpLoras, { recursive: true });await fs.writeFile(join(tmpLoras, 'lora-realstagram-v7.safetensors'), 'pre-existing');const fetchImpl = async (url) => {- if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, text: async () => JSON.stringify(FAKE_MODEL )};throw new Error(`should not download: ${url}`);};await expect(@@ -285,7 +285,7 @@ describe('installFromCivitai', () => {it('surfaces a friendly auth error when download is gated (no key)', async () => {const fetchImpl = async (url) => {- if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, text: async () => JSON.stringify(FAKE_MODEL )};return { ok: false, status: 401, statusText: 'Unauthorized' };};await expect(@@ -295,7 +295,7 @@ describe('installFromCivitai', () => {it('surfaces a different auth error message when a key was provided but download still fails', async () => {const fetchImpl = async (url) => {- if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, text: async () => JSON.stringify(FAKE_MODEL )};return { ok: false, status: 403, statusText: 'Forbidden' };};// Provide apiKey inline so hasApiKey=true@@ -317,7 +317,7 @@ describe('installFromCivitai', () => {const destFilename = 'lora-realstagram-v7.safetensors';const fetchImpl = async (url) => {- if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, json: async () => FAKE_MODEL };+ if (url.startsWith('https://civitai.com/api/v1/models/')) return { ok: true, status: 200, text: async () => JSON.stringify(FAKE_MODEL )};if (url.startsWith('https://civitai.com/api/download/models/7')) {// Plant the dest file to simulate a concurrent install winning before// our link() call — this is what makes link() return EEXIST.diff --git a/server/services/memoryClassifier.js b/server/services/memoryClassifier.jsindex 7edba194ba..43618e50d0 100644--- a/server/services/memoryClassifier.js+++ b/server/services/memoryClassifier.js@@ -11,6 +11,7 @@ import { join } from 'path';import { getStageTemplate } from './promptService.js';import { ensureDir, safeJSONParse, PATHS } from '../lib/fileUtils.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { readResponseJson } from '../lib/readResponseJson.js';import { getMemories } from './memoryBackend.js';const MODEL_LIST_TIMEOUT_MS = 5000;@@ -196,7 +197,7 @@ async function ensureLLMModelLoaded(config) {if (!listResponse?.ok) return null;- const payload = await listResponse.json().catch(() => null);+ const payload = await readResponseJson(listResponse);const allModels = payload?.data || [];const llmModels = allModels.filter(m => m.type === 'llm');@@ -271,7 +272,7 @@ async function callLLM(prompt, config) {throw new Error(`LLM API error ${response.status}: ${error}`);}- const data = await response.json();+ const data = await readResponseJson(response);return data.choices?.[0]?.message?.content || '';}diff --git a/server/services/messageApiSync.js b/server/services/messageApiSync.jsindex 8084abc006..c27cdf5a1e 100644--- a/server/services/messageApiSync.js+++ b/server/services/messageApiSync.js@@ -7,6 +7,7 @@import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { readResponseJson } from '../lib/readResponseJson.js';import { getToken, clearTokenCache } from './messageTokenExtractor.js';const GRAPH_API_TIMEOUT_MS = 30000;@@ -71,7 +72,7 @@ export async function syncOutlookApi(account, cache, io, options = {}) {return { messages: [], status: 'api-error' };}- const data = await response.json();+ const data = await readResponseJson(response);const items = data.value || [];for (const m of items) {