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
refactor([insights-callprovider-nonjson-test]): consolidate fetch-Response test mocks onto shared helper
[._.]/ Adam Eivy47debe281efd
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex d0582adaa0..dc1d521f28 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -36,7 +36,7 @@- **[cos-on-demand-mark-app-review-started-dedupe]** When several on-demand improvement requests for the same app are processed in one CoS dispatch cycle, the app's activity record is now marked review-started once instead of once per request (no user-facing change).- **[shared-tolerant-fetch-json-helper]** Hardened the HTTP clients that talk to local model backends, the managed browser, and the background agent runner: a non-JSON/HTML error response now surfaces the real error instead of crashing with "Unexpected token <", via one shared tolerant JSON-body reader (no user-facing change).- **[tolerant-fetch-json-additional-clients]** Extended that same tolerant JSON-body reader to the remaining fetch clients (calendar/message sync, the memory and insights LLM calls, the local-LLM playground, Civitai, Telegram, and the code-review runner), so a non-JSON/HTML error body surfaces the real error instead of crashing — and the code-review runner now reports the server's actual error text instead of a misleading "no content" (no user-facing change).-- **[insights-callprovider-nonjson-test]** Added regression-test coverage pinning the insights LLM client's non-JSON-error guard so a malformed provider response can't silently overwrite the cached cross-domain narrative or theme analysis (no user-facing change).+- **[insights-callprovider-nonjson-test]** Added regression-test coverage pinning the insights LLM client's non-JSON-error guard so a malformed provider response can't silently overwrite the cached cross-domain narrative or theme analysis, and consolidated the hand-rolled fetch-`Response` test mocks across the server suites onto one shared helper (no user-facing change).- **[cos-agent-output-write-amplification] Streamed CoS agent output no longer rewrites the entire agent-state file once per line.** A shared ~250ms output batcher now coalesces the runner's per-line output events and direct-CLI stdout/stderr into single state writes (draining before an agent is marked complete), cutting agent-state write churn on chatty agents from dozens of writes/sec to a few — with no change to the live output tail (no user-facing change).- **[subagent-spawner-top-level-side-effects]** The CoS agent spawner now initializes explicitly at server startup instead of as a side effect of being imported, so importing it (in tests or elsewhere) no longer re-arms its event listeners and timers (no user-facing change).diff --git a/PLAN.md b/PLAN.mdindex 3655944819..cd3c073c47 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,7 +6,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changelClaimable, well-specified, no decision needed — `/claim`-able. Unordered.-- [ ] [shared-fetch-response-test-mock] **Extract a shared fetch-`Response` mock helper for the server test suites.** The `const okResponse = (body) => ({ ok: true, status: 200, text: async () => body })` (and `json:`-style variants) is now hand-rolled inline across several server tests — `insightsService.test.js`, `calendarApiSync.test.js`, `messageApiSync.test.js`, `codeReview.test.js`, `civitai.test.js`, `civitaiSuggestions.test.js`, `loras.test.js`, `localLlmPlayground.test.js` — and `cosRunnerClient.test.js` already defines a `mockResponse(ok, data)`. Promote one `mockJsonResponse({ ok, status, body })` / `mockTextResponse(...)` helper (a test-utils module the suites import) and migrate the inline copies so a future `readResponseJson`-style change to the body-read mechanism is a one-file edit, not N. Surfaced repeatedly by /simplify reuse review across the tolerant-fetch-json PRs (2026-06-01).- [ ] [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.- [ ] [conflict-journal-issues] **Issue-level conflict journaling.** The share-bucket importer hook (`server/services/sharing/importer.js` `applyAutoMerge`→`mergeOne`) is gated to `universe`/`series`; child issues ride LWW silently. Extend the journal to issues (needs the issue merge path to thread a `source` + call `maybeJournalBeforeOverwrite`).- [ ] [conflict-journal-deep-diff] **`diffSummary` is top-level shallow only.** `conflictJournal.diffSummary` compares top-level fields via canonicalStringify, so the UI shows "categories differ" rather than which variation/canon entry changed. Add per-field deep diffing for richer InlineDiff rendering in the Conflicts tab.diff --git a/server/lib/README.md b/server/lib/README.mdindex 38c6b2988f..86a0c54ff0 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -198,4 +198,4 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|| `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. |-| `testHelper.js` | Test HTTP request helper. |+| `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`). |diff --git a/server/lib/civitai.test.js b/server/lib/civitai.test.jsindex bcefd76101..c307476c62 100644--- a/server/lib/civitai.test.js+++ b/server/lib/civitai.test.js@@ -1,4 +1,5 @@import { describe, it, expect } from 'vitest';+import { mockJsonResponse } from './testHelper.js';import {applyDownloadToken,baseModelToRunner,@@ -267,7 +268,7 @@ describe('fetchCivitaiModel', () => {calledUrl = url;expect(opts.headers.Accept).toBe('application/json');expect(opts.headers.Authorization).toBe('Bearer k');- return { ok: true, status: 200, text: async () => JSON.stringify({ id: 1, name: 'X' }) };+ return mockJsonResponse({ id: 1, name: 'X' });};const out = await fetchCivitaiModel('123', { apiKey: 'k', fetchImpl });expect(calledUrl).toBe('https://civitai.com/api/v1/models/123');@@ -283,7 +284,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, text: async () => '{}' }; };+ const fetchImpl = async () => { called = true; return mockJsonResponse({}); };await expect(fetchCivitaiModel('abc', { fetchImpl })).rejects.toThrow(/Invalid Civitai model id/);expect(called).toBe(false);});diff --git a/server/lib/testHelper.js b/server/lib/testHelper.jsindex 0443537131..2302756d29 100644--- a/server/lib/testHelper.js+++ b/server/lib/testHelper.js@@ -98,3 +98,32 @@ export function request(app) {patch: (path) => new RequestBuilder(app, 'PATCH', path),};}++/**+ * Mock a fetch `Response` whose body is read via `.text()` — the read path used+ * by `readResponseJson` and every fetch-based client. Use this for the common+ * case of a JSON body: pass the value, it's serialized into `text()`.+ *+ * fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [] }));+ *+ * @param {*} body - serialized into the response body via JSON.stringify+ * @param {{ ok?: boolean, status?: number }} [opts]+ */+export function mockJsonResponse(body, { ok = true, status = 200 } = {}) {+ const text = JSON.stringify(body);+ return { ok, status, text: async () => text };+}++/**+ * Mock a fetch `Response` with a raw-string body read via `.text()` — for+ * non-JSON / HTML / blank bodies (the masquerade cases) and error text.+ *+ * fetchWithTimeout.mockResolvedValue(mockTextResponse('<html>502</html>'));+ * fetchWithTimeout.mockResolvedValue(mockTextResponse('boom', { ok: false, status: 500 }));+ *+ * @param {string} [body] - returned verbatim by `text()`+ * @param {{ ok?: boolean, status?: number }} [opts]+ */+export function mockTextResponse(body = '', { ok = true, status = 200 } = {}) {+ return { ok, status, text: async () => body };+}diff --git a/server/services/calendarApiSync.test.js b/server/services/calendarApiSync.test.jsindex bacbd599dd..b7930bc9d4 100644--- a/server/services/calendarApiSync.test.js+++ b/server/services/calendarApiSync.test.js@@ -11,10 +11,10 @@ vi.mock('../lib/fetchWithTimeout.js', () => ({import { getToken } from './messageTokenExtractor.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js';import { syncOutlookCalendarApi } from './calendarApiSync.js';const ACCOUNT = { id: 'acc-1', email: '[email protected]' };-const okResponse = (body) => ({ ok: true, status: 200, text: async () => body });describe('syncOutlookCalendarApi — malformed-body masquerade guard', () => {beforeEach(() => {@@ -27,13 +27,13 @@ describe('syncOutlookCalendarApi — malformed-body masquerade guard', () => {// event absent from a "success" fetch — so a transient HTML error page would// wipe the calendar cache. It must surface as api-error (no prune) instead.it('returns api-error (not empty success) on a non-JSON 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse('<html><body>502 Bad Gateway</body></html>'));+ fetchWithTimeout.mockResolvedValue(mockTextResponse('<html><body>502 Bad Gateway</body></html>'));const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);expect(result).toEqual({ events: [], status: 'api-error' });});it('returns api-error on a blank 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(''));+ fetchWithTimeout.mockResolvedValue(mockTextResponse(''));const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);expect(result.status).toBe('api-error');});@@ -41,14 +41,14 @@ describe('syncOutlookCalendarApi — malformed-body masquerade guard', () => {// A legitimately-empty calendar still reports success (so the reconcile can// prune correctly) — the guard must not conflate valid-empty with malformed.it('still reports success for a valid empty { value: [] } body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [] }));const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);expect(result.status).toBe('success');expect(result.events).toEqual([]);});it('parses events from a valid populated body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [{ Id: 'evt-1', Subject: 'Standup' }] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [{ Id: 'evt-1', Subject: 'Standup' }] }));const result = await syncOutlookCalendarApi(ACCOUNT, { events: [] }, null);expect(result.status).toBe('success');expect(result.events).toHaveLength(1);diff --git a/server/services/civitaiSuggestions.test.js b/server/services/civitaiSuggestions.test.jsindex 9ce7b3932e..1aa01759a2 100644--- a/server/services/civitaiSuggestions.test.js+++ b/server/services/civitaiSuggestions.test.js@@ -1,4 +1,5 @@import { describe, it, expect, beforeEach, vi } from 'vitest';+import { mockJsonResponse } from '../lib/testHelper.js';let svc;@@ -33,12 +34,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, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated-${m[1]}`, 'Flux.1 D'))};+ if (m) return mockJsonResponse(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, text: async () => JSON.stringify({ items })};+ return mockJsonResponse({ items });};const out = await svc.getSuggestions({ fetchImpl, limit: 5 });expect(Array.isArray(out.curated)).toBe(true);@@ -61,9 +62,9 @@ describe('getSuggestions', () => {calls += 1;// First curated call 404s; rest succeed.if (calls === 1) return { ok: false, status: 404 };- return { ok: true, status: 200, text: async () => JSON.stringify(buildModel(Number(m[1]), `Ok-${m[1]}`, 'Flux.1 D'))};+ return mockJsonResponse(buildModel(Number(m[1]), `Ok-${m[1]}`, 'Flux.1 D'));}- return { ok: true, status: 200, text: async () => JSON.stringify({ items: [buildModel(9999, 'Search', 'Flux.1 D')] })};+ return mockJsonResponse({ 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 +77,8 @@ describe('getSuggestions', () => {const fetchImpl = async (url) => {calls += 1;const m = url.match(/api\/v1\/models\/(\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')] })};+ if (m) return mockJsonResponse(buildModel(Number(m[1]), `Curated`, 'Flux.1 D'));+ return mockJsonResponse({ items: [buildModel(1, 'Cached', 'Flux.1 D')] });};await svc.getSuggestions({ fetchImpl });const callsAfterFirst = calls;@@ -93,9 +94,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, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated`, 'Flux.1 D'))};+ if (m) return mockJsonResponse(buildModel(Number(m[1]), `Curated`, 'Flux.1 D'));fetchCalls += 1;- return { ok: true, status: 200, text: async () => JSON.stringify({ items: makeItems(24) })};+ return mockJsonResponse({ items: makeItems(24) });};// First call uses limit=4 — cache is populated at MAX (24 entries).@@ -117,9 +118,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, text: async () => JSON.stringify(buildModel(Number(m[1]), `Curated`, 'Flux.1 D'))};+ if (m) return mockJsonResponse(buildModel(Number(m[1]), `Curated`, 'Flux.1 D'));fetchCalls += 1;- return { ok: true, status: 200, text: async () => JSON.stringify({ items: makeItems(24) })};+ return mockJsonResponse({ items: makeItems(24) });};// First call: limit=24 — populates cache with 24 cards.@@ -141,8 +142,8 @@ describe('getSuggestions', () => {const fetchImpl = async (url) => {calls += 1;const m = url.match(/api\/v1\/models\/(\d+)$/);- 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: [] })};+ if (m) return mockJsonResponse(buildModel(Number(m[1]), `C`, 'Flux.1 D'));+ return mockJsonResponse({ items: [] });};await svc.getSuggestions({ fetchImpl });const callsAfterFirst = calls;@@ -155,26 +156,22 @@ describe('getSuggestions', () => {const m = url.match(/api\/v1\/models\/(\d+)$/);if (m) {const id = Number(m[1]);- return {- ok: true,- status: 200,- text: async () => JSON.stringify({- ...buildModel(id, 'Multi', 'Flux.1 D'),- modelVersions: [- // Most recent (first) per family wins. Two flux2 versions —- // only the first should be in installs.flux2.- { id: 100, baseModel: 'Flux.2', files: [{ name: 'a.safetensors', primary: true, sizeKB: 1024 }] },- { id: 99, baseModel: 'Flux.2', files: [{ name: 'older.safetensors', primary: true, sizeKB: 900 }] },- { id: 80, baseModel: 'Z-Image', files: [{ name: 'z.safetensors', primary: true, sizeKB: 800 }] },- { id: 70, baseModel: 'Ernie-Image', files: [{ name: 'e.safetensors', primary: true, sizeKB: 700 }] },- { id: 60, baseModel: 'Flux.1 D', files: [{ name: 'f1.safetensors', primary: true, sizeKB: 600 }] },- // Unsupported base — shouldn't appear in installs- { id: 50, baseModel: 'SDXL 1.0', files: [{ name: 's.safetensors', primary: true, sizeKB: 500 }] },- ],- }),- };+ return mockJsonResponse({+ ...buildModel(id, 'Multi', 'Flux.1 D'),+ modelVersions: [+ // Most recent (first) per family wins. Two flux2 versions —+ // only the first should be in installs.flux2.+ { id: 100, baseModel: 'Flux.2', files: [{ name: 'a.safetensors', primary: true, sizeKB: 1024 }] },+ { id: 99, baseModel: 'Flux.2', files: [{ name: 'older.safetensors', primary: true, sizeKB: 900 }] },+ { id: 80, baseModel: 'Z-Image', files: [{ name: 'z.safetensors', primary: true, sizeKB: 800 }] },+ { id: 70, baseModel: 'Ernie-Image', files: [{ name: 'e.safetensors', primary: true, sizeKB: 700 }] },+ { id: 60, baseModel: 'Flux.1 D', files: [{ name: 'f1.safetensors', primary: true, sizeKB: 600 }] },+ // 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, text: async () => JSON.stringify({ items: [] })};+ return mockJsonResponse({ items: [] });};const out = await svc.getSuggestions({ fetchImpl });const card = out.curated[0];@@ -195,19 +192,15 @@ describe('getSuggestions', () => {if (m) {// Multi-version model — Flux.1 D + Flux.2.const id = Number(m[1]);- return {- ok: true,- status: 200,- 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 mockJsonResponse({+ ...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, text: async () => JSON.stringify({ items: [] })};+ return mockJsonResponse({ items: [] });};const out = await svc.getSuggestions({ fetchImpl });const card = out.curated[0];diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsindex 7574bbc9a1..0d4195542b 100644--- a/server/services/codeReview.test.js+++ b/server/services/codeReview.test.js@@ -16,6 +16,7 @@ vi.mock('./settings.js', () => ({vi.mock('./lmStudioManager.js', () => ({ getBaseUrl: () => 'http://localhost:1234' }))vi.mock('./ollamaManager.js', () => ({ getBaseUrl: () => 'http://localhost:11434' }))+import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js'import {isLocalLlmReviewer,pickCodeReviewDefaults,@@ -126,11 +127,7 @@ describe('codeReview helpers', () => {beforeEach(() => {// Default fetch mock — chat-completions success with a static body. Each// test that wants a different shape replaces this in its own setup.- global.fetch = vi.fn().mockResolvedValue({- ok: true,- status: 200,- text: () => Promise.resolve(JSON.stringify({ choices: [{ message: { content: 'No findings.' } }] })),- })+ global.fetch = vi.fn().mockResolvedValue(mockJsonResponse({ choices: [{ message: { content: 'No findings.' } }] }))})it('rejects unsupported reviewer backends', async () => {@@ -168,11 +165,7 @@ describe('codeReview helpers', () => {})it('surfaces a non-2xx HTTP error with the status code', async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: false,- status: 500,- text: () => Promise.resolve('boom'),- })+ global.fetch = vi.fn().mockResolvedValue(mockTextResponse('boom', { ok: false, status: 500 }))const r = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: 'x' })expect(r.ok).toBe(false)expect(r.error).toMatch(/lmstudio API error 500: boom/)@@ -186,22 +179,14 @@ describe('codeReview helpers', () => {})it('flags an empty model response so the agent never silently records "no findings"', async () => {- global.fetch = vi.fn().mockResolvedValue({- ok: true,- status: 200,- text: () => Promise.resolve(JSON.stringify({ choices: [{ message: { content: '' } }] })),- })+ global.fetch = vi.fn().mockResolvedValue(mockJsonResponse({ 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>'),- })+ global.fetch = vi.fn().mockResolvedValue(mockTextResponse('<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/)diff --git a/server/services/insightsService.test.js b/server/services/insightsService.test.jsindex efebba9415..2a98d9faf1 100644--- a/server/services/insightsService.test.js+++ b/server/services/insightsService.test.js@@ -9,10 +9,10 @@ vi.mock('../lib/fetchWithTimeout.js', () => ({}));import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js';import { callProviderAISimple } from './insightsService.js';const PROVIDER = { type: 'api', endpoint: 'http://localhost:1234/v1' };-const okResponse = (body) => ({ ok: true, status: 200, text: async () => body });describe('insightsService.callProviderAISimple — non-JSON-body guard', () => {beforeEach(() => {@@ -25,14 +25,14 @@ describe('insightsService.callProviderAISimple — non-JSON-body guard', () => {// It must surface as { error } so the `if (result.error) return` guard bails// before any write.it('returns { error } (not empty success) on a non-JSON 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse('<html><body>502 Bad Gateway</body></html>'));+ fetchWithTimeout.mockResolvedValue(mockTextResponse('<html><body>502 Bad Gateway</body></html>'));const result = await callProviderAISimple(PROVIDER, 'm', 'prompt');expect(result.text).toBeUndefined();expect(result.error).toMatch(/non-JSON response/);});it('returns { error } on a blank 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(''));+ fetchWithTimeout.mockResolvedValue(mockTextResponse(''));const result = await callProviderAISimple(PROVIDER, 'm', 'prompt');expect(result.error).toMatch(/non-JSON response/);});@@ -41,19 +41,19 @@ describe('insightsService.callProviderAISimple — non-JSON-body guard', () => {// still flow through as { text: '' } — the guard must not conflate valid-empty// with a parse failure.it('returns { text: "" } for a valid body with empty content', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ choices: [{ message: { content: '' } }] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ choices: [{ message: { content: '' } }] }));const result = await callProviderAISimple(PROVIDER, 'm', 'prompt');expect(result).toEqual({ text: '' });});it('returns the content for a valid populated body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ choices: [{ message: { content: 'hello' } }] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ choices: [{ message: { content: 'hello' } }] }));const result = await callProviderAISimple(PROVIDER, 'm', 'prompt');expect(result).toEqual({ text: 'hello' });});it('returns { error } with the status code on a non-2xx response', async () => {- fetchWithTimeout.mockResolvedValue({ ok: false, status: 500, text: async () => 'boom' });+ fetchWithTimeout.mockResolvedValue(mockTextResponse('boom', { ok: false, status: 500 }));const result = await callProviderAISimple(PROVIDER, 'm', 'prompt');expect(result.error).toMatch(/Provider returned 500: boom/);});diff --git a/server/services/loras.test.js b/server/services/loras.test.jsindex 56513b2cce..f8b82ef7e4 100644--- a/server/services/loras.test.js+++ b/server/services/loras.test.js@@ -1,4 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import { mockJsonResponse } from '../lib/testHelper.js';import { existsSync, mkdtempSync, rmSync, writeFileSync, readFileSync } from 'fs';import { tmpdir } from 'os';import { join } from 'path';@@ -220,7 +221,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, text: async () => JSON.stringify(FAKE_MODEL)};+ return mockJsonResponse(FAKE_MODEL);}if (url.startsWith('https://civitai.com/api/download/models/7')) {// Return a Web ReadableStream so Readable.fromWeb can consume it.@@ -250,7 +251,7 @@ describe('installFromCivitai', () => {});it('refuses to install non-LoRA model types', async () => {- const fetchImpl = async () => ({ ok: true, status: 200, text: async () => JSON.stringify({ ...FAKE_MODEL, type: 'Checkpoint' })});+ const fetchImpl = async () => (mockJsonResponse({ ...FAKE_MODEL, type: 'Checkpoint' }));await expect(lorasService.installFromCivitai({ url: 'https://civitai.com/models/2600698' }, { fetchImpl }),).rejects.toThrow(/not a LoRA/);@@ -261,7 +262,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, text: async () => JSON.stringify({ ...FAKE_MODEL, type: 'DoRA' })};+ return mockJsonResponse({ ...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 +276,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, text: async () => JSON.stringify(FAKE_MODEL)};+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(FAKE_MODEL);throw new Error(`should not download: ${url}`);};await expect(@@ -285,7 +286,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, text: async () => JSON.stringify(FAKE_MODEL)};+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(FAKE_MODEL);return { ok: false, status: 401, statusText: 'Unauthorized' };};await expect(@@ -295,7 +296,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, text: async () => JSON.stringify(FAKE_MODEL)};+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(FAKE_MODEL);return { ok: false, status: 403, statusText: 'Forbidden' };};// Provide apiKey inline so hasApiKey=true@@ -317,7 +318,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, text: async () => JSON.stringify(FAKE_MODEL)};+ if (url.startsWith('https://civitai.com/api/v1/models/')) return mockJsonResponse(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/messageApiSync.test.js b/server/services/messageApiSync.test.jsindex 3d9bdc06ba..388de5835e 100644--- a/server/services/messageApiSync.test.js+++ b/server/services/messageApiSync.test.js@@ -11,10 +11,10 @@ vi.mock('../lib/fetchWithTimeout.js', () => ({import { getToken } from './messageTokenExtractor.js';import { fetchWithTimeout } from '../lib/fetchWithTimeout.js';+import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js';import { syncOutlookApi } from './messageApiSync.js';const ACCOUNT = { id: 'acc-1', email: '[email protected]' };-const okResponse = (body) => ({ ok: true, status: 200, text: async () => body });describe('syncOutlookApi — malformed-body masquerade guard', () => {beforeEach(() => {@@ -27,27 +27,27 @@ describe('syncOutlookApi — malformed-body masquerade guard', () => {// Playwright fallback in messageSync.js (and mid-pagination would prune still// -valid cached messages). It must return null to preserve the fallback.it('returns null (triggering the Playwright fallback) on a non-JSON 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse('<html><body>502 Bad Gateway</body></html>'));+ fetchWithTimeout.mockResolvedValue(mockTextResponse('<html><body>502 Bad Gateway</body></html>'));const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });expect(result).toBeNull();});it('returns null on a blank 200 body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(''));+ fetchWithTimeout.mockResolvedValue(mockTextResponse(''));const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });expect(result).toBeNull();});// A legitimately-empty inbox still reports success (no spurious fallback).it('still reports success for a valid empty { value: [] } body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [] }));const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'full' });expect(result.status).toBe('success');expect(result.messages).toEqual([]);});it('parses messages from a valid populated body', async () => {- fetchWithTimeout.mockResolvedValue(okResponse(JSON.stringify({ value: [{ Id: 'msg-1', Subject: 'Hello' }] })));+ fetchWithTimeout.mockResolvedValue(mockJsonResponse({ value: [{ Id: 'msg-1', Subject: 'Hello' }] }));const result = await syncOutlookApi(ACCOUNT, { messages: [] }, null, { mode: 'unread' });expect(result.status).toBe('success');expect(result.messages).toHaveLength(1);