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): event-driven buildId invalidation, not async refresh (#1828)

[._.]/ Adam Eivyc2b1c5f00d42
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 3575622342..292deacbda 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -17,7 +17,7 @@
## Fixed
-- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; it now serves a cached snapshot and refreshes the mtime/hash off the hot path (deduped + throttled, primed synchronously at boot). The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)
+- **Blocking sync I/O removed from request/completion hot paths** — several syscalls ran synchronously on paths that serve live SSE/socket traffic, freezing the event loop for their duration. `checkForTaskCommit` (`agentRunTracking.js`) ran a `spawnSync('git', ['log', …])` on the completion path of every failed CoS run (100ms–2s on a large repo); it now uses the async, hard-timeout `bufferedSpawn`. `buildId.js` `statSync`'d `client/dist/index.html` on every SPA navigation; it now serves a cached snapshot and invalidates it via an `fs.watch` on the dist directory, so a rebuild is recomputed synchronously on the next read (served HTML always matches the on-disk chunks — no stale-chunk window) without any per-request stat. The avatar (`routes/avatar.js`) and attachment (`routes/attachments.js`) routes swapped `existsSync`/`statSync` for async `fs.access`/`fs.stat` (via a new canonical `pathExists` helper in `fileUtils.js`), and uploads now call the idempotent `ensureDir` directly. Separately, the tombstone-prune paths for authors/tracks/creative-director projects (DB + file backends) wrapped their per-record `deleteSyncBaseHash` loops in `withBaseHashFlushBatch`, collapsing N `sync_base_hashes.json` rewrites into one. (#1828)
- **External API model/metadata fetches now time out instead of stalling callers indefinitely** — `_fetchGeminiModels` (Gemini model refresh in `aiToolkit/providers.js`) made a `fetch` with no `AbortSignal`, unlike every other provider model-fetch in that file, so a hung Google endpoint could block a model-refresh request forever; it now uses the same `AbortSignal.timeout(8000)`. `fetchCivitaiModel` and `searchCivitaiLoras` (`server/lib/civitai.js`) likewise passed no signal, so a Civitai hang stalled LoRA metadata/search callers; both now default to `AbortSignal.timeout(10000)` and accept a caller-provided `signal` override. (#1827)
- **Unguarded async `child_process` handlers can no longer crash the Node process** — several `close`/`error` event handlers were `async` and `await`ed disk writes / completion bookkeeping with no `try/catch`, so a single failed write (e.g. a full disk) or a throwing completion hook surfaced as an unhandled rejection and took down the whole server. Wrapped the at-risk handler bodies in `server/services/runner.js` (both `close` and `error`), `videoTimeline/local.js`, `agentCliSpawning.js` (both `close` and `error`), and both the CLI `close` handler and the detached `processStream().catch` in `aiToolkit/runner.js`. The recovery paths now still settle callers waiting on `onComplete` with failure metadata (so a finalization failure surfaces as a failed run instead of hanging forever), with the completion hook isolated from `onComplete` so a throwing `onRunFailed` can't block the caller from settling. Also replaced the two silent recovery-critical `.catch(() => {})` swallows in `cos-runner/index.js` with logged failures so a lost completion-metadata write is visible instead of silently dropping a finished task. (#1825)
- Catalog "Appears in" panel no longer renders dangling chips that deep-link to soft-deleted universe/series/creative-director targets — the detail page filters refs to live targets only (the orphan stays recoverable via the "Orphaned" album). Also fixed a stale resolver bug where soft-deleted Creative Director projects (#1564) wrongly resolved as live, and extended orphan-bucket detection so a deleted CD project's ex-cast surfaces as orphaned rather than unlinked. (#1812)
diff --git a/server/lib/buildId.js b/server/lib/buildId.js
index 66e9daa014..d6140c1935 100644
--- a/server/lib/buildId.js
+++ b/server/lib/buildId.js
@@ -15,40 +15,38 @@
* back to `'dev'` and the socket emission is a no-op match.
*/
-import { existsSync, readFileSync, statSync } from 'fs';
-import { readFile, stat } from 'fs/promises';
+import { existsSync, readFileSync, statSync, watch } from 'fs';
import { createHash } from 'crypto';
import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
const __dirname = dirname(fileURLToPath(import.meta.url));
const INDEX_PATH = join(__dirname, '..', '..', 'client', 'dist', 'index.html');
+const DIST_DIR = dirname(INDEX_PATH);
-// 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.
+// Cached snapshot of the stamped HTML + its build id, plus an event-driven
+// staleness flag. Vite rewrites index.html every build (new chunk filenames
+// inside), so a pure module-level cache would keep serving the old stamped HTML
+// — the browser would then request chunk filenames that no longer exist on disk
+// → 404 → black page.
//
-// The cache is refreshed OFF the request hot path: the synchronous getters
-// return the cached snapshot immediately and kick a non-blocking `fs.stat` +
-// `fs.readFile` refresh. The previous implementation `statSync`'d on every SPA
-// navigation, blocking the event loop for that I/O on each request. The first
-// call primes the cache synchronously (server boot) so the very first response
-// is correct; thereafter a rebuild is picked up on the next request after the
-// async refresh settles (sub-millisecond on a local disk). Refreshes are
-// deduped (one in flight) and throttled so a request burst can't fan out a
-// `stat` per request.
+// The previous design `statSync`'d index.html on EVERY SPA navigation to detect
+// a rebuild. That blocked the event loop for that I/O on each request. Instead
+// we watch the dist directory: any write to index.html flags the cache stale,
+// and the next getter recomputes synchronously exactly once. So a request never
+// pays a stat, yet a rebuild-while-running is reflected immediately on the very
+// next read — the served HTML always matches the on-disk chunks (no stale-chunk
+// window). In production the server is restarted as part of an update (the
+// client is rebuilt while the process is down), so the boot-time prime already
+// reads the fresh bundle; the watcher only matters for a manual rebuild against
+// a long-running dev server.
let cached = null;
-let refreshing = null; // in-flight refresh promise, or null
-let lastRefreshAt = 0; // throttle clock (ms)
-
-const REFRESH_THROTTLE_MS = 1000;
+let dirty = false;
+let watcher = null;
const DEV_SNAPSHOT = { id: 'dev', html: null, mtimeMs: 0 };
-// Pure: hash + stamp the meta tag into the html. Shared by the sync prime and
-// the async refresh so the two paths can't drift.
+// Pure: hash + stamp the meta tag into the html.
function deriveFromHtml(html, mtimeMs) {
const id = createHash('sha256').update(html).digest('hex').slice(0, 12);
// Inject the meta tag once. Idempotent: replace if already present
@@ -62,47 +60,49 @@ function deriveFromHtml(html, mtimeMs) {
return { id, html: stamped, mtimeMs };
}
-// Synchronous prime — used once on the first getter call (server boot) so the
-// cache is never empty when a value is read. One sync stat+read here is fine; it
-// happens at most once, not per request.
-function primeSync() {
- if (!existsSync(INDEX_PATH)) {
- cached = DEV_SNAPSHOT;
- return cached;
- }
+// Synchronous (re)compute — reads index.html once. Runs at boot (the first
+// getter call) and again only after the watcher flags a rebuild, NOT per
+// request. The mtime is captured purely for cache-equality diagnostics.
+function computeSync() {
+ if (!existsSync(INDEX_PATH)) return DEV_SNAPSHOT;
const mtimeMs = statSync(INDEX_PATH).mtimeMs;
- cached = deriveFromHtml(readFileSync(INDEX_PATH, 'utf8'), mtimeMs);
- return cached;
+ return deriveFromHtml(readFileSync(INDEX_PATH, 'utf8'), mtimeMs);
}
-// Async refresh — recompute only when the mtime moved. Runs off the request
-// path so its I/O never blocks the event loop for the current response.
-async function refresh() {
- const s = await stat(INDEX_PATH).catch(() => null);
- if (!s) {
- if (!cached || cached.id !== 'dev') cached = DEV_SNAPSHOT;
- return cached;
+// Watch the dist DIRECTORY (Vite rewrites index.html via atomic rename, which a
+// file-level watch loses after the first swap). Any event touching index.html
+// marks the cache stale. Lazily armed on first read so it costs nothing in
+// `npm run dev` (no dist dir) and re-arms if the directory appears later.
+function ensureWatcher() {
+ if (watcher || !existsSync(DIST_DIR)) return;
+ // fs.watch can throw on platforms/filesystems without change notification;
+ // a failure just means we fall back to the boot-time prime (correct for the
+ // production restart-on-update flow), so swallow and leave watcher null.
+ try {
+ watcher = watch(DIST_DIR, (_event, filename) => {
+ // filename is null on some platforms — treat any event as a possible
+ // index.html change rather than miss a rebuild.
+ if (!filename || filename === 'index.html') dirty = true;
+ });
+ watcher.unref(); // never keep the event loop alive
+ watcher.on('error', () => { closeWatcher(); }); // re-arm on next read
+ } catch {
+ watcher = null;
}
- if (!cached || cached.mtimeMs !== s.mtimeMs) {
- const html = await readFile(INDEX_PATH, 'utf8').catch(() => null);
- if (html != null) cached = deriveFromHtml(html, s.mtimeMs);
- }
- return cached;
}
-// Kick a deduped, throttled background refresh. Non-blocking — the caller reads
-// the (possibly one-request-stale) cache while this settles.
-function scheduleRefresh() {
- if (refreshing) return;
- const now = Date.now();
- if (now - lastRefreshAt < REFRESH_THROTTLE_MS) return;
- lastRefreshAt = now;
- refreshing = refresh().finally(() => { refreshing = null; });
+function closeWatcher() {
+ if (!watcher) return;
+ try { watcher.close(); } catch { /* already closed */ }
+ watcher = null;
}
function ensureFresh() {
- if (!cached) return primeSync();
- scheduleRefresh();
+ ensureWatcher();
+ if (!cached || dirty) {
+ cached = computeSync();
+ dirty = false;
+ }
return cached;
}
@@ -115,16 +115,20 @@ export function getStampedIndexHtml() {
}
/**
- * Force a refresh and resolve the resulting snapshot. Bypasses the throttle so
- * callers that need the freshest value right now (boot warm-up, tests) can
- * `await` it. The hot-path getters never call this — they stay non-blocking via
- * `scheduleRefresh`.
+ * Force a synchronous recompute and return the resulting snapshot. The hot-path
+ * getters recompute only when the watcher flags a rebuild; this is the explicit
+ * hook for callers that want to recompute right now (boot warm-up, tests).
*
- * @returns {Promise<{id: string, html: string|null, mtimeMs: number}>}
+ * @returns {{id: string, html: string|null, mtimeMs: number}}
*/
-export async function refreshBuildId() {
- if (!cached) primeSync();
- lastRefreshAt = Date.now();
- refreshing = refresh().finally(() => { refreshing = null; });
- return refreshing;
+export function refreshBuildId() {
+ cached = computeSync();
+ dirty = false;
+ return cached;
+}
+
+/** Test-only: tear down the dist watcher so a `vi.resetModules()` suite doesn't
+ * leak watch handles across re-imports. */
+export function __closeWatcherForTests() {
+ closeWatcher();
}
diff --git a/server/lib/buildId.test.js b/server/lib/buildId.test.js
index 02e2879caa..a0da8f0a01 100644
--- a/server/lib/buildId.test.js
+++ b/server/lib/buildId.test.js
@@ -27,7 +27,12 @@ beforeEach(async () => {
}
});
-afterEach(() => {
+afterEach(async () => {
+ // Tear down the dist watcher the current module instance armed, before the
+ // next test's vi.resetModules() orphans the handle. (Import returns the same
+ // instance the test used — resetModules runs in beforeEach, not yet here.)
+ const mod = await import('./buildId.js').catch(() => null);
+ mod?.__closeWatcherForTests?.();
if (preservedIndex !== null) {
writeFileSync(INDEX_PATH, preservedIndex);
preservedIndex = null;
@@ -53,14 +58,15 @@ describe('buildId — cache invalidation', () => {
expect(htmlA).toContain(`<meta name="portos-build-id" content="${idA}">`);
expect(htmlA).toContain('body>A');
- // Simulate a Vite rebuild: new content, new mtime.
+ // Simulate a Vite rebuild: new content, new mtime. The hot-path getters
+ // recompute only on a watcher signal; refreshBuildId() is the explicit,
+ // synchronous recompute hook (deterministic — no fs.watch timing).
writeFileSync(INDEX_PATH, '<html><head></head><body>B</body></html>');
const t1 = new Date('2026-02-01T00:00:00Z');
utimesSync(INDEX_PATH, t1, t1);
- // The refresh is async + off the hot path, so settle it explicitly (this
- // bypasses the throttle the synchronous getters honor).
- await mod.refreshBuildId();
+ const snap = mod.refreshBuildId();
+ expect(snap.id).not.toBe(idA);
const idB = mod.getBuildId();
const htmlB = mod.getStampedIndexHtml();
@@ -69,25 +75,28 @@ describe('buildId — cache invalidation', () => {
expect(htmlB).toContain('body>B');
});
- it('getters serve the cached snapshot until the async refresh settles (no hot-path re-stat)', async () => {
+ it('the dist watcher invalidates the cache so a rebuild is picked up off the hot path', async () => {
writeFileSync(INDEX_PATH, '<html><head></head><body>old</body></html>');
const t0 = new Date('2026-05-01T00:00:00Z');
utimesSync(INDEX_PATH, t0, t0);
const mod = await import('./buildId.js');
- const idOld = mod.getBuildId(); // primes
+ const idOld = mod.getBuildId(); // primes + arms the dist watcher
expect(idOld).not.toBe('dev');
- // Rebuild on disk. The synchronous getter must still return the cached
- // (stale) value within the throttle window — it does not re-stat per call.
+ // Rebuild on disk. The synchronous getter does NOT re-stat per call, so the
+ // change is observed only once the dir watcher fires and flags the cache
+ // stale — poll briefly to let the (async) watch event land.
writeFileSync(INDEX_PATH, '<html><head></head><body>new</body></html>');
const t1 = new Date('2026-05-02T00:00:00Z');
utimesSync(INDEX_PATH, t1, t1);
- expect(mod.getBuildId()).toBe(idOld);
- // Once the explicit refresh settles, the next read reflects the rebuild.
- const snap = await mod.refreshBuildId();
- expect(snap.id).not.toBe(idOld);
+ let idNew = idOld;
+ for (let i = 0; i < 60 && idNew === idOld; i++) {
+ await new Promise((r) => setTimeout(r, 50));
+ idNew = mod.getBuildId();
+ }
+ expect(idNew).not.toBe(idOld);
expect(mod.getStampedIndexHtml()).toContain('body>new');
});