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

Centralize the streaming-wrapper error envelope into apiCore.throwApiError (#5047)

Bryandero98814fd3f14dce
diff --git a/client/src/services/apiCore.js b/client/src/services/apiCore.js
index 9ef835b9ef..93b2e9e6c7 100644
--- a/client/src/services/apiCore.js
+++ b/client/src/services/apiCore.js
@@ -21,6 +21,28 @@ export function maybeRedirectToLogin(response, error) {
}
}
+// Shared `!response.ok` envelope: parse the server's JSON error body, bounce to
+// /login on session expiry, and throw an Error carrying `.code`/`.status`/
+// `.context` from the response. Toasting is NOT done here — request() does its
+// own (with `silent` support); the streaming/blob callers that bypass request()
+// to read a raw Response deliberately surface their own errors instead.
+export async function throwApiError(response) {
+ const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ // Auth gate (server: services/authGate.js) returns 401 with code AUTH_REQUIRED
+ // for any /api request without a valid session. Bounce to /login so the
+ // user can re-authenticate; skip if we're already there.
+ maybeRedirectToLogin(response, error);
+ const err = new Error(error.error || `HTTP ${response.status}`);
+ err.code = error?.code;
+ err.status = response.status;
+ // Forward structured context the server attached to the error (e.g.
+ // ERR_PARTIAL_COMMIT_ISSUES carries `{ universeId, seriesId,
+ // arcAlreadyPersisted, skipArcOnRetry }` so the Importer client can
+ // shape its retry without re-overwriting persisted state).
+ if (error?.context) err.context = error.context;
+ throw err;
+}
+
export async function request(endpoint, options = {}) {
const { silent, responseType, ...fetchOptions } = options;
const url = `${API_BASE}${endpoint}`;
@@ -45,29 +67,19 @@ export async function request(endpoint, options = {}) {
}
if (!response.ok) {
- const error = await response.json().catch(() => ({ error: 'Request failed' }));
- const errorMessage = error.error || `HTTP ${response.status}`;
- // Auth gate (server: services/authGate.js) returns 401 with code AUTH_REQUIRED
- // for any /api request without a valid session. Bounce to /login so the
- // user can re-authenticate; skip if we're already there.
- maybeRedirectToLogin(response, error);
- if (!silent) {
- // Platform unavailability is a warning, not an error
- if (error.code === 'PLATFORM_UNAVAILABLE') {
- toast(errorMessage, { icon: '⚠️' });
- } else if (error.code !== 'AUTH_REQUIRED') {
- toast.error(errorMessage);
+ try {
+ await throwApiError(response);
+ } catch (err) {
+ if (!silent) {
+ // Platform unavailability is a warning, not an error
+ if (err.code === 'PLATFORM_UNAVAILABLE') {
+ toast(err.message, { icon: '⚠️' });
+ } else if (err.code !== 'AUTH_REQUIRED') {
+ toast.error(err.message);
+ }
}
+ throw err;
}
- const err = new Error(errorMessage);
- err.code = error?.code;
- err.status = response.status;
- // Forward structured context the server attached to the error (e.g.
- // ERR_PARTIAL_COMMIT_ISSUES carries `{ universeId, seriesId,
- // arcAlreadyPersisted, skipArcOnRetry }` so the Importer client can
- // shape its retry without re-overwriting persisted state).
- if (error?.context) err.context = error.context;
- throw err;
}
// Handle 204 No Content
diff --git a/client/src/services/apiCore.test.js b/client/src/services/apiCore.test.js
new file mode 100644
index 0000000000..c81deaa9e7
--- /dev/null
+++ b/client/src/services/apiCore.test.js
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// The real Toast default export is callable (`toast(msg, opts)`) AND carries
+// `.error`/`.success`/etc, mirroring react-hot-toast's API — a plain object
+// mock would make request()'s `toast(err.message, { icon })` call throw.
+vi.mock('../components/ui/Toast', () => {
+ const toastFn = vi.fn();
+ toastFn.error = vi.fn();
+ toastFn.success = vi.fn();
+ return { default: toastFn };
+});
+
+import toast from '../components/ui/Toast';
+import { throwApiError, request } from './apiCore.js';
+
+const makeResponse = ({ status = 400, ok = false, json = null } = {}) => ({
+ status,
+ ok,
+ json: json === null ? async () => { throw new Error('not json'); } : async () => json,
+});
+
+beforeEach(() => {
+ global.fetch = vi.fn();
+ toast.mockReset();
+ toast.error.mockReset();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('throwApiError', () => {
+ it('throws with the server message, code, and status', async () => {
+ const response = makeResponse({ status: 404, json: { error: 'not found', code: 'NOT_FOUND' } });
+ await expect(throwApiError(response)).rejects.toMatchObject({
+ message: 'not found',
+ code: 'NOT_FOUND',
+ status: 404,
+ });
+ });
+
+ it('forwards structured error.context onto the thrown error', async () => {
+ const context = { universeId: 'u1', seriesId: 's1', arcAlreadyPersisted: true };
+ const response = makeResponse({
+ status: 409,
+ json: { error: 'partial commit', code: 'ERR_PARTIAL_COMMIT_ISSUES', context },
+ });
+ await expect(throwApiError(response)).rejects.toMatchObject({ context });
+ });
+
+ it('omits context when the server did not send any', async () => {
+ const response = makeResponse({ status: 500, json: { error: 'boom' } });
+ try {
+ await throwApiError(response);
+ throw new Error('expected throwApiError to throw');
+ } catch (err) {
+ expect(err.context).toBeUndefined();
+ }
+ });
+
+ it('falls back to an HTTP-status message when the body is not JSON', async () => {
+ const response = makeResponse({ status: 502 }); // json:null → makeResponse's json() rejects
+ await expect(throwApiError(response)).rejects.toMatchObject({ message: 'HTTP 502' });
+ });
+});
+
+describe('request() error path (now delegating to throwApiError)', () => {
+ it('rejects with the same shape throwApiError produces, context included', async () => {
+ const context = { retryable: false };
+ global.fetch.mockResolvedValue(
+ makeResponse({ status: 422, json: { error: 'bad input', code: 'VALIDATION', context } }),
+ );
+ await expect(request('/x')).rejects.toMatchObject({ code: 'VALIDATION', status: 422, context });
+ expect(toast.error).toHaveBeenCalledWith('bad input');
+ });
+
+ it('does not toast for PLATFORM_UNAVAILABLE errors (warns instead)', async () => {
+ global.fetch.mockResolvedValue(
+ makeResponse({ status: 503, json: { error: 'offline', code: 'PLATFORM_UNAVAILABLE' } }),
+ );
+ await expect(request('/x')).rejects.toMatchObject({ code: 'PLATFORM_UNAVAILABLE' });
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+
+ it('stays silent when { silent: true } is passed', async () => {
+ global.fetch.mockResolvedValue(makeResponse({ status: 500, json: { error: 'boom' } }));
+ await expect(request('/x', { silent: true })).rejects.toMatchObject({ status: 500 });
+ expect(toast.error).not.toHaveBeenCalled();
+ });
+});
diff --git a/client/src/services/apiImageVideo.js b/client/src/services/apiImageVideo.js
index 875f7f8e8b..f2431889b1 100644
--- a/client/src/services/apiImageVideo.js
+++ b/client/src/services/apiImageVideo.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
+import { request, API_BASE, throwApiError } from './apiCore.js';
import { filterHardwareCompatibleModels } from '../utils/systemCapabilities.js';
// Image gen — local backend extras (gallery, models, LoRAs, cancel, delete).
@@ -481,7 +481,7 @@ export const installLoraFromHuggingface = ({ url, family, file, silent = false }
// cross-origin navigation; (2) EventSource auto-reconnects on any transport
// drop, which for this NON-idempotent install would silently start a second
// multi-GB download — a single fetch never retries; (3) it honors session expiry
-// — a 401 AUTH_REQUIRED bounces to /login via maybeRedirectToLogin exactly like
+// — a 401 AUTH_REQUIRED bounces to /login via throwApiError exactly like
// request(), instead of dead-ending on a generic stream error. Frames are
// SSE-encoded (`data: {json}\n\n`).
export async function installLoraFromHuggingfaceStream({ url, family, file, onProgress, signal } = {}) {
@@ -492,11 +492,7 @@ export async function installLoraFromHuggingfaceStream({ url, family, file, onPr
signal,
});
if (!response.ok || !response.body?.getReader) {
- const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
- maybeRedirectToLogin(response, err);
- const e = new Error(err.error || `HTTP ${response.status}`);
- e.code = err.code || null;
- throw e;
+ await throwApiError(response);
}
const reader = response.body.getReader();
diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.js
index 674594946d..3804a79dc6 100644
--- a/client/src/services/apiLocalLlm.js
+++ b/client/src/services/apiLocalLlm.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
+import { request, API_BASE, throwApiError } from './apiCore.js';
// Local LLM backends (Ollama / LM Studio) — status, model management, migrate.
// Installed models per backend come back inside getLocalLlmStatus().
@@ -185,11 +185,9 @@ export async function streamLocalLlmTest(payload, { signal, onToken } = {}) {
signal,
});
if (!response.ok || !response.body?.getReader) {
- const err = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
// Honor session expiry the same way request() does — a streaming run that
// 401s should bounce to /login, not just toast and strand the user here.
- maybeRedirectToLogin(response, err);
- throw new Error(err.error || `HTTP ${response.status}`);
+ await throwApiError(response);
}
const reader = response.body.getReader();
diff --git a/client/src/services/apiMedia.js b/client/src/services/apiMedia.js
index 763193c43d..3aedf1cf81 100644
--- a/client/src/services/apiMedia.js
+++ b/client/src/services/apiMedia.js
@@ -1,4 +1,4 @@
-import { request, API_BASE, maybeRedirectToLogin } from './apiCore.js';
+import { request, API_BASE, throwApiError } from './apiCore.js';
import { formatBytes } from '../utils/formatters.js';
import {
validateImageFile,
@@ -319,12 +319,7 @@ export const cleanImage = async (file, steps = {}) => {
if (!response) throw new Error('Server unreachable — check your connection and try again');
if (!response.ok) {
- const error = await response.json().catch(() => ({ error: 'Failed to clean image' }));
- maybeRedirectToLogin(response, error);
- const err = new Error(error.error || `HTTP ${response.status}`);
- err.code = error?.code;
- err.status = response.status;
- throw err;
+ await throwApiError(response);
}
// GPU FLUX round-trip: the server enqueued a job and returned 202 + JSON
@@ -358,11 +353,7 @@ export const fetchCleanResult = async (jobId) => {
throw e;
}
if (!response.ok) {
- const err = await response.json().catch(() => ({ error: 'Failed to fetch clean result' }));
- maybeRedirectToLogin(response, err);
- const e = new Error(err.error || `HTTP ${response.status}`);
- e.code = err?.code; e.status = response.status;
- throw e;
+ await throwApiError(response);
}
const reportHeader = response.headers.get('X-Clean-Report');
let report = null;
diff --git a/client/src/services/apiMedia.test.js b/client/src/services/apiMedia.test.js
index 6494f0fbc4..34c12a1c2f 100644
--- a/client/src/services/apiMedia.test.js
+++ b/client/src/services/apiMedia.test.js
@@ -8,6 +8,17 @@ vi.mock('./apiCore.js', () => ({
request: (...a) => request(...a),
API_BASE: '/api',
maybeRedirectToLogin: vi.fn(),
+ // Mirrors the real apiCore.throwApiError (minus the redirect side effect,
+ // already covered by the maybeRedirectToLogin mock above) so assertions
+ // against `.code`/`.status`/`.context`/message keep working unchanged.
+ throwApiError: vi.fn(async (response) => {
+ const error = await response.json().catch(() => ({ error: `HTTP ${response.status}` }));
+ const err = new Error(error.error || `HTTP ${response.status}`);
+ err.code = error?.code;
+ err.status = response.status;
+ if (error?.context) err.context = error.context;
+ throw err;
+ }),
}));
let cleanImage;