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

refactor([useautorefetch-compare-caller-rollout]): extract sameJsonShape helper, drop isTerminal state

Adam Eivy8a4951551fd4
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index de1c594811..ec3d5b0386 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,7 +19,7 @@
- **[strip-stage-runhistory-from-list-payloads] Pipeline list views stay lean as version history grows.** The sidebar's recent-issues list and the per-series issue list no longer ship each stage's full draft history on every read — the History button on an issue's detail page still shows the full set, but list responses can no longer balloon to many megabytes once a series has many issues with deep histories.
- **GOALS.md is now purely strategic; CoS runtime guidance lives in `docs/GOALS_OPERATIONAL.md`.** The per-domain operational goals, task-generation priorities, and core principles that the autonomous agent reads have been split out of GOALS.md so each file has a single concern. No behavior change — the Goal Progress dashboard still reads the same goals; only the file path moved.
- **[useautorefetch-poll-result-dedup] `useAutoRefetch` callers can now opt into skipping re-renders when the poll result is logically unchanged.** The hook accepts an optional `compare(prev, next)` callback; when it returns true the previous data reference is preserved, so React's set-state bail-out kicks in and the subtree doesn't re-render. The first fetch always sets data (the comparator only runs when both sides are non-null). Useful for monotonic snapshots like `(a, b) => a.updatedAt === b.updatedAt` on widgets that poll every few seconds. No behavior change for existing callers; rollout to individual widgets tracked separately.
-- **[useautorefetch-compare-caller-rollout] Brain, Digital Twin, and the pipeline Episode Video stage skip wasted re-renders when their polls return unchanged data.** Brain (30s) and Digital Twin (30s) headers now stay stable through identical poll ticks instead of flashing through a fresh render every interval. The Episode Video stage's bespoke "skip if updatedAt/status match" check inside `setCdProject` is gone — that dedup now lives in the shared hook alongside the rest of the polling surface, and stops polling automatically once a project is complete or failed. The other audited high-frequency surfaces (Processes, Agents, the render queue, Chief of Staff, Browser status, and the MeatSpace overview fan-out) were left as-is because their payloads carry continuously-changing CPU/memory/runtime fields where the comparator would almost never fire.
+- **[useautorefetch-compare-caller-rollout] Brain, Digital Twin, and the pipeline Episode Video stage skip wasted re-renders when their polls return unchanged data.** Brain (30s) and Digital Twin (30s) headers now stay stable through identical poll ticks instead of flashing through a fresh render every interval. The Episode Video stage's bespoke "skip if updatedAt/status match" check inside `setCdProject` is gone — that dedup now lives in the shared hook alongside the rest of the polling surface, so a long render session no longer churns the UI when nothing has changed. The other audited high-frequency surfaces (Processes, Agents, the render queue, Chief of Staff, Browser status, and the MeatSpace overview fan-out) were left as-is because their payloads carry continuously-changing CPU/memory/runtime fields where the comparator would almost never fire.
- **[useautorefetch-shared-visibility-listener] Internal: `useAutoRefetch` consumers now share one `visibilitychange` listener.** Each caller used to attach its own `document.addEventListener('visibilitychange', …)`, so a Dashboard with 20+ widgets ran 20+ listeners and 20+ near-simultaneous refetches on every tab show. A new `useVisibilityEvent` hook keeps the document-level listener count at one regardless of subscriber count, fanning out to all subscribers from a singleton emitter. No user-visible behavior change.
- **[codex5-polling-consolidation] PortOS pages stop polling the server while the tab is hidden.** Twenty pages and widgets (Brain, Digital Twin, Chief of Staff, CyberCity, Image Gen, Loops, Browser, the apps Processes/Update tabs, the cos Insights/Summary/Agent panels, the meatspace Overview, the media render queue, the pipeline Episode Video stage, the Creative Director detail, the brain Links tab, the System Health page, the agents process list, and the city HUD) used to fire their refresh requests on a fixed timer regardless of tab visibility; now they pause while the tab is in the background and refresh once when it comes back. Effect: less background network and battery drain, no perceptible change while a tab is actually in use.
diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
index d70b82e653..809cced1e5 100644
--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx
@@ -44,23 +44,19 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {
// for an unstarted episodeVideo stage.
const [aspectRatio, setAspectRatio] = useState(stage.aspectRatio || '16:9');
const [quality, setQuality] = useState(stage.quality || 'standard');
- // Tracked separately so the hook's `enabled` prop can reference the latest
- // status without a TDZ on rawCdProject. Updated via an effect below.
- const [isTerminal, setIsTerminal] = useState(false);
- // Poll while the project could still mutate. Pauses on hidden tab via
- // useAutoRefetch's visibility short-circuit and stops once status is terminal.
- // The compare option skips re-renders when the monotonic snapshot is unchanged.
+ // Poll while a project id is bound. Pauses on hidden tab via the hook's
+ // visibility short-circuit; identical snapshots dedup via the compare option
+ // so terminal projects no longer trigger re-renders even though the poll
+ // continues. Single-user app on Tailscale — the small bandwidth cost of
+ // polling a complete project until the user navigates away is negligible.
const { data: rawCdProject, refetch: refetchCdProject } = useAutoRefetch(
() => getCreativeDirectorProject(cdProjectId, { slim: true }).catch((err) => {
console.log(`pipeline:episode poll error ${err.message}`);
return null;
}),
POLL_INTERVAL_MS,
- {
- enabled: !!cdProjectId && !isTerminal,
- compare: sameProjectSnapshot,
- },
+ { enabled: !!cdProjectId, compare: sameProjectSnapshot },
);
// After a restart the hook still holds the previous project's snapshot until
@@ -68,13 +64,6 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {
// new context.
const cdProject = rawCdProject?.id === cdProjectId ? rawCdProject : null;
- // Mirror the project's terminal status into local state so the hook's
- // enabled gate stops polling once the project is complete/failed, and
- // resumes when a restart lands a fresh non-terminal project.
- useEffect(() => {
- setIsTerminal(isTerminalProjectStatus(cdProject?.status));
- }, [cdProject?.status]);
-
// Fire an immediate fetch on cdProjectId change so a project swap doesn't
// wait a full poll interval before the new project appears.
useEffect(() => {
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index e0065857bd..ec2cfa3dec 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -59,6 +59,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `joinInfluenceList.js` | Mirror of `joinInfluenceList` in server universe builder. |
| `loopbackHost.js` | `isLoopbackHost(host)` / `isLoopbackOrigin()` / `describeMicAvailability()` — Secure Context / loopback-origin heuristics. Use these in any new mic, clipboard, or `getUserMedia`-gated surface; matches the full `127.0.0.0/8` range, IPv6 `::1`, and the browser-bracketed `[::1]` form. |
| `mediaNavigation.js` | `getAdjacentMedia(items, item)` — prev/next computation for lightboxes. |
+| `sameJsonShape.js` | `sameJsonShape(prev, next)` — JSON.stringify-based equality for `useAutoRefetch`'s `compare` option on small, deterministically-shaped poll payloads. |
| `unsorted.js` | Synthetic "Unsorted" collection from media not filed in any real collection. |
| `upsertByIdPrepend.js` | Newest-first upsert into an id-keyed list. |
| `voiceLabel.js` | `formatVoiceLabel(v, engine?)` — display label for a TTS voice record. Engine-specific formatters plug into a lookup table; new engines extend that map. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index fce2795092..65571f90d8 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -30,6 +30,7 @@ export * from './genUtils.js';
export * from './joinInfluenceList.js';
export * from './loopbackHost.js';
export * from './mediaNavigation.js';
+export * from './sameJsonShape.js';
export * from './unsorted.js';
export * from './upsertByIdPrepend.js';
export * from './voiceLabel.js';
diff --git a/client/src/lib/sameJsonShape.js b/client/src/lib/sameJsonShape.js
new file mode 100644
index 0000000000..8ce1390c69
--- /dev/null
+++ b/client/src/lib/sameJsonShape.js
@@ -0,0 +1,10 @@
+// Stringified-shape equality for `useAutoRefetch`'s `compare` option and other
+// "skip the re-render when nothing changed" callers. JSON.stringify is the
+// right tool when:
+// - the payload is small (poll snapshots, not large lists),
+// - the source is a server route that returns deterministic key order, and
+// - values are JSON-safe primitives + plain objects + arrays.
+// For monotonic keys like `updatedAt`/`status` prefer a typed comparator —
+// this is the fallback when no single key captures equality.
+export const sameJsonShape = (prev, next) =>
+ JSON.stringify(prev) === JSON.stringify(next);
diff --git a/client/src/lib/sameJsonShape.test.js b/client/src/lib/sameJsonShape.test.js
new file mode 100644
index 0000000000..5e6c6006d2
--- /dev/null
+++ b/client/src/lib/sameJsonShape.test.js
@@ -0,0 +1,32 @@
+import { describe, it, expect } from 'vitest';
+import { sameJsonShape } from './sameJsonShape.js';
+
+describe('sameJsonShape', () => {
+ it('returns true for structurally equal small objects', () => {
+ expect(sameJsonShape({ a: 1, b: 'x' }, { a: 1, b: 'x' })).toBe(true);
+ });
+
+ it('returns true for nested equal objects', () => {
+ expect(sameJsonShape(
+ { counts: { a: 1, b: 2 }, lastDigest: '2026-05-21' },
+ { counts: { a: 1, b: 2 }, lastDigest: '2026-05-21' },
+ )).toBe(true);
+ });
+
+ it('returns false when a leaf value differs', () => {
+ expect(sameJsonShape({ a: 1 }, { a: 2 })).toBe(false);
+ });
+
+ it('returns false when a key is added or removed', () => {
+ expect(sameJsonShape({ a: 1 }, { a: 1, b: 2 })).toBe(false);
+ expect(sameJsonShape({ a: 1, b: 2 }, { a: 1 })).toBe(false);
+ });
+
+ it('treats null and undefined as different', () => {
+ expect(sameJsonShape({ a: null }, { a: undefined })).toBe(false);
+ });
+
+ it('treats two nulls as equal', () => {
+ expect(sameJsonShape(null, null)).toBe(true);
+ });
+});
diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsx
index 892be21372..d64d2db8e2 100644
--- a/client/src/pages/Brain.jsx
+++ b/client/src/pages/Brain.jsx
@@ -5,6 +5,7 @@ import {Brain as BrainIcon} from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import TabPills from '../components/ui/TabPills';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { sameJsonShape } from '../lib/sameJsonShape';
import { TABS } from '../components/brain/constants';
import { timeAgo } from '../utils/formatters';
@@ -21,14 +22,6 @@ import DailyLogTab from '../components/brain/tabs/DailyLogTab';
import ConfigTab from '../components/brain/tabs/ConfigTab';
import ImportTab from '../components/brain/tabs/ImportTab';
-// Brain summary + settings are stable JSON snapshots: counts, flags, and
-// timestamps. JSON.stringify is fine here because the payload is small and the
-// server returns keys in a deterministic order; skipping setData when the
-// stringified shape is unchanged avoids the 30s re-render churn that ripples
-// into the header + active tab.
-const sameBrainPayload = (prev, next) =>
- JSON.stringify(prev) === JSON.stringify(next);
-
export default function Brain() {
const { tab } = useParams();
const navigate = useNavigate();
@@ -43,7 +36,7 @@ export default function Brain() {
}, []);
const { data, loading, refetch } = useAutoRefetch(fetchData, 30_000, {
- compare: sameBrainPayload,
+ compare: sameJsonShape,
});
const summary = data?.summary ?? null;
const settings = data?.settings ?? null;
diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsx
index 0d1119abcb..fe027abef9 100644
--- a/client/src/pages/DigitalTwin.jsx
+++ b/client/src/pages/DigitalTwin.jsx
@@ -5,15 +5,10 @@ import { Heart } from 'lucide-react';
import BrailleSpinner from '../components/BrailleSpinner';
import TabPills from '../components/ui/TabPills';
import { useAutoRefetch } from '../hooks/useAutoRefetch';
+import { sameJsonShape } from '../lib/sameJsonShape';
import { TABS, getHealthColor, getHealthLabel } from '../components/digital-twin/constants';
-// Digital Twin status + settings are small stable snapshots (counts, scores,
-// last-test metadata). Identical 30s polls dominate; JSON.stringify on the
-// combined payload skips the setData when nothing changed.
-const sameTwinPayload = (prev, next) =>
- JSON.stringify(prev) === JSON.stringify(next);
-
import OverviewTab from '../components/digital-twin/tabs/OverviewTab';
import DocumentsTab from '../components/digital-twin/tabs/DocumentsTab';
import TestTab from '../components/digital-twin/tabs/TestTab';
@@ -42,7 +37,7 @@ export default function DigitalTwin() {
}, []);
const { data, loading, refetch } = useAutoRefetch(fetchData, 30_000, {
- compare: sameTwinPayload,
+ compare: sameJsonShape,
});
const status = data?.status ?? null;
const settings = data?.settings ?? null;