Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix 3D preview taking the whole page down when a mesh can't load

Adam Eivy4f4a165113cd
diff --git a/client/src/components/ErrorBoundary.jsx b/client/src/components/ErrorBoundary.jsx
index bd7fdb6dc0..a90c47c744 100644
--- a/client/src/components/ErrorBoundary.jsx
+++ b/client/src/components/ErrorBoundary.jsx
@@ -16,6 +16,12 @@ export default class ErrorBoundary extends Component {
componentDidCatch(error, errorInfo) {
if (isStaleChunkError(error) && reloadOnceForStaleChunk()) return;
console.error(`💥 React Error: ${error.message}`, errorInfo);
+ // `onError` lets a caller that owns chrome AROUND the failed subtree react
+ // to the failure — an r3f `<Canvas>` can only degrade to `fallback={null}`
+ // inside the scene, so the DOM-side message has to be rendered by the
+ // parent from its own state (GlbViewer's mesh-load panel). Not called on
+ // the stale-chunk path above: that reloads the page.
+ this.props.onError?.(error);
}
render() {
diff --git a/client/src/components/media/GlbViewer.jsx b/client/src/components/media/GlbViewer.jsx
index 603e630d87..78988f954c 100644
--- a/client/src/components/media/GlbViewer.jsx
+++ b/client/src/components/media/GlbViewer.jsx
@@ -6,7 +6,8 @@ import {
OrbitControls,
useGLTF,
} from '@react-three/drei';
-import { Download, Rotate3d, SlidersHorizontal } from 'lucide-react';
+import { AlertTriangle, Download, RefreshCw, Rotate3d, SlidersHorizontal } from 'lucide-react';
+import ErrorBoundary from '../ErrorBoundary';
import { GltfPrimitive } from '../../hooks/useClonedGltf';
const DEFAULT_BACKGROUND = '#050505';
@@ -75,6 +76,71 @@ function GlbModel({ src, forceOpaque }) {
return <GltfPrimitive object={renderedScene} />;
}
+// A mesh that fails to load must not take the page with it. Anything thrown
+// inside an r3f `<Canvas>` — a 404 on the .glb, a non-glTF body reaching the
+// parser, a WebGL context failure — is caught by the Canvas and re-thrown from
+// its OWN render (`if (error) throw error`), so with no boundary around it the
+// nearest one is the router's errorElement and the whole route is replaced by
+// "PortOS could not load this page". `fallback={null}` degrades the scene (the
+// shared boundary's documented r3f mode) while `onError` hands the failure to
+// the viewer, which owns the DOM chrome and renders the panel below.
+
+// One table so every recognized cause reads the same way. The raw messages are
+// useless on their own: the glTF parser JSON.parses whatever bytes it is handed,
+// so a 200 HTML body (an SPA fallback answering a path that isn't really
+// served) surfaces as a JSON syntax error naming a `<` token.
+const FAILURE_HINTS = [
+ [
+ /Unexpected token '<'|<!DOCTYPE/i,
+ 'The server answered with a web page instead of the mesh file — the asset may be missing or the server may still be restarting.',
+ ],
+ [/\b404\b|not found/i, 'The mesh file is no longer on disk.'],
+ [/webgl/i, 'This display cannot create a WebGL context, so 3D previews cannot render here.'],
+];
+
+const errorText = (error) => String(error?.message || error || '');
+
+export function glbFailureHint(error) {
+ const message = errorText(error);
+ return FAILURE_HINTS.find(([pattern]) => pattern.test(message))?.[1] || null;
+}
+
+// r3f prefixes every loader failure with "Could not load <url>", so this is what
+// separates "the bytes never arrived" from a failure thrown after the mesh was
+// already parsed (context loss, a throw downstream of the load). Only the former
+// justifies evicting drei's cache on retry — see retryLoad.
+const isLoadFailure = (error) => /^Could not load/i.test(errorText(error));
+
+function GlbLoadFailure({ error, onRetry }) {
+ const hint = glbFailureHint(error);
+ return (
+ // `.port-media-overlay` (not `bg-black/NN` + `text-gray-200`) because this
+ // panel floats over the canvas surface, whose backdrop is a user-picked
+ // color: on a day theme the hardcoded light ink is remapped to dark and the
+ // heading renders near-invisible. See "Media overlay chrome" in index.css.
+ // Deliberately not `ui/Banner`: its `bg-port-error/10` tint is built to sit
+ // on a page, not over an arbitrary canvas backdrop.
+ <div
+ data-testid="glb-load-error"
+ className="port-media-overlay absolute inset-0 flex flex-col items-center justify-center gap-2 p-4 text-center"
+ >
+ <AlertTriangle className="h-6 w-6 text-port-error" aria-hidden="true" />
+ <p className="text-sm font-medium">This 3D model could not be loaded</p>
+ {hint && <p className="max-w-sm text-xs text-port-text-muted">{hint}</p>}
+ <p className="max-w-full break-all font-mono text-[10px] leading-snug text-port-text-muted">
+ {errorText(error)}
+ </p>
+ <button
+ type="button"
+ onClick={onRetry}
+ className="port-media-overlay-item mt-1 inline-flex items-center gap-1.5 rounded-md border border-port-border px-3 py-1.5 text-xs font-medium"
+ >
+ <RefreshCw className="h-3.5 w-3.5" /> Retry
+ </button>
+ </div>
+ );
+}
+
// Own `scene.environmentIntensity` directly rather than passing drei's
// `environmentIntensity` prop: drei applies it from an effect that doesn't
// declare it as a dependency. drei's `applyProps` skips `undefined`, so omitting
@@ -137,7 +203,24 @@ export default function GlbViewer({
const [environmentIntensity, setEnvironmentIntensity] = useState(0.6);
const [showEnvironmentBackground, setShowEnvironmentBackground] = useState(true);
const [controlsOpen, setControlsOpen] = useState(false);
+ // A load failure is stored WITH the src it belongs to, so pointing the viewer
+ // at a different mesh drops the panel without an effect — and one record's
+ // failure never sticks to the next one.
+ const [failure, setFailure] = useState(null);
if (!src) return null;
+ const loadError = failure?.src === src ? failure.error : null;
+ const retryLoad = () => {
+ // suspend-react (under drei's useGLTF) caches the REJECTION against the URL
+ // and re-throws it on every later render, so clearing the panel alone would
+ // show the same error straight back — drop the cache entry first. Dropping
+ // the panel is what remounts the boundary and the canvas.
+ //
+ // Only for a load failure: the same call evicts a SUCCESSFULLY parsed scene
+ // just as readily, so clearing after (say) a lost WebGL context would throw
+ // away a good multi-MB mesh and re-download it.
+ if (isLoadFailure(loadError)) useGLTF.clear(src);
+ setFailure(null);
+ };
const href = downloadHref || src;
// With an explicit download endpoint the server's Content-Disposition wins, so
// a bare `download` attribute is enough; otherwise infer a name from the URL.
@@ -152,43 +235,53 @@ export default function GlbViewer({
{/* Settings live in a collapsed strip BELOW the canvas, not an overlay —
an always-on panel covered the upper-right quadrant of the model.
`aria-controls` is set only while the panel is mounted; the collapsed
- state removes it, and a dangling IDREF is invalid ARIA. */}
- <button
- type="button"
- onClick={() => setControlsOpen((open) => !open)}
- aria-expanded={controlsOpen}
- aria-controls={controlsOpen ? controlsPanelId : undefined}
- aria-label="Preview display settings"
- title="Preview display settings"
- className={`port-media-overlay-strong port-media-overlay-item absolute right-2 top-2 z-10 inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded-md border border-port-border focus-visible:ring-2 focus-visible:ring-port-accent sm:min-h-0 sm:min-w-0 sm:p-1.5 ${controlsOpen ? 'ring-1 ring-port-accent' : ''}`}
- >
- <SlidersHorizontal className="h-4 w-4" />
- </button>
+ state removes it, and a dangling IDREF is invalid ARIA. Gone while the
+ failure panel is up: it is `z-10` over that panel, and every control
+ behind it drives a canvas that is no longer mounted. */}
+ {!loadError && (
+ <button
+ type="button"
+ onClick={() => setControlsOpen((open) => !open)}
+ aria-expanded={controlsOpen}
+ aria-controls={controlsOpen ? controlsPanelId : undefined}
+ aria-label="Preview display settings"
+ title="Preview display settings"
+ className={`port-media-overlay-strong port-media-overlay-item absolute right-2 top-2 z-10 inline-flex min-h-[44px] min-w-[44px] items-center justify-center rounded-md border border-port-border focus-visible:ring-2 focus-visible:ring-port-accent sm:min-h-0 sm:min-w-0 sm:p-1.5 ${controlsOpen ? 'ring-1 ring-port-accent' : ''}`}
+ >
+ <SlidersHorizontal className="h-4 w-4" />
+ </button>
+ )}
{/* No `<color attach="background">`: r3f canvases are alpha-clear, so the
surface's CSS color already IS the backdrop. A scene-level color only
duplicates it while racing Environment's own scene.background
save/restore whenever the HDRI toggle or the picker changes. */}
- <Canvas camera={{ position: [0, 0, 3], fov: 45 }} dpr={[1, 2]}>
- <ambientLight intensity={ambientIntensity} />
- <directionalLight position={[4, 6, 5]} intensity={keyIntensity} />
- <directionalLight position={[-4, -2, -5]} intensity={fillIntensity} />
- <Suspense fallback={null}>
- {/* Keep the HDRI in public/ instead of using drei's remote presets:
- preview lighting and the default backdrop must work offline. */}
- <Environment
- files={ENVIRONMENT_HDRI}
- background={showEnvironmentBackground}
- backgroundBlurriness={ENVIRONMENT_BACKGROUND_BLUR}
- />
- <EnvironmentIntensity value={environmentIntensity} reassertOn={showEnvironmentBackground} />
- <Bounds fit clip observe margin={1.2}>
- <GlbModel src={src} forceOpaque={forceOpaque} />
- </Bounds>
- </Suspense>
- <OrbitControls makeDefault enablePan enableZoom enableRotate />
- </Canvas>
+ {loadError ? (
+ <GlbLoadFailure error={loadError} onRetry={retryLoad} />
+ ) : (
+ <ErrorBoundary fallback={null} onError={(error) => setFailure({ src, error })}>
+ <Canvas camera={{ position: [0, 0, 3], fov: 45 }} dpr={[1, 2]}>
+ <ambientLight intensity={ambientIntensity} />
+ <directionalLight position={[4, 6, 5]} intensity={keyIntensity} />
+ <directionalLight position={[-4, -2, -5]} intensity={fillIntensity} />
+ <Suspense fallback={null}>
+ {/* Keep the HDRI in public/ instead of using drei's remote presets:
+ preview lighting and the default backdrop must work offline. */}
+ <Environment
+ files={ENVIRONMENT_HDRI}
+ background={showEnvironmentBackground}
+ backgroundBlurriness={ENVIRONMENT_BACKGROUND_BLUR}
+ />
+ <EnvironmentIntensity value={environmentIntensity} reassertOn={showEnvironmentBackground} />
+ <Bounds fit clip observe margin={1.2}>
+ <GlbModel src={src} forceOpaque={forceOpaque} />
+ </Bounds>
+ </Suspense>
+ <OrbitControls makeDefault enablePan enableZoom enableRotate />
+ </Canvas>
+ </ErrorBoundary>
+ )}
</div>
- {controlsOpen && (
+ {controlsOpen && !loadError && (
<div
id={controlsPanelId}
className="grid gap-x-6 gap-y-2 border-t border-port-border bg-port-card px-3 py-2.5 text-xs text-gray-200 sm:grid-cols-2"
@@ -225,8 +318,10 @@ export default function GlbViewer({
</div>
)}
<div className="flex items-center justify-between gap-2 border-t border-port-border px-3 py-2">
+ {/* Kept mounted while errored so `justify-between` still parks the
+ download link on the right — the orbit hint is what drops out. */}
<span className="inline-flex items-center gap-1.5 text-xs text-gray-500">
- <Rotate3d className="h-3.5 w-3.5" /> Drag to orbit · scroll to zoom
+ {!loadError && <><Rotate3d className="h-3.5 w-3.5" /> Drag to orbit · scroll to zoom</>}
</span>
<a
href={href}
diff --git a/client/src/components/media/GlbViewer.test.jsx b/client/src/components/media/GlbViewer.test.jsx
index 59311e7599..e63c86f2fd 100644
--- a/client/src/components/media/GlbViewer.test.jsx
+++ b/client/src/components/media/GlbViewer.test.jsx
@@ -1,23 +1,39 @@
import { fireEvent, render, screen } from '@testing-library/react';
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { BoxGeometry, Group, Mesh, MeshStandardMaterial } from 'three';
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
// The three.js stack can't run in jsdom (no WebGL context) and none of it is
// under test here — this file covers the chrome AROUND the canvas (the download
-// link + the empty-src guard). Bounds drops the model subtree: mounting
-// <primitive>/<mesh> would surface unknown DOM elements and r3f hands back
-// HTMLElement refs without the three.js API. Canvas retains the lighting and
-// environment elements so their interactive wiring stays covered.
+// link, the empty-src guard, the load-failure panel). The model subtree mounts
+// so `useGLTF` is really called (that is what throws on a bad asset), with
+// GltfPrimitive stubbed out: rendering <primitive>/<mesh> would surface unknown
+// DOM elements and r3f hands back HTMLElement refs without the three.js API.
+// Canvas retains the lighting and environment elements so their interactive
+// wiring stays covered.
// `mockScene` stands in for the three.js scene `useThree` hands the viewer, so
// the environment-intensity assertions below check the value the component
// actually writes onto the scene — not merely a prop handed to a mocked
// <Environment>, which would stay green through the exact regression the
// source guards against (memoizing the environment children).
-const { mockScene } = vi.hoisted(() => ({ mockScene: {} }));
+// The two failure modes are mocked separately because they behave differently:
+// `gltf.error` fails the LOADER the way drei does, mirroring suspend-react's real
+// caching (the rejection is remembered against the URL and re-thrown from the
+// render phase until `useGLTF.clear(url)` drops it — without that, nothing could
+// tell a working Retry from one that only looks like it re-fetched), while
+// `canvas.error` fails the CANVAS ITSELF, which is how r3f surfaces a WebGL
+// context failure: from its own render, with nothing cached to evict.
+const { mockScene, gltf, canvas } = vi.hoisted(() => ({
+ mockScene: {},
+ gltf: { error: null, rejections: new Map() },
+ canvas: { error: null },
+}));
vi.mock('@react-three/fiber', () => ({
- Canvas: ({ children }) => <div data-testid="glb-canvas">{children}</div>,
+ Canvas: ({ children }) => {
+ if (canvas.error) throw canvas.error;
+ return <div data-testid="glb-canvas">{children}</div>;
+ },
useThree: (selector) => selector({ scene: mockScene }),
}));
vi.mock('@react-three/drei', () => ({
@@ -33,14 +49,28 @@ vi.mock('@react-three/drei', () => ({
{children}
</div>
),
- Bounds: () => null,
- useGLTF: Object.assign(() => ({ scene: {} }), { clear: vi.fn() }),
+ Bounds: ({ children }) => children,
+ useGLTF: Object.assign((url) => {
+ if (gltf.error) gltf.rejections.set(url, gltf.error);
+ const cached = gltf.rejections.get(url);
+ if (cached) throw cached;
+ return { scene: {} };
+ }, { clear: vi.fn((url) => gltf.rejections.delete(url)) }),
}));
+vi.mock('../../hooks/useClonedGltf', () => ({ GltfPrimitive: () => null }));
-import GlbViewer, { cloneGlbSceneWithOpaqueMaterials } from './GlbViewer';
+import { useGLTF } from '@react-three/drei';
+import GlbViewer, { cloneGlbSceneWithOpaqueMaterials, glbFailureHint } from './GlbViewer';
const openControls = () => fireEvent.click(screen.getByLabelText('Preview display settings'));
+beforeEach(() => {
+ gltf.error = null;
+ gltf.rejections.clear();
+ canvas.error = null;
+ useGLTF.clear.mockClear();
+});
+
describe('GlbViewer', () => {
it('renders nothing without a src', () => {
const { container } = render(<GlbViewer src="" />);
@@ -193,3 +223,86 @@ describe('GlbViewer', () => {
expect(material).toMatchObject({ transparent: true, opacity: 0.2, depthWrite: false });
});
});
+
+describe('GlbViewer load failures', () => {
+ // React and the shared ErrorBoundary both log every caught error.
+ let logged;
+ beforeEach(() => {
+ logged = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ });
+ afterEach(() => { vi.restoreAllMocks(); });
+
+ // The reported failure: a dev server answering an unproxied /data path with
+ // index.html, so the glTF parser JSON.parses HTML. It escaped the canvas and
+ // replaced the entire route with the router's error page.
+ it('shows an inline panel instead of letting a load error take the page down', () => {
+ gltf.error = new Error(
+ "Could not load /data/image-to-3d/abc/model.glb?v=1: Unexpected token '<', \"<!DOCTYPE \"... is not valid JSON",
+ );
+ // Nothing catches this above the viewer: without its own boundary the throw
+ // escapes `render` here, exactly as it escapes to the router in the app.
+ render(<GlbViewer src="/data/image-to-3d/abc/model.glb?v=1" />);
+
+ expect(screen.getByTestId('glb-load-error')).toBeInTheDocument();
+ expect(screen.getByText('This 3D model could not be loaded')).toBeInTheDocument();
+ expect(screen.getByText(/answered with a web page instead of the mesh file/i)).toBeInTheDocument();
+ expect(screen.queryByTestId('glb-canvas')).not.toBeInTheDocument();
+ // The download link survives; the controls that drive the now-unmounted
+ // canvas do not — the settings toggle sits `z-10` OVER this panel.
+ expect(screen.getByRole('link', { name: /Download \.glb/i })).toBeInTheDocument();
+ expect(screen.queryByText(/Drag to orbit/)).not.toBeInTheDocument();
+ expect(screen.queryByLabelText('Preview display settings')).not.toBeInTheDocument();
+ expect(logged).toHaveBeenCalledWith(expect.stringContaining('💥 React Error'), expect.anything());
+ });
+
+ it('drops the cached rejection when the user retries', () => {
+ gltf.error = new Error('Could not load /data/image-to-3d/abc/model.glb: 404 Not Found');
+ render(<GlbViewer src="/data/image-to-3d/abc/model.glb" />);
+ expect(screen.getByText(/no longer on disk/i)).toBeInTheDocument();
+
+ gltf.error = null;
+ fireEvent.click(screen.getByRole('button', { name: /Retry/i }));
+
+ // Without the clear, suspend-react re-throws the SAME cached rejection for
+ // this URL on every later render and Retry can never recover.
+ expect(useGLTF.clear).toHaveBeenCalledWith('/data/image-to-3d/abc/model.glb');
+ expect(screen.queryByTestId('glb-load-error')).not.toBeInTheDocument();
+ expect(screen.getByTestId('glb-canvas')).toBeInTheDocument();
+ });
+
+ // The failure is remembered against the src that produced it, so one record's
+ // dead mesh can't stick to the next model the viewer is pointed at.
+ it('clears the failure when the viewer is pointed at another mesh', () => {
+ gltf.error = new Error('Could not load /a.glb: boom');
+ const { rerender } = render(<GlbViewer src="/a.glb" />);
+ expect(screen.getByTestId('glb-load-error')).toBeInTheDocument();
+
+ gltf.error = null;
+ rerender(<GlbViewer src="/b.glb" />);
+
+ expect(screen.queryByTestId('glb-load-error')).not.toBeInTheDocument();
+ expect(screen.getByTestId('glb-canvas')).toBeInTheDocument();
+ });
+
+ // `useGLTF.clear` evicts a parsed scene as readily as a rejection, so a
+ // failure thrown AFTER the bytes landed must not cost a multi-MB re-download.
+ it('keeps the cached mesh when the failure was not a load failure', () => {
+ canvas.error = new Error('THREE.WebGLRenderer: Error creating WebGL context.');
+ render(<GlbViewer src="/data/image-to-3d/abc/model.glb" />);
+ expect(screen.getByText(/cannot create a WebGL context/i)).toBeInTheDocument();
+
+ canvas.error = null;
+ fireEvent.click(screen.getByRole('button', { name: /Retry/i }));
+
+ expect(useGLTF.clear).not.toHaveBeenCalled();
+ expect(screen.getByTestId('glb-canvas')).toBeInTheDocument();
+ });
+
+ it('only names a cause it can actually recognize', () => {
+ expect(glbFailureHint(new Error('something went sideways'))).toBeNull();
+ expect(glbFailureHint(new Error('<!DOCTYPE html>'))).toMatch(/web page/i);
+ expect(glbFailureHint(new Error('responded with 404'))).toMatch(/no longer on disk/i);
+ expect(glbFailureHint(new Error('Error creating WebGL context'))).toMatch(/WebGL/i);
+ });
+});
diff --git a/client/vite.config.js b/client/vite.config.js
index 3bea627723..71e2ca300a 100644
--- a/client/vite.config.js
+++ b/client/vite.config.js
@@ -50,17 +50,16 @@ export default defineConfig(({ mode }) => {
changeOrigin: true,
secure: false
},
- '/data/images': {
- target: API_TARGET,
- changeOrigin: true,
- secure: false
- },
- '/data/videos': {
- target: API_TARGET,
- changeOrigin: true,
- secure: false
- },
- '/data/video-thumbnails': {
+ // Every `/data/**` asset mount at once, instead of a hand-maintained
+ // list that silently fell behind the server's (see docs/PORTS.md:
+ // an unproxied `/data` path is answered by Vite's SPA fallback with
+ // index.html and a 200, so a binary loader parses HTML). Anchored as a
+ // regex on purpose: Vite matches a plain context with a bare
+ // `url.startsWith`, so a `'/data'` key would also swallow the `/data`
+ // (Data Manager) and `/datadog` client routes and hand them the API's
+ // stale built index.html. `scripts/dev-proxy-drift.test.js` holds both
+ // halves of that — mounts covered, client routes untouched.
+ '^/data/': {
target: API_TARGET,
changeOrigin: true,
secure: false
diff --git a/docs/PORTS.md b/docs/PORTS.md
index 5d42a54713..e890a6cfb3 100644
--- a/docs/PORTS.md
+++ b/docs/PORTS.md
@@ -53,7 +53,8 @@ vite dev (npm run dev) ──── :5554 ─ Vite dev server (dev only, separa
Rules of thumb:
1. **`:5555` is the only port a remote user ever needs.** The scheme (HTTP vs HTTPS) flips based on whether a TLS cert is provisioned (`npm run setup:cert`); the port number does not.
2. **`:5553` is a convenience for local terminals.** When HTTPS is on, `https://localhost:5555` would trip a cert warning (the cert covers `<machine>.<tailnet>.ts.net`, not `localhost`). The loopback HTTP mirror on `:5553` lets curl/scripts skip TLS entirely. It binds to `127.0.0.1` only — never reachable over the network.
-3. **`:5554` is `vite dev` only.** In `npm run dev`, Vite serves the React UI from `:5554` and proxies `/api` calls to `:5555`. In `npm start` (production), the React build is served from `:5555` itself; `:5554` is unused.
+3. **`:5554` is `vite dev` only.** In `npm run dev`, Vite serves the React UI from `:5554` and proxies `/api`, `/data` and `/socket.io` to `:5555`. In `npm start` (production), the React build is served from `:5555` itself; `:5554` is unused.
+ - **Anything the server serves must be in that proxy list.** An unproxied path does not 404 in dev — Vite's SPA fallback answers it with `index.html` and a `200`, so a loader expecting bytes parses HTML and fails somewhere far from the cause (a missing `/data/image-to-3d` entry surfaced as `Unexpected token '<' … is not valid JSON` from the GLB viewer, which took its whole route down). `/data` is therefore proxied as one wildcard prefix, and `scripts/dev-proxy-drift.test.js` fails if a server `/data/**` mount ever falls outside it.
## Defining Ports in ecosystem.config.cjs
diff --git a/scripts/dev-proxy-drift.test.js b/scripts/dev-proxy-drift.test.js
new file mode 100644
index 0000000000..873bd10220
--- /dev/null
+++ b/scripts/dev-proxy-drift.test.js
@@ -0,0 +1,81 @@
+/**
+ * Drift guard for the Vite dev proxy, in both directions.
+ *
+ * Under `npm run dev` (and under PM2, which runs the UI as the Vite dev server)
+ * the browser talks to :5554, so anything the API serves must be proxied to
+ * :5555 — and anything the CLIENT routes must NOT be. Both mistakes fail
+ * quietly, which is why they are pinned here rather than left to review:
+ *
+ * - a MISSING mount is answered by Vite's SPA fallback with index.html and a
+ * 200, so a binary loader parses HTML and reports something unrelated to
+ * the cause (`/data/image-to-3d` was absent, and the GLB viewer died on
+ * "Unexpected token '<' ... is not valid JSON", taking its route with it);
+ * - an OVER-BROAD context steals a page: Vite matches a plain context with a
+ * bare `url.startsWith`, so a `'/data'` key would also capture the `/data`
+ * and `/datadog` routes and hand the browser the API's built index.html.
+ *
+ * Full story in docs/PORTS.md.
+ */
+import { beforeAll, describe, it, expect } from 'vitest';
+import { readFileSync } from 'fs';
+import { dirname, join } from 'path';
+import { fileURLToPath } from 'url';
+
+import { NAV_COMMANDS } from '../server/lib/navManifest.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
+const read = (rel) => readFileSync(join(REPO_ROOT, rel), 'utf8');
+
+/** Every `app.use('/data…', …)` mount declared by the server. */
+function serverDataMounts(source) {
+ return [...source.matchAll(/app\.use\(\s*'(\/data(?:\/[^']*)?)'/g)].map(([, path]) => path);
+}
+
+/**
+ * The dev server's REAL proxy contexts — the config is a plain factory, so this
+ * asks it rather than regexing the source. That matters: a regex over the file
+ * cannot tell a plain prefix from a `^`-anchored regex key, which is exactly
+ * the distinction the assertions below turn on.
+ */
+async function devProxyContexts() {
+ const { default: defineConfigFn } = await import('../client/vite.config.js');
+ const config = await defineConfigFn({ mode: 'development', command: 'serve' });
+ return Object.keys(config.server.proxy);
+}
+
+/**
+ * Vite's own matcher, mirrored from `doesProxyContextMatchUrl` — a leading `^`
+ * makes the context a regex, anything else is a bare prefix test. Re-deriving
+ * it here is the point: the bug this guards is a context whose match is wider
+ * than it looks.
+ */
+const proxyMatches = (context, url) =>
+ (context[0] === '^' && new RegExp(context).test(url)) || url.startsWith(context);
+
+describe('vite dev proxy vs the server and the client router', () => {
+ // `server/index.js` boots the app on import, so its mounts stay a source read.
+ const mounts = serverDataMounts(read('server/index.js'));
+ let contexts;
+ beforeAll(async () => { contexts = await devProxyContexts(); });
+
+ it('finds the mounts and the proxy contexts it is comparing', () => {
+ // A regex that silently matched nothing would make every assertion below
+ // vacuously true.
+ expect(mounts.length).toBeGreaterThan(5);
+ expect(contexts).toContain('/api');
+ });
+
+ it('proxies an asset under every /data mount the server serves', () => {
+ const unproxied = mounts.filter(
+ (mount) => !contexts.some((context) => proxyMatches(context, `${mount}/probe.bin`)),
+ );
+ expect(unproxied).toEqual([]);
+ });
+
+ it('leaves every client route to the dev server', () => {
+ const stolen = NAV_COMMANDS
+ .map((command) => command.path)
+ .filter((path) => contexts.some((context) => proxyMatches(context, path)));
+ expect(stolen).toEqual([]);
+ });
+});