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
route all error responses through a shared sendErrorResponse helper (#2845)
[._.]/ Adam Eivy48592595440c
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 45e4eb1f73..c731869ffe 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -54,3 +54,4 @@- **[issue-2836] Extract helpers from `generateManagedAppImprovementTaskForType()`** — the ~533-line function in `server/services/cosTaskGenerator.js` is decomposed into named metadata-building and gate-checking helpers (`buildImprovementTaskMetadata`, `resolveTaskInputHook`, `resolveClaimWorkRouting`, `applyPerpetualWorkGate`, `resolveBranchReconcileBlock`, `resolveIssueReconcileBlock`, `resolveReferenceWatchBlock`, `resolvePrWatcherBlock`), each returning a `{ skip }` / prompt-block result so the main function reads as a thin orchestrator. Prompt resolution (reviewers/author-filter/swarm directives plus the token-replacement chain) moves into `buildImprovementTaskDescription`, and the provider/model/effort pin layering into `applyProviderModelPins`. Behavior-preserving — no change to task generation, park/convergence semantics, or dispatch ordering.- **Commit the `server/` and `client/` lockfiles** — both were gitignored purely "to reduce merge noise" (`bbeab937d`), which left Dependabot able to see only the ~45 dependencies declared in their `package.json` files and blind to ~560 transitive packages; the repo's entire alert history is one alert against the root lockfile, whose tree has a single direct dep (pm2). CI's `npm install --prefix server|client` steps become `npm ci`, so the two trees holding all application code now resolve deterministically instead of re-resolving on every run and on every user's install. `setup-node`'s npm cache keys off all three lockfiles. `browser/package-lock.json` stays ignored (its `node_modules` is committed instead). Unrelated to the npm-workspaces revert in `b743222be`, which was about exFAT's lack of symlink support.- **Apply the mergeable Dependabot bumps in one commit** — server `vitest`/`@vitest/coverage-v8` 4.1.9→4.1.10 and `node-pty` 1.2.0-beta.10→beta.14; client `react`/`react-dom` 19.2.7→19.2.8, `vite` 8.0.16→8.1.5, and `@tailwindcss/postcss` 4.3.1→4.3.3. Applied together with regenerated lockfiles because the individual PRs predate lockfile tracking and each ERESOLVE'd in isolation: the two vitest packages must move in lockstep, `@tailwindcss/postcss` was stranded a patch behind the already-merged `tailwindcss` 4.3.3, and Dependabot's `react-dom` PR would have left `react` mismatched at 19.2.7. Holding back `undici` 8 (breaks the DNS-rebinding connect-time IP pinning in `safeUrlFetch.js`, #1859) and `eslint`/`@eslint/js` 10 (`[email protected]` peers at `^9.7`).+- **[issue-2845] Standardize the `loraTraining` sample 404 error envelope** — new `sendErrorResponse`/`buildErrorEnvelope` helpers in `server/lib/errorHandler.js` build the shared `{ error, code, timestamp }` body in one place; `asyncHandler`, `errorMiddleware`, the `res.sendFile` 404 callback in `server/routes/loraTraining.js`, and the `authGate` 401/403 short-circuits now all route through it, so responses raised outside a handler's catch no longer omit `code`/`timestamp`.diff --git a/server/lib/README.md b/server/lib/README.mdindex 010bfe3066..be667e216c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -271,7 +271,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `authGate.js` | Express + Socket.IO middleware that gates `/api/*` and `/data/*` behind the password set in `settings.secrets.auth`. No-op when auth is off; emits 401 `AUTH_REQUIRED` (or plain text for `/data/*`) when on and the request has no valid session token. Consults `apiRegistry.isRegistryPublic` so an exposed+passwordless API (voice/sdapi) bypasses the gate on its public prefix only. || `domainAutonomy.js` | Per-domain autonomy guardrails (pure). `AUTONOMY_DOMAINS`/`DOMAIN_IDS`/`DOMAIN_MODES` (`off`/`dry-run`/`execute`), `getDomainMode(config, id)`, and `normalizeDomainAutonomy(raw)` to coerce a hand-edited/partial map. Default per domain is `execute` (reproduces pre-#711 behavior, so no migration needed). Also `CREATIVE_DOMAIN`/`getCreativeAutonomyMode(config)` (#2183) — the Creative Director orchestrator domain, kept out of `DOMAIN_IDS` and defaulting to mirror the `cos` mode. || `domainBudgets.js` | Per-domain daily autonomy budgets (pure). `BUDGET_LIMIT_FIELDS` (`maxActionsPerDay`/`maxMinutesPerDay`), `getDomainBudget(config, id)`, `normalizeDomainBudgets(raw)`, `hasBudget(budget)`, and `evaluateBudget(budget, usage)` → `{ withinBudget, exceeded }`. A `null`/non-positive cap means unlimited (default per domain, so no migration needed). Token/$ caps are intentionally absent — CLI subscription providers expose no per-run metering. Usage ledger + gate wiring live in `services/domainUsage.js`. |-| `errorHandler.js` | `ServerError` + `asyncHandler` middleware. |+| `errorHandler.js` | `ServerError` + `asyncHandler` middleware, plus `sendErrorResponse`/`buildErrorEnvelope` for the standard `{ error, code, timestamp }` body outside a handler's catch. || `extensionErrors.js` | `isExtensionError(payload)` — true when a client error report came from a browser extension's injected content script (extension URL scheme in `source`/`stack`/`message`, or a short list of vendor/runtime message signatures) rather than from PortOS. Consumed by `services/clientErrors.js` to keep un-actionable extension noise out of the Review Hub *and* out of the 1/sec throttle slot, where it would displace real errors. **Authoritative copy** — mirrored at `client/src/lib/extensionErrors.js`, parity enforced by `extensionErrors.mirror.test.js`. || `lwwTimestamp.js` | Last-writer-wins timestamp comparison for cross-instance sync merges. `parseTsMs(s)` (Date.parse → epoch ms or null), `compareNewerWins(candidate, incumbent)` (true iff candidate strictly newer; unparseable-loses, tie → incumbent — used to decide remote-overwrites-local), `compareEarlierWins(a, b)` (−1/0/1 earliest-wins tiebreak; unparseable-loses). Single source of the LWW polarity shared by `mergeMediaCollectionsFromSync` / `mergeAuthorsFromSync` etc. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. |diff --git a/server/lib/authGate.js b/server/lib/authGate.jsindex a7a9c94464..311c4ce6a7 100644--- a/server/lib/authGate.js+++ b/server/lib/authGate.js@@ -5,6 +5,7 @@ import { extractToken, isAuthEnabled, verifyPassword, verifySession } from '../simport { extractBasicPassword, isCrossOrigin } from '../../lib/portosAuthCore.js';import { getSettings, settingsEvents } from '../services/settings.js';import { isRegistryPublic } from './apiRegistry.js';+import { sendErrorResponse, ServerError } from './errorHandler.js';// Paths that bypass the auth gate even when a password is set:// - /api/auth/status, /api/auth/whoami, /api/auth/login → the login UI@@ -70,7 +71,9 @@ export const authGate = async (req, res, next) => {// session), so a same-tailnet attacker could force-logout a user// cross-origin if the guard sat behind the public-path bypass.if (isCrossOrigin(req)) {- res.status(403).json({ error: 'Cross-origin request rejected', code: 'CROSS_ORIGIN_BLOCKED' });+ sendErrorResponse(res, new ServerError('Cross-origin request rejected', {+ status: 403, code: 'CROSS_ORIGIN_BLOCKED',+ }));return;}const path = req.path;@@ -101,7 +104,9 @@ export const authGate = async (req, res, next) => {res.status(401).type('text/plain').send('Unauthorized');return;}- res.status(401).json({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ sendErrorResponse(res, new ServerError('Authentication required', {+ status: 401, code: 'AUTH_REQUIRED',+ }));};// Socket.IO middleware. Run after a successful HTTP-side handshake — samediff --git a/server/lib/authGate.test.js b/server/lib/authGate.test.jsindex 049a819565..a516b17eff 100644--- a/server/lib/authGate.test.js+++ b/server/lib/authGate.test.js@@ -79,7 +79,7 @@ describe('authGate middleware', () => {const gated = await runGate(authGate, { path: '/api/cos', headers: {} });expect(gated.called).toBe(false);expect(gated.res.statusCode).toBe(401);- expect(gated.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ expect(gated.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED', timestamp: expect.any(Number) });});it('stays fail-closed when a corrupt settings.json is loaded via reloadSettings (#2684)', async () => {@@ -116,7 +116,7 @@ describe('authGate middleware', () => {const result = await runGate(authGate, { path: '/api/cos', headers: {} });expect(result.called).toBe(false);expect(result.res.statusCode).toBe(401);- expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED', timestamp: expect.any(Number) });});it('allows /api routes when the cookie token is valid', async () => {@@ -166,7 +166,7 @@ describe('authGate middleware', () => {const result = await runGate(authGate, { path: '/sdapi/v1/sd-models', headers: {} });expect(result.called).toBe(false);expect(result.res.statusCode).toBe(401);- expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED' });+ expect(result.res.body).toEqual({ error: 'Authentication required', code: 'AUTH_REQUIRED', timestamp: expect.any(Number) });});it('treats a malformed cookie value as no token (clean 401, not 500)', async () => {diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex c2ebced9ba..13fd27f030 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -127,22 +127,50 @@ export function asyncHandler(fn) {console.error(details ? `${logMsg}: ${JSON.stringify(details)}` : logMsg);}- const safeContext = sanitizeContext(error.context);-- if (io) {- emitErrorEvent(io, error, safeContext);- }-- return res.status(error.status).json({- error: error.message,- code: error.code,- timestamp: error.timestamp,- ...(safeContext && Object.keys(safeContext).length > 0 && { context: safeContext })- });+ return sendErrorResponse(res, error, { io });});};}+/**+ * Build the standard PortOS error body: `{ error, code, timestamp }` plus a+ * `context` when the sanitized context has anything left in it. Every error+ * response the API emits goes through here so no route can invent its own+ * envelope shape.+ */+export function buildErrorEnvelope(error, safeContext) {+ return {+ error: error.message,+ code: error.code,+ timestamp: error.timestamp,+ ...(safeContext && Object.keys(safeContext).length > 0 && { context: safeContext })+ };+}++/**+ * Send an error as the standard envelope, sanitizing context once and (when an+ * `io` is supplied) emitting the matching socket event so the two channels+ * can't drift on what's stripped.+ *+ * Use this from anywhere that must answer a request OUTSIDE `asyncHandler`'s+ * catch — `res.sendFile` callbacks, middleware that short-circuits, PTY/timer+ * callbacks — where `throw` has nothing to bubble to. It never throws and+ * no-ops the write once headers are sent.+ *+ * @returns {ServerError} the normalized error, for callers that want to log it.+ */+export function sendErrorResponse(res, err, { io } = {}) {+ const error = normalizeError(err);+ const safeContext = sanitizeContext(error.context);+ if (io) {+ emitErrorEvent(io, error, safeContext);+ }+ if (!res.headersSent) {+ res.status(error.status).json(buildErrorEnvelope(error, safeContext));+ }+ return error;+}+/*** Walk an Error's `cause` chain (Node's native fetch wraps the actual reason* in `err.cause` — without unwrapping, server logs show only "fetch failed").@@ -295,24 +323,10 @@ export function errorMiddleware(err, req, res, next) {console.error(logMsg);}- // Sanitize once and share with both the socket event and the HTTP body so- // the two channels can't drift on what's stripped — mirrors asyncHandler.- const safeContext = sanitizeContext(error.context);-- // Emit Socket.IO event- if (io) {- emitErrorEvent(io, error, safeContext);- }-- // Send response. Include `context` (e.g. a service's `details` / `modelId`)- // when present, matching the envelope asyncHandler emits — synchronous- // handlers that throw a ServerError land here, not in asyncHandler.- res.status(error.status).json({- error: error.message,- code: error.code,- timestamp: error.timestamp,- ...(safeContext && Object.keys(safeContext).length > 0 && { context: safeContext })- });+ // Emit the socket event and send the shared envelope — synchronous handlers+ // that throw a ServerError land here, not in asyncHandler, so both paths must+ // produce the same body.+ sendErrorResponse(res, error, { io });}/**diff --git a/server/lib/errorHandler.test.js b/server/lib/errorHandler.test.jsindex 041b183ff3..783c0b1e83 100644--- a/server/lib/errorHandler.test.js+++ b/server/lib/errorHandler.test.js@@ -6,7 +6,9 @@ import {errorEvents,errorMiddleware,createServiceErrorMapper,- asyncHandler+ asyncHandler,+ buildErrorEnvelope,+ sendErrorResponse} from './errorHandler.js';// Build a fake Express req/res pair. `res.status()` and `res.json()` are@@ -382,4 +384,67 @@ describe('errorHandler.js', () => {expect(res.json.mock.calls[0][0].code).toBe('NOT_FOUND');});});++ describe('sendErrorResponse', () => {+ const makeRes = (overrides = {}) => {+ const res = { headersSent: false, ...overrides };+ res.status = vi.fn(() => res);+ res.json = vi.fn(() => res);+ return res;+ };++ it('emits the standard envelope for callers outside a handler catch', () => {+ const res = makeRes();+ sendErrorResponse(res, new ServerError('Sample not found', { status: 404 }));++ expect(res.status).toHaveBeenCalledWith(404);+ const body = res.json.mock.calls[0][0];+ expect(body.error).toBe('Sample not found');+ expect(body.code).toBe('NOT_FOUND');+ expect(typeof body.timestamp).toBe('number');+ });++ it('normalizes a plain Error and returns the ServerError to the caller', () => {+ const res = makeRes();+ const error = sendErrorResponse(res, new Error('kaboom'));++ expect(error).toBeInstanceOf(ServerError);+ expect(res.status).toHaveBeenCalledWith(500);+ expect(res.json.mock.calls[0][0].code).toBe('INTERNAL_ERROR');+ });++ it('does not write once headers are already sent', () => {+ const res = makeRes({ headersSent: true });+ sendErrorResponse(res, new ServerError('too late', { status: 404 }));++ expect(res.status).not.toHaveBeenCalled();+ expect(res.json).not.toHaveBeenCalled();+ });++ it('emits the socket event with the sanitized context when io is supplied', () => {+ const res = makeRes();+ const io = { emit: vi.fn() };+ // `errorEvents` is an EventEmitter — an 'error' emit with no listener+ // re-throws, so subscribe for the duration of this assertion.+ const listener = vi.fn();+ errorEvents.on('error', listener);+ sendErrorResponse(+ res,+ new ServerError('boom', { status: 400, context: { modelId: 'm', apiKey: 'secret' } }),+ { io }+ );++ const payload = io.emit.mock.calls.find(([event]) => event === 'error:occurred')[1];+ expect(payload.context).toEqual({ modelId: 'm' });+ expect(res.json.mock.calls[0][0].context).toEqual({ modelId: 'm' });+ errorEvents.off('error', listener);+ });+ });++ describe('buildErrorEnvelope', () => {+ it('omits context when the sanitized context is empty', () => {+ const body = buildErrorEnvelope(new ServerError('nope', { status: 400 }), {});+ expect(body).toEqual({ error: 'nope', code: 'BAD_REQUEST', timestamp: expect.any(Number) });+ });+ });});diff --git a/server/routes/loraTraining.js b/server/routes/loraTraining.jsindex e12718c8dc..4a5bd8b62a 100644--- a/server/routes/loraTraining.js+++ b/server/routes/loraTraining.js@@ -10,7 +10,7 @@ import { Router } from 'express';import { rm } from 'fs/promises';import { join } from 'path';import { z } from 'zod';-import { asyncHandler, ServerError } from '../lib/errorHandler.js';+import { asyncHandler, sendErrorResponse, ServerError } from '../lib/errorHandler.js';import { startTrainingRunSchema, validateRequest } from '../lib/validation.js';import { assertSafeFilename } from '../lib/fileUtils.js';import { resolveFlux2Python, isFlux2VenvHealthy, resolveMfluxPython } from '../lib/pythonSetup.js';@@ -155,8 +155,11 @@ router.get('/runs/:id/samples', asyncHandler(async (req, res) => {router.get('/runs/:id/samples/:filename', asyncHandler(async (req, res) => {const run = await getRunRequired(req.params.id);assertSafeFilename(req.params.filename, { extensions: ['.png'], subject: 'sample filename' });+ // The sendFile callback fires outside asyncHandler's catch (the handler's+ // promise has already resolved), so a throw here would have nothing to bubble+ // to — build the standard envelope directly instead.res.sendFile(join(runSamplesDir(run.id), req.params.filename), (err) => {- if (err && !res.headersSent) res.status(404).json({ error: 'Sample not found' });+ if (err) sendErrorResponse(res, new ServerError('Sample not found', { status: 404 }));});}));diff --git a/server/routes/loraTraining.test.js b/server/routes/loraTraining.test.jsnew file mode 100644index 0000000000..064e1fe467--- /dev/null+++ b/server/routes/loraTraining.test.js@@ -0,0 +1,70 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import express from 'express';+import { tmpdir } from 'os';+import { join } from 'path';+import { mkdtemp, writeFile } from 'fs/promises';+import { request } from '../lib/testHelper.js';++// The route module pulls in the whole training service graph at import time —+// stub every collaborator so the suite only exercises the HTTP layer.+const svc = vi.hoisted(() => ({ samplesDir: '' }));+vi.mock('../services/loraTraining/index.js', () => ({+ clearDatasetForDeletedLora: vi.fn(),+ deleteRun: vi.fn(),+ getRunRequired: vi.fn(async (id) => ({ id, status: 'completed' })),+ isMfluxTrainAvailable: () => false,+ listCheckpoints: vi.fn(),+ listRuns: vi.fn(),+ listSamples: vi.fn(),+ promoteCheckpoint: vi.fn(),+ resumeTrainingRun: vi.fn(),+ runDir: vi.fn(),+ runSamplesDir: () => svc.samplesDir,+ startTrainingRun: vi.fn(),+}));+vi.mock('../services/loraTraining/runtimes.js', () => ({ TRAINING_DEFAULTS: {} }));+vi.mock('../services/settings.js', () => ({ getSettings: async () => ({}) }));+vi.mock('../services/mediaJobQueue/index.js', () => ({+ attachSseClient: vi.fn(),+ cancelJob: vi.fn(),+}));+vi.mock('../services/loras.js', () => ({ deleteLora: vi.fn() }));+vi.mock('../lib/pythonSetup.js', () => ({+ resolveFlux2Python: () => null,+ isFlux2VenvHealthy: async () => false,+ resolveMfluxPython: () => null,+}));++import { errorMiddleware } from '../lib/errorHandler.js';+import loraTrainingRoutes from './loraTraining.js';++function makeApp() {+ const app = express();+ app.use('/api/lora-training', loraTrainingRoutes);+ app.use(errorMiddleware);+ return app;+}++describe('lora-training sample serving', () => {+ let app;+ beforeEach(async () => {+ app = makeApp();+ svc.samplesDir = await mkdtemp(join(tmpdir(), 'portos-lora-samples-'));+ });++ it('serves an existing sample', async () => {+ await writeFile(join(svc.samplesDir, 'step-1.png'), 'png-bytes');+ const r = await request(app).get('/api/lora-training/runs/run-1/samples/step-1.png');+ expect(r.status).toBe(200);+ });++ // The 404 fires from the sendFile callback, outside asyncHandler's catch —+ // it must still carry the shared `{ error, code, timestamp }` envelope (#2845).+ it('returns the standard error envelope when the sample is missing', async () => {+ const r = await request(app).get('/api/lora-training/runs/run-1/samples/missing.png');+ expect(r.status).toBe(404);+ expect(r.body.error).toBe('Sample not found');+ expect(r.body.code).toBe('NOT_FOUND');+ expect(typeof r.body.timestamp).toBe('number');+ });+});