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([issue-760]): standardize route error responses on ServerError
[._.]/ Adam Eivy7a5f85e162bd
diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 2565e850ca..dd84b63cbc 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -49,7 +49,10 @@ export class ServerError extends Error {super(message);this.name = 'ServerError';this.status = options.status || 500;- this.code = options.code || 'INTERNAL_ERROR';+ // Derive the machine-readable code from the HTTP status when the caller+ // didn't pass one explicitly — so `new ServerError(msg, { status: 404 })`+ // emits `NOT_FOUND`, not `INTERNAL_ERROR`. An explicit `code` always wins.+ this.code = options.code || getErrorCode(this.status);this.timestamp = Date.now();this.context = options.context || {};this.severity = options.severity || 'error'; // error, critical, warning@@ -163,7 +166,7 @@ export function normalizeError(err) {/*** Get appropriate error code from HTTP status*/-function getErrorCode(status) {+export function getErrorCode(status) {const codeMap = {400: 'BAD_REQUEST',401: 'UNAUTHORIZED',diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.jsindex 9e50c3f6b9..2c08c2893d 100644--- a/server/lib/errorHandler.test.js+++ b/server/lib/errorHandler.test.js@@ -35,6 +35,18 @@ describe('errorHandler.js', () => {expect(error.context).toEqual({ resource: 'user' });});+ it('should derive code from status when no explicit code is passed', () => {+ expect(new ServerError('nope', { status: 404 }).code).toBe('NOT_FOUND');+ expect(new ServerError('bad', { status: 400 }).code).toBe('BAD_REQUEST');+ expect(new ServerError('conflict', { status: 409 }).code).toBe('CONFLICT');+ expect(new ServerError('down', { status: 503 }).code).toBe('SERVICE_UNAVAILABLE');+ });++ it('should let an explicit code override the status-derived one', () => {+ const error = new ServerError('dup', { status: 409, code: 'DUPLICATE_ENTRY' });+ expect(error.code).toBe('DUPLICATE_ENTRY');+ });+it('should be an instance of Error', () => {const error = new ServerError('Test');expect(error instanceof Error).toBe(true);diff --git a/server/routes/apps.js b/server/routes/apps.jsindex ee3c54225e..1424244878 100644--- a/server/routes/apps.js+++ b/server/routes/apps.js@@ -299,12 +299,12 @@ router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {}if (!iconPath || !await pathExists(iconPath)) {- return res.status(404).json({ error: 'No app icon found' });+ throw new ServerError('No app icon found', { status: 404 });}const contentType = getIconContentType(iconPath);const iconStat = await stat(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));- if (!iconStat) return res.status(404).json({ error: 'No app icon found' });+ if (!iconStat) throw new ServerError('No app icon found', { status: 404 });const etag = `W/"${iconStat.mtimeMs.toString(36)}-${iconStat.size.toString(36)}"`;res.set('Content-Type', contentType);@@ -325,7 +325,7 @@ router.get('/:id/icon', loadApp, asyncHandler(async (req, res) => {}const iconData = await readFile(iconPath).catch(e => e.code === 'ENOENT' ? null : Promise.reject(e));- if (!iconData) return res.status(404).json({ error: 'No app icon found' });+ if (!iconData) throw new ServerError('No app icon found', { status: 404 });res.send(iconData);}));diff --git a/server/routes/avatar.js b/server/routes/avatar.jsindex 80b07eae0a..360057d923 100644--- a/server/routes/avatar.js+++ b/server/routes/avatar.js@@ -2,6 +2,7 @@ import { Router } from 'express';import { existsSync, statSync, createReadStream } from 'fs';import { join } from 'path';import { PATHS } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.js';const router = Router();const AVATAR_PATH = join(PATHS.data, 'avatar', 'model.glb');@@ -30,7 +31,7 @@ router.head('/model.glb', (req, res) => {router.get('/model.glb', (req, res) => {if (!existsSync(AVATAR_PATH)) {- return res.status(404).json({ error: 'No avatar model configured. Drop a GLB at data/avatar/model.glb' });+ throw new ServerError('No avatar model configured. Drop a GLB at data/avatar/model.glb', { status: 404 });}res.set('Content-Type', 'model/gltf-binary');res.set('Cache-Control', 'public, max-age=60');diff --git a/server/routes/backup.js b/server/routes/backup.jsindex ed600fe29c..b3101305c1 100644--- a/server/routes/backup.js+++ b/server/routes/backup.js@@ -1,5 +1,5 @@import { Router } from 'express';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, restoreRequestSchema } from '../lib/validation.js';import * as backup from '../services/backup.js';import { getSettings } from '../services/settings.js';@@ -24,7 +24,7 @@ router.post('/run', asyncHandler(async (req, res) => {const settings = await getSettings();const destPath = settings.backup?.destPath;if (!destPath) {- return res.status(400).json({ error: 'BACKUP_NOT_CONFIGURED', message: 'No backup destination configured in settings' });+ throw new ServerError('No backup destination configured in settings', { status: 400, code: 'BACKUP_NOT_CONFIGURED' });}const excludePaths = settings.backup?.excludePaths || [];const disabledDefaultExcludes = settings.backup?.disabledDefaultExcludes || [];diff --git a/server/routes/backup.test.js b/server/routes/backup.test.jsindex a376870e2b..f564db4bd6 100644--- a/server/routes/backup.test.js+++ b/server/routes/backup.test.js@@ -71,7 +71,9 @@ describe('backup routes', () => {getSettings.mockResolvedValue({ backup: {} });const res = await request(buildApp()).post('/api/backup/run');expect(res.status).toBe(400);- expect(res.body.error).toBe('BACKUP_NOT_CONFIGURED');+ // Standard error envelope: machine code in `code`, human text in `error`.+ expect(res.body.code).toBe('BACKUP_NOT_CONFIGURED');+ expect(res.body.error).toBe('No backup destination configured in settings');expect(backup.runBackup).not.toHaveBeenCalled();});diff --git a/server/routes/browser.js b/server/routes/browser.jsindex e2449ae61e..8f70ccb472 100644--- a/server/routes/browser.js+++ b/server/routes/browser.js@@ -1,6 +1,6 @@import express from 'express';import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { validateChromePath, validateMacAppBundle } from '../lib/browserConfig.js';import { isSafeIngestUrl } from '../lib/catalogValidation.js';@@ -137,7 +137,7 @@ router.get('/pages', asyncHandler(async (req, res) => {router.get('/version', asyncHandler(async (req, res) => {const version = await browserService.getCdpVersion();if (!version) {- return res.status(503).json({ error: 'Browser not reachable' });+ throw new ServerError('Browser not reachable', { status: 503 });}res.json(version);}));@@ -164,7 +164,7 @@ const RISKY_DOWNLOAD_EXTS = new Set(['.html', '.htm', '.svg', '.js', '.mjs', '.x// browser; the listing UI passes ?attachment=1 + HTML5 `download` for save-to-disk.router.get('/downloads/:name', asyncHandler(async (req, res) => {const file = await browserService.resolveDownload(req.params.name);- if (!file) return res.status(404).json({ error: 'File not found' });+ if (!file) throw new ServerError('File not found', { status: 404 });res.set('X-Content-Type-Options', 'nosniff');// Files of the same name can be replaced by a fresh Chrome download; bypass// any aggressive client/intermediary caching so the user always sees current.@@ -184,7 +184,7 @@ router.get('/downloads/:name', asyncHandler(async (req, res) => {// DELETE /api/browser/downloads/:name - Remove a downloaded filerouter.delete('/downloads/:name', asyncHandler(async (req, res) => {const removed = await browserService.deleteDownload(req.params.name);- if (!removed) return res.status(404).json({ error: 'File not found' });+ if (!removed) throw new ServerError('File not found', { status: 404 });console.log(`🗑️ Browser download deleted: ${req.params.name}`);res.json({ success: true });}));diff --git a/server/routes/calendar.js b/server/routes/calendar.jsindex 71b9a0e108..4bd1b3bfc1 100644--- a/server/routes/calendar.js+++ b/server/routes/calendar.js@@ -132,7 +132,7 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {throw new ServerError('Invalid account ID format', { status: 400, code: 'VALIDATION_ERROR' });}const status = await calendarSync.getSyncStatus(req.params.accountId);- if (!status) return res.status(404).json({ error: 'Account not found' });+ if (!status) throw new ServerError('Account not found', { status: 404 });res.json(status);}));@@ -140,7 +140,7 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {router.get('/events', asyncHandler(async (req, res) => {const { accountId, search, startDate, endDate } = req.query;if (accountId && !UUID_RE.test(accountId)) {- return res.status(400).json({ error: 'Invalid accountId format' });+ throw new ServerError('Invalid accountId format', { status: 400 });}const { limit: parsedLimit, offset: parsedOffset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 200 });const result = await calendarSync.getEvents({@@ -156,10 +156,10 @@ router.get('/events', asyncHandler(async (req, res) => {router.get('/events/:accountId/:eventId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid accountId format' });+ throw new ServerError('Invalid accountId format', { status: 400 });}const event = await calendarSync.getEvent(req.params.accountId, req.params.eventId);- if (!event) return res.status(404).json({ error: 'Event not found' });+ if (!event) throw new ServerError('Event not found', { status: 404 });res.json(event);}));@@ -238,7 +238,7 @@ router.post('/google/auth/credentials', asyncHandler(async (req, res) => {router.get('/google/auth/url', asyncHandler(async (req, res) => {const result = await googleAuth.getAuthUrl();- if (result.error) return res.status(400).json({ error: result.error });+ if (result.error) throw new ServerError(result.error, { status: 400 });res.json(result);}));@@ -336,7 +336,12 @@ router.get('/debug/token-status', asyncHandler(async (req, res) => {router.post('/debug/test-token', asyncHandler(async (req, res) => {const provider = 'outlook';const tokenResult = await getToken(provider);- if (tokenResult.error) return res.status(503).json(tokenResult);+ if (tokenResult.error) {+ throw new ServerError(tokenResult.message || tokenResult.error, {+ status: 503,+ context: { reason: tokenResult.error, provider: tokenResult.provider }+ });+ }const decoded = tokenResult.decoded || {};const tokenInfo = {diff --git a/server/routes/codeReview.js b/server/routes/codeReview.jsindex c9df2bb982..01ef240984 100644--- a/server/routes/codeReview.js+++ b/server/routes/codeReview.js@@ -1,6 +1,6 @@import { Router } from 'express'import { z } from 'zod'-import { asyncHandler } from '../lib/errorHandler.js'+import { asyncHandler, ServerError } from '../lib/errorHandler.js'import { validateRequest, LOCAL_LLM_REVIEWERS } from '../lib/validation.js'import { getSettings } from '../services/settings.js'import { runLocalCodeReview, getCodeReviewDefaults } from '../services/codeReview.js'@@ -43,8 +43,10 @@ router.post('/local', asyncHandler(async (req, res) => {timeoutMs: body.timeoutMs,})if (!result.ok) {- res.status(502).json(result)- return+ throw new ServerError(result.error || 'Code review failed', {+ status: 502,+ context: { backend: result.backend, model: result.model }+ })}res.json(result)}))diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.jsindex d3d14fddc2..aac4d4813e 100644--- a/server/routes/codeReview.test.js+++ b/server/routes/codeReview.test.js@@ -117,8 +117,10 @@ describe('POST /api/code-review/local', () => {.send({ backend: 'lmstudio', model: 'm', diff: 'diff --git a b' })expect(res.status).toBe(502)- expect(res.body.ok).toBe(false)+ // Standard error envelope: the failure message lands in `error`, and the+ // reviewer backend/model carry through in `context` for diagnostics.expect(res.body.error).toMatch(/lmstudio API error/)+ expect(res.body.context).toEqual({ backend: 'lmstudio', model: 'm' })})it('returns 200 with findings on success', async () => {diff --git a/server/routes/database.js b/server/routes/database.jsindex a5f876c724..b821f6ffe5 100644--- a/server/routes/database.js+++ b/server/routes/database.js@@ -2,7 +2,7 @@ import { Router } from 'express';import { execFile } from 'child_process';import { existsSync } from 'fs';import { join } from 'path';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { checkHealth, query } from '../lib/db.js';import { PATHS } from '../lib/fileUtils.js';@@ -207,7 +207,7 @@ router.get('/status', asyncHandler(async (req, res) => {router.post('/switch', asyncHandler(async (req, res) => {const { target, migrate } = req.body;if (!target || !['docker', 'native'].includes(target)) {- return res.status(400).json({ error: 'target must be "docker" or "native"' });+ throw new ServerError('target must be "docker" or "native"', { status: 400 });}const io = req.app.get('io');@@ -218,9 +218,9 @@ router.post('/switch', asyncHandler(async (req, res) => {const result = await runDbScript(['migrate']);if (result.exitCode !== 0) {emit('error', { message: 'Migration failed' });- return res.status(500).json({- error: 'Migration failed',- details: result.stderr || result.stdout+ throw new ServerError('Migration failed', {+ status: 500,+ context: { details: result.stderr || result.stdout }});}emit('complete', { message: `Migration to ${target} complete` });@@ -232,18 +232,18 @@ router.post('/switch', asyncHandler(async (req, res) => {const switchResult = await runDbScript([target === 'docker' ? 'use-docker' : 'use-native']);if (switchResult.exitCode !== 0) {emit('error', { message: 'Switch failed' });- return res.status(500).json({- error: 'Switch failed',- details: switchResult.stderr || switchResult.stdout+ throw new ServerError('Switch failed', {+ status: 500,+ context: { details: switchResult.stderr || switchResult.stdout }});}const startResult = await runDbScript(['start']);if (startResult.exitCode !== 0) {emit('error', { message: `Failed to start ${target} database` });- return res.status(500).json({- error: `Failed to start ${target} database`,- details: startResult.stderr || startResult.stdout+ throw new ServerError(`Failed to start ${target} database`, {+ status: 500,+ context: { details: startResult.stderr || startResult.stdout }});}@@ -306,7 +306,7 @@ router.post('/sync', asyncHandler(async (req, res) => {const exportResult = await runDbScript(['export', `sync-${Date.now()}`]);if (exportResult.exitCode !== 0) {emit('error', { message: 'Export failed' });- return res.status(500).json({ error: 'Export failed', details: exportResult.stderr || exportResult.stdout });+ throw new ServerError('Export failed', { status: 500, context: { details: exportResult.stderr || exportResult.stdout } });}const exportLines = exportResult.stdout.trim().split('\n');const dumpFile = exportLines[exportLines.length - 1]?.trim();@@ -319,7 +319,7 @@ router.post('/sync', asyncHandler(async (req, res) => {], 5_000, pgEnv(targetPort));if (readyResult.exitCode !== 0) {emit('error', { message: `${targetMode} database not running on port ${targetPort}. Start it first.` });- return res.status(400).json({ error: `${targetMode} database not running on port ${targetPort}. Start it first.` });+ throw new ServerError(`${targetMode} database not running on port ${targetPort}. Start it first.`, { status: 400 });}// Ensure target has the portos role and database (native pg may lack the role)@@ -355,7 +355,7 @@ router.post('/sync', asyncHandler(async (req, res) => {if (importResult.exitCode !== 0) {emit('error', { message: `Import into ${targetMode} failed` });- return res.status(500).json({ error: `Import into ${targetMode} failed`, details: importResult.stderr || importResult.stdout });+ throw new ServerError(`Import into ${targetMode} failed`, { status: 500, context: { details: importResult.stderr || importResult.stdout } });}emit('complete', { message: `Data synced to ${targetMode}` });@@ -366,7 +366,7 @@ router.post('/sync', asyncHandler(async (req, res) => {router.post('/start', asyncHandler(async (req, res) => {const { backend } = req.body;if (!backend || !['docker', 'native'].includes(backend)) {- return res.status(400).json({ error: 'backend must be "docker" or "native"' });+ throw new ServerError('backend must be "docker" or "native"', { status: 400 });}if (backend === 'docker') {@@ -383,7 +383,7 @@ router.post('/start', asyncHandler(async (req, res) => {router.post('/stop', asyncHandler(async (req, res) => {const { backend } = req.body;if (!backend || !['docker', 'native'].includes(backend)) {- return res.status(400).json({ error: 'backend must be "docker" or "native"' });+ throw new ServerError('backend must be "docker" or "native"', { status: 400 });}if (backend === 'docker') {@@ -400,14 +400,14 @@ router.post('/stop', asyncHandler(async (req, res) => {router.post('/destroy', asyncHandler(async (req, res) => {const { backend } = req.body;if (!backend || !['docker', 'native'].includes(backend)) {- return res.status(400).json({ error: 'backend must be "docker" or "native"' });+ throw new ServerError('backend must be "docker" or "native"', { status: 400 });}// Safety: don't destroy the active backendconst statusResult = await runDbScript(['status']);const currentMode = parseDbMode(statusResult.stdout);if (backend === currentMode) {- return res.status(400).json({ error: 'Cannot destroy the active backend. Switch to the other backend first.' });+ throw new ServerError('Cannot destroy the active backend. Switch to the other backend first.', { status: 400 });}if (backend === 'docker') {@@ -438,9 +438,9 @@ router.post('/setup-native', asyncHandler(async (req, res) => {const result = await runDbScript(['setup-native']);if (result.exitCode !== 0) {emitProgress(io, 'error', 'Native setup failed');- return res.status(500).json({- error: 'Native PostgreSQL setup failed',- details: result.stderr || result.stdout+ throw new ServerError('Native PostgreSQL setup failed', {+ status: 500,+ context: { details: result.stderr || result.stdout }});}@@ -463,7 +463,7 @@ router.post('/export', asyncHandler(async (req, res) => {'-h', 'localhost', '-p', port, '-U', pgUser], 5_000, env);if (readyResult.exitCode !== 0) {- return res.status(400).json({ error: `${backend} database not running on port ${port}` });+ throw new ServerError(`${backend} database not running on port ${port}`, { status: 400 });}const dumpDir = join(rootDir, 'data', 'db-dumps');await runCmd('mkdir', ['-p', dumpDir], 5_000);@@ -475,7 +475,7 @@ router.post('/export', asyncHandler(async (req, res) => {'--no-owner', '--no-privileges', '--if-exists', '--clean', '-f', dumpFile], 120_000, env);if (result.exitCode !== 0) {- return res.status(500).json({ error: 'Export failed', details: result.stderr || result.stdout });+ throw new ServerError('Export failed', { status: 500, context: { details: result.stderr || result.stdout } });}return res.json({ success: true, dumpFile });}@@ -483,9 +483,9 @@ router.post('/export', asyncHandler(async (req, res) => {// Default: export from active backend via db.shconst result = await runDbScript(['export']);if (result.exitCode !== 0) {- return res.status(500).json({- error: 'Export failed',- details: result.stderr || result.stdout+ throw new ServerError('Export failed', {+ status: 500,+ context: { details: result.stderr || result.stdout }});}const dumpLines = result.stdout.trim().split('\n');diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 3ab1a26d66..3de2d13678 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -145,7 +145,7 @@ router.post('/port', asyncHandler(async (req, res) => {// Use lsof on macOS/Linux to find processconst safePort = parseInt(port, 10);if (!Number.isInteger(safePort) || safePort < 1 || safePort > 65535) {- return res.status(400).json({ error: `Invalid port number: ${port}` });+ throw new ServerError(`Invalid port number: ${port}`, { status: 400 });}const command = process.platform === 'darwin'? `lsof -i :${safePort} -P -n | grep LISTEN`diff --git a/server/routes/feeds.js b/server/routes/feeds.jsindex 983b1522b3..2d2a701e1a 100644--- a/server/routes/feeds.js+++ b/server/routes/feeds.js@@ -15,7 +15,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, parsePagination } from '../lib/validation.js';import * as feedsService from '../services/feeds.js';@@ -55,8 +55,7 @@ router.post('/', asyncHandler(async (req, res) => {const { url } = validateRequest(addFeedSchema, req.body);const result = await feedsService.addFeed(url);if (result.error) {- res.status(400).json({ error: result.error });- return;+ throw new ServerError(result.error, { status: 400 });}res.status(201).json(result.feed);}));@@ -78,8 +77,7 @@ router.post('/items/read-all', asyncHandler(async (req, res) => {router.post('/items/:id/read', asyncHandler(async (req, res) => {const result = await feedsService.markItemRead(req.params.id);if (result.error) {- res.status(404).json({ error: result.error });- return;+ throw new ServerError(result.error, { status: 404 });}res.json(result);}));@@ -88,8 +86,7 @@ router.post('/items/:id/read', asyncHandler(async (req, res) => {router.post('/:id/refresh', asyncHandler(async (req, res) => {const result = await feedsService.refreshFeed(req.params.id);if (result.error) {- res.status(404).json({ error: result.error });- return;+ throw new ServerError(result.error, { status: 404 });}res.json(result);}));@@ -98,8 +95,7 @@ router.post('/:id/refresh', asyncHandler(async (req, res) => {router.delete('/:id', asyncHandler(async (req, res) => {const result = await feedsService.removeFeed(req.params.id);if (result.error) {- res.status(404).json({ error: result.error });- return;+ throw new ServerError(result.error, { status: 404 });}res.json(result);}));diff --git a/server/routes/github.js b/server/routes/github.jsindex 7b2cf41f66..16fb86549e 100644--- a/server/routes/github.js+++ b/server/routes/github.js@@ -1,5 +1,5 @@import express from 'express';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, githubRepoUpdateSchema, githubSecretSchema } from '../lib/validation.js';import * as githubService from '../services/github.js';@@ -63,7 +63,7 @@ router.get('/secrets', asyncHandler(async (req, res) => {router.put('/secrets/:name', asyncHandler(async (req, res) => {const name = req.params.name;if (!/^[A-Z0-9_]{1,100}$/.test(name)) {- return res.status(400).json({ error: 'Invalid secret name. Use uppercase letters, digits, and underscores only.' });+ throw new ServerError('Invalid secret name. Use uppercase letters, digits, and underscores only.', { status: 400 });}const { value } = validateRequest(githubSecretSchema, req.body);const result = await githubService.setSecret(name, value);@@ -76,7 +76,7 @@ router.put('/secrets/:name', asyncHandler(async (req, res) => {router.post('/secrets/:name/sync', asyncHandler(async (req, res) => {const name = req.params.name;if (!/^[A-Z0-9_]{1,100}$/.test(name)) {- return res.status(400).json({ error: 'Invalid secret name. Use uppercase letters, digits, and underscores only.' });+ throw new ServerError('Invalid secret name. Use uppercase letters, digits, and underscores only.', { status: 400 });}const result = await githubService.syncSecretToRepos(name);res.json(result);diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex 18bf81f55f..fabd089460 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -424,12 +424,12 @@ router.get('/models/status', asyncHandler(async (_req, res) => {router.get('/models/:modelId/download', asyncHandler(async (req, res) => {const model = getImageModels().find((m) => m.id === req.params.modelId);if (!model) {- return res.status(404).json({ error: `Unknown model id: ${req.params.modelId}` });+ throw new ServerError(`Unknown model id: ${req.params.modelId}`, { status: 404 });}const repos = requiredReposForModel(model);if (!repos) {- return res.status(400).json({- error: `Model "${model.id}" has no HuggingFace repo on file — cannot pre-download.`,+ throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file — cannot pre-download.`, {+ status: 400,code: 'NO_REPO_FOR_MODEL',});}@@ -455,7 +455,7 @@ router.get('/gallery', asyncHandler(async (_req, res) => {router.get('/:jobId/events', (req, res) => {if (attachQueueSseClient(req.params.jobId, res)) return;if (imageGen.attachSseClient(req.params.jobId, res)) return;- res.status(404).json({ error: 'Job not found or expired' });+ throw new ServerError('Job not found or expired', { status: 404 });});router.post('/cancel', asyncHandler(async (req, res) => {@@ -796,7 +796,7 @@ const invalidateSetupCheck = (pythonPath) => {router.get('/setup/check', asyncHandler(async (req, res) => {const { pythonPath } = validateRequest(checkSchema, req.query);if (!isAllowedPython(pythonPath)) {- return res.status(400).json({ error: 'pythonPath must be a python interpreter (basename python/python3/python3.NN)' });+ throw new ServerError('pythonPath must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });}// mtime keys auto-bust when the interpreter binary itself changes (rare but// surfaces brew upgrades / re-symlinks). A stat() failure (path not found)@@ -828,11 +828,11 @@ const venvSchema = z.object({router.post('/setup/create-venv', asyncHandler(async (req, res) => {const { basePython } = validateRequest(venvSchema, req.body || {});if (basePython && !isAllowedPython(basePython)) {- return res.status(400).json({ error: 'basePython must be a python interpreter (basename python/python3/python3.NN)' });+ throw new ServerError('basePython must be a python interpreter (basename python/python3/python3.NN)', { status: 400 });}const base = basePython || (await detectPython());if (!base) {- return res.status(400).json({ error: 'No base Python 3 found to bootstrap a venv. Install Python 3.10+ first.' });+ throw new ServerError('No base Python 3 found to bootstrap a venv. Install Python 3.10+ first.', { status: 400 });}const target = join(PATHS.data, 'python', 'venv');const venvPython = await createVenv(base, target);diff --git a/server/routes/instances.js b/server/routes/instances.jsindex 697071da18..9267ffb6cc 100644--- a/server/routes/instances.js+++ b/server/routes/instances.js@@ -131,7 +131,7 @@ router.post('/provision-cert', asyncHandler(async (req, res) => {const result = await provisionTailscaleCert();if (!result.ok) {// Map to apiCore.js error envelope so the client auto-toasts the message.- return res.status(400).json({ error: result.message, code: result.reason });+ throw new ServerError(result.message, { status: 400, code: result.reason });}res.json(result);}));diff --git a/server/routes/lmstudio.js b/server/routes/lmstudio.jsindex c3a90caf3d..1c746ba302 100644--- a/server/routes/lmstudio.js+++ b/server/routes/lmstudio.js@@ -7,7 +7,7 @@import { Router } from 'express'import * as lmStudioManager from '../services/lmStudioManager.js'import * as localThinking from '../services/localThinking.js'-import { asyncHandler } from '../lib/errorHandler.js'+import { asyncHandler, ServerError } from '../lib/errorHandler.js'const router = Router()@@ -33,10 +33,7 @@ router.get('/models', asyncHandler(async (req, res) => {const available = await lmStudioManager.checkLMStudioAvailable()if (!available) {- return res.status(503).json({- error: 'LM Studio not available',- available: false- })+ throw new ServerError('LM Studio not available', { status: 503, context: { available: false } })}const models = await lmStudioManager.getLoadedModels(true)@@ -58,7 +55,7 @@ router.post('/download', asyncHandler(async (req, res) => {const { modelId } = req.bodyif (!modelId) {- return res.status(400).json({ error: 'modelId is required' })+ throw new ServerError('modelId is required', { status: 400 })}const result = await lmStudioManager.downloadModel(modelId)@@ -73,7 +70,7 @@ router.post('/load', asyncHandler(async (req, res) => {const { modelId } = req.bodyif (!modelId) {- return res.status(400).json({ error: 'modelId is required' })+ throw new ServerError('modelId is required', { status: 400 })}const result = await lmStudioManager.loadModel(modelId)@@ -88,7 +85,7 @@ router.post('/unload', asyncHandler(async (req, res) => {const { modelId } = req.bodyif (!modelId) {- return res.status(400).json({ error: 'modelId is required' })+ throw new ServerError('modelId is required', { status: 400 })}const result = await lmStudioManager.unloadModel(modelId)@@ -103,7 +100,7 @@ router.post('/completion', asyncHandler(async (req, res) => {const { prompt, model, maxTokens, temperature, systemPrompt } = req.bodyif (!prompt) {- return res.status(400).json({ error: 'prompt is required' })+ throw new ServerError('prompt is required', { status: 400 })}const result = await lmStudioManager.quickCompletion(prompt, {@@ -124,7 +121,7 @@ router.post('/analyze-task', asyncHandler(async (req, res) => {const { description, id, metadata } = req.bodyif (!description) {- return res.status(400).json({ error: 'description is required' })+ throw new ServerError('description is required', { status: 400 })}const analysis = await localThinking.analyzeTask({@@ -144,7 +141,7 @@ router.post('/classify-memory', asyncHandler(async (req, res) => {const { content } = req.bodyif (!content) {- return res.status(400).json({ error: 'content is required' })+ throw new ServerError('content is required', { status: 400 })}const classification = await localThinking.classifyMemory(content)@@ -159,7 +156,7 @@ router.post('/embeddings', asyncHandler(async (req, res) => {const { text, model } = req.bodyif (!text) {- return res.status(400).json({ error: 'text is required' })+ throw new ServerError('text is required', { status: 400 })}const result = await lmStudioManager.getEmbeddings(text, { model })diff --git a/server/routes/localLlm.js b/server/routes/localLlm.jsindex ec5f520e93..73610fb9fd 100644--- a/server/routes/localLlm.js+++ b/server/routes/localLlm.js@@ -9,7 +9,7 @@*/import { Router } from 'express'-import { asyncHandler } from '../lib/errorHandler.js'+import { asyncHandler, ServerError } from '../lib/errorHandler.js'import {validateRequest,localLlmInstallSchema,@@ -47,7 +47,7 @@ router.get('/status', asyncHandler(async (req, res) => {// GET /api/local-llm/catalog?backend=ollama&q=llama — curated install pickerrouter.get('/catalog', asyncHandler(async (req, res) => {const { backend, q } = req.query- if (!isBackend(backend)) return res.status(400).json({ error: 'backend must be "ollama" or "lmstudio"' })+ if (!isBackend(backend)) throw new ServerError('backend must be "ollama" or "lmstudio"', { status: 400 })const installed = (await listModels(backend)).map((m) => m.id)const models = q ? searchCatalog(backend, q, installed) : getCatalog(backend, installed)res.json({ backend, models })@@ -74,7 +74,7 @@ router.post('/install-backend', asyncHandler(async (req, res) => {})if (!result.success) {emit('error', result.error || 'Install failed')- return res.status(502).json({ error: result.error || 'Install failed', backend })+ throw new ServerError(result.error || 'Install failed', { status: 502, context: { backend } })}emit('complete', `${backend === 'ollama' ? 'Ollama' : 'LM Studio'} installed${result.note ? ` — ${result.note}` : ''}`)res.json(result)@@ -97,7 +97,7 @@ router.post('/ollama-service', asyncHandler(async (req, res) => {})if (!result.success) {emit('error', result.error || `Ollama ${action} failed`)- return res.status(502).json({ error: result.error || `Ollama ${action} failed` })+ throw new ServerError(result.error || `Ollama ${action} failed`, { status: 502 })}const completeLabel = {start: 'Ollama is running',@@ -129,7 +129,7 @@ router.post('/install', asyncHandler(async (req, res) => {// Forward structured `code` (e.g. OLLAMA_OUTDATED) so the client can offer// a recovery action — like prompting to upgrade Ollama — instead of just// surfacing the raw error string in a toast.- return res.status(502).json({ error: result.error || 'Install failed', modelId, ...(result.code ? { code: result.code } : {}) })+ throw new ServerError(result.error || 'Install failed', { status: 502, ...(result.code ? { code: result.code } : {}), context: { modelId } })}emit('complete', result.pending? `${modelId} download started in LM Studio — it'll finish in the background`@@ -150,7 +150,7 @@ router.post('/upgrade-backend', asyncHandler(async (req, res) => {})if (!result.success) {emit('error', result.error || 'Upgrade failed')- return res.status(502).json({ error: result.error || 'Upgrade failed', backend })+ throw new ServerError(result.error || 'Upgrade failed', { status: 502, context: { backend } })}emit('complete', `${backend === 'ollama' ? 'Ollama' : 'LM Studio'} upgraded${result.note ? ` — ${result.note}` : ''}`)res.json(result)@@ -160,7 +160,7 @@ router.post('/upgrade-backend', asyncHandler(async (req, res) => {router.post('/delete', asyncHandler(async (req, res) => {const { backend, modelId } = validateRequest(localLlmDeleteSchema, req.body)const result = await deleteModel(backend, modelId)- if (!result.success) return res.status(502).json({ error: result.error || 'Delete failed', modelId })+ if (!result.success) throw new ServerError(result.error || 'Delete failed', { status: 502, context: { modelId } })res.json({ success: true, ...result })}))@@ -172,7 +172,7 @@ router.post('/switch', asyncHandler(async (req, res) => {const result = await switchBackend(to)if (!result.success) {emit('error', result.error || 'Switch failed')- return res.status(500).json({ error: result.error || 'Switch failed' })+ throw new ServerError(result.error || 'Switch failed', { status: 500 })}emit('complete', `${to} is now the default backend`)res.json(result)@@ -187,7 +187,7 @@ router.post('/migrate', asyncHandler(async (req, res) => {const result = await migrateBackend(to, { mode, onProgress: ({ event, message }) => emit(event, message) })if (!result.success) {emit('error', result.error || 'Migration failed')- return res.status(500).json({ error: result.error || 'Migration failed' })+ throw new ServerError(result.error || 'Migration failed', { status: 500 })}res.json(result)}))@@ -207,7 +207,7 @@ router.get('/loaded', asyncHandler(async (req, res) => {// it here to keep each backend's quirks behind its own router.router.post('/unload', asyncHandler(async (req, res) => {const { backend, modelId } = validateRequest(localLlmUnloadSchema, req.body)- if (backend !== 'ollama') return res.status(400).json({ error: 'backend must be "ollama" (use /api/lmstudio/unload for LM Studio)' })+ if (backend !== 'ollama') throw new ServerError('backend must be "ollama" (use /api/lmstudio/unload for LM Studio)', { status: 400 })const result = await unloadOllamaModel(modelId)// "not loaded" is an idempotent no-op (the model already isn't resident// — between the panel's last poll and this click it may have hit Ollama's@@ -218,7 +218,7 @@ router.post('/unload', asyncHandler(async (req, res) => {if (result.reason === 'not loaded') {return res.json({ success: true, unloaded: false, reason: result.reason, modelId })}- return res.status(502).json({ error: result.reason || 'unload failed', modelId })+ throw new ServerError(result.reason || 'unload failed', { status: 502, context: { modelId } })}res.json({ success: true, ...result })}))diff --git a/server/routes/localLlm.test.js b/server/routes/localLlm.test.jsindex b7ed300c26..8fc00ee6f3 100644--- a/server/routes/localLlm.test.js+++ b/server/routes/localLlm.test.js@@ -173,7 +173,11 @@ describe('local LLM memory-management routes', () => {.send({ backend: 'ollama', modelId: 'llama3.2' });expect(res.status).toBe(502);- expect(res.body).toEqual({ error: 'Ollama unreachable', modelId: 'llama3.2' });+ // Standard error envelope (errorHandler): message in `error`, machine code+ // derived from status, the modelId carried in `context` for diagnostics.+ expect(res.body.error).toBe('Ollama unreachable');+ expect(res.body.code).toBe('BAD_GATEWAY');+ expect(res.body.context).toEqual({ modelId: 'llama3.2' });expect(unloadModel).toHaveBeenCalledWith('llama3.2');});diff --git a/server/routes/media.js b/server/routes/media.jsindex 985bb36fea..3302786d1e 100644--- a/server/routes/media.js+++ b/server/routes/media.js@@ -1,7 +1,7 @@import express from 'express';import { z } from 'zod';import mediaService from '../services/mediaService.js';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';const router = express.Router();@@ -57,7 +57,7 @@ router.get('/video', (req, res) => {const videoStream = mediaService.getVideoStream();if (!videoStream) {- return res.status(404).json({ error: 'Video stream not active' });+ throw new ServerError('Video stream not active', { status: 404 });}res.setHeader('Content-Type', 'multipart/x-mixed-replace; boundary=frame');@@ -101,7 +101,7 @@ router.get('/audio', (req, res) => {const audioStream = mediaService.getAudioStream();if (!audioStream) {- return res.status(404).json({ error: 'Audio stream not active' });+ throw new ServerError('Audio stream not active', { status: 404 });}res.setHeader('Content-Type', 'audio/webm');diff --git a/server/routes/messages.js b/server/routes/messages.jsindex c29b3c2ea7..89fd7bf968 100644--- a/server/routes/messages.js+++ b/server/routes/messages.js@@ -1,6 +1,6 @@import express from 'express';import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest, parsePagination } from '../lib/validation.js';import { UUID_RE } from '../lib/fileUtils.js';import * as messageAccounts from '../services/messageAccounts.js';@@ -86,21 +86,21 @@ router.post('/accounts', asyncHandler(async (req, res) => {router.put('/accounts/:id', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const updates = validateRequest(updateAccountSchema, req.body);const account = await messageAccounts.updateAccount(req.params.id, updates);- if (!account) return res.status(404).json({ error: 'Account not found' });+ if (!account) throw new ServerError('Account not found', { status: 404 });req.app.get('io')?.emit('messages:changed', {});res.json(account);}));router.delete('/accounts/:id', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const deleted = await messageAccounts.deleteAccount(req.params.id);- if (!deleted) return res.status(404).json({ error: 'Account not found' });+ if (!deleted) throw new ServerError('Account not found', { status: 404 });// Clean up related dataawait messageSync.deleteCache(req.params.id).catch(() => {});await messageDrafts.deleteDraftsByAccountId(req.params.id).catch(() => {});@@ -111,21 +111,21 @@ router.delete('/accounts/:id', asyncHandler(async (req, res) => {// === Sync Routes ===router.post('/sync/:accountId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const mode = ['unread', 'full'].includes(req.body?.mode) ? req.body.mode : 'unread';const io = req.app.get('io');const result = await messageSync.syncAccount(req.params.accountId, io, { mode });- if (result.error) return res.status(result.status || 404).json({ error: result.error });+ if (result.error) throw new ServerError(result.error, { status: result.status || 404 });res.json(result);}));router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const status = await messageSync.getSyncStatus(req.params.accountId);- if (!status) return res.status(404).json({ error: 'Account not found' });+ if (!status) throw new ServerError('Account not found', { status: 404 });res.json(status);}));@@ -133,7 +133,7 @@ router.get('/sync/:accountId/status', asyncHandler(async (req, res) => {router.get('/inbox', asyncHandler(async (req, res) => {const { accountId, search } = req.query;if (accountId && !UUID_RE.test(accountId)) {- return res.status(400).json({ error: 'Invalid accountId format' });+ throw new ServerError('Invalid accountId format', { status: 400 });}const { limit: parsedLimit, offset: parsedOffset } = parsePagination(req.query, { defaultLimit: 50, maxLimit: 100 });const result = await messageSync.getMessages({@@ -153,9 +153,9 @@ router.get('/triage-rules', asyncHandler(async (req, res) => {router.delete('/triage-rules/:index', asyncHandler(async (req, res) => {const index = parseInt(req.params.index, 10);- if (Number.isNaN(index) || index < 0) return res.status(400).json({ error: 'Invalid rule index' });+ if (Number.isNaN(index) || index < 0) throw new ServerError('Invalid rule index', { status: 400 });const deleted = await deleteRule(index);- if (!deleted) return res.status(404).json({ error: 'Rule not found' });+ if (!deleted) throw new ServerError('Rule not found', { status: 404 });res.status(204).send();}));@@ -187,7 +187,7 @@ router.post('/evaluate', asyncHandler(async (req, res) => {router.get('/drafts', asyncHandler(async (req, res) => {const { accountId, status } = req.query;if (accountId && !UUID_RE.test(accountId)) {- return res.status(400).json({ error: 'Invalid accountId format' });+ throw new ServerError('Invalid accountId format', { status: 400 });}const drafts = await messageDrafts.listDrafts({ accountId, status });res.json(drafts);@@ -196,10 +196,10 @@ router.get('/drafts', asyncHandler(async (req, res) => {router.post('/drafts', asyncHandler(async (req, res) => {const data = validateRequest(createDraftSchema, req.body);const account = await messageAccounts.getAccount(data.accountId);- if (!account) return res.status(404).json({ error: 'Account not found' });+ if (!account) throw new ServerError('Account not found', { status: 404 });const derivedSendVia = account.type === 'gmail' ? 'api' : 'playwright';if (data.sendVia && data.sendVia !== derivedSendVia) {- return res.status(400).json({ error: `sendVia "${data.sendVia}" conflicts with account type "${account.type}" (expected "${derivedSendVia}")` });+ throw new ServerError(`sendVia "${data.sendVia}" conflicts with account type "${account.type}" (expected "${derivedSendVia}")`, { status: 400 });}data.sendVia = derivedSendVia;const draft = await messageDrafts.createDraft(data);@@ -210,7 +210,7 @@ router.post('/drafts', asyncHandler(async (req, res) => {router.post('/drafts/generate', asyncHandler(async (req, res) => {const data = validateRequest(generateDraftSchema, req.body);const account = await messageAccounts.getAccount(data.accountId);- if (!account) return res.status(404).json({ error: 'Account not found' });+ if (!account) throw new ServerError('Account not found', { status: 404 });// Fetch the original message to build AI replylet replyBody = '';@@ -251,54 +251,54 @@ router.post('/drafts/generate', asyncHandler(async (req, res) => {router.put('/drafts/:id', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid draft ID format' });+ throw new ServerError('Invalid draft ID format', { status: 400 });}const updates = validateRequest(updateDraftSchema, req.body);const draft = await messageDrafts.updateDraft(req.params.id, updates);- if (!draft) return res.status(404).json({ error: 'Draft not found' });+ if (!draft) throw new ServerError('Draft not found', { status: 404 });res.json(draft);}));router.post('/drafts/:id/approve', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid draft ID format' });+ throw new ServerError('Invalid draft ID format', { status: 400 });}const draft = await messageDrafts.approveDraft(req.params.id);- if (!draft) return res.status(404).json({ error: 'Draft not found' });+ if (!draft) throw new ServerError('Draft not found', { status: 404 });res.json(draft);}));router.post('/drafts/:id/send', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid draft ID format' });+ throw new ServerError('Invalid draft ID format', { status: 400 });}const io = req.app.get('io');const result = await messageSender.sendDraft(req.params.id, io);if (!result.success) {- return res.status(result.status || 500).json({ code: result.code, error: result.error });+ throw new ServerError(result.error, { status: result.status || 500, code: result.code });}res.json(result);}));router.delete('/drafts/:id', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid draft ID format' });+ throw new ServerError('Invalid draft ID format', { status: 400 });}const deleted = await messageDrafts.deleteDraft(req.params.id);- if (!deleted) return res.status(404).json({ error: 'Draft not found' });+ if (!deleted) throw new ServerError('Draft not found', { status: 404 });res.status(204).send();}));// === Browser Launch Route ===router.post('/launch/:accountId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const account = await messageAccounts.getAccount(req.params.accountId);- if (!account) return res.status(404).json({ error: 'Account not found' });- if (account.type === 'gmail') return res.status(400).json({ error: 'Gmail uses the Google API, not browser automation' });+ if (!account) throw new ServerError('Account not found', { status: 404 });+ if (account.type === 'gmail') throw new ServerError('Gmail uses the Google API, not browser automation', { status: 400 });const result = await launchProvider(account.type);- if (!result.success) return res.status(503).json({ error: result.error });+ if (!result.success) throw new ServerError(result.error, { status: 503 });res.json(result);}));@@ -337,7 +337,7 @@ const ALLOWED_PROVIDERS = ['outlook', 'teams'];router.put('/selectors/:provider', asyncHandler(async (req, res) => {if (!ALLOWED_PROVIDERS.includes(req.params.provider)) {- return res.status(400).json({ error: 'Invalid provider' });+ throw new ServerError('Invalid provider', { status: 400 });}const { selectors } = validateRequest(updateSelectorsSchema, req.body);const updated = await updateSelectors(req.params.provider, selectors);@@ -346,7 +346,7 @@ router.put('/selectors/:provider', asyncHandler(async (req, res) => {router.post('/selectors/:provider/test', asyncHandler(async (req, res) => {if (!ALLOWED_PROVIDERS.includes(req.params.provider)) {- return res.status(400).json({ error: 'Invalid provider' });+ throw new ServerError('Invalid provider', { status: 400 });}const result = await testSelectors(req.params.provider);res.json(result);@@ -355,9 +355,9 @@ router.post('/selectors/:provider/test', asyncHandler(async (req, res) => {// === Thread Route ===router.get('/thread/:accountId/:threadId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid accountId format' });+ throw new ServerError('Invalid accountId format', { status: 400 });}- if (!req.params.threadId) return res.status(400).json({ error: 'threadId is required' });+ if (!req.params.threadId) throw new ServerError('threadId is required', { status: 400 });const messages = await messageSync.getThread(req.params.accountId, req.params.threadId);res.json({ messages });}));@@ -371,14 +371,14 @@ const messageParamsSchema = z.object({// === Per-message refresh ===router.post('/:accountId/:messageId/refresh', asyncHandler(async (req, res) => {const parsed = messageParamsSchema.safeParse(req.params);- if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });+ if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });const { accountId, messageId } = parsed.data;const message = await messageSync.getMessage(accountId, messageId);- if (!message) return res.status(404).json({ error: 'Message not found' });+ if (!message) throw new ServerError('Message not found', { status: 404 });const result = await messageSync.refreshMessage(accountId, messageId);if (result?.error) {const status = result.error === 'no-browser' || result.error === 'auth-required' ? 503 : 502;- return res.status(status).json({ error: result.message || result.error });+ throw new ServerError(result.message || result.error, { status });}req.app.get('io')?.emit('messages:changed', {});res.json(result);@@ -387,11 +387,11 @@ router.post('/:accountId/:messageId/refresh', asyncHandler(async (req, res) => {// === Fetch full content for preview-only messages ===router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.accountId)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}const { accountId } = req.params;const account = await messageAccounts.getAccount(accountId);- if (!account) return res.status(404).json({ error: 'Account not found' });+ if (!account) throw new ServerError('Account not found', { status: 404 });if (account.type !== 'outlook') return res.json({ updated: 0, total: 0 });const force = req.body?.force === true;@@ -411,7 +411,7 @@ router.post('/fetch-full/:accountId', asyncHandler(async (req, res) => {// === Clear account cache ===router.post('/accounts/:id/cache/clear', asyncHandler(async (req, res) => {if (!UUID_RE.test(req.params.id)) {- return res.status(400).json({ error: 'Invalid account ID format' });+ throw new ServerError('Invalid account ID format', { status: 400 });}await messageSync.deleteCache(req.params.id);req.app.get('io')?.emit('messages:changed', {});@@ -421,11 +421,11 @@ router.post('/accounts/:id/cache/clear', asyncHandler(async (req, res) => {// === Message Action Route (archive/delete) ===router.post('/:accountId/:messageId/action', asyncHandler(async (req, res) => {const parsed = messageParamsSchema.safeParse(req.params);- if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });+ if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });const { accountId, messageId } = parsed.data;const action = req.body?.action;if (!['archive', 'delete'].includes(action)) {- return res.status(400).json({ error: 'Invalid action — must be "archive" or "delete"' });+ throw new ServerError('Invalid action — must be "archive" or "delete"', { status: 400 });}const result = await executeAction(accountId, messageId, action);req.app.get('io')?.emit('messages:changed', {});@@ -443,7 +443,12 @@ router.get('/debug/token-status', asyncHandler(async (req, res) => {router.post('/debug/test-token', asyncHandler(async (req, res) => {const provider = ALLOWED_TOKEN_PROVIDERS.includes(req.body?.provider) ? req.body.provider : 'outlook';const tokenResult = await getToken(provider);- if (tokenResult.error) return res.status(503).json(tokenResult);+ if (tokenResult.error) {+ throw new ServerError(tokenResult.message || tokenResult.error, {+ status: 503,+ context: { reason: tokenResult.error, provider: tokenResult.provider }+ });+ }const decoded = tokenResult.decoded || {};const tokenInfo = {@@ -470,9 +475,9 @@ router.post('/debug/clear-token', asyncHandler(async (req, res) => {router.get('/:accountId/:messageId', asyncHandler(async (req, res) => {const parsed = messageParamsSchema.safeParse(req.params);- if (!parsed.success) return res.status(400).json({ error: 'Invalid accountId or messageId format' });+ if (!parsed.success) throw new ServerError('Invalid accountId or messageId format', { status: 400 });const message = await messageSync.getMessage(parsed.data.accountId, parsed.data.messageId);- if (!message) return res.status(404).json({ error: 'Message not found' });+ if (!message) throw new ServerError('Message not found', { status: 404 });res.json(message);}));diff --git a/server/routes/pipeline.js b/server/routes/pipeline.jsindex 617653ac4d..4c963afd45 100644--- a/server/routes/pipeline.js+++ b/server/routes/pipeline.js@@ -1393,7 +1393,7 @@ router.post('/series/:id/seasons/:seasonId/generate-beats', asyncHandler(async (router.get('/series/:id/seasons/:seasonId/generate-beats/progress', (req, res) => {const attached = volumeBeatsRunner.attachClient(req.params.seasonId, res);if (!attached) {- res.status(404).json({ error: 'No active beat-sheet run for this volume' });+ throw new ServerError('No active beat-sheet run for this volume', { status: 404 });}});@@ -2224,7 +2224,7 @@ router.post('/issues/:id/auto-run-text', asyncHandler(async (req, res) => {router.get('/issues/:id/auto-run-text/progress', (req, res) => {const attached = autoRunner.attachClient(req.params.id, res);if (!attached) {- res.status(404).json({ error: 'No active auto-run for this issue' });+ throw new ServerError('No active auto-run for this issue', { status: 404 });}});@@ -2271,7 +2271,7 @@ router.post('/series/:id/editorial/analyze', asyncHandler(async (req, res) => {router.get('/series/:id/editorial/analyze/progress', (req, res) => {const attached = editorialRunner.attachClient(req.params.id, res);if (!attached) {- res.status(404).json({ error: 'No active editorial analysis for this series' });+ throw new ServerError('No active editorial analysis for this series', { status: 404 });}});diff --git a/server/routes/providers.js b/server/routes/providers.jsindex dd93845c6b..0a00556c7c 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -55,11 +55,11 @@ export function createPortOSProviderRoutes(aiToolkit) {router.put('/active', asyncHandler(async (req, res) => {const { id } = req.body;if (!id) {- return res.status(400).json({ error: 'Provider ID required' });+ throw new ServerError('Provider ID required', { status: 400 });}const provider = await providerService.setActiveProvider(id);if (!provider) {- return res.status(404).json({ error: 'Provider not found' });+ throw new ServerError('Provider not found', { status: 404 });}res.json(sanitizeProvider(provider));}));@@ -130,7 +130,7 @@ export function createPortOSProviderRoutes(aiToolkit) {// Sanitized GET /:id — must be after specific /:id/* routes aboverouter.get('/:id', asyncHandler(async (req, res) => {const provider = await providerService.getProviderById(req.params.id);- if (!provider) return res.status(404).json({ error: 'Provider not found' });+ if (!provider) throw new ServerError('Provider not found', { status: 404 });res.json(sanitizeProvider(provider));}));@@ -142,11 +142,11 @@ export function createPortOSProviderRoutes(aiToolkit) {// POST path now blocks.router.put('/:id', asyncHandler(async (req, res) => {const existing = await providerService.getProviderById(req.params.id);- if (!existing) return res.status(404).json({ error: 'Provider not found' });+ if (!existing) throw new ServerError('Provider not found', { status: 404 });const validation = validate(providerSchema.partial(), req.body);if (!validation.success) {- return res.status(400).json({ error: 'Invalid provider data', details: validation.errors });+ throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });}const updates = { ...validation.data };@@ -177,7 +177,7 @@ export function createPortOSProviderRoutes(aiToolkit) {router.post('/', asyncHandler(async (req, res) => {const validation = validate(providerSchema, req.body);if (!validation.success) {- return res.status(400).json({ error: 'Invalid provider data', details: validation.errors });+ throw new ServerError('Invalid provider data', { status: 400, code: 'VALIDATION_ERROR', context: { details: validation.errors } });}const provider = await providerService.createProvider(validation.data);res.status(201).json(sanitizeProvider(provider));diff --git a/server/routes/sdapi.js b/server/routes/sdapi.jsindex 0f0ba261c0..0847a2eaa4 100644--- a/server/routes/sdapi.js+++ b/server/routes/sdapi.js@@ -47,7 +47,7 @@ const ensureExposed = async () => {router.use(asyncHandler(async (req, res, next) => {if (await ensureExposed()) return next();- res.status(403).json({ error: 'PortOS A1111 API is disabled — toggle "Expose A1111 API" in Settings > Image Gen' });+ throw new ServerError('PortOS A1111 API is disabled — toggle "Expose A1111 API" in Settings > Image Gen', { status: 403 });}));// Mirrors A1111's /sdapi/v1/options. Most clients only consultdiff --git a/server/routes/storyBuilder.js b/server/routes/storyBuilder.jsindex 482566669a..1fafd414c9 100644--- a/server/routes/storyBuilder.js+++ b/server/routes/storyBuilder.js@@ -150,7 +150,7 @@ router.get('/:id/steps/:stepId/progress', (req, res) => {assertStep(req.params.stepId);const attached = attachClient(req.params.id, req.params.stepId, res);if (!attached) {- res.status(404).json({ error: 'No active run for this step' });+ throw new ServerError('No active run for this step', { status: 404 });}});diff --git a/server/routes/systemHealth.js b/server/routes/systemHealth.jsindex a6aa48e7cd..f51da22ca8 100644--- a/server/routes/systemHealth.js+++ b/server/routes/systemHealth.js@@ -7,7 +7,7 @@ import * as cos from '../services/cos.js';import { getSelf } from '../services/instances.js';import { checkHealth } from '../lib/db.js';import { getCurrentVersion } from '../services/updateChecker.js';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { getMemoryStats } from '../lib/memoryStats.js';import { getSettings, updateSettingsWith } from '../services/settings.js';@@ -261,7 +261,7 @@ router.put('/health/thresholds', asyncHandler(async (req, res) => {};for (const [k, v] of Object.entries(incoming)) {if (!Number.isFinite(v)) {- return res.status(400).json({ error: `Invalid threshold value for ${k}` });+ throw new ServerError(`Invalid threshold value for ${k}`, { status: 400 });}}const next = {@@ -271,10 +271,10 @@ router.put('/health/thresholds', asyncHandler(async (req, res) => {diskCritical: clamp(Math.round(incoming.diskCritical), 50, 99)};if (next.memoryWarn >= next.memoryCritical) {- return res.status(400).json({ error: 'memoryWarn must be less than memoryCritical' });+ throw new ServerError('memoryWarn must be less than memoryCritical', { status: 400 });}if (next.diskWarn >= next.diskCritical) {- return res.status(400).json({ error: 'diskWarn must be less than diskCritical' });+ throw new ServerError('diskWarn must be less than diskCritical', { status: 400 });}// Merge the health thresholds against the freshest snapshot inside the writediff --git a/server/routes/tools.js b/server/routes/tools.jsindex 99deb257fd..fa3bbfa0d5 100644--- a/server/routes/tools.js+++ b/server/routes/tools.js@@ -6,7 +6,7 @@import { Router } from 'express';import { z } from 'zod';-import { asyncHandler } from '../lib/errorHandler.js';+import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import * as toolsService from '../services/tools.js';@@ -48,7 +48,7 @@ router.get('/summary', asyncHandler(async (req, res) => {router.get('/:id', asyncHandler(async (req, res) => {const id = validateRequest(toolIdSchema, req.params.id);const tool = await toolsService.getTool(id);- if (!tool) return res.status(404).json({ error: 'Tool not found' });+ if (!tool) throw new ServerError('Tool not found', { status: 404 });res.json(tool);}));@@ -64,7 +64,7 @@ router.put('/:id', asyncHandler(async (req, res) => {const id = validateRequest(toolIdSchema, req.params.id);const data = validateRequest(updateToolSchema, req.body);const tool = await toolsService.updateTool(id, data);- if (!tool) return res.status(404).json({ error: 'Tool not found' });+ if (!tool) throw new ServerError('Tool not found', { status: 404 });res.json(tool);}));diff --git a/server/routes/videoGen.js b/server/routes/videoGen.jsindex 12d3e6ded8..39c570920b 100644--- a/server/routes/videoGen.js+++ b/server/routes/videoGen.js@@ -384,9 +384,9 @@ router.get('/models/status', asyncHandler(async (_req, res) => {router.get('/models/:modelId/download', asyncHandler(async (req, res) => {const model = listVideoModels().find((m) => m.id === req.params.modelId);- if (!model) return res.status(404).json({ error: `Unknown video model: ${req.params.modelId}` });+ if (!model) throw new ServerError(`Unknown video model: ${req.params.modelId}`, { status: 404 });const repo = repoForModel(model);- if (!repo) return res.status(400).json({ error: `Model "${model.id}" has no HuggingFace repo on file.`, code: 'NO_REPO_FOR_MODEL' });+ if (!repo) throw new ServerError(`Model "${model.id}" has no HuggingFace repo on file.`, { status: 400, code: 'NO_REPO_FOR_MODEL' });await startHfDownloadStream({ req, res, repo });}));@@ -397,7 +397,7 @@ router.get('/text-encoder/download', asyncHandler(async (req, res) => {// Local-path encoders (LM Studio) are not downloadable — they're served// off disk and the status endpoint already reports cached: true for them.if (!isHfRepoId(repo)) {- return res.status(400).json({ error: 'Active text encoder is a local-path entry, not an HF repo.', code: 'NOT_DOWNLOADABLE' });+ throw new ServerError('Active text encoder is a local-path entry, not an HF repo.', { status: 400, code: 'NOT_DOWNLOADABLE' });}await startHfDownloadStream({ req, res, repo });}));@@ -788,7 +788,7 @@ router.get('/active', (_req, res) => {router.get('/:jobId/events', (req, res) => {const ok = attachSseClient(req.params.jobId, res);- if (!ok) res.status(404).json({ error: 'Job not found or expired' });+ if (!ok) throw new ServerError('Job not found or expired', { status: 404 });});router.post('/cancel', asyncHandler(async (req, res) => {diff --git a/server/routes/videoGen.test.js b/server/routes/videoGen.test.jsindex ac279b2d32..b0fdf6c6d8 100644--- a/server/routes/videoGen.test.js+++ b/server/routes/videoGen.test.js@@ -1,6 +1,7 @@import { describe, it, expect, vi, beforeEach } from 'vitest';import express from 'express';import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';vi.mock('../services/settings.js', () => ({getSettings: vi.fn(async () => ({ imageGen: { local: { pythonPath: '/usr/bin/python3' } } })),@@ -172,6 +173,7 @@ describe('videoGen routes', () => {app = express();app.use(express.json());app.use('/api/video-gen', videoGenRoutes);+ app.use(errorMiddleware);vi.clearAllMocks();// Reset the upload holder so a test that set a pending upload but// bailed before the route consumed it can't leak into the next test.diff --git a/server/routes/videoTimeline.js b/server/routes/videoTimeline.jsindex fb52683aed..b94fb15928 100644--- a/server/routes/videoTimeline.js+++ b/server/routes/videoTimeline.js@@ -71,7 +71,7 @@ router.post('/projects/:id/render', asyncHandler(async (req, res) => {router.get('/:jobId/events', (req, res) => {const ok = attachSseClient(req.params.jobId, res);- if (!ok) res.status(404).json({ error: 'Job not found or expired' });+ if (!ok) throw new ServerError('Job not found or expired', { status: 404 });});router.post('/:jobId/cancel', (req, res) => {diff --git a/server/routes/voice.js b/server/routes/voice.jsindex a059175ed9..f080fd7f63 100644--- a/server/routes/voice.js+++ b/server/routes/voice.js@@ -160,7 +160,7 @@ router.get('/voices', asyncHandler(async (req, res) => {router.post('/piper/fetch', asyncHandler(async (req, res) => {const voice = (req.body?.voice || '').toString();if (!findPiperVoice(voice)) {- return res.status(400).json({ error: `unknown piper voice: ${voice}` });+ throw new ServerError(`unknown piper voice: ${voice}`, { status: 400 });}const cfg = await getVoiceConfig();const result = await downloadPiperVoice(voice, cfg);@@ -172,9 +172,9 @@ router.post('/piper/fetch', asyncHandler(async (req, res) => {// without saving first (e.g. flip to Piper, hit ▶, before clicking Save).router.post('/test', asyncHandler(async (req, res) => {const text = (req.body?.text || '').toString().trim();- if (!text) return res.status(400).json({ error: 'text is required' });+ if (!text) throw new ServerError('text is required', { status: 400 });if (text.length > MAX_VOICE_TEXT_LEN) {- return res.status(400).json({ error: `text too long (${text.length} > ${MAX_VOICE_TEXT_LEN} chars)` });+ throw new ServerError(`text too long (${text.length} > ${MAX_VOICE_TEXT_LEN} chars)`, { status: 400 });}const voice = (req.body?.voice || '').toString().trim() || undefined;const engine = validEngine((req.body?.engine || '').toString().trim());