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
address review (codex): throttled stat for buildId, drop fragile fs.watch (#1828)
[._.]/ Adam Eivya48b8084be94
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 292deacbda..2006565fe8 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 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)+- **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; the freshness check is now throttled to at most once per second (the hot path between checks is a clock comparison, no syscall), so a rebuild re-syncs the served HTML with the on-disk chunks within the throttle window instead of paying a stat per navigation. 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.fallback.test.js b/server/lib/buildId.fallback.test.jsdeleted file mode 100644index 8a98bd3919..0000000000--- a/server/lib/buildId.fallback.test.js+++ /dev/null@@ -1,57 +0,0 @@-import { describe, it, expect, beforeEach, vi } from 'vitest';--// Simulate a platform/filesystem where fs.watch is unavailable, with index.html-// fully in-memory so this file never touches the real client/dist/index.html-// (and so can't race the sibling buildId.test.js, which vitest may run in a-// parallel worker). The buildId module must fall back to a throttled stat so a-// rebuild is still detected instead of serving stale chunk URLs until restart-// (codex review #1828).-const state = { mtimeMs: 1000, html: '<html><head></head><body>A</body></html>', indexExists: true };--vi.mock('fs', async (importOriginal) => {- const actual = await importOriginal();- return {- ...actual,- watch: vi.fn(() => { throw new Error('fs.watch unsupported'); }),- existsSync: vi.fn((p) => (String(p).endsWith('index.html') ? state.indexExists : true)),- statSync: vi.fn(() => ({ mtimeMs: state.mtimeMs })),- readFileSync: vi.fn(() => state.html),- };-});--beforeEach(() => {- vi.resetModules();- state.mtimeMs = 1000;- state.html = '<html><head></head><body>A</body></html>';- state.indexExists = true;-});--describe('buildId — degraded mode (fs.watch unavailable)', () => {- it('falls back to a stat so a rebuild is still detected without the watcher', async () => {- const mod = await import('./buildId.js');- const idA = mod.getBuildId(); // primes (the `!cached` path — no stat fallback yet)- expect(idA).not.toBe('dev');-- // Rebuild: new content + mtime. With no watcher, the next read's throttled- // stat fallback (lastStatAt is still 0 after the prime) fires and recomputes.- // NOTE: don't read again before mutating — in degraded mode the fallback is- // throttled to one stat per STAT_FALLBACK_MS, so an intervening read would- // consume the window and suppress this rebuild detection (bounded staleness- // is the intended degraded-mode tradeoff).- state.html = '<html><head></head><body>B</body></html>';- state.mtimeMs = 2000;-- const idB = mod.getBuildId();- expect(idB).not.toBe(idA);- expect(mod.getStampedIndexHtml()).toContain('body>B');- });-- it('drops to id=dev when index.html disappears while the watcher is unavailable', async () => {- const mod = await import('./buildId.js');- expect(mod.getBuildId()).not.toBe('dev'); // primes from in-memory A-- state.indexExists = false;- expect(mod.getBuildId()).toBe('dev');- expect(mod.getStampedIndexHtml()).toBe(null);- });-});diff --git a/server/lib/buildId.js b/server/lib/buildId.jsindex 7a90bb040f..c98aff1a73 100644--- a/server/lib/buildId.js+++ b/server/lib/buildId.js@@ -15,41 +15,36 @@* back to `'dev'` and the socket emission is a no-op match.*/-import { existsSync, readFileSync, statSync, watch } from 'fs';+import { existsSync, readFileSync, statSync } 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);-// 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.+// Cached snapshot of the stamped HTML + its build id, keyed on the index.html+// mtime. 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 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.+// a rebuild, blocking the event loop for that I/O on each request. We now+// THROTTLE the freshness check: at most one `stat` per CHECK_THROTTLE_MS+// regardless of request rate. Between checks the hot path is just a clock+// comparison (no syscall). On a check the (cheap, OS-inode-cached) `stat`+// compares mtime and recomputes only on an actual change, so the served HTML+// re-syncs with the on-disk chunks within the throttle window — bounded, and it+// always self-heals (no reliance on filesystem change events, which drop on+// some platforms). 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 throttled check only matters for a manual+// rebuild against a long-running dev server.let cached = null;-let dirty = false;-let watcher = null;-let lastStatAt = 0;+let lastCheckAt = 0;-// When the watcher CAN'T be armed (fs.watch unsupported, or it errored out), a-// rebuild would otherwise go undetected until restart. In that degraded mode we-// fall back to a stat — throttled so it stays cheap — so the cache self-heals.-// No stat is taken while the watcher is healthy.-const STAT_FALLBACK_MS = 1000;+const CHECK_THROTTLE_MS = 1000;const DEV_SNAPSHOT = { id: 'dev', html: null, mtimeMs: 0 };@@ -67,49 +62,17 @@ function deriveFromHtml(html, mtimeMs) {return { id, html: stamped, mtimeMs };}-// 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.+// Synchronous (re)compute — reads index.html once. Runs at boot and again only+// when a throttled check detects a changed mtime, NOT on every request.function computeSync() {if (!existsSync(INDEX_PATH)) return DEV_SNAPSHOT;const mtimeMs = statSync(INDEX_PATH).mtimeMs;return deriveFromHtml(readFileSync(INDEX_PATH, 'utf8'), mtimeMs);}-// 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- // The watcher only catches FUTURE writes; if the dist dir just appeared- // (a build completed against a running dev server), recompute once so an- // index.html that landed before the watcher armed isn't missed.- dirty = true;- } catch {- watcher = null;- }-}--// Degraded-mode fallback: only runs when the watcher is NOT armed. A throttled-// stat detects a rebuild so the cache can't go permanently stale on a platform-// without working fs.watch. Cheap (OS inode cache) and bounded to one per-// STAT_FALLBACK_MS regardless of request rate.-function maybeStatRefresh() {- const now = Date.now();- if (now - lastStatAt < STAT_FALLBACK_MS) return;- lastStatAt = now;+// Throttled freshness check. Cheap (`stat` hits the OS inode cache) and capped+// at one per CHECK_THROTTLE_MS, so request bursts collapse to a single check.+function checkForRebuild() {if (!existsSync(INDEX_PATH)) {if (cached.id !== 'dev') cached = DEV_SNAPSHOT;return;@@ -117,21 +80,16 @@ function maybeStatRefresh() {if (statSync(INDEX_PATH).mtimeMs !== cached.mtimeMs) cached = computeSync();}-function closeWatcher() {- if (!watcher) return;- try { watcher.close(); } catch { /* already closed */ }- watcher = null;-}-function ensureFresh() {- ensureWatcher();- if (!cached || dirty) {+ if (!cached) {cached = computeSync();- dirty = false;- } else if (!watcher) {- // Watcher couldn't be armed/maintained — fall back to a throttled stat so a- // rebuild is still picked up instead of serving stale chunks until restart.- maybeStatRefresh();+ lastCheckAt = Date.now();+ return cached;+ }+ const now = Date.now();+ if (now - lastCheckAt >= CHECK_THROTTLE_MS) {+ lastCheckAt = now;+ checkForRebuild();}return cached;}@@ -145,20 +103,15 @@ export function getStampedIndexHtml() {}/**- * 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).+ * Force a synchronous recompute (bypassing the throttle) and return the+ * resulting snapshot. The hot-path getters recompute at most once per throttle+ * window; this is the explicit hook for callers that need the freshest value+ * right now (boot warm-up, tests).** @returns {{id: string, html: string|null, mtimeMs: number}}*/export function refreshBuildId() {cached = computeSync();- dirty = false;+ lastCheckAt = Date.now();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.jsindex a0da8f0a01..9b22ec0a61 100644--- a/server/lib/buildId.test.js+++ b/server/lib/buildId.test.js@@ -27,12 +27,8 @@ beforeEach(async () => {}});-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?.();+afterEach(() => {+ vi.useRealTimers();if (preservedIndex !== null) {writeFileSync(INDEX_PATH, preservedIndex);preservedIndex = null;@@ -58,9 +54,9 @@ 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. The hot-path getters- // recompute only on a watcher signal; refreshBuildId() is the explicit,- // synchronous recompute hook (deterministic — no fs.watch timing).+ // Simulate a Vite rebuild: new content, new mtime. refreshBuildId() is the+ // explicit synchronous recompute hook (bypasses the throttle window the+ // hot-path getters honor) — deterministic, no 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);@@ -75,27 +71,30 @@ describe('buildId — cache invalidation', () => {expect(htmlB).toContain('body>B');});- it('the dist watcher invalidates the cache so a rebuild is picked up off the hot path', async () => {+ it('serves the cached snapshot within the throttle window, then re-syncs after it (no per-request stat)', async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date('2026-05-01T00:00:00Z'));+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 + arms the dist watcher+ const idOld = mod.getBuildId(); // primes; stamps the throttle clockexpect(idOld).not.toBe('dev');- // 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.+ // Rebuild on disk. Within the throttle window the getter must NOT re-stat —+ // it serves the cached (stale) snapshot.writeFileSync(INDEX_PATH, '<html><head></head><body>new</body></html>');- const t1 = new Date('2026-05-02T00:00:00Z');+ const t1 = new Date('2026-05-01T00:10:00Z');utimesSync(INDEX_PATH, t1, t1);+ vi.advanceTimersByTime(500); // < CHECK_THROTTLE_MS (1000ms)+ expect(mod.getBuildId()).toBe(idOld);- let idNew = idOld;- for (let i = 0; i < 60 && idNew === idOld; i++) {- await new Promise((r) => setTimeout(r, 50));- idNew = mod.getBuildId();- }+ // Past the throttle window the next read re-stats, sees the new mtime, and+ // recomputes — so the served HTML re-syncs with the on-disk chunks.+ vi.advanceTimersByTime(600); // now > 1000ms since the prime+ const idNew = mod.getBuildId();expect(idNew).not.toBe(idOld);expect(mod.getStampedIndexHtml()).toContain('body>new');});