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

address review (codex): make the App.jsx route scan and spaPaths patterns actually work (#4688)

[._.]/ Adam Eivy44f31c23f896
diff --git a/client/src/components/cos/CoSCanvasGuard.jsx b/client/src/components/cos/CoSCanvasGuard.jsx
index 671bbe49ea..0972728270 100644
--- a/client/src/components/cos/CoSCanvasGuard.jsx
+++ b/client/src/components/cos/CoSCanvasGuard.jsx
@@ -39,16 +39,20 @@ function WebGLUnavailableHint({ background = false }) {
);
}
-function AvatarAssetFailure({ background = false, error }) {
+// Named for the failure, not the cause: four of the six avatars are procedural
+// scenes with no GLB at all, so a throw from one of those is a render failure
+// rather than a load failure. `glbFailureHint` names a cause only when it
+// recognizes one, and the raw message covers the rest.
+function AvatarRenderFailure({ background = false, error }) {
// `null` from the shared hint table means "we don't recognize this" — fall
// back to the raw message rather than inventing a cause.
const hint = glbFailureHint(error);
return (
<div className={panelClass(background)} data-testid="cos-avatar-asset-error" role="alert">
<div className="text-2xl mb-2" aria-hidden="true">⚠️</div>
- <div className="text-xs font-semibold text-gray-200 mb-1">Avatar failed to load</div>
+ <div className="text-xs font-semibold text-gray-200 mb-1">Avatar could not be displayed</div>
<div className="text-[10px] text-gray-400 leading-snug">
- {hint || glbErrorText(error) || 'The avatar model could not be loaded.'}
+ {hint || glbErrorText(error) || 'The 3D avatar could not be rendered.'}
</div>
</div>
);
@@ -75,7 +79,7 @@ export default function CoSCanvasGuard({
const error = failure?.key === resetKey ? failure.error : null;
if (!supported) return <WebGLUnavailableHint background={background} />;
- if (error) return <AvatarAssetFailure background={background} error={error} />;
+ if (error) return <AvatarRenderFailure background={background} error={error} />;
return (
<CoSAvatarFrame label={label} background={background}>
diff --git a/client/src/components/cos/CoSCanvasGuard.test.jsx b/client/src/components/cos/CoSCanvasGuard.test.jsx
index 159ef498d4..117fcb3d30 100644
--- a/client/src/components/cos/CoSCanvasGuard.test.jsx
+++ b/client/src/components/cos/CoSCanvasGuard.test.jsx
@@ -92,10 +92,22 @@ describe('CoSCanvasGuard', () => {
// Both panels are the guard's own. The GLB-loading callers used to pass a
// "no model — run setup" hint here, but they only reach the guard after a HEAD
// request proved the model IS there, so that hint was wrong on both branches.
- it('owns both panels, with no caller override', () => {
+ it('owns both panels, ignoring a fallback a caller tries to pass', () => {
+ // The prop is gone, so this passes one anyway: restoring the old override
+ // would make the guard render it and fail here. Without a hostile prop the
+ // test would stay green through exactly the regression it guards.
+ const hostile = { fallback: <div data-testid="caller-fallback" /> };
+
cleanup();
webgl.available = false;
- render(<CoSCanvasGuard><div /></CoSCanvasGuard>);
+ render(<CoSCanvasGuard {...hostile}><div /></CoSCanvasGuard>);
expect(screen.getByText(/This display has no WebGL/i)).toBeInTheDocument();
+ expect(screen.queryByTestId('caller-fallback')).not.toBeInTheDocument();
+
+ cleanup();
+ webgl.available = true;
+ render(<CoSCanvasGuard {...hostile}><Boom error={new Error('boom')} /></CoSCanvasGuard>);
+ expect(screen.getByTestId('cos-avatar-asset-error')).toBeInTheDocument();
+ expect(screen.queryByTestId('caller-fallback')).not.toBeInTheDocument();
});
});
diff --git a/scripts/dev-proxy-drift.test.js b/scripts/dev-proxy-drift.test.js
index bbac784325..1425809382 100644
--- a/scripts/dev-proxy-drift.test.js
+++ b/scripts/dev-proxy-drift.test.js
@@ -71,27 +71,43 @@ const navPaths = NAV_COMMANDS.map((command) => command.path);
* would therefore be invisible to a nav-manifest-only check — and the terminator
* would 404 it in production with nothing failing near the new route.
*
- * Nesting has to be resolved rather than read off each tag, because App.jsx
- * nests (`<Route path="media"><Route path="image" …/></Route>` is `/media/image`).
- * A depth-tracking scan is enough here and keeps the guard dependency-free — a
- * real JSX parse would mean pulling a parser into the server test runner, whose
- * CI job installs only the server's dependencies.
+ * Nesting has to be RESOLVED, not read off each tag, because App.jsx nests:
+ * `<Route path="media" …><Route path="image" …/></Route>` is `/media/image`.
+ * Hence the hand-rolled scan below instead of a regex per tag — a tag's
+ * attributes contain `>` inside JSX expressions (`element={<MediaGen />}`), so
+ * anything matching `<Route[^>]*>` ends the tag in the middle of `element` and
+ * reads every child as a sibling. Parsing properly would mean pulling a JSX
+ * parser into the SERVER test runner, whose CI job installs only the server's
+ * dependencies — so this tracks brace depth and quotes itself.
*/
function clientRoutePaths(source) {
const paths = [];
const stack = [];
- const TAG = /<Route\b([^>]*?)(\/?)>|<\/Route>/g;
- for (const [tag, attrs, selfClosing] of source.matchAll(TAG)) {
- if (tag === '</Route>') { stack.pop(); continue; }
+ for (let i = source.indexOf('<Route'); i !== -1; i = source.indexOf('<Route', i + 1)) {
+ if (source.startsWith('</Route>', i - 1)) continue;
+ let depth = 0;
+ let quote = null;
+ let end = -1;
+ for (let j = i + 6; j < source.length; j++) {
+ const char = source[j];
+ if (quote) { if (char === quote) quote = null; continue; }
+ if (char === '"' || char === "'" || char === '`') { quote = char; continue; }
+ if (char === '{') depth += 1;
+ else if (char === '}') depth -= 1;
+ else if (char === '>' && depth === 0) { end = j; break; }
+ }
+ if (end === -1) break;
+ const attrs = source.slice(i + 6, end);
+ const selfClosing = attrs.trimEnd().endsWith('/');
+ // An index route (no `path`) resolves to its parent, and a pathless layout
+ // route adds no segment — both are a null frame on the stack.
const path = attrs.match(/\bpath="([^"]*)"/)?.[1] ?? null;
- // An index route (no `path`) resolves to its parent, and a layout route
- // with no path adds no segment — both are represented by a null frame.
- const segments = [...stack, path].filter((segment) => segment);
if (path !== null) {
- const joined = segments.join('/').replace(/\/+/g, '/');
+ const joined = [...stack, path].filter((segment) => segment).join('/').replace(/\/+/g, '/');
paths.push(joined.startsWith('/') ? joined : `/${joined}`);
}
if (!selfClosing) stack.push(path);
+ i = end;
}
return paths;
}
@@ -146,8 +162,15 @@ describe('the asset table vs what the server mounts', () => {
describe('server-owned prefixes vs the client router', () => {
const routePaths = [...new Set([...navPaths, ...clientRoutePaths(read('client/src/App.jsx'))])];
- it('finds the client routes it is comparing', () => {
- expect(routePaths.length).toBeGreaterThan(50);
+ it('resolves App.jsx\'s nested routes rather than reading each tag flat', () => {
+ // Asserting on the UNION would prove nothing — NAV_COMMANDS alone satisfies
+ // it, so `clientRoutePaths` could return [] and this would stay green. These
+ // paths exist only as nested children, and the flat reading of them (`/image`)
+ // is what a tag-at-a-time regex produces once `element={<MediaGen />}` ends
+ // the match early.
+ const scanned = clientRoutePaths(read('client/src/App.jsx'));
+ expect(scanned).toContain('/media/image');
+ expect(scanned).not.toContain('/image');
expect(routePaths).toContain('/data');
});
diff --git a/server/lib/assetMounts.js b/server/lib/assetMounts.js
index 02cd40e0e3..25ce6882ee 100644
--- a/server/lib/assetMounts.js
+++ b/server/lib/assetMounts.js
@@ -88,6 +88,29 @@ export const ASSET_MOUNTS = ASSET_ROUTE_PREFIXES.map((route) => ({
gate: ASSET_GATES[route],
}));
+/**
+ * A `spaPaths` entry as a predicate over a REQUEST path.
+ *
+ * Not a string compare: an entry is a route PATTERN, and the client router's own
+ * convention produces parameterized ones (`/data/:category`). Comparing literals
+ * would 404 every concrete `/data/images` while the declaration sat in the list
+ * looking correct — and `scripts/dev-proxy-drift.test.js` points people at this
+ * list when it fails, so it has to mean what it appears to mean.
+ */
+function toRouteMatcher(pattern) {
+ const source = pattern
+ .split('/')
+ .map((segment) => {
+ if (segment.startsWith(':')) return '[^/]+';
+ if (segment === '*') return '.*';
+ return segment.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ })
+ .join('/');
+ const regex = new RegExp(`^${source}$`);
+ return (path) => regex.test(path);
+}
+
+
/**
* Mount every asset route, then close each server-owned namespace with a 404.
*
@@ -99,17 +122,24 @@ export const ASSET_MOUNTS = ASSET_ROUTE_PREFIXES.map((route) => ({
* (#4688); an API client gets HTML where it expects JSON, with a success
* status. The envelope comes from `sendErrorResponse` so this 404 is the same
* shape as every other one PortOS emits.
+ *
+ * `ownedPrefixes` defaults to the real list; a test overrides it to exercise a
+ * `spaPaths` shape the app does not happen to use yet.
*/
-export function mountAssetRoutes(app) {
+export function mountAssetRoutes(app, ownedPrefixes = SERVER_OWNED_PREFIXES) {
ASSET_MOUNTS.forEach(({ route, dir, gate }) => {
app.use(route, ...(gate ? [gate] : []), express.static(dir(), ASSET_STATIC_OPTS));
});
- SERVER_OWNED_PREFIXES.forEach(({ prefix, spaPaths }) => {
- app.use(prefix, (req, res, next) => (
+ ownedPrefixes.forEach(({ prefix, spaPaths }) => {
+ const spaMatchers = spaPaths.map(toRouteMatcher);
+ app.use(prefix, (req, res, next) => {
// `app.use('/data', …)` reduces the page's own request to `req.path === '/'`.
- spaPaths.includes(prefix + (req.path === '/' ? '' : req.path))
- ? next()
- : sendErrorResponse(res, new ServerError('Not found', { status: 404 }))
- ));
+ // The trailing slash is stripped because `express.static` 301s a directory
+ // request to one (`/data/images` → `/data/images/`), and the redirect lands
+ // back here — an entry that matched the first form would miss the second.
+ const path = (prefix + (req.path === '/' ? '' : req.path)).replace(/\/+$/, '') || prefix;
+ if (spaMatchers.some((matches) => matches(path))) return next();
+ return sendErrorResponse(res, new ServerError('Not found', { status: 404 }));
+ });
});
}
diff --git a/server/lib/assetMounts.test.js b/server/lib/assetMounts.test.js
index f49ffd026c..96d3e842e4 100644
--- a/server/lib/assetMounts.test.js
+++ b/server/lib/assetMounts.test.js
@@ -98,6 +98,24 @@ describe('the server-owned namespace terminators', () => {
expect(res.text).toContain('PortOS');
});
+ // `spaPaths` entries are route PATTERNS, not literals — the drift guard tells
+ // people to add a client route there when it fails, and the router convention
+ // produces parameterized ones. A literal compare would 404 every concrete
+ // path while the declaration sat in the list looking correct.
+ it('lets a parameterized spaPaths entry through to the SPA', async () => {
+ const patterned = express();
+ mountAssetRoutes(patterned, [{ prefix: '/data', spaPaths: ['/data', '/data/:category'] }]);
+ patterned.use(spaFallback);
+
+ const page = await request(patterned).get('/data/images');
+ expect(page.status).toBe(200);
+ expect(page.text).toContain('PortOS');
+
+ // ...and only one segment deep, exactly as the pattern says.
+ const tooDeep = await request(patterned).get('/data/images/nested/thing');
+ expect(tooDeep.status).toBe(404);
+ });
+
it('still serves an asset from a mount', async () => {
const res = await request(app).get('/data/images/probe.png');
expect(res.status).toBe(200);