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(build): invalidate buildId cache when client/dist/index.html changes

[._.]/ Adam Eivyfb3e5d054f11
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 02899cdb42..a1db9eec24 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -945,6 +945,22 @@
## Fixed
+- **Stale-build cache — buildId now invalidates when `client/dist/index.html` changes.**
+ The boot-time cache in `server/lib/buildId.js` was load-once: once captured,
+ the server kept serving the *original* stamped index.html — referencing the
+ *original* Vite chunk filenames — even after a subsequent `npm run build`
+ rewrote `client/dist/` with new chunk hashes. The old chunk files were gone
+ from disk, so the browser got 404s on every code-split chunk and rendered
+ a black page; the only workaround was restarting the server. Same caching
+ affected `getBuildId()`, so the socket's `build:id` emit reported the *old*
+ build id and the stale-build toast never fired. Fix: cache keyed on the
+ file's mtime, recomputed on read when the mtime advances. The SPA-fallback
+ handler in `server/index.js` was also pulling the stamped HTML once at boot
+ outside the route handler; moved inside the handler so it picks up rebuilds
+ per request. **Files:** `server/lib/buildId.js`, `server/index.js`. New
+ `server/lib/buildId.test.js` covers the rebuild path, the no-change cache
+ hit, and the missing-file dev fallback.
+
- **Arc header — "Generate arc" stays accurate when only a shape is picked.**
After the sanitizer started preserving shape-only arcs, any series created
with a Vonnegut shape but no other arc content immediately showed
diff --git a/server/index.js b/server/index.js
index 1fd81fc9e8..42ca3a6e95 100644
--- a/server/index.js
+++ b/server/index.js
@@ -485,12 +485,15 @@ if (existsSync(CLIENT_DIST)) {
// Skip asset requests (.js, .css, etc.) so stale chunk requests get a proper 404
// instead of index.html with text/html MIME type. We serve the stamped HTML
// string (with <meta name="portos-build-id"> injected) instead of sendFile
- // so the bundled JS can read its own build id at boot.
- const stampedIndexHtml = getStampedIndexHtml();
+ // so the bundled JS can read its own build id at boot. Re-read per request —
+ // a `npm run build` between server start and the request rewrites index.html
+ // with new chunk filenames; a stale snapshot would tell the browser to load
+ // chunks that no longer exist on disk.
app.get('/{*splat}', (req, res, next) => {
if (req.path.match(/\.\w+$/) && !req.path.endsWith('.html')) {
return next();
}
+ const stampedIndexHtml = getStampedIndexHtml();
if (stampedIndexHtml) {
res.type('html').send(stampedIndexHtml);
} else {
diff --git a/server/lib/buildId.js b/server/lib/buildId.js
index 86c221fae0..a9a8d6b28f 100644
--- a/server/lib/buildId.js
+++ b/server/lib/buildId.js
@@ -15,7 +15,7 @@
* back to `'dev'` and the socket emission is a no-op match.
*/
-import { existsSync, readFileSync } from 'fs';
+import { existsSync, readFileSync, statSync } from 'fs';
import { createHash } from 'crypto';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
@@ -23,31 +23,45 @@ import { dirname, join } from 'path';
const __dirname = dirname(fileURLToPath(import.meta.url));
const INDEX_PATH = join(__dirname, '..', '..', 'client', 'dist', 'index.html');
+// Cache keyed on the index.html mtime — Vite rewrites this file every build,
+// so a changed mtime means new chunk filenames inside. A pure module-level
+// cache would keep serving the old stamped HTML (and reporting the old build
+// id over the socket) after `npm run build`, so the browser would request
+// chunk filenames that no longer exist on disk → 404 → black page.
let cached = null;
function compute() {
if (!existsSync(INDEX_PATH)) {
- return { id: 'dev', html: null };
+ return { id: 'dev', html: null, mtimeMs: 0 };
}
+ const mtimeMs = statSync(INDEX_PATH).mtimeMs;
const html = readFileSync(INDEX_PATH, 'utf8');
const id = createHash('sha256').update(html).digest('hex').slice(0, 12);
- // Inject the meta tag once at boot. Idempotent: if a previous boot already
- // injected (unlikely — Vite rewrites index.html on every build), regex
- // replace instead of double-inserting.
+ // Inject the meta tag once. Idempotent: replace if already present
+ // (defensive — Vite rewrites the whole file so the marker shouldn't survive
+ // a rebuild, but checking keeps the function safe to call repeatedly).
const META = `<meta name="portos-build-id" content="${id}">`;
const META_RE = /<meta name="portos-build-id" content="[^"]*">/;
const stamped = META_RE.test(html)
? html.replace(META_RE, META)
: html.replace('</head>', ` ${META}\n </head>`);
- return { id, html: stamped };
+ return { id, html: stamped, mtimeMs };
+}
+
+function ensureFresh() {
+ if (!existsSync(INDEX_PATH)) {
+ if (!cached || cached.id !== 'dev') cached = { id: 'dev', html: null, mtimeMs: 0 };
+ return cached;
+ }
+ const mtimeMs = statSync(INDEX_PATH).mtimeMs;
+ if (!cached || cached.mtimeMs !== mtimeMs) cached = compute();
+ return cached;
}
export function getBuildId() {
- if (!cached) cached = compute();
- return cached.id;
+ return ensureFresh().id;
}
export function getStampedIndexHtml() {
- if (!cached) cached = compute();
- return cached.html;
+ return ensureFresh().html;
}
diff --git a/server/lib/buildId.test.js b/server/lib/buildId.test.js
new file mode 100644
index 0000000000..c9ca00712e
--- /dev/null
+++ b/server/lib/buildId.test.js
@@ -0,0 +1,103 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { writeFileSync, mkdirSync, rmSync, existsSync, utimesSync } from 'fs';
+import { join, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const DIST_DIR = join(__dirname, '..', '..', 'client', 'dist');
+const INDEX_PATH = join(DIST_DIR, 'index.html');
+
+// These tests touch the real client/dist/index.html that `buildId.js` reads,
+// so they save the existing file, mutate it, and restore on teardown. They
+// MUST run serially (vitest default in a single file) so they don't trample
+// each other.
+let preservedIndex = null;
+let distCreated = false;
+
+beforeEach(async () => {
+ // Force a fresh module load each test — the module-level cache is the
+ // whole subject of these tests.
+ vi.resetModules();
+ if (existsSync(INDEX_PATH)) {
+ const { readFileSync } = await import('fs');
+ preservedIndex = readFileSync(INDEX_PATH, 'utf8');
+ } else if (!existsSync(DIST_DIR)) {
+ mkdirSync(DIST_DIR, { recursive: true });
+ distCreated = true;
+ }
+});
+
+afterEach(() => {
+ if (preservedIndex !== null) {
+ writeFileSync(INDEX_PATH, preservedIndex);
+ preservedIndex = null;
+ } else if (distCreated) {
+ rmSync(DIST_DIR, { recursive: true, force: true });
+ distCreated = false;
+ } else if (existsSync(INDEX_PATH)) {
+ rmSync(INDEX_PATH);
+ }
+});
+
+describe('buildId — cache invalidation', () => {
+ it('recomputes when index.html mtime changes (the rebuild path)', async () => {
+ writeFileSync(INDEX_PATH, '<html><head></head><body>A</body></html>');
+ // Pin the mtime to a known past timestamp so the change is unambiguous.
+ const t0 = new Date('2026-01-01T00:00:00Z');
+ utimesSync(INDEX_PATH, t0, t0);
+
+ const mod = await import('./buildId.js');
+ const idA = mod.getBuildId();
+ const htmlA = mod.getStampedIndexHtml();
+ expect(idA).not.toBe('dev');
+ expect(htmlA).toContain(`<meta name="portos-build-id" content="${idA}">`);
+ expect(htmlA).toContain('body>A');
+
+ // Simulate a Vite rebuild: new content, new mtime.
+ writeFileSync(INDEX_PATH, '<html><head></head><body>B</body></html>');
+ const t1 = new Date('2026-02-01T00:00:00Z');
+ utimesSync(INDEX_PATH, t1, t1);
+
+ const idB = mod.getBuildId();
+ const htmlB = mod.getStampedIndexHtml();
+ expect(idB).not.toBe(idA);
+ expect(htmlB).toContain(`<meta name="portos-build-id" content="${idB}">`);
+ expect(htmlB).toContain('body>B');
+ });
+
+ it('returns the same id from cache when mtime is unchanged', async () => {
+ writeFileSync(INDEX_PATH, '<html><head></head><body>same</body></html>');
+ const t0 = new Date('2026-03-01T00:00:00Z');
+ utimesSync(INDEX_PATH, t0, t0);
+
+ const mod = await import('./buildId.js');
+ const id1 = mod.getBuildId();
+ const id2 = mod.getBuildId();
+ const id3 = mod.getBuildId();
+ expect(id1).toBe(id2);
+ expect(id2).toBe(id3);
+ });
+
+ it('falls back to id=dev with null html when index.html is missing', async () => {
+ if (existsSync(INDEX_PATH)) rmSync(INDEX_PATH);
+
+ const mod = await import('./buildId.js');
+ expect(mod.getBuildId()).toBe('dev');
+ expect(mod.getStampedIndexHtml()).toBe(null);
+ });
+
+ it('replaces an existing portos-build-id meta tag instead of double-stamping', async () => {
+ writeFileSync(
+ INDEX_PATH,
+ '<html><head><meta name="portos-build-id" content="ABCDEF123456"></head><body>x</body></html>',
+ );
+ const t0 = new Date('2026-04-01T00:00:00Z');
+ utimesSync(INDEX_PATH, t0, t0);
+
+ const mod = await import('./buildId.js');
+ const html = mod.getStampedIndexHtml();
+ const matches = html.match(/portos-build-id/g) || [];
+ expect(matches).toHaveLength(1);
+ expect(html).not.toContain('content="ABCDEF123456"');
+ });
+});