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
feat([useautorefetch-poll-result-dedup]): opt-in compare to skip re-renders on unchanged poll results (#420)
[._.]/ Adam Eivy7ffd77ead089
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3ae80d82b3..956c16c764 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -17,6 +17,7 @@- **[codex5-bundle-lazy-routes] Dashboard widgets load on demand.** A dashboard layout now only downloads the widgets it actually uses — the first paint of a slimmed-down layout no longer drags in every widget in the registry, and slow widgets render their own placeholder while loading instead of blocking sibling cells. Also adds an `npm run build:analyze` script for inspecting bundle composition during development.- **[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.- **[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.## Fixeddiff --git a/PLAN.md b/PLAN.mdindex 52298c7927..31605ad6e3 100644--- a/PLAN.md+++ b/PLAN.md@@ -4,7 +4,7 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up-- [ ] [useautorefetch-poll-result-dedup] **`useAutoRefetch` poll-result deduplication.** Surfaced by /simplify during `[codex5-polling-consolidation]`. After migrating 20 callers to `useAutoRefetch`, every poll still calls `setData(result)` unconditionally — re-rendering even when the API returned bytewise-identical state. `EpisodeVideoStage` is the only pre-existing dedup site (`(prev, p) => prev.updatedAt === p.updatedAt && prev.status === p.status`); the rest (ProcessesTab, AgentsPage, Brain summary, DigitalTwin status, meatspace OverviewTab fan-out, MediaJobsQueue, ChiefOfStaff, Browser status, etc.) re-render every interval. Options: (a) accept an optional `compareKey: (data) => string` option on the hook so callers can opt into signature-compare, (b) wrap the hook's internal `setData` to default to `Object.is` comparison and only the rare case (deep object reuse) needs explicit opt-in. Low priority — UI churn is invisible but burns CPU on the Dashboard's many widgets.+- [ ] [useautorefetch-compare-caller-rollout] **Roll out `useAutoRefetch`'s `compare` option to high-frequency Dashboard widgets.** The hook now accepts `{ compare(prev, next) }` to skip the `setData` (and the consequent re-render) when the new poll result is logically equivalent. Audit each poll site — ProcessesTab, AgentsPage, Brain summary, DigitalTwin status, meatspace OverviewTab fan-out, MediaJobsQueue, ChiefOfStaff, Browser status — and add a comparator wherever the API returns a monotonic key (`updatedAt`, version, status) or a stable list shape. EpisodeVideoStage already does this in its own `setCdProject` — migrate it to use the hook's `data` path so the dedup lives in one place. Low priority; UI churn is invisible but burns CPU on Dashboards with many widgets.- [ ] [useautorefetch-shared-visibility-listener] **Shared `visibilitychange` listener for `useAutoRefetch` consumers.** Each `useAutoRefetch` caller currently attaches its own `document.addEventListener('visibilitychange', ...)`. On a page with 20+ widgets (Dashboard), tab show fires 20+ near-simultaneous `loadData()` calls. Extract a singleton emitter (e.g. `client/src/hooks/useVisibilityEvent.js`) and have `useAutoRefetch` subscribe to that instead. Trivial overhead today; revisit if Dashboard widget count grows or profiling flags it.- [ ] [useautorefetch-pollonly-mode] **`useAutoRefetch` `{ pollOnly: true }` mode.** Several callers (Brain, DigitalTwin, ChiefOfStaff, meatspace OverviewTab, MediaJobsQueue, Loops, etc.) use the hook purely as a poll tick — they own their own state via the fetchFn's side-effects and ignore `data` / `loading`. The `return null;` ceremony is documented but signals "I'm not using the hook's data". Add a `{ pollOnly: true }` option that skips the `data` / `loading` useStates and returns `{ refetch }` only, so side-effect-only callers don't carry unused state. Defer until there are enough such callers that the noise is worth abstracting.- [ ] [agents-tab-cooldown-tick-extraction] **Extract a shared cooldown-tick hook for the agents tabs.** `agents/{OverviewTab,ToolsTab,WorldTab}.jsx` each spin a 1s `setInterval` that both (a) ticks `setTick(t => t + 1)` so countdown labels update and (b) conditionally refetches rate limits when every cooldown has expired. Not a fit for `useAutoRefetch` (the tick is primarily UI-driven, the refetch is incidental). Extract `useCooldownTick({ cooldownEnds, onAllExpired })` so all three callers share one tested implementation. Surfaced while migrating sibling pollers in `[codex5-polling-consolidation]`.diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.jsindex 18fdd4d588..8b3f945f17 100644--- a/client/src/hooks/useAutoRefetch.js+++ b/client/src/hooks/useAutoRefetch.js@@ -17,18 +17,38 @@ import { useState, useEffect, useRef, useCallback } from 'react';* @param {boolean} [options.immediate=true] - when false, skip the on-mount fetch* and wait `intervalMs` before the first fetch. Use when the caller already* performs a one-shot fetch via another path (e.g. `useCityData.fetchAll`).+ * @param {(prev:any, next:any)=>boolean} [options.compare] - when provided,+ * each fetch keeps the previous reference (skipping the re-render) if+ * `compare(prev, next)` returns true. Only invoked when both `prev` and+ * `next` are non-null — the first fetch always sets data. Use for polls+ * that return monotonic snapshots (e.g. `(a, b) => a.updatedAt === b.updatedAt`).* @returns {{ data: any, loading: boolean, refetch: Function }}*/export function useAutoRefetch(fetchFn, intervalMs, options = {}) {- const { enabled = true, immediate = true } = options;+ const { enabled = true, immediate = true, compare } = options;const [data, setData] = useState(null);const [loading, setLoading] = useState(true);const fetchRef = useRef(fetchFn);+ const compareRef = useRef(compare);useEffect(() => {fetchRef.current = fetchFn;}, [fetchFn]);+ // Kept in a ref so callers can pass an inline arrow without re-creating+ // applyResult/refetch on every render.+ useEffect(() => {+ compareRef.current = compare;+ }, [compare]);++ const applyResult = useCallback((result) => {+ setData((prev) => {+ const cmp = compareRef.current;+ if (cmp && prev != null && result != null && cmp(prev, result)) return prev;+ return result;+ });+ }, []);+// Stable, unconditional refetch for callers (Refresh buttons, post-mutation// refresh paths, and key-change effects that need an immediate fetch with// the new closure). Bypasses the visibility short-circuit — when a user@@ -36,7 +56,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {const refetch = useCallback(async () => {try {const result = await fetchRef.current();- setData(result);+ applyResult(result);setLoading(false);return result;} catch (err) {@@ -44,7 +64,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {setLoading(false);return undefined;}- }, []);+ }, [applyResult]);useEffect(() => {if (!enabled) return undefined;@@ -56,7 +76,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {try {const result = await fetchRef.current();if (cancelled) return;- setData(result);+ applyResult(result);setLoading(false);} catch (err) {console.warn(`⚠️ Auto-refetch failed: ${err.message}`);@@ -81,7 +101,7 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {document.removeEventListener('visibilitychange', handleVisibilityChange);}};- }, [intervalMs, enabled, immediate]);+ }, [intervalMs, enabled, immediate, applyResult]);return { data, loading, refetch };}diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsxindex 6fe2e4984e..fec30efcf6 100644--- a/client/src/hooks/useAutoRefetch.test.jsx+++ b/client/src/hooks/useAutoRefetch.test.jsx@@ -124,4 +124,83 @@ describe('useAutoRefetch', () => {rerender({ fn: second });await waitFor(() => expect(second.mock.calls.length).toBeGreaterThanOrEqual(1));});++ it('preserves the previous data reference when compare returns true', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce({ updatedAt: 1, status: 'idle' })+ .mockResolvedValue({ updatedAt: 1, status: 'idle' });+ const compare = (prev, next) =>+ prev.updatedAt === next.updatedAt && prev.status === next.status;++ const { result } = renderHook(() => useAutoRefetch(fetchFn, 20, { compare }));++ await waitFor(() => expect(result.current.data).not.toBeNull());+ const first = result.current.data;++ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(3));+ expect(result.current.data).toBe(first);+ });++ it('replaces data when compare returns false', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce({ updatedAt: 1 })+ .mockResolvedValueOnce({ updatedAt: 2 });+ const compare = (prev, next) => prev.updatedAt === next.updatedAt;++ const { result } = renderHook(+ () => useAutoRefetch(fetchFn, 60_000, { enabled: false, compare }),+ );++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toEqual({ updatedAt: 1 });++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toEqual({ updatedAt: 2 });+ });++ it('always sets data on first fetch even with compare configured', async () => {+ const fetchFn = vi.fn().mockResolvedValue({ updatedAt: 1 });+ const compare = vi.fn(() => true);++ const { result } = renderHook(() => useAutoRefetch(fetchFn, 60_000, { compare }));++ await waitFor(() => expect(result.current.data).toEqual({ updatedAt: 1 }));+ expect(compare).not.toHaveBeenCalled();+ });++ it('compare also applies to the manual refetch path', async () => {+ const snapshot = { updatedAt: 1 };+ const fetchFn = vi.fn()+ .mockResolvedValueOnce(snapshot)+ .mockResolvedValueOnce({ updatedAt: 1 });+ const compare = (prev, next) => prev.updatedAt === next.updatedAt;++ const { result } = renderHook(+ () => useAutoRefetch(fetchFn, 60_000, { enabled: false, compare }),+ );++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toBe(snapshot);++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toBe(snapshot);+ });++ it('compare is bypassed when the new result is null, replacing prior data', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce({ updatedAt: 1 })+ .mockResolvedValueOnce(null);+ const compare = vi.fn(() => true);++ const { result } = renderHook(+ () => useAutoRefetch(fetchFn, 60_000, { enabled: false, compare }),+ );++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toEqual({ updatedAt: 1 });++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toBeNull();+ expect(compare).not.toHaveBeenCalled();+ });});