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
feat([codex5-client-error-reporter]): surface browser errors in Review Hub
[._.]/ Adam Eivyec9adb21c58f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bb8b1dfd79..6ca247fa64 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -2,6 +2,7 @@## Added+- **[codex5-client-error-reporter] Browser-side errors and unhandled promise rejections surface in Review Hub.** Crashes that used to vanish into the browser console now land as Review Hub alerts so they can be triaged alongside server errors and CoS work. Repeats of the same error inside an hour aggregate into a single entry, and bursty render storms are throttled so the hub stays readable.- **[versioning-diff-view-per-stage-persist-last-n] Pipeline text stages now keep a version history.** Each regenerate snapshots the prior draft (up to five back) and a new "History" button on the Idea / Prose / Comic Script / Teleplay editors opens a side-by-side word diff against the current version with one-click restore.## Changeddiff --git a/PLAN.md b/PLAN.mdindex 01eb066210..7fbac6420f 100644--- a/PLAN.md+++ b/PLAN.md@@ -7,7 +7,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel- [ ] [agent-spawn-widen-try-finally-guard] **Widen the `spawningTasks` guard in `agentLifecycle.js` to cover the whole spawn path.** `server/services/agentLifecycle.js:~165` adds `task.id` to `spawningTasks` but the `try/finally` only wraps a narrow window; an uncaught throw inside `buildAgentPrompt`, `writeFile('prompt.txt')`, `createAgentRun`, or `registerAgent` (lines ~165–525) leaks the guard forever, permanently blocking re-spawns of that task id until process restart. Four `it.skip('TODO(plan.md backlog): …')` tests at `agentLifecycle.test.js:440-490` already pin the regression and flip green on fix. Single-user system means a stuck guard is silently un-recoverable.- [ ] [backport-pre-023-migrations-to-_lib] **Back-port pre-023 prompt-replace migrations onto `scripts/migrations/_lib.js`.** 003 / 004 / 005 / 006 / 010 / 013 / 019 all clone the inline `applyMigration` + per-file scan + customized-skip warning pattern that `_lib.js` now centralizes. Wrap any `OLD_SHIPPED_MD5: string` entries (003 / 004 / 006) into single-element arrays to match the `accepted[filename]: string[]` shape. Drop ~70 LOC per migration; nothing changes behaviorally so the only risk is mis-typed hashes — review each diff alongside a re-run of its test against the `_testHelpers.js` `runPromptMigrationTests`. Settled-history migrations have a higher rewrite-bar than active code, so a separate PR with focused review is appropriate. Surfaced by /simplify during `[pipeline-idea-stage-character-detail-plumbing]`.- [ ] [codex5-polling-consolidation] **[P2][PERF]** Migrate remaining `setInterval` callers to `useAutoRefetch`. The shared hook at `client/src/hooks/useAutoRefetch.js` exists; 20+ pages/components still spin local `setInterval`s — ChiefOfStaff, Brain, DigitalTwin, Loops, Browser, CyberCity, ImageGen, Ambient, AgentsPage, calendar, meatspace, city tabs. Migrate each to `useAutoRefetch` (which already provides the `document.visibilityState === 'hidden'` short-circuit); for domains with a Socket.IO event stream, switch to event-driven refetch instead of polling.-- [ ] [codex5-client-error-reporter] **[P2][OBSERVABILITY]** Funnel client errors into Review Hub. `client/src/main.jsx`'s `window.onerror` + `unhandledrejection` listeners only `console.log` today. Add `POST /api/client-errors` with redaction (drop tokens / long payloads) + rate-limit (~1/sec, drop duplicates by message+stack hash). Surface grouped client errors in the Review Hub feed; optionally raise a CoS task at a configurable threshold.- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Finish intent-named layouts + morning default + widget suggestions. `server/services/dashboardLayouts.js` seeds `morning-review` and `ops` already; still missing `Deep Work`, `Health`, `Agent Watch`. Add the three remaining seeded layouts, a "make this my morning default" toggle that activates a layout in a configured time window, and a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.- [ ] [migrate-two-remaining-local-formatters] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 88e6565177..e0065857bd 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -53,6 +53,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|+| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. || `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. || `genUtils.js` | Shared bits between Image Gen and Video Gen pages. || `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |diff --git a/client/src/lib/clientErrorReporter.js b/client/src/lib/clientErrorReporter.jsnew file mode 100644index 0000000000..d26f569be7--- /dev/null+++ b/client/src/lib/clientErrorReporter.js@@ -0,0 +1,138 @@+/**+ * Client error reporter — POSTs window.onerror + unhandledrejection events to+ * `/api/client-errors` for aggregation in the Review Hub.+ *+ * In-memory dedup (60s window per message+stack hash) plus a 1/sec throttle+ * to keep render storms from flooding the server; both mirror the server-side+ * aggregator's behavior so identical guards exist on both ends. The reporter+ * is fire-and-forget: it never throws, and any failure during fetch is+ * swallowed so the unhandledrejection handler can't recurse into itself.+ */++const ENDPOINT = '/api/client-errors';+const MIN_SEND_INTERVAL_MS = 1000;+const DEDUP_WINDOW_MS = 60 * 1000;+const MAX_RECENT = 64;++const recentHashes = new Map(); // hash -> firstSentAt+let lastSentAt = 0;++function hashString(input) {+ // Lightweight FNV-1a 32-bit, hex. Not cryptographic — only enough to+ // collapse repeated render storms before they cross the network.+ let h = 0x811c9dc5;+ for (let i = 0; i < input.length; i++) {+ h ^= input.charCodeAt(i);+ h = (h + ((h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24))) >>> 0;+ }+ return h.toString(16).padStart(8, '0');+}++function hashError(message, stack, source) {+ const stackKey = (stack || '').split('\n').slice(0, 3).join('\n');+ return hashString(`${message}\n${stackKey}\n${source || ''}`);+}++function pruneRecent(now) {+ for (const [hash, sentAt] of recentHashes) {+ if (now - sentAt > DEDUP_WINDOW_MS) recentHashes.delete(hash);+ }+ while (recentHashes.size > MAX_RECENT) {+ const oldest = recentHashes.keys().next().value;+ recentHashes.delete(oldest);+ }+}++function extractFromReason(reason) {+ if (reason instanceof Error) {+ return { message: reason.message || String(reason), stack: reason.stack };+ }+ if (reason && typeof reason === 'object') {+ return { message: String(reason.message ?? JSON.stringify(reason)), stack: reason.stack };+ }+ return { message: String(reason ?? 'Unknown'), stack: undefined };+}++/**+ * Build the report payload from a raw browser event description. Exported for+ * tests; production wires call `reportClientError` directly.+ */+export function buildPayload(input) {+ const base = {+ type: input.type === 'unhandledrejection' ? 'unhandledrejection' : 'error',+ url: typeof window !== 'undefined' ? window.location.href : undefined,+ userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : undefined,+ };++ if (input.type === 'unhandledrejection') {+ const { message, stack } = extractFromReason(input.reason);+ return { ...base, message, stack };+ }++ if (input.error instanceof Error) {+ return {+ ...base,+ message: input.error.message || input.message || 'Unknown error',+ stack: input.error.stack,+ source: input.filename,+ line: input.lineno,+ column: input.colno,+ };+ }++ return {+ ...base,+ message: input.message || 'Unknown error',+ source: input.filename,+ line: input.lineno,+ column: input.colno,+ };+}++/**+ * Report a client-side error. Resolves to:+ * - `{ sent: true }` — sent to the server.+ * - `{ sent: false, reason: 'duplicate' | 'rate-limited' | 'no-fetch' | 'transport-error' }`+ *+ * Never throws.+ */+export async function reportClientError(input) {+ if (typeof fetch !== 'function') return { sent: false, reason: 'no-fetch' };++ const payload = buildPayload(input);+ if (!payload.message) return { sent: false, reason: 'empty' };++ const now = Date.now();+ if (now - lastSentAt < MIN_SEND_INTERVAL_MS) {+ return { sent: false, reason: 'rate-limited' };+ }+ const hash = hashError(payload.message, payload.stack, payload.source);+ if (recentHashes.has(hash)) {+ return { sent: false, reason: 'duplicate' };+ }++ recentHashes.set(hash, now);+ lastSentAt = now;+ pruneRecent(now);++ // Raw `fetch` (not the shared `request()` helper) because we need+ // `keepalive: true` so the POST survives a tab unload triggered by the+ // crash itself, and we must never throw — an exception inside the+ // `unhandledrejection` handler would itself become an unhandled rejection.+ const ok = await fetch(ENDPOINT, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(payload),+ keepalive: true,+ }).then(r => r.ok).catch(() => false);++ return ok ? { sent: true } : { sent: false, reason: 'transport-error' };+}++/**+ * Reset all in-memory state. Test-only.+ */+export function _resetForTests() {+ recentHashes.clear();+ lastSentAt = 0;+}diff --git a/client/src/lib/clientErrorReporter.test.js b/client/src/lib/clientErrorReporter.test.jsnew file mode 100644index 0000000000..3b2d5e4ce3--- /dev/null+++ b/client/src/lib/clientErrorReporter.test.js@@ -0,0 +1,101 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { reportClientError, buildPayload, _resetForTests } from './clientErrorReporter';++beforeEach(() => {+ _resetForTests();+ vi.restoreAllMocks();+ globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true }));+});++describe('buildPayload', () => {+ it('extracts message + stack from an unhandledrejection Error reason', () => {+ const err = new Error('rejected!');+ err.stack = 'Error: rejected!\n at foo (foo.js:1:1)';+ const out = buildPayload({ type: 'unhandledrejection', reason: err });+ expect(out.type).toBe('unhandledrejection');+ expect(out.message).toBe('rejected!');+ expect(out.stack).toContain('foo.js');+ });++ it('handles unhandledrejection with a string reason', () => {+ const out = buildPayload({ type: 'unhandledrejection', reason: 'plain string' });+ expect(out.message).toBe('plain string');+ expect(out.stack).toBeUndefined();+ });++ it('extracts message + stack + filename/lineno/colno from an error event', () => {+ const err = new Error('boom');+ err.stack = 'Error: boom\n at foo (foo.js:1:1)';+ const out = buildPayload({+ type: 'error',+ error: err,+ message: 'unhelpful',+ filename: 'foo.js',+ lineno: 1,+ colno: 1,+ });+ expect(out.message).toBe('boom');+ expect(out.source).toBe('foo.js');+ expect(out.line).toBe(1);+ expect(out.column).toBe(1);+ });+});++describe('reportClientError', () => {+ it('POSTs the payload to /api/client-errors and resolves with { sent: true }', async () => {+ const result = await reportClientError({ type: 'error', message: 'boom' });+ expect(result.sent).toBe(true);+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const [url, init] = globalThis.fetch.mock.calls[0];+ expect(url).toBe('/api/client-errors');+ expect(init.method).toBe('POST');+ expect(init.headers['Content-Type']).toBe('application/json');+ const body = JSON.parse(init.body);+ expect(body.type).toBe('error');+ expect(body.message).toBe('boom');+ });++ it('drops duplicate reports without re-sending', async () => {+ const payload = {+ type: 'error',+ message: 'same',+ error: Object.assign(new Error('same'), { stack: 'Error\n at foo (foo.js:1:1)' }),+ };+ const first = await reportClientError(payload);+ expect(first.sent).toBe(true);++ const realNow = Date.now;+ vi.spyOn(Date, 'now').mockReturnValue(realNow() + 2000);++ const second = await reportClientError(payload);+ expect(second.sent).toBe(false);+ expect(second.reason).toBe('duplicate');+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);++ Date.now = realNow;+ });++ it('rate-limits reports that arrive faster than once per second', async () => {+ const first = await reportClientError({ type: 'error', message: 'a' });+ expect(first.sent).toBe(true);++ const second = await reportClientError({ type: 'error', message: 'b' });+ expect(second.sent).toBe(false);+ expect(second.reason).toBe('rate-limited');+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ });++ it('returns transport-error when fetch rejects, never throws', async () => {+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('offline')));+ const result = await reportClientError({ type: 'error', message: 'boom' });+ expect(result.sent).toBe(false);+ expect(result.reason).toBe('transport-error');+ });++ it('returns transport-error when fetch resolves with !ok', async () => {+ globalThis.fetch = vi.fn(() => Promise.resolve({ ok: false }));+ const result = await reportClientError({ type: 'error', message: 'boom' });+ expect(result.sent).toBe(false);+ expect(result.reason).toBe('transport-error');+ });+});diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex f76a3b041e..fce2795092 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -24,6 +24,7 @@ export * from './wrImageDefaults.js';export * from './graphSimulation.js';// === Generic UI / collection utilities ===+export * from './clientErrorReporter.js';export * from './clipboard.js';export * from './genUtils.js';export * from './joinInfluenceList.js';diff --git a/client/src/main.jsx b/client/src/main.jsxindex 872f7aeff4..dd1f32f80a 100644--- a/client/src/main.jsx+++ b/client/src/main.jsx@@ -5,6 +5,7 @@ import { Toaster } from './components/ui/Toast';import ErrorBoundary from './components/ErrorBoundary';import { ThemeProvider } from './components/ThemeContext';import { isStaleChunkError, reloadOnceForStaleChunk } from './utils/staleChunkReload';+import { reportClientError } from './lib/clientErrorReporter';import App from './App';import './index.css';@@ -24,12 +25,21 @@ window.addEventListener('unhandledrejection', (event) => {return;}console.error(`❌ Unhandled Promise Rejection: ${event.reason}`);+ reportClientError({ type: 'unhandledrejection', reason: event.reason });event.preventDefault();});// Handle global errorswindow.addEventListener('error', (event) => {console.error(`💥 Global Error: ${event.message}`);+ reportClientError({+ type: 'error',+ message: event.message,+ error: event.error,+ filename: event.filename,+ lineno: event.lineno,+ colno: event.colno,+ });});ReactDOM.createRoot(document.getElementById('root')).render(diff --git a/server/index.js b/server/index.jsindex 6bbec15253..ad1b095a56 100644--- a/server/index.js+++ b/server/index.js@@ -28,6 +28,7 @@ import gitRoutes from './routes/git.js';import usageRoutes from './routes/usage.js';import screenshotsRoutes from './routes/screenshots.js';import attachmentsRoutes from './routes/attachments.js';+import clientErrorsRoutes from './routes/clientErrors.js';import uploadsRoutes from './routes/uploads.js';import imageCleanRoutes from './routes/imageClean.js';import agentsRoutes from './routes/agents.js';@@ -350,6 +351,7 @@ app.use('/api/dashboard/layouts', dashboardLayoutsRoutes);app.use('/api/media/collections', mediaCollectionsRoutes);app.use('/api/media/annotations', mediaAnnotationsRoutes);app.use('/api/attachments', attachmentsRoutes);+app.use('/api/client-errors', clientErrorsRoutes);app.use('/api/backup', backupRoutes);app.use('/api/database', databaseRoutes);app.use('/api/uploads', uploadsRoutes);diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex 454231d06a..a53b58e886 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -16,15 +16,22 @@ const causeSuffix = (error) =>error.context?.causeChain ? ` ← ${error.context.causeChain}` : '';/**- * Build the path portion of a request URL for logging — strips the query- * string so tokens (e.g. `?access_token=…`) don't leak into server logs.- * Falls back through `originalUrl` → `url` → '/'.+ * Strip the `?query` (and everything after) from a URL or request path so+ * tokens like `?access_token=…` don't leak into server logs or stored error+ * reports. Returns the input unchanged when there is no query string.*/-const routePath = (req) => {- const raw = req.originalUrl || req.url || '/';- const qIndex = raw.indexOf('?');- return qIndex === -1 ? raw : raw.slice(0, qIndex);-};+export function stripQueryString(url) {+ if (typeof url !== 'string') return url;+ const qIndex = url.indexOf('?');+ return qIndex === -1 ? url : url.slice(0, qIndex);+}++/**+ * Build the path portion of a request URL for logging. Falls back through+ * `originalUrl` → `url` → '/' and runs `stripQueryString` to keep tokens out+ * of server logs.+ */+const routePath = (req) => stripQueryString(req.originalUrl || req.url || '/');/*** Enhanced error object with metadatadiff --git a/server/lib/validation.js b/server/lib/validation.jsindex e75c86cb5c..e229075c9e 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -959,6 +959,27 @@ export function validateRequest(schema, data) {});}+// =============================================================================+// CLIENT ERROR REPORT+// =============================================================================++// Browser-emitted error reports (window.onerror + unhandledrejection).+// The field caps here are outer bounds — anything bigger is a runaway producer+// and is refused before validation; the storage-size caps live in+// services/clientErrors.js and are intentionally lower (the Review Hub entry+// is a UI surface, not a forensic log).+export const CLIENT_ERROR_TYPES = ['error', 'unhandledrejection'];+export const clientErrorReportSchema = z.object({+ type: z.enum(CLIENT_ERROR_TYPES),+ message: z.string().min(1).max(2000),+ stack: z.string().max(20000).optional(),+ source: z.string().max(2000).optional(),+ line: z.number().int().nonnegative().optional(),+ column: z.number().int().nonnegative().optional(),+ url: z.string().max(2000).optional(),+ userAgent: z.string().max(1000).optional(),+});+// =============================================================================// PAGINATION HELPERS// =============================================================================diff --git a/server/routes/clientErrors.js b/server/routes/clientErrors.jsnew file mode 100644index 0000000000..01ebde4a01--- /dev/null+++ b/server/routes/clientErrors.js@@ -0,0 +1,23 @@+/**+ * Client Error Reporter Routes+ *+ * POST /api/client-errors — receive a browser-side error report. Aggregation+ * (rate-limit + dedup + redaction) happens in services/clientErrors.js; the+ * response surfaces accepted/duplicate/rate-limited so the client can log it+ * but never retry — duplicates are expected during render storms.+ */++import { Router } from 'express';+import { asyncHandler } from '../lib/errorHandler.js';+import { validateRequest, clientErrorReportSchema } from '../lib/validation.js';+import { recordClientError } from '../services/clientErrors.js';++const router = Router();++router.post('/', asyncHandler(async (req, res) => {+ const payload = validateRequest(clientErrorReportSchema, req.body);+ const result = await recordClientError(payload);+ res.status(202).json(result);+}));++export default router;diff --git a/server/routes/clientErrors.test.js b/server/routes/clientErrors.test.jsnew file mode 100644index 0000000000..463d0c372b--- /dev/null+++ b/server/routes/clientErrors.test.js@@ -0,0 +1,88 @@+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/clientErrors.js', () => ({+ recordClientError: vi.fn(),+}));++const svc = await import('../services/clientErrors.js');+const { default: routes } = await import('./clientErrors.js');++const makeApp = () => {+ const app = express();+ app.use(express.json());+ app.use('/api/client-errors', routes);+ app.use(errorMiddleware);+ return app;+};++beforeEach(() => {+ vi.clearAllMocks();+});++describe('POST /api/client-errors', () => {+ it('accepts a well-formed error payload and forwards it to the service', async () => {+ svc.recordClientError.mockResolvedValue({ accepted: true, itemId: 'r1' });+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({+ type: 'error',+ message: 'boom',+ stack: 'Error: boom\n at foo (foo.js:1:1)',+ url: 'https://portos/dash',+ });++ expect(res.status).toBe(202);+ expect(res.body).toEqual({ accepted: true, itemId: 'r1' });+ expect(svc.recordClientError).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'error', message: 'boom' }),+ );+ });++ it('accepts an unhandledrejection payload', async () => {+ svc.recordClientError.mockResolvedValue({ accepted: true, itemId: 'r2' });+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({ type: 'unhandledrejection', message: 'rejected' });+ expect(res.status).toBe(202);+ expect(svc.recordClientError).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'unhandledrejection' }),+ );+ });++ it('echoes back the dedup / rate-limit reasons from the service', async () => {+ svc.recordClientError.mockResolvedValue({ accepted: false, reason: 'duplicate' });+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({ type: 'error', message: 'boom' });+ expect(res.status).toBe(202);+ expect(res.body).toEqual({ accepted: false, reason: 'duplicate' });+ });++ it('rejects an unknown type with 400', async () => {+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({ type: 'panic', message: 'boom' });+ expect(res.status).toBe(400);+ expect(res.body.code).toBe('VALIDATION_ERROR');+ expect(svc.recordClientError).not.toHaveBeenCalled();+ });++ it('rejects a payload with a message that exceeds the cap', async () => {+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({ type: 'error', message: 'x'.repeat(2001) });+ expect(res.status).toBe(400);+ expect(svc.recordClientError).not.toHaveBeenCalled();+ });++ it('rejects a payload missing the message field', async () => {+ const res = await request(makeApp())+ .post('/api/client-errors')+ .send({ type: 'error' });+ expect(res.status).toBe(400);+ expect(svc.recordClientError).not.toHaveBeenCalled();+ });+});diff --git a/server/services/clientErrors.js b/server/services/clientErrors.jsnew file mode 100644index 0000000000..6f851acfa6--- /dev/null+++ b/server/services/clientErrors.js@@ -0,0 +1,174 @@+/**+ * Client Error Aggregator+ *+ * Receives error reports from the browser (window.onerror / unhandledrejection+ * via POST /api/client-errors), redacts obvious secrets, de-duplicates by+ * message+stack hash, throttles to a slow trickle, and surfaces unique+ * groups in the Review Hub.+ *+ * Single-user / single-process — in-memory rate-limit and dedup state is fine.+ */++import { createHash } from 'crypto';+import * as reviewService from './review.js';+import { redactOutput } from '../lib/commandSecurity.js';+import { stripQueryString } from '../lib/errorHandler.js';++const MAX_MESSAGE_CHARS = 500;+const MAX_STACK_CHARS = 4000;+const MAX_URL_CHARS = 500;+const MAX_USER_AGENT_CHARS = 300;++// Throttle: backstop against a buggy client that bypasses its own throttle.+// At steady state the client is the primary limiter; this guarantees the+// server can't be DoS'd into writing the Review Hub at line rate.+const MIN_ACCEPT_INTERVAL_MS = 1000;+// Dedup window matches `reviewService.createItem`'s own alert-dedup window+// (24h, keyed off `metadata.referenceId`) so an entry that evicts here+// doesn't desync from the downstream "you already have this alert" check.+const DEDUP_WINDOW_MS = 24 * 60 * 60 * 1000;+const MAX_HASH_ENTRIES = 256;++// Tokens that should never appear in stored fields. Pattern-based so we do+// not bind to any one provider's secret shape — anything with an obvious+// auth-ish silhouette (key=value, key: value, `bearer <token>`, or a known+// provider prefix) is stripped. JSON `"KEY":"value"` shapes are caught by+// the shared `redactOutput` helper below.+const SECRET_LIKE_PATTERNS = [+ /(api[_-]?key|access[_-]?token|secret|password|authorization)\s*[=:]\s*['"]?[\w.\-/+=]{8,}/gi,+ /\bbearer\s+[\w.\-/+=]{12,}/gi,+ /\bsk-[A-Za-z0-9\-_]{16,}/g,+ /\bAKIA[0-9A-Z]{16}\b/g,+];++const REDACTED = '[REDACTED]';++const recentHashes = new Map(); // hash -> firstSeenAt+let lastAcceptedAt = 0;++function redactSecrets(str) {+ if (typeof str !== 'string' || !str) return str;+ let out = redactOutput(str);+ for (const re of SECRET_LIKE_PATTERNS) out = out.replace(re, REDACTED);+ return out;+}++function truncate(str, max) {+ if (typeof str !== 'string') return undefined;+ const trimmed = str.trim();+ if (!trimmed) return undefined;+ return trimmed.length > max ? `${trimmed.slice(0, max)}…` : trimmed;+}++function sanitize(payload) {+ const message = redactSecrets(truncate(payload.message, MAX_MESSAGE_CHARS)) || 'Unknown client error';+ const stack = redactSecrets(truncate(payload.stack, MAX_STACK_CHARS));+ const url = truncate(stripQueryString(payload.url), MAX_URL_CHARS);+ const userAgent = truncate(payload.userAgent, MAX_USER_AGENT_CHARS);+ const source = truncate(payload.source, MAX_URL_CHARS);+ return {+ type: payload.type,+ message,+ stack,+ url,+ userAgent,+ source,+ line: Number.isInteger(payload.line) ? payload.line : undefined,+ column: Number.isInteger(payload.column) ? payload.column : undefined,+ };+}++function hashError({ message, stack, source }) {+ // Stack frames carry line/column noise that diverges across builds; key+ // on the first 3 lines so a true regression dedups across HMR cycles.+ const stackKey = (stack || '').split('\n').slice(0, 3).join('\n');+ return createHash('sha256').update(`${message}${stackKey}${source || ''}`).digest('hex').slice(0, 16);+}++function buildDescription(payload) {+ const lines = [];+ if (payload.url) lines.push(`URL: ${payload.url}`);+ if (payload.source) {+ const loc = [payload.source];+ if (payload.line != null) loc.push(`:${payload.line}`);+ if (payload.column != null) loc.push(`:${payload.column}`);+ lines.push(`Source: ${loc.join('')}`);+ }+ if (payload.userAgent) lines.push(`UA: ${payload.userAgent}`);+ if (payload.type) lines.push(`Type: ${payload.type}`);+ if (payload.stack) lines.push('', payload.stack);+ return lines.join('\n');+}++function buildTitle(payload) {+ const prefix = payload.type === 'unhandledrejection' ? 'Unhandled rejection' : 'Client error';+ return `${prefix}: ${payload.message.slice(0, 120)}`;+}++function pruneRecent(now) {+ for (const [hash, firstSeenAt] of recentHashes) {+ if (now - firstSeenAt > DEDUP_WINDOW_MS) recentHashes.delete(hash);+ }+ while (recentHashes.size > MAX_HASH_ENTRIES) {+ const oldest = recentHashes.keys().next().value;+ recentHashes.delete(oldest);+ }+}++/**+ * Record a client error report.+ *+ * Resolves to `{ accepted, reason?, itemId? }`. Never throws — a Review Hub+ * write failure is logged and reported as `reason: 'review-hub-write-failed'`+ * so the route stays write-once / no-retry.+ */+export async function recordClientError(rawPayload) {+ const now = Date.now();++ // Throttle gate runs before sanitize so a flooded endpoint doesn't burn the+ // regex passes on a payload we're about to drop. The 24h dedup window does+ // the heavy lifting for repeated identical errors; this is the safety net.+ if (now - lastAcceptedAt < MIN_ACCEPT_INTERVAL_MS) {+ return { accepted: false, reason: 'rate-limited' };+ }++ const payload = sanitize(rawPayload);+ const hash = hashError(payload);++ if (recentHashes.has(hash)) {+ return { accepted: false, reason: 'duplicate' };+ }++ const item = await reviewService.createItem({+ type: 'alert',+ title: buildTitle(payload),+ description: buildDescription(payload),+ metadata: {+ referenceId: `client-error:${hash}`,+ category: 'client-error',+ kind: payload.type,+ source: payload.source,+ line: payload.line,+ column: payload.column,+ url: payload.url,+ },+ }).catch(err => {+ console.error(`❌ Failed to record client error to Review Hub: ${err.message}`);+ return null;+ });++ if (!item) return { accepted: false, reason: 'review-hub-write-failed' };++ recentHashes.set(hash, now);+ lastAcceptedAt = now;+ pruneRecent(now);+ return { accepted: true, itemId: item.id };+}++/**+ * Reset all in-memory state. Test-only — never called from production paths.+ */+export function _resetForTests() {+ recentHashes.clear();+ lastAcceptedAt = 0;+}diff --git a/server/services/clientErrors.test.js b/server/services/clientErrors.test.jsnew file mode 100644index 0000000000..b99ca30939--- /dev/null+++ b/server/services/clientErrors.test.js@@ -0,0 +1,123 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./review.js', () => ({+ createItem: vi.fn(),+}));++const review = await import('./review.js');+const { recordClientError, _resetForTests } = await import('./clientErrors.js');++beforeEach(() => {+ vi.clearAllMocks();+ _resetForTests();+ review.createItem.mockImplementation(async ({ title, metadata }) => ({+ id: `item-${metadata?.referenceId ?? title}`,+ title,+ metadata,+ }));+});++describe('recordClientError', () => {+ it('forwards the first report to Review Hub as an alert with a referenceId', async () => {+ const result = await recordClientError({+ type: 'error',+ message: 'Cannot read properties of undefined',+ stack: 'TypeError: x\n at Foo (foo.js:1:1)',+ url: 'https://portos/dashboard',+ source: '/assets/index.js',+ line: 42,+ column: 7,+ });++ expect(result.accepted).toBe(true);+ expect(review.createItem).toHaveBeenCalledTimes(1);+ const arg = review.createItem.mock.calls[0][0];+ expect(arg.type).toBe('alert');+ expect(arg.title).toMatch(/^Client error: /);+ expect(arg.metadata.category).toBe('client-error');+ expect(arg.metadata.referenceId).toMatch(/^client-error:[0-9a-f]{16}$/);+ });++ it('redacts api-key-shaped secrets in the message and stack', async () => {+ await recordClientError({+ type: 'error',+ message: 'fetch failed with apiKey="sk-abcdef0123456789abcdef0123" and details',+ stack: 'Error\n at AuthorizedRequest (api.js:5:9) bearer abcdef0123456789abcdef',+ });++ const arg = review.createItem.mock.calls[0][0];+ expect(arg.title).toContain('[REDACTED]');+ expect(arg.description).toContain('[REDACTED]');+ expect(arg.description).not.toContain('sk-abcdef0123456789abcdef0123');+ });++ it('strips the query string from the captured page URL', async () => {+ await recordClientError({+ type: 'error',+ message: 'boom',+ url: 'https://portos/secret?token=keepout',+ });++ const arg = review.createItem.mock.calls[0][0];+ expect(arg.description).toContain('URL: https://portos/secret');+ expect(arg.description).not.toContain('token=keepout');+ });++ it('drops duplicate reports within the dedup window', async () => {+ const payload = {+ type: 'error',+ message: 'same error',+ stack: 'Error: same error\n at foo (foo.js:1:1)\n at bar (bar.js:2:2)',+ };+ const first = await recordClientError(payload);+ expect(first.accepted).toBe(true);++ // Wait past the 1s rate-limit so the dedup branch (not rate-limit) is exercised.+ const realDateNow = Date.now;+ const fakeNow = realDateNow() + 2000;+ vi.spyOn(Date, 'now').mockReturnValue(fakeNow);++ const second = await recordClientError(payload);+ expect(second.accepted).toBe(false);+ expect(second.reason).toBe('duplicate');+ expect(review.createItem).toHaveBeenCalledTimes(1);++ Date.now = realDateNow;+ });++ it('drops reports that arrive faster than the 1/sec throttle', async () => {+ const first = await recordClientError({+ type: 'error',+ message: 'err A',+ stack: 'Error: A\n at a (a.js:1:1)',+ });+ expect(first.accepted).toBe(true);++ const second = await recordClientError({+ type: 'error',+ message: 'err B',+ stack: 'Error: B\n at b (b.js:1:1)',+ });+ expect(second.accepted).toBe(false);+ expect(second.reason).toBe('rate-limited');+ expect(review.createItem).toHaveBeenCalledTimes(1);+ });++ it('truncates oversize messages and stacks rather than passing them through', async () => {+ await recordClientError({+ type: 'error',+ message: 'm'.repeat(2000),+ stack: 's'.repeat(20000),+ });+ const arg = review.createItem.mock.calls[0][0];+ expect(arg.title.length).toBeLessThan(200);+ expect(arg.description.length).toBeLessThan(5000);+ });++ it('returns a failure marker when the Review Hub write fails', async () => {+ review.createItem.mockRejectedValueOnce(new Error('disk full'));+ const result = await recordClientError({ type: 'error', message: 'boom' });+ expect(result.accepted).toBe(false);+ expect(result.reason).toBe('review-hub-write-failed');+ });+});