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
ignore browser-extension errors in the Review Hub, and fix the toast crash they were masking
[._.]/ Adam Eivy1ad71c68b9d8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 76cbba9c6b..7680525bd8 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -19,6 +19,8 @@- The Chief of Staff status panel's Learning card no longer spills its skipped-task count outside the card on mobile. The "(3 skipped)" note used to sit beside the success rate on one line, where it was too wide to fit a narrow card and rendered past the border; it now sits on its own line under the percentage and truncates if it can't fit.- The Brain **Graph** tab is now usable on a phone. The graph canvas sizes itself to the viewport instead of a fixed 500px (which overflowed a landscape phone entirely and left no room to scroll past a canvas that swallows drags), the controls bar stacks into readable rows instead of cramming a breadcrumb, seven type filters, and both buttons into one line, and the type filters wrap with a proper tap target. The legend — ten rows that blanketed a phone-sized graph — now shows automatically only when there's room for it and collapses behind a "Legend" toggle everywhere else, including a landscape phone (which is wide enough to look like a desktop but far too short). The hover tooltip no longer flashes under your finger advertising a double-click that touch can't do (tap the node and use the detail panel's "Explore connections" instead), and it no longer runs off the right edge in a narrow window. "Explore connections" moved out of a cramped side column onto its own full-width row, above the record text so it stays reachable on a long entry.- [issue-2669] The Series Pipeline no longer shows two stacked error toasts when a stage or arc action fails — the custom-catch callers now pass `{ silent: true }` so only their own toast fires, not the shared `request()` helper's default one too. Swept the pipeline stages/canvas area (ArcCanvas, the Audio/ComicPages/ComicScript/Storyboards/Idea stages, and the Pipeline series/issue/manuscript-editor pages, including the `useLockToggle` volume lock and the `useAsyncAction` editorial review) and threaded a backward-compatible `options` arg into the affected API wrappers (arc generate/verify/resolve/derive, volume beats + episodes, season and issue CRUD, stage generate/extract/render/refine, manuscript fetch + completeness, and the audio line/music-library calls).+- **The Review Hub no longer files alerts for browser-extension errors.** Extensions (crypto wallets, password managers, ad blockers) inject scripts into the page, so anything they throw — "Failed to connect to MetaMask" and friends — used to surface as an actionable PortOS alert even though nothing in the app can fix it. Those errors are now identified by their provenance (the failing script lives at a `chrome-extension://` / `moz-extension://` / Safari-extension URL) and dropped both in the browser and on the server, with a narrow message check for wallet rejections that arrive with no stack at all. Any such alerts already sitting in your hub are dismissed once on upgrade, so you don't have to clear them by hand. This also stops extension noise from crowding out real errors: each end accepts at most one error per second, so an extension error used to silently swallow a genuine PortOS failure that happened a moment later.+- **Every toast crashed when PortOS was reached over plain HTTP.** Toast ids were minted with `crypto.randomUUID()`, which browsers only expose on secure origins — so over Tailscale on `http://`, any toast threw `crypto.randomUUID is not a function`, including the error toasts meant to tell you a request had failed. Ids now come from a shared `uuidv4()` helper that falls back to `crypto.getRandomValues` (available on insecure origins) and still yields a spec-valid v4. This is what produced the `crypto.randomUUID` alerts in the Review Hub — it was PortOS's own bug, not an extension, so it is deliberately still reported.- [issue-2669] Sharing, Messages, and Calendar screens no longer show two stacked error toasts when a share/subscribe/export/save/sync action fails — the custom-catch callers now pass `{ silent: true }` so only their own toast fires, not the shared `request()` helper's default one too. Swept the Messages/calendar/sharing feature area (both ConfigTabs, InboxTab, ReviewTab, ShareToButton, and the Sharing page) and threaded a backward-compatible `options` arg into the affected API wrappers (`evaluateMessages`, `enableGmailApi`, `getGoogleAuthUrl`, `create/updateMessageAccount`, `create/updateCalendarAccount`, `updateSubcalendars`, `saveGoogleAuthCredentials`, `start/runGoogleAutoConfig`, `confirmDailyReviewEvent`).- Creative Director projects that use the Antigravity provider no longer get stuck on "Planning." The agent now reliably receives its instructions instead of launching and sitting idle at an empty prompt (it waits for Antigravity's input box to be ready before sending, the same way the Claude provider does), so planning actually runs to completion.- A Creative Director project no longer wedges in "Planning" when its agent is interrupted or crashes mid-run. The stuck run is now cleaned up as soon as the dead agent is detected, so the project can retry on its own instead of waiting for the next server restart.diff --git a/client/eslint.config.js b/client/eslint.config.jsindex 2da4a04c89..07e9cd224f 100644--- a/client/eslint.config.js+++ b/client/eslint.config.js@@ -103,6 +103,18 @@ export default [caughtErrorsIgnorePattern: '^_'}],'no-undef': 'error',+ // `crypto.randomUUID` only exists in a SECURE context. PortOS is routinely+ // reached over plain HTTP via Tailscale, where it is undefined — so every+ // bare call is a crash for the users on that deployment (it took out every+ // toast until `lib/uuid.js` landed). The footgun was independently+ // rediscovered at half a dozen sites, each inventing a different+ // workaround, so a shared helper alone was not enough to stop it: this+ // rule is what actually holds the line. `no-restricted-properties` is NOT+ // a substitute — it misses `globalThis.crypto.randomUUID`.+ 'no-restricted-syntax': ['error', {+ selector: "MemberExpression[property.name='randomUUID']",+ message: 'crypto.randomUUID is undefined on insecure origins (PortOS over plain HTTP via Tailscale). Import { uuidv4 } from lib/uuid.js instead.',+ }],'no-useless-escape': 'error','react-hooks/rules-of-hooks': 'error',// exhaustive-deps is dominated by the deliberate run-once-on-mount pattern across@@ -124,4 +136,12 @@ export default ['react-hooks/globals': 'off',},},+ {+ // `lib/uuid.js` is the one place allowed to probe `crypto.randomUUID` — it+ // exists to wrap it. Tests may reference it to simulate an insecure origin.+ files: ['src/lib/uuid.js', 'src/**/*.test.{js,jsx}'],+ rules: {+ 'no-restricted-syntax': 'off',+ },+ },];diff --git a/client/src/components/ui/Toast.jsx b/client/src/components/ui/Toast.jsxindex 0b109908cd..33a3b50d2e 100644--- a/client/src/components/ui/Toast.jsx+++ b/client/src/components/ui/Toast.jsx@@ -5,6 +5,7 @@*/import { useState, useEffect } from 'react';+import { uuidv4 } from '../../lib/uuid.js';let toasts = [];const listeners = new Set();@@ -26,7 +27,10 @@ const fingerprintFor = (content, type) =>typeof content === 'string' ? `${type}::${content}` : null;function add(content, opts = {}, type = 'default') {- const id = opts.id || crypto.randomUUID();+ // `uuidv4`, not `crypto.randomUUID` — the latter is undefined on insecure+ // origins (PortOS over plain HTTP via Tailscale), where it threw out of+ // every toast, including the ones the API client raises to report a failure.+ const id = opts.id || uuidv4();const duration = opts.duration !== undefined ? opts.duration : (type === 'loading' ? Infinity : DEFAULT_DURATION);// Skip if an identical toast was just shown — but only when the callerdiff --git a/client/src/components/ui/Toast.test.jsx b/client/src/components/ui/Toast.test.jsxindex 5cef0d5745..94f40741dc 100644--- a/client/src/components/ui/Toast.test.jsx+++ b/client/src/components/ui/Toast.test.jsx@@ -1,4 +1,4 @@-import { describe, it, expect, afterEach } from 'vitest';+import { describe, it, expect, afterEach, vi } from 'vitest';import { render, screen, cleanup, act } from '@testing-library/react';import { toast, Toaster } from './Toast.jsx';@@ -6,6 +6,25 @@ import { toast, Toaster } from './Toast.jsx';afterEach(() => {act(() => toast.dismiss());cleanup();+ vi.unstubAllGlobals();+});++describe('Toast on an insecure origin', () => {+ // Regression: `add()` minted ids with a bare `crypto.randomUUID()`, which is+ // undefined outside a secure context. PortOS is routinely reached over plain+ // HTTP via Tailscale, so EVERY toast threw `crypto.randomUUID is not a+ // function` there — including the error toasts the API client raises to+ // report a failure, which surfaced it as an unhandled rejection.+ it('renders without crypto.randomUUID (plain HTTP via Tailscale)', () => {+ vi.stubGlobal('crypto', {+ getRandomValues: globalThis.crypto.getRandomValues.bind(globalThis.crypto),+ });+ expect(globalThis.crypto.randomUUID).toBeUndefined();++ render(<Toaster />);+ expect(() => act(() => { toast.error('Request failed'); })).not.toThrow();+ expect(screen.getByRole('alert')).toHaveTextContent('Request failed');+ });});describe('Toaster accessibility', () => {diff --git a/client/src/hooks/usePendingListRows.js b/client/src/hooks/usePendingListRows.jsindex bd1d9edf92..0adcabbf1e 100644--- a/client/src/hooks/usePendingListRows.js+++ b/client/src/hooks/usePendingListRows.js@@ -25,16 +25,12 @@// into promotion is the user blurring the required column (no live// drafts on sibling columns at that moment).//-// `globalThis.crypto` rather than bare `crypto`: bare `crypto?.…` throws-// ReferenceError in some non-secure-context envs; going through `globalThis`-// short-circuits cleanly to the Date+Math fallback.import { useState } from 'react';+import { uuidv4 } from '../lib/uuid.js';-function mintId(prefix) {- const uuid = globalThis.crypto?.randomUUID?.()- ?? `${Date.now().toString(36)}${Math.random().toString(36).slice(2)}`;- return `${prefix}${uuid}`;-}+// `uuidv4` keeps the `<prefix><uuid>` shape above intact even on the insecure+// origins where `crypto.randomUUID` is undefined — see lib/uuid.js.+const mintId = (prefix) => `${prefix}${uuidv4()}`;export default function usePendingListRows({persisted = [],diff --git a/client/src/hooks/usePendingListRows.test.jsx b/client/src/hooks/usePendingListRows.test.jsxindex e50d306a5d..b9d7a26106 100644--- a/client/src/hooks/usePendingListRows.test.jsx+++ b/client/src/hooks/usePendingListRows.test.jsx@@ -132,17 +132,20 @@ describe('usePendingListRows', () => {expect(result.current.isPending(1)).toBe(true);});- it('addRow without crypto.randomUUID falls back to Date+Math (no crash)', () => {+ it('addRow still mints a prefixed id without crypto.randomUUID (insecure origin)', () => {// jsdom's `crypto` getter is non-writable, so swap randomUUID via spy- // instead of reassigning `globalThis.crypto`.+ // instead of reassigning `globalThis.crypto`. `uuidv4` (lib/uuid.js) owns+ // the fallback; this only pins that the `<prefix><id>` shape survives it.const spy = vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(undefined);const { result } = renderHook(() => usePendingListRows({persisted: [], requiredColumn: 'name', idPrefix: 'wd-', blankRow: WARDROBE_BLANK, onChange: vi.fn(),}));act(() => result.current.addRow());- expect(result.current.merged[0].id.startsWith('wd-')).toBe(true);- // Suffix is the Date+Math fallback string — non-empty.- expect(result.current.merged[0].id.length).toBeGreaterThan('wd-'.length);+ // Assert the real v4 shape, not just "non-empty" — a regression to a+ // non-uuid fallback would otherwise slip through.+ expect(result.current.merged[0].id).toMatch(+ /^wd-[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,+ );spy.mockRestore();});});diff --git a/client/src/hooks/usePostSession.js b/client/src/hooks/usePostSession.jsindex f76a92d551..769c07263a 100644--- a/client/src/hooks/usePostSession.js+++ b/client/src/hooks/usePostSession.js@@ -1,6 +1,7 @@import { useState, useCallback, useRef, useEffect } from 'react';import { generatePostDrill, submitPostSession, scorePostLlmDrill, submitTrainingEntry } from '../services/api';import toast from '../components/ui/Toast';+import { uuidv4 } from '../lib/uuid.js';import {LLM_DRILL_TYPES, MEMORY_DRILL_TYPES, DRILL_TO_DOMAIN, countLlmCorrect,WORDPLAY_LLM_DRILL_TYPES, LLM_TRAINING_CORRECT_THRESHOLD,@@ -16,23 +17,10 @@ const RUN_STORAGE_KEY = 'post.activeRun';// reload, and an `idle`/`saved` run has nothing live to restore.const RESTORABLE_STATES = new Set(['drilling', 'between-drills', 'complete']);-// uuid v4 usable in non-secure contexts. `crypto.randomUUID` only exists in a-// secure context (HTTPS / localhost) — PortOS is commonly reached over plain-// HTTP via Tailscale, where it's undefined — but `crypto.getRandomValues` is-// available there too, so derive a spec-valid v4 from it (the server validates-// the id with Zod `.uuid()`). Math.random is the last-ditch fallback.-function newRunId() {- if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {- return crypto.randomUUID();- }- const b = new Uint8Array(16);- if (typeof crypto !== 'undefined' && crypto.getRandomValues) crypto.getRandomValues(b);- else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);- b[6] = (b[6] & 0x0f) | 0x40; // version 4- b[8] = (b[8] & 0x3f) | 0x80; // variant 10- const h = [...b].map(x => x.toString(16).padStart(2, '0'));- return `${h[0]}${h[1]}${h[2]}${h[3]}-${h[4]}${h[5]}-${h[6]}${h[7]}-${h[8]}${h[9]}-${h[10]}${h[11]}${h[12]}${h[13]}${h[14]}${h[15]}`;-}+// The server validates this id with Zod `.uuid()`, so it has to stay+// spec-valid on the insecure origins where `crypto.randomUUID` is undefined —+// which is exactly what `uuidv4` guarantees.+const newRunId = () => uuidv4();function loadRunSnapshot() {if (typeof sessionStorage === 'undefined') return null;diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex a36016e6b7..79b713a802 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -75,7 +75,7 @@ grep -i "what you want to do" client/src/lib/README.md| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. || `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. || `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |-| `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. |+| `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup, dropping browser-extension errors (see `extensionErrors.js`) before either gate. Wired from `main.jsx`; never call directly from React components. || `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. || `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. || `compareHelpers.js` | `equalByKeys(a, b, keys)` / `equalListByKeys(a, b, keys)` — typed key-based equality for `useAutoRefetch`'s `compare`. Keys are property names, dotted paths (`'context.running'`), or `(item) => value` accessors. The typed alternative to `sameJsonShape` when a monotonic timestamp or unrendered field would break stringify-equality dedup. |@@ -83,6 +83,7 @@ grep -i "what you want to do" client/src/lib/README.md| `diffLines.js` | `diffLineBlocks(oldText, newText)` → `{ blocks }` (`{ type: 'same', lines }` / `{ type: 'change', oldLines, newLines }`) — line-level Myers LCS with common prefix/suffix trim and a 4M-cell `LINE_DIFF_CELL_CAP` guard. The structural layer behind `HunkDiff` (collapse same-blocks to context, word-diff each change-block). || `diffWords.js` | `diffWords(oldText, newText)` → `{ tooLarge, oldRuns, newRuns }` — word-level Myers LCS core (tokenize on whitespace, common prefix/suffix trim, collapse to `{ text, changed }` runs, 4M-cell `DIFF_CELL_CAP` guard on the trimmed middle). Shared by `InlineDiff` (stacked), `SideBySideDiff` (columnar), and `HunkDiff`'s change blocks. || `downloadBlob.js` | `downloadBlob(data, filename, type?)` — trigger a browser "Save as…" for a Blob / ArrayBuffer / typed array / string, with object-URL + temporary `<a>` cleanup. Use instead of inlining `URL.createObjectURL` + `<a download>`. |+| `extensionErrors.js` | `isExtensionError(payload)` — true when an error report came from a browser extension's injected content script rather than from PortOS, so `clientErrorReporter` can drop it instead of spending its 1/sec throttle slot on an error we can't fix. Client mirror of the authoritative `server/lib/extensionErrors.js` (parity enforced by `server/lib/extensionErrors.mirror.test.js`); the server re-checks, since a long-lived tab can still be running an old bundle. || `genUtils.js` | Shared bits between Image Gen and Video Gen pages. || `healthProvenance.js` | `PROVENANCE_LEVELS` / `getProvenanceLevel(level)` — the `data-backed`/`inferred`/`experimental`/`speculative` trust taxonomy (label, tone, description, "what would change this?" copy) behind the `ProvenanceChip` source-style chips on MeatSpace / genome / death-clock / longevity views. Pure data; the chip component maps tone→color and id→icon. || `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |@@ -101,6 +102,7 @@ grep -i "what you want to do" client/src/lib/README.md| `sketchCanvas.js` | Pure stroke model + 2D-context renderer for the media annotation canvas (`createStroke`, `appendPoint`, `undoStrokes`, `drawStrokes`, `clampSize`). Points stored in natural-pixel space; erase strokes use `destination-out`. Used by `AnnotationCanvas.jsx` / `MediaAnnotate.jsx` (#2036). || `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. || `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |+| `uuid.js` | `uuidv4()` — spec-valid v4 uuid that also works on **insecure origins**. Reach for this instead of `crypto.randomUUID()`, which only exists in a secure context (HTTPS / localhost) and throws `crypto.randomUUID is not a function` for the many users who reach PortOS over plain HTTP via Tailscale. Falls back to `crypto.getRandomValues` (available on insecure origins), then `Math.random`. || `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |## Page-scoped pure helpersdiff --git a/client/src/lib/clientErrorReporter.js b/client/src/lib/clientErrorReporter.jsindex f01bd027f3..96da76170c 100644--- a/client/src/lib/clientErrorReporter.js+++ b/client/src/lib/clientErrorReporter.js@@ -10,6 +10,7 @@*/import { evictOldest } from './boundedMap.js';+import { isExtensionError } from './extensionErrors.js';const ENDPOINT = '/api/client-errors';const MIN_SEND_INTERVAL_MS = 1000;@@ -142,7 +143,7 @@ function safeBody(payload) {/*** Report a client-side error. Resolves to:* - `{ sent: true }` — sent to the server.- * - `{ sent: false, reason: 'duplicate' | 'rate-limited' | 'no-fetch' | 'transport-error' | 'caught' | 'empty' }`+ * - `{ sent: false, reason: 'duplicate' | 'extension' | 'rate-limited' | 'no-fetch' | 'transport-error' | 'caught' | 'empty' }`** Never throws — any synchronous exception while building the payload or any* fetch failure resolves to `{ sent: false, reason }`. This is critical because@@ -159,6 +160,11 @@ export async function reportClientError(input) {payload = buildPayload(input);if (!payload.message) return { sent: false, reason: 'empty' };+ // Before the throttle below, so an extension error can't consume the 1/sec+ // slot and drop a real PortOS error arriving behind it. See+ // lib/extensionErrors.js for why we filter these at all.+ if (isExtensionError(payload)) return { sent: false, reason: 'extension' };+if (now - lastSentAt < MIN_SEND_INTERVAL_MS) {return { sent: false, reason: 'rate-limited' };}diff --git a/client/src/lib/clientErrorReporter.test.js b/client/src/lib/clientErrorReporter.test.jsindex 38291d7a13..6800e6dd56 100644--- a/client/src/lib/clientErrorReporter.test.js+++ b/client/src/lib/clientErrorReporter.test.js@@ -194,3 +194,40 @@ describe('reportClientError', () => {expect(result.reason).toBe('transport-error');});});++describe('browser-extension errors', () => {+ it('never POSTs an error thrown by an injected content script', async () => {+ const result = await reportClientError({+ type: 'error',+ message: "Cannot read properties of null (reading 'ethereum')",+ filename: 'chrome-extension://examplewalletextensionid00000000/inpage.js',+ lineno: 1,+ colno: 1,+ });++ expect(result).toEqual({ sent: false, reason: 'extension' });+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('detects an extension frame in a rejected Error stack', async () => {+ const err = new Error('boom');+ err.stack = 'Error: boom\n at inject (moz-extension://abcd-1234/content.js:5:9)';+ const result = await reportClientError({ type: 'unhandledrejection', reason: err });++ expect(result.reason).toBe('extension');+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('does not spend the throttle slot, so a real error right behind it still sends', async () => {+ // Without the pre-throttle filter, the extension error below would take+ // the 1/sec slot and the genuine error would be lost as `rate-limited`+ // before ever leaving the browser.+ await reportClientError({ type: 'unhandledrejection', reason: 'Failed to connect to MetaMask' });+ const real = await reportClientError({ type: 'error', message: 'Genuine PortOS failure' });++ expect(real.sent).toBe(true);+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ const body = JSON.parse(globalThis.fetch.mock.calls[0][1].body);+ expect(body.message).toBe('Genuine PortOS failure');+ });+});diff --git a/client/src/lib/extensionErrors.js b/client/src/lib/extensionErrors.jsnew file mode 100644index 0000000000..22eec6eadb--- /dev/null+++ b/client/src/lib/extensionErrors.js@@ -0,0 +1,34 @@+/**+ * Browser-extension error detection — client mirror of+ * server/lib/extensionErrors.js, which is authoritative and carries the+ * rationale (why provenance-first, why the message list stays short, why both+ * ends filter). Port logic changes verbatim; parity is enforced by+ * server/lib/extensionErrors.mirror.test.js.+ */++// NOTE: no `g` flag — `.test()` on a /g/ regex is stateful via lastIndex.+const EXTENSION_SCHEME_RE = /(?:chrome-extension|moz-extension|safari-extension|safari-web-extension|ms-browser-extension|opera-extension|webkit-masked-url):\/\/|\bextensions::/i;++const EXTENSION_MESSAGE_RE = [+ /\bMetaMask\b/i,+];++/**+ * True when an error report originated from a browser extension rather than+ * PortOS itself. Checks `source` / `stack` / `message`; never `url` (the page+ * location is ours even when an extension throws on top of it).+ */+export function isExtensionError(payload) {+ if (!payload || typeof payload !== 'object') return false;++ const str = (v) => (typeof v === 'string' ? v : '');+ const source = str(payload.source);+ const stack = str(payload.stack);+ const message = str(payload.message);++ if (EXTENSION_SCHEME_RE.test(source)) return true;+ if (EXTENSION_SCHEME_RE.test(stack)) return true;+ if (EXTENSION_SCHEME_RE.test(message)) return true;++ return EXTENSION_MESSAGE_RE.some(re => re.test(message));+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex bd48a75256..400ce4086a 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -57,6 +57,7 @@ export * from './consoleFilters.js';export * from './diffLines.js';export * from './diffWords.js';export * from './downloadBlob.js';+export * from './extensionErrors.js';export * from './genUtils.js';export * from './healthProvenance.js';export * from './joinInfluenceList.js';@@ -105,5 +106,6 @@ export * from './terminalTheme.js';export * from './tribe.js';export * from './tribeCadence.js';export * from './universeBuilderExpand.js';+export * from './uuid.js';export * from './wrSceneCursor.js';export * from './writingGuide.js';diff --git a/client/src/lib/uuid.js b/client/src/lib/uuid.jsnew file mode 100644index 0000000000..d71a9273c9--- /dev/null+++ b/client/src/lib/uuid.js@@ -0,0 +1,35 @@+/**+ * uuid v4 that also works on insecure origins.+ *+ * `crypto.randomUUID` only exists in a SECURE context (HTTPS / localhost).+ * PortOS is commonly reached over plain HTTP via Tailscale, where it is+ * undefined — so a bare `crypto.randomUUID()` throws `crypto.randomUUID is not+ * a function` for exactly the users on the app's most common deployment.+ * `crypto.getRandomValues` IS available on insecure origins, so derive a+ * spec-valid v4 from it (callers that hand the id to a Zod `.uuid()` route+ * depend on it being spec-valid); Math.random is the last-ditch fallback.+ *+ * Use this instead of calling `crypto.randomUUID()` directly.+ */++/** @returns {string} A spec-valid v4 uuid. */+export function uuidv4() {+ // `globalThis.crypto` rather than bare `crypto`: bare `crypto?.…` throws+ // ReferenceError in some non-secure-context envs, where going through+ // globalThis short-circuits cleanly. The `typeof` check on the RESULT (not+ // just on the method) also covers a stubbed randomUUID that returns nothing.+ const native = globalThis.crypto?.randomUUID?.();+ if (typeof native === 'string') return native;++ const b = new Uint8Array(16);+ if (globalThis.crypto?.getRandomValues) globalThis.crypto.getRandomValues(b);+ else for (let i = 0; i < 16; i++) b[i] = Math.floor(Math.random() * 256);+ b[6] = (b[6] & 0x0f) | 0x40; // version 4+ b[8] = (b[8] & 0x3f) | 0x80; // variant 10++ // Slice a single hex string rather than interpolating 16 indexed bytes — the+ // indexed form invites a silent mis-index (a repeated `h[1]`) that still+ // produces a well-formed, unique-looking uuid, so no test would catch it.+ const h = [...b].map(x => x.toString(16).padStart(2, '0')).join('');+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;+}diff --git a/client/src/lib/uuid.test.js b/client/src/lib/uuid.test.jsnew file mode 100644index 0000000000..c6a649cf9a--- /dev/null+++ b/client/src/lib/uuid.test.js@@ -0,0 +1,55 @@+import { describe, it, expect, vi, afterEach } from 'vitest';+import { uuidv4 } from './uuid.js';++const V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;++afterEach(() => {+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+});++describe('uuidv4', () => {+ it('returns a spec-valid v4 uuid', () => {+ expect(uuidv4()).toMatch(V4_RE);+ });++ it('returns distinct ids across calls', () => {+ const ids = new Set(Array.from({ length: 200 }, () => uuidv4()));+ expect(ids.size).toBe(200);+ });++ it('uses the native crypto.randomUUID when the context is secure', () => {+ const spy = vi.spyOn(globalThis.crypto, 'randomUUID')+ .mockReturnValue('11111111-2222-4333-8444-555555555555');+ expect(uuidv4()).toBe('11111111-2222-4333-8444-555555555555');+ expect(spy).toHaveBeenCalled();+ });++ // The regression this helper exists for: `crypto.randomUUID` only exists in+ // a secure context, so on PortOS over plain HTTP via Tailscale a bare+ // `crypto.randomUUID()` threw out of every toast. Each degraded environment+ // below must still yield a spec-valid v4 rather than throw.+ describe('insecure origin (PortOS over plain HTTP via Tailscale)', () => {+ it('falls back when randomUUID is absent but getRandomValues works', () => {+ vi.stubGlobal('crypto', { getRandomValues: globalThis.crypto.getRandomValues.bind(globalThis.crypto) });+ expect(globalThis.crypto.randomUUID).toBeUndefined();+ expect(uuidv4()).toMatch(V4_RE);+ });++ it('falls back when randomUUID exists but returns nothing (stubbed/polyfilled)', () => {+ vi.spyOn(globalThis.crypto, 'randomUUID').mockReturnValue(undefined);+ expect(uuidv4()).toMatch(V4_RE);+ });++ it('falls back to Math.random when crypto has neither method', () => {+ vi.stubGlobal('crypto', {});+ expect(uuidv4()).toMatch(V4_RE);+ });++ it('does not throw when there is no crypto global at all', () => {+ vi.stubGlobal('crypto', undefined);+ expect(() => uuidv4()).not.toThrow();+ expect(uuidv4()).toMatch(V4_RE);+ });+ });+});diff --git a/client/src/pages/VideoGen.jsx b/client/src/pages/VideoGen.jsxindex 88aaaceca3..4cf7cfa622 100644--- a/client/src/pages/VideoGen.jsx+++ b/client/src/pages/VideoGen.jsx@@ -27,6 +27,7 @@import { useState, useEffect, useRef, useCallback, useMemo } from 'react';import { useSearchParams, useNavigate, Link } from 'react-router-dom';import Drawer from '../components/Drawer';+import { uuidv4 } from '../lib/uuid.js';import { ImageGenTab } from '../components/settings/ImageGenTab';import LocalSetupPanel from '../components/settings/LocalSetupPanel';import RuntimeInstallModal from '../components/install/RuntimeInstallModal';@@ -91,10 +92,7 @@ const MODES = [{ id: 'a2v', label: 'Audio', icon: Music, desc: 'Audio-to-video (audio drives motion + sync)' },];-const newQueueId = () =>- (typeof crypto !== 'undefined' && crypto.randomUUID)- ? crypto.randomUUID()- : `q-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;+const newQueueId = () => uuidv4();const videoModelMemoryGb = (model) => {const explicit = Number(model?.memoryGb);diff --git a/docs/features/error-handling.md b/docs/features/error-handling.mdindex 592499faa7..caeee51e01 100644--- a/docs/features/error-handling.md+++ b/docs/features/error-handling.md@@ -60,11 +60,61 @@ Errors include rich context for debugging:- Severity level- Auto-fix flag+## Browser Error Capture++`main.jsx` wires `window.onerror` + `unhandledrejection` to `reportClientError`, which+POSTs to `/api/client-errors`; the aggregator surfaces each unique group in the Review Hub+as a `type: 'alert'` item (`metadata.category: 'client-error'`).++### Extension errors are filtered out++Extensions (wallets, password managers, ad blockers) inject content scripts into the page's+realm, so anything they throw lands in **our** handlers. Those errors are not in the app's+control and not actionable — the user cannot fix MetaMask by changing PortOS — so+`isExtensionError()` drops them at both ends.++Detection is **provenance-first**: an extension URL scheme (`chrome-extension://`,+`moz-extension://`, `safari-web-extension://`, `webkit-masked-url://`, …) in the script+`source` or the `stack` proves the frame is not ours. This does the real work — every+extension error observed so far carries such a frame. A single message pattern+(`MetaMask`) backstops the one case provenance cannot see: a wallet rejecting with a bare+string, which carries no frames at all.++Four constraints worth preserving when touching this:++- **Filter before the throttle, on both ends.** The client reporter and the server+ aggregator each gate on a 1/sec throttle. An extension error that takes the slot drops a+ genuine PortOS error arriving <1s behind it. Filtering early keeps the budget for errors+ we can act on — it is a correctness rule, not an optimization.+- **Filter before sanitize (server).** `sanitize()` caps the stack at 4000 chars, which can+ cut off the extension frame that is the only proof of provenance. Detection runs on the+ raw payload.+- **Never match on `url`.** That field is the *page* location, which is ours even when an+ extension throws on top of it. Only `source` / `stack` / `message` are evidence.+- **Keep the message list near-empty.** Each pattern is a permanent silent-drop rule, and+ the failure modes are asymmetric: a missed extension error is noise the user dismisses in+ one click, while an over-broad pattern hides a real bug forever. Add one only when a real+ observed error escaped provenance *and* the string is absent from our source. Cautionary+ case: `crypto.randomUUID is not a function` *looks* like extension noise but was our own+ crash on insecure origins (see `client/src/lib/uuid.js`) — its live alert had no+ extension frame at all. It is explicitly not filtered, and regression tests pin that on+ the predicate, the aggregator, and the cleanup migration.++The server re-checks rather than trusting the client: PortOS installs update on their own+schedule and a long-lived tab keeps running an old bundle.++The filter is prospective, so `scripts/migrations/195-dismiss-extension-error-alerts.js`+applies the same predicate once to alerts already filed (status → `dismissed`, never+deleted), so existing installs converge instead of carrying stale extension alerts forever.+## Implementation Files| File | Purpose ||------|---------|| `server/lib/errorHandler.js` | Error classes, asyncHandler, middleware |+| `server/lib/extensionErrors.js` | `isExtensionError()` — browser-extension detection (authoritative; mirrored to `client/src/lib/extensionErrors.js`) |+| `server/services/clientErrors.js` | Client-error aggregator: extension filter → throttle → redact → dedup → Review Hub alert |+| `client/src/lib/clientErrorReporter.js` | Browser-side capture + POST, with the same extension filter at the source || `server/services/autoFixer.js` | Auto-fix task creation and deduplication || `server/services/socket.js` | Socket.IO error event forwarding || `server/routes/*.js` | All routes use asyncHandler wrapper |diff --git a/scripts/migrations/195-dismiss-extension-error-alerts.js b/scripts/migrations/195-dismiss-extension-error-alerts.jsnew file mode 100644index 0000000000..831460a0bc--- /dev/null+++ b/scripts/migrations/195-dismiss-extension-error-alerts.js@@ -0,0 +1,108 @@+/**+ * Dismiss Review Hub alerts that were filed for browser-extension errors.+ *+ * Background:+ * Extensions (crypto wallets, password managers, ad blockers) inject content+ * scripts into the page's realm, so anything they throw surfaced through the+ * app's own `unhandledrejection` handler and was filed as an actionable+ * `client-error` alert — e.g. "Unhandled rejection: Failed to connect to+ * MetaMask". Nothing in PortOS can fix those, so the capture path now drops+ * them (`server/lib/extensionErrors.js`).+ *+ * That fix is prospective only: alerts already filed stay pending forever,+ * which is exactly the noise the filter exists to remove. This migration+ * applies the *same* predicate retroactively so existing installs converge on+ * the new behavior instead of carrying stale alerts indefinitely.+ *+ * Approach:+ * - Reuses `isExtensionError` rather than re-encoding "what is an extension+ * error" here — a second definition would drift from the runtime filter.+ * - Reconstructs the detection payload from what `recordClientError` stored:+ * `metadata.source` plus the stack that `buildDescription` appended after+ * the header block. The header's own `URL:` line (the *page* location) is+ * deliberately excluded — it is ours even when an extension throws on top+ * of it, and feeding it to the matcher could misclassify a real error.+ * - Flips `status` to 'dismissed' rather than deleting: the record keeps its+ * id and stays auditable, matching how the Review Hub itself clears items.+ * - Only touches `status: 'pending'` items in `category: 'client-error'`.+ * Anything the user already triaged is left alone.+ *+ * No-op by construction on installs with no such alerts (the overwhelmingly+ * common case) — the file is only rewritten when something actually matched.+ */++import { readFile, writeFile } from 'fs/promises';+import { join } from 'path';++import { isExtensionError } from '../../server/lib/extensionErrors.js';++const ITEMS_REL = 'data/review/items.json';++// `buildDescription` emits a header block (URL/Source/UA/Type), then a blank+// line, then the stack. Take only what follows the blank line so the page URL+// in the header can never reach the matcher.+function stackFromDescription(description) {+ if (typeof description !== 'string') return '';+ const idx = description.indexOf('\n\n');+ return idx === -1 ? '' : description.slice(idx + 2);+}++// Rebuild the shape `isExtensionError` expects from the stored alert.+// `buildTitle` prefixed the message with "Unhandled rejection: " / "Client+// error: "; strip it so the message matches what was originally reported.+function payloadFromItem(item) {+ const title = typeof item?.title === 'string' ? item.title : '';+ return {+ type: item?.metadata?.kind,+ message: title.replace(/^(?:Unhandled rejection|Client error):\s*/, ''),+ source: item?.metadata?.source,+ stack: stackFromDescription(item?.description),+ };+}++export default {+ async up({ rootDir }) {+ const path = join(rootDir, ITEMS_REL);+ const raw = await readFile(path, 'utf-8').catch((err) => {+ if (err.code === 'ENOENT') return null;+ throw err;+ });+ if (raw == null) {+ console.log('✅ Review alerts: no items file — nothing to dismiss');+ return { dismissed: 0, reason: 'no-file' };+ }++ let items;+ try {+ items = JSON.parse(raw);+ } catch {+ // A corrupt items file is not this migration's problem to fix, and+ // rewriting it would risk destroying recoverable data.+ console.warn('⚠️ Review alerts: items file is not valid JSON — skipping');+ return { dismissed: 0, reason: 'unparseable' };+ }+ if (!Array.isArray(items)) {+ console.warn('⚠️ Review alerts: items file is not an array — skipping');+ return { dismissed: 0, reason: 'unexpected-shape' };+ }++ const now = new Date().toISOString();+ let dismissed = 0;+ const next = items.map((item) => {+ if (item?.status !== 'pending') return item;+ if (item?.metadata?.category !== 'client-error') return item;+ if (!isExtensionError(payloadFromItem(item))) return item;+ dismissed++;+ return { ...item, status: 'dismissed', updatedAt: now };+ });++ if (dismissed === 0) {+ console.log('✅ Review alerts: no pending browser-extension alerts — no changes');+ return { dismissed: 0 };+ }++ await writeFile(path, JSON.stringify(next, null, 2) + '\n');+ console.log(`🧹 Review alerts: dismissed ${dismissed} browser-extension alert(s)`);+ return { dismissed };+ },+};diff --git a/scripts/migrations/195-dismiss-extension-error-alerts.test.js b/scripts/migrations/195-dismiss-extension-error-alerts.test.jsnew file mode 100644index 0000000000..1f682e6498--- /dev/null+++ b/scripts/migrations/195-dismiss-extension-error-alerts.test.js@@ -0,0 +1,136 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import { mkdtemp, mkdir, rm, readFile, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';++import migration from './195-dismiss-extension-error-alerts.js';++let rootDir;++const ITEMS_REL = 'data/review/items.json';++async function seed(items) {+ await mkdir(join(rootDir, 'data', 'review'), { recursive: true });+ await writeFile(join(rootDir, ITEMS_REL), JSON.stringify(items, null, 2));+}++async function readItems() {+ return JSON.parse(await readFile(join(rootDir, ITEMS_REL), 'utf-8'));+}++// Mirrors `buildDescription`: header block, blank line, then the stack.+const describeAlert = ({ url, source, stack }) =>+ [`URL: ${url}`, ...(source ? [`Source: ${source}`] : []), 'UA: TestAgent', 'Type: unhandledrejection', '', stack]+ .join('\n');++const alert = (overrides = {}) => ({+ id: 'item-1',+ type: 'alert',+ status: 'pending',+ title: 'Unhandled rejection: boom',+ description: describeAlert({ url: 'https://portos/dashboard', stack: 'Error: boom\n at f (/assets/index.js:1:1)' }),+ metadata: { category: 'client-error', kind: 'unhandledrejection', referenceId: 'client-error:abc' },+ ...overrides,+});++beforeEach(async () => {+ rootDir = await mkdtemp(join(tmpdir(), 'portos-mig195-'));+});++afterEach(async () => {+ await rm(rootDir, { recursive: true, force: true });+});++describe('195-dismiss-extension-error-alerts', () => {+ it('dismisses an alert whose stack has an extension frame', async () => {+ await seed([alert({+ title: 'Unhandled rejection: Cannot read properties of null',+ description: describeAlert({+ url: 'https://portos/dashboard',+ stack: 'TypeError\n at inject (chrome-extension://abcdef/inpage.js:1:1)',+ }),+ })]);++ const result = await migration.up({ rootDir });++ expect(result.dismissed).toBe(1);+ expect((await readItems())[0].status).toBe('dismissed');+ });++ it('dismisses a stackless MetaMask rejection via its message', async () => {+ await seed([alert({+ title: 'Unhandled rejection: Failed to connect to MetaMask',+ description: describeAlert({ url: 'https://portos/cos', stack: '' }),+ })]);++ expect((await migration.up({ rootDir })).dismissed).toBe(1);+ });++ it('does NOT dismiss `crypto.randomUUID is not a function` — that is our own bug', async () => {+ // The regression that matters: this alert looks like extension noise but is+ // PortOS crashing on an insecure origin. Retroactively hiding it would bury+ // a real bug the user needs to see.+ await seed([alert({+ title: 'Unhandled rejection: crypto.randomUUID is not a function',+ description: describeAlert({+ url: 'http://example-host.ts.net:5554/apps/demo',+ stack: 'TypeError\n at add (http://example-host.ts.net:5554/assets/index.js:9:9)',+ }),+ })]);++ const result = await migration.up({ rootDir });++ expect(result.dismissed).toBe(0);+ expect((await readItems())[0].status).toBe('pending');+ });++ it('never matches on the page URL alone', async () => {+ // `url` is window.location.href — ours even when an extension throws on it.+ // The header block must stay out of the matcher.+ await seed([alert({+ description: describeAlert({+ url: 'https://portos/apps/chrome-extension://spoof',+ stack: 'Error: boom\n at f (/assets/index.js:1:1)',+ }),+ })]);++ expect((await migration.up({ rootDir })).dismissed).toBe(0);+ });++ it('leaves already-triaged and non-client-error items alone', async () => {+ const extensionStack = 'TypeError\n at inject (chrome-extension://abcdef/inpage.js:1:1)';+ await seed([+ alert({ id: 'a', status: 'completed', description: describeAlert({ url: 'https://portos/x', stack: extensionStack }) }),+ alert({ id: 'b', status: 'dismissed', description: describeAlert({ url: 'https://portos/x', stack: extensionStack }) }),+ alert({ id: 'c', metadata: { category: 'todo' }, description: describeAlert({ url: 'https://portos/x', stack: extensionStack }) }),+ ]);++ const result = await migration.up({ rootDir });++ expect(result.dismissed).toBe(0);+ const items = await readItems();+ expect(items.map(i => i.status)).toEqual(['completed', 'dismissed', 'pending']);+ });++ it('is a no-op that does not rewrite the file when nothing matches', async () => {+ await seed([alert()]);+ const before = await readFile(join(rootDir, ITEMS_REL), 'utf-8');++ expect((await migration.up({ rootDir })).dismissed).toBe(0);+ expect(await readFile(join(rootDir, ITEMS_REL), 'utf-8')).toBe(before);+ });++ it('tolerates a missing items file', async () => {+ expect(await migration.up({ rootDir })).toEqual({ dismissed: 0, reason: 'no-file' });+ });++ it('skips an unparseable or unexpectedly-shaped items file rather than destroying it', async () => {+ await mkdir(join(rootDir, 'data', 'review'), { recursive: true });+ await writeFile(join(rootDir, ITEMS_REL), '{not json');+ expect((await migration.up({ rootDir })).reason).toBe('unparseable');+ expect(await readFile(join(rootDir, ITEMS_REL), 'utf-8')).toBe('{not json');++ await writeFile(join(rootDir, ITEMS_REL), '{"items":[]}');+ expect((await migration.up({ rootDir })).reason).toBe('unexpected-shape');+ });+});diff --git a/server/lib/README.md b/server/lib/README.mdindex 3be36cb129..2917e2ee1a 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -269,6 +269,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `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. |+| `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. || `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |@@ -289,6 +290,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `mirrorParity.js` | Source-comparison primitives for the `*.mirror.test.js` server↔client parity tests: `stripCommentsAndNormalize` (so per-side commentary may diverge but logic may not), `extractDeclaration(src, name)` (balanced `{}`/`()`/`[]` walk over `function` / `async function` / `const`), and `compareDeclaration(serverSrc, clientSrc, name)`. Use these instead of hand-rolling a brace-walker per mirror. Pure — no `vitest` import — so callers own the assertions. || `mockPathsDataRoot.js` | Shared Vitest helpers for `PATHS.data → temp dir` and no-peer record creation guards. || `settingsTestUtil.js` | `bindSettingsFile(dataRoot)` → `writeSettingsFile`/`mergeSettingsFile`: direct settings.json disk writes that also drop the `getSettings()` read cache (dynamic-import reset) so a stale cache can't survive a bypass-`save()` write. || `testHelper.js` | Test helpers: `request()` (supertest-style HTTP) + `mockJsonResponse`/`mockTextResponse` (fetch `Response` mocks read via `.text()`). |diff --git a/server/lib/canonPrompt.mirror.test.js b/server/lib/canonPrompt.mirror.test.jsindex f6d4608567..f28110cba0 100644--- a/server/lib/canonPrompt.mirror.test.js+++ b/server/lib/canonPrompt.mirror.test.js@@ -14,73 +14,22 @@* excluded from the mirror contract by the "Server-only" comment.** Comparison strategy: strip single-line and multi-line comments, then- * normalize whitespace before diffing. This means JSDoc divergence between- * the two sides does NOT fail the test — only code logic differences do.+ * normalize whitespace before diffing (see lib/mirrorParity.js). This means+ * JSDoc divergence between the two sides does NOT fail the test — only code+ * logic differences do.*/import { describe, it, expect } from 'vitest';import { readFileSync } from 'fs';-import { resolve } from 'path';+import { resolve, dirname } from 'path';import { fileURLToPath } from 'url';-import { dirname } from 'path';+import { compareDeclaration, extractDeclaration } from './mirrorParity.js';const __dirname = dirname(fileURLToPath(import.meta.url));const SERVER_PATH = resolve(__dirname, 'canonPrompt.js');const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/canonPrompt.js');-/** Strip single-line (//) and block (/* ... */) comments, then normalize whitespace. */-function stripCommentsAndNormalize(src) {- // Remove block comments (non-greedy, including JSDoc)- let s = src.replace(/\/\*[\s\S]*?\*\//g, '');- // Remove single-line comments- s = s.replace(/\/\/[^\n]*/g, '');- // Collapse runs of whitespace (including newlines) to a single space- s = s.replace(/\s+/g, ' ').trim();- return s;-}--/**- * Extract the body of a named declaration from source text.- *- * Matches:- * - `function NAME(` ... balanced braces- * - `const NAME = Object.freeze(` ... balanced parens- * - `export function NAME(` ... balanced braces- * - `export const NAME = Object.freeze(` ... balanced parens/objects- *- * Returns the matched text (declaration through closing delimiter), or null.- */-function extractDeclaration(src, name) {- // Find the start of the declaration (with or without `export`)- const startRe = new RegExp(- `(?:export\\s+)?(?:function|const|async function)\\s+${name}[\\s=(]`,- );- const match = startRe.exec(src);- if (!match) return null;-- const start = match.index;- let depth = 0;- let i = start;- let foundOpen = false;-- // Walk forward tracking brace/paren depth to find the end of the declaration- while (i < src.length) {- const ch = src[i];- if (ch === '{' || ch === '(') {- depth++;- foundOpen = true;- } else if (ch === '}' || ch === ')') {- depth--;- if (foundOpen && depth === 0) {- return src.slice(start, i + 1);- }- }- i++;- }- return null;-}-// Declarations that must be textually identical (code-only, comments stripped)const MIRRORED_NAMES = ['SHORT_SPEC',@@ -115,15 +64,11 @@ describe('canonPrompt server↔client mirror parity', () => {for (const name of MIRRORED_NAMES) {it(`${name} is present and identical on both sides (code only)`, () => {- const serverDecl = extractDeclaration(serverSrc, name);- const clientDecl = extractDeclaration(clientSrc, name);+ const { serverDecl, clientDecl, serverNorm, clientNorm } =+ compareDeclaration(serverSrc, clientSrc, name);expect(serverDecl, `server/lib/canonPrompt.js is missing declaration: ${name}`).not.toBeNull();expect(clientDecl, `client/src/lib/canonPrompt.js is missing declaration: ${name}`).not.toBeNull();-- const serverNorm = stripCommentsAndNormalize(serverDecl);- const clientNorm = stripCommentsAndNormalize(clientDecl);-expect(clientNorm, `"${name}" code diverged between server and client`).toBe(serverNorm);});}diff --git a/server/lib/extensionErrors.js b/server/lib/extensionErrors.jsnew file mode 100644index 0000000000..44328f3f04--- /dev/null+++ b/server/lib/extensionErrors.js@@ -0,0 +1,76 @@+/**+ * Browser-extension error detection.+ *+ * Content scripts injected by extensions (wallets, password managers, ad+ * blockers) run in the page's realm, so anything they throw surfaces through+ * OUR `window.onerror` / `unhandledrejection` handlers and lands in the Review+ * Hub as an actionable alert. Those errors are not in the app's control and+ * are not actionable — a user cannot fix MetaMask by changing PortOS.+ *+ * Beyond noise, they actively displace real errors: both the client reporter+ * and the server aggregator gate on a 1/sec throttle, so an extension error+ * accepted at T causes a genuine PortOS error at T+500ms to be dropped as+ * `rate-limited` and lost. That is why both ends check this BEFORE their+ * throttle gate rather than filtering at the Review Hub on read.+ *+ * Detection is provenance-first: an extension URL scheme in the script source+ * or the stack is proof the frame is not ours. Message matching is the+ * fallback for stackless rejections (`reject('Failed to connect to MetaMask')`+ * carries no frames at all) and is deliberately kept to a short list of+ * vendor/runtime strings PortOS provably never emits — a message pattern is a+ * blunt instrument that can hide a real bug, so each addition must be verified+ * absent from our own source first.+ *+ * This module is MIRRORED at client/src/lib/extensionErrors.js. This server+ * copy is authoritative; parity is enforced by extensionErrors.mirror.test.js.+ */++// URL schemes an injected content script can run from. Provenance beats+// message matching: if a frame's script lives at one of these, it is not ours.+// NOTE: no `g` flag — `.test()` on a /g/ regex is stateful via lastIndex and+// would alternate true/false across calls.+const EXTENSION_SCHEME_RE = /(?:chrome-extension|moz-extension|safari-extension|safari-web-extension|ms-browser-extension|opera-extension|webkit-masked-url):\/\/|\bextensions::/i;++// Fallback for extension errors that arrive with NO usable stack, where+// provenance has nothing to match on. Every entry is a permanent, silent+// drop rule, so the bar is deliberately high — add one only when:+// 1. an actual observed error escaped the provenance check above, AND+// 2. the string is absent from our own source (grep before adding).+// The failure modes are asymmetric: an extension error we miss is mild noise+// the user can dismiss, while an over-broad pattern hides a real bug forever.+// When in doubt, leave it out and let provenance do the work.+const EXTENSION_MESSAGE_RE = [+ // Injected wallet providers reject with a bare string ("Failed to connect to+ // MetaMask"), which carries no frames. PortOS has no crypto/wallet code at+ // all, so any mention of one is the extension talking.+ /\bMetaMask\b/i,+];++/**+ * True when an error report originated from a browser extension rather than+ * PortOS itself.+ *+ * Checks `source` (the script URL), `stack`, and `message`. Deliberately does+ * NOT check `url` — that is the *page* location (`window.location.href`),+ * which is always ours even when an extension throws on top of it.+ *+ * Safe to call on a raw, unsanitized payload; every field is treated as+ * untrusted and non-string values are ignored.+ */+export function isExtensionError(payload) {+ if (!payload || typeof payload !== 'object') return false;++ const str = (v) => (typeof v === 'string' ? v : '');+ const source = str(payload.source);+ const stack = str(payload.stack);+ const message = str(payload.message);++ // Provenance: an extension scheme anywhere in the script URL or the stack.+ // The message is checked too — a failed dynamic import or fetch names the+ // offending extension URL in its message with no stack attached.+ if (EXTENSION_SCHEME_RE.test(source)) return true;+ if (EXTENSION_SCHEME_RE.test(stack)) return true;+ if (EXTENSION_SCHEME_RE.test(message)) return true;++ return EXTENSION_MESSAGE_RE.some(re => re.test(message));+}diff --git a/server/lib/extensionErrors.mirror.test.js b/server/lib/extensionErrors.mirror.test.jsnew file mode 100644index 0000000000..c6a96fa6a9--- /dev/null+++ b/server/lib/extensionErrors.mirror.test.js@@ -0,0 +1,48 @@+/**+ * Mirror parity test for server/lib/extensionErrors.js ↔ client/src/lib/extensionErrors.js+ *+ * Both ends filter extension errors (each protects its own 1/sec throttle from+ * being spent on an un-actionable error), so the two copies must agree on what+ * counts as one. A drifted client would send noise the server drops — or worse,+ * silently drop a real error the server would have kept.+ *+ * Comparison strips comments, so the intentionally divergent header commentary+ * does not fail the test — only logic does.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'fs';+import { resolve, dirname } from 'path';+import { fileURLToPath } from 'url';+import { compareDeclaration } from './mirrorParity.js';++const __dirname = dirname(fileURLToPath(import.meta.url));++const SERVER_PATH = resolve(__dirname, 'extensionErrors.js');+const CLIENT_PATH = resolve(__dirname, '../../client/src/lib/extensionErrors.js');++const MIRRORED_NAMES = ['EXTENSION_SCHEME_RE', 'EXTENSION_MESSAGE_RE', 'isExtensionError'];++describe('extensionErrors server↔client mirror parity', () => {+ const serverSrc = readFileSync(SERVER_PATH, 'utf8');+ const clientSrc = readFileSync(CLIENT_PATH, 'utf8');++ it('both files are non-empty', () => {+ expect(serverSrc.length).toBeGreaterThan(100);+ expect(clientSrc.length).toBeGreaterThan(100);+ });++ for (const name of MIRRORED_NAMES) {+ it(`${name} is present and identical on both sides (code only)`, () => {+ const { serverDecl, clientDecl, serverNorm, clientNorm } =+ compareDeclaration(serverSrc, clientSrc, name);++ expect(serverDecl, `server/lib/extensionErrors.js is missing: ${name}`).not.toBeNull();+ expect(clientDecl, `client/src/lib/extensionErrors.js is missing: ${name}`).not.toBeNull();+ expect(+ clientNorm,+ `"${name}" diverged — the server copy is authoritative; port the change verbatim`,+ ).toBe(serverNorm);+ });+ }+});diff --git a/server/lib/extensionErrors.test.js b/server/lib/extensionErrors.test.jsnew file mode 100644index 0000000000..a8ec522de2--- /dev/null+++ b/server/lib/extensionErrors.test.js@@ -0,0 +1,118 @@+import { describe, it, expect } from 'vitest';+import { isExtensionError } from './extensionErrors.js';++describe('isExtensionError', () => {+ describe('provenance — extension URL schemes', () => {+ const SCHEMES = [+ 'chrome-extension://abcdefghijklmnop/inpage.js',+ 'moz-extension://1234-5678/content.js',+ 'safari-extension://com.example.ext/injected.js',+ 'safari-web-extension://ABCD-1234/injected.js',+ 'ms-browser-extension://abcd/content.js',+ 'opera-extension://abcd/content.js',+ 'webkit-masked-url://hidden/',+ ];++ for (const url of SCHEMES) {+ it(`flags ${url.split('://')[0]} in \`source\``, () => {+ expect(isExtensionError({ message: 'boom', source: url })).toBe(true);+ });++ it(`flags ${url.split('://')[0]} in \`stack\``, () => {+ expect(isExtensionError({+ message: 'boom',+ stack: `TypeError: boom\n at inject (${url}:1:1)`,+ })).toBe(true);+ });+ }++ it('flags the legacy `extensions::` internal frame', () => {+ expect(isExtensionError({+ message: 'boom',+ stack: 'Error\n at extensions::SafeBuiltins:12:34',+ })).toBe(true);+ });++ it('flags an extension URL named in the message with no stack', () => {+ expect(isExtensionError({+ message: 'Failed to fetch dynamically imported module: chrome-extension://abc/x.js',+ })).toBe(true);+ });++ it('matches the scheme case-insensitively', () => {+ expect(isExtensionError({ message: 'boom', source: 'CHROME-EXTENSION://ABC/x.js' })).toBe(true);+ });++ it('is not stateful across repeated calls (regex has no `g` flag)', () => {+ // A /g/ regex would alternate true/false via lastIndex. Same input must+ // give the same answer every time or filtering becomes a coin flip.+ const payload = { message: 'boom', source: 'chrome-extension://abc/inpage.js' };+ expect([1, 2, 3, 4].map(() => isExtensionError(payload))).toEqual([true, true, true, true]);+ });+ });++ describe('message signatures — stackless extension rejections', () => {+ // The screenshot case from the Review Hub: MetaMask rejects with a bare+ // string, so there is no stack or source to key off.+ it('flags a bare "Failed to connect to MetaMask" rejection', () => {+ expect(isExtensionError({ type: 'unhandledrejection', message: 'Failed to connect to MetaMask' })).toBe(true);+ });++ it('leaves un-evidenced extension-ish messages to the provenance check', () => {+ // The message list is intentionally minimal (see the module comment).+ // These chrome.runtime strings are real extension noise, but every+ // instance observed so far carries an extension frame, so provenance+ // already catches them and a blanket message rule would only add+ // silent-drop surface. They are filtered when a stack proves it...+ const runtimeNoise = 'The message port closed before a response was received.';+ expect(isExtensionError({ message: runtimeNoise })).toBe(false);+ // ...like this.+ expect(isExtensionError({+ message: runtimeNoise,+ stack: 'Error\n at m (chrome-extension://abc/content.js:1:1)',+ })).toBe(true);+ });+ });++ describe('PortOS errors are never filtered', () => {+ it('does NOT flag `crypto.randomUUID is not a function`', () => {+ // Regression guard: this one looks like extension noise but is OUR bug+ // on insecure origins (see client/src/lib/uuid.js). Filtering it would+ // have hidden a real crash in every toast.+ expect(isExtensionError({+ type: 'unhandledrejection',+ message: 'crypto.randomUUID is not a function',+ url: 'http://example-host.ts.net:5554/apps/portos-demo',+ })).toBe(false);+ });++ it('does not flag an ordinary app error', () => {+ expect(isExtensionError({+ message: "Cannot read properties of undefined (reading 'id')",+ source: 'http://example-host.ts.net:5555/assets/index-abc123.js',+ stack: "TypeError\n at Foo (http://example-host.ts.net:5555/assets/index-abc123.js:10:5)",+ })).toBe(false);+ });++ it('does not flag on `url` alone — the page is ours even when an extension throws on it', () => {+ // `url` is window.location.href. If a page URL could trigger the filter,+ // a hostile/odd route would silently disable error reporting.+ expect(isExtensionError({+ message: 'boom',+ url: 'http://example-host.ts.net:5555/apps/chrome-extension://spoof',+ })).toBe(false);+ });+ });++ describe('untrusted input', () => {+ it('returns false for non-object payloads', () => {+ for (const v of [null, undefined, 'string', 42, true, []]) {+ expect(isExtensionError(v)).toBe(false);+ }+ });++ it('ignores non-string fields rather than throwing', () => {+ expect(isExtensionError({ message: 42, stack: {}, source: ['x'] })).toBe(false);+ });+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex 67d4dfe514..49a1a1e98b 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -239,9 +239,11 @@ export * from './authGate.js';export * from './domainAutonomy.js';export * from './domainBudgets.js';export * from './errorHandler.js';+export * from './extensionErrors.js';export * from './lwwTimestamp.js';export * from './mapWithConcurrency.js';export * from './markedSection.js';+export * from './mirrorParity.js';export * from './objects.js';export * from './openapiSpec.js';export * from './shellQuote.js';diff --git a/server/lib/mirrorParity.js b/server/lib/mirrorParity.jsnew file mode 100644index 0000000000..bdfeafc304--- /dev/null+++ b/server/lib/mirrorParity.js@@ -0,0 +1,83 @@+/**+ * Shared source-comparison helpers for server↔client "mirror" parity tests.+ *+ * Several client modules are byte-for-byte mirrors of an authoritative server+ * module (see the "server mirrors" section of client/src/lib/README.md). Each+ * mirror is pinned by a `<name>.mirror.test.js` that extracts the mirrored+ * declarations from both files and diffs them with comments stripped, so+ * per-side commentary can diverge but logic cannot.+ *+ * Every such test needs the same two primitives, and hand-rolling them per+ * mirror means a bug in the brace-walker has to be found and fixed once per+ * copy — copies that had already drifted (one handled `async function`, the+ * other counted brackets) before this was extracted.+ *+ * Deliberately pure — no `vitest` import — so the server/lib barrel does not+ * pull a test framework into production. Callers own the assertions.+ */++/**+ * Strip single-line (`//`) and block (`/* … *\/`) comments, then collapse all+ * whitespace runs to a single space.+ *+ * This is what lets the two sides carry different commentary — only code+ * survives the normalization.+ */+export function stripCommentsAndNormalize(src) {+ return src+ .replace(/\/\*[\s\S]*?\*\//g, '')+ .replace(/\/\/[^\n]*/g, '')+ .replace(/\s+/g, ' ')+ .trim();+}++/**+ * Extract a top-level declaration by name — `function` / `async function` /+ * `const` (including `Object.freeze(…)` and array/object literal bodies).+ *+ * Walks from the declaration to the first opening delimiter and returns the+ * slice through its match, tracking `{}`, `()` and `[]` together. Returns the+ * declaration text, or `null` when the name is absent.+ */+export function extractDeclaration(src, name) {+ const startRe = new RegExp(`(?:export\\s+)?(?:async\\s+function|function|const)\\s+${name}[\\s=(]`);+ const match = startRe.exec(src);+ if (!match) return null;++ const start = match.index;+ let depth = 0;+ let foundOpen = false;++ for (let i = start; i < src.length; i++) {+ const ch = src[i];+ if (ch === '{' || ch === '(' || ch === '[') {+ depth++;+ foundOpen = true;+ } else if (ch === '}' || ch === ')' || ch === ']') {+ depth--;+ if (foundOpen && depth === 0) return src.slice(start, i + 1);+ }+ }+ return null;+}++/**+ * Compare one named declaration across two sources.+ *+ * Returns `{ serverDecl, clientDecl, serverNorm, clientNorm, match }` —+ * `*Decl` are null when absent, so a caller can tell "missing" apart from+ * "present but diverged" and assert each with its own message.+ */+export function compareDeclaration(serverSrc, clientSrc, name) {+ const serverDecl = extractDeclaration(serverSrc, name);+ const clientDecl = extractDeclaration(clientSrc, name);+ const serverNorm = serverDecl == null ? null : stripCommentsAndNormalize(serverDecl);+ const clientNorm = clientDecl == null ? null : stripCommentsAndNormalize(clientDecl);+ return {+ serverDecl,+ clientDecl,+ serverNorm,+ clientNorm,+ match: serverNorm != null && serverNorm === clientNorm,+ };+}diff --git a/server/services/clientErrors.js b/server/services/clientErrors.jsindex 1879489913..ccd8aaaf8f 100644--- a/server/services/clientErrors.js+++ b/server/services/clientErrors.js@@ -13,6 +13,7 @@ import { createHash } from 'crypto';import * as reviewService from './review.js';import { redactOutput } from '../lib/commandSecurity.js';import { stripQueryString } from '../lib/errorHandler.js';+import { isExtensionError } from '../lib/extensionErrors.js';const MAX_MESSAGE_CHARS = 500;const MAX_STACK_CHARS = 4000;@@ -128,6 +129,15 @@ function pruneRecent(now) {export async function recordClientError(rawPayload) {const now = Date.now();+ // Before the throttle: an extension error taking the 1/sec slot would drop a+ // real PortOS error arriving behind it. Before sanitize: MAX_STACK_CHARS+ // would truncate away the extension frame that proves provenance.+ // Re-checked here even though current clients filter at the source — a+ // long-lived tab keeps running an old bundle.+ if (isExtensionError(rawPayload)) {+ return { accepted: false, reason: 'extension' };+ }+// 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.diff --git a/server/services/clientErrors.test.js b/server/services/clientErrors.test.jsindex 93a4d8db6c..5a49a280da 100644--- a/server/services/clientErrors.test.js+++ b/server/services/clientErrors.test.js@@ -183,4 +183,68 @@ describe('recordClientError', () => {expect(arg.description).toContain('URL: https://portos/callback');expect(arg.description).not.toContain('access_token');});++ describe('browser-extension errors', () => {+ it('never reaches the Review Hub when thrown by an injected content script', async () => {+ const result = await recordClientError({+ type: 'error',+ message: "Cannot read properties of null (reading 'ethereum')",+ source: 'chrome-extension://examplewalletextensionid00000000/inpage.js',+ url: 'https://portos/dashboard',+ });++ expect(result).toEqual({ accepted: false, reason: 'extension' });+ expect(review.createItem).not.toHaveBeenCalled();+ });++ it('does not spend the throttle slot, so a real error right behind it still lands', async () => {+ // The whole reason the filter runs BEFORE the throttle gate: an+ // extension error accepted at T would drop a genuine PortOS error at+ // T+<1s as `rate-limited`, losing it permanently.+ await recordClientError({+ type: 'unhandledrejection',+ message: 'Failed to connect to MetaMask',+ });+ const real = await recordClientError({+ type: 'error',+ message: 'Genuine PortOS failure',+ source: '/assets/index.js',+ });++ expect(real.accepted).toBe(true);+ expect(review.createItem).toHaveBeenCalledTimes(1);+ expect(review.createItem.mock.calls[0][0].title).toContain('Genuine PortOS failure');+ });++ it('still reports an extension frame that sits past the stack truncation limit', async () => {+ // Detection runs on the RAW payload for this reason — sanitize() caps+ // the stack at 4000 chars, which would cut off the only proof of+ // provenance and let the error through as if it were ours.+ const deepStack = [+ 'TypeError: boom',+ ...Array.from({ length: 200 }, (_, i) => ` at frame${i} (https://portos/assets/index.js:${i}:1)`),+ ' at inject (chrome-extension://abcdefghijklmnop/inpage.js:1:1)',+ ].join('\n');+ expect(deepStack.length).toBeGreaterThan(4000);++ const result = await recordClientError({ type: 'error', message: 'boom', stack: deepStack });++ expect(result.reason).toBe('extension');+ expect(review.createItem).not.toHaveBeenCalled();+ });++ it('does NOT filter `crypto.randomUUID is not a function` — that is our own bug', async () => {+ // Insecure-origin crash from PortOS's own code (see client/src/lib/uuid.js).+ // It superficially resembles extension noise; filtering it would hide a+ // real crash that fires from every toast.+ const result = await recordClientError({+ type: 'unhandledrejection',+ message: 'crypto.randomUUID is not a function',+ url: 'http://example-host.ts.net:5554/apps/portos-demo',+ });++ expect(result.accepted).toBe(true);+ expect(review.createItem).toHaveBeenCalledTimes(1);+ });+ });});