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-compare-caller-rollout]): migrate EpisodeVideoStage, Brain, and Digital Twin to hook's compare option
Adam Eivy7efede7c7976
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 1338badc92..de1c594811 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -19,6 +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-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/PLAN.md b/PLAN.mdindex 05441f20ce..258583b57d 100644--- a/PLAN.md+++ b/PLAN.md@@ -4,7 +4,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up-- [ ] [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-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]`.- [ ] [codex5-onboarding-capability-map] **[P2][ONBOARDING]** Capability map of connected systems. One page showing each integration's status: Providers (per-provider configured/available/throttled), Calendar, Brain/memory embeddings, Voice (mic + TTS), Tailscale + HTTPS, Genome/health imports, Telegram/messages, App registry/PM2. Each row links to the relevant settings page. Doubles as a setup checklist and a runtime health overview.diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex 2c51062741..d70b82e653 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -9,6 +9,15 @@ import ScenePreview from '../../creative-director/ScenePreview';import { useAsyncAction } from '../../../hooks/useAsyncAction';import { useAutoRefetch } from '../../../hooks/useAutoRefetch';+// Monotonic snapshot: a poll is logically equivalent when the project's id,+// updatedAt, and status all match. Including `id` guards against the restart+// edge case where prev/next describe different projects with coincidentally+// matching keys.+const sameProjectSnapshot = (prev, next) =>+ prev.id === next.id+ && prev.updatedAt === next.updatedAt+ && prev.status === next.status;+const POLL_INTERVAL_MS = 4000;const isTerminalProjectStatus = (s) => s === 'complete' || s === 'failed';@@ -29,40 +38,47 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {const storyboardScenes = issue.stages?.storyboards?.scenes || [];const usableScenes = storyboardScenes.filter((s) => (s?.description || '').trim().length > 0);- const [cdProject, setCdProject] = useState(null);const [confirmRestart, setConfirmRestart] = useState(false);// Initialize from the persisted stage values so a page reload (or a fresh// tab) doesn't lose the user's previous picks. Falls through to defaults// 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.- const { refetch: refetchCdProject } = useAutoRefetch(- async () => {- const p = await getCreativeDirectorProject(cdProjectId, { slim: true }).catch((err) => {- console.log(`pipeline:episode poll error ${err.message}`);- return null;- });- if (!p) return null;- // Skip the setState (and downstream re-render + scene re-sort) when the- // poll returns the same monotonic snapshot we already hold.- setCdProject((prev) => (- prev && prev.updatedAt === p.updatedAt && prev.status === p.status ? prev : p- ));+ // The compare option skips re-renders when the monotonic snapshot is unchanged.+ 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 && !isTerminalProjectStatus(cdProject?.status) },+ {+ enabled: !!cdProjectId && !isTerminal,+ compare: sameProjectSnapshot,+ },);- // Clear the displayed project on stage reset; refetch immediately on id- // change so a project swap doesn't strand the previous project on screen- // until the next interval tick.+ // After a restart the hook still holds the previous project's snapshot until+ // the next fetch lands; filter by id so the stale view doesn't paint into the+ // 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(() => {- if (!cdProjectId) setCdProject(null);- else refetchCdProject();+ if (cdProjectId) refetchCdProject();}, [cdProjectId, refetchCdProject]);const [runSubmit, submitting] = useAsyncAction(@@ -87,11 +103,10 @@ export default function EpisodeVideoStage({ issue, series, onStageUpdate }) {const result = await runSubmit({ force });if (!result) return;if (force) {- // Only clear the prior project view AFTER the restart kickoff succeeds.- // Clearing pre-flight (which we used to do) meant a failed restart- // tore the in-flight progress UI off the page even though the- // previous CD project was still rendering.- setCdProject(null);+ // The prior project view clears automatically because the cdProjectId+ // filter on `rawCdProject` drops the stale snapshot once onStageUpdate+ // swaps to the new id. A failed restart leaves the previous project+ // visible because cdProjectId is unchanged in that path.toast.success(`Restarted: ${result.cdProjectId?.slice(0, 8) ?? '?'}`);} else if (result.reused) {toast.success(`Reusing in-flight CD project ${result.cdProjectId?.slice(0, 8) ?? '?'}`);diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 10da549dae..892be21372 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -1,4 +1,4 @@-import { useState, useCallback } from 'react';+import { useCallback } from 'react';import { useParams, useNavigate } from 'react-router-dom';import * as api from '../services/api';import {Brain as BrainIcon} from 'lucide-react';@@ -21,27 +21,32 @@ 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();const activeTab = tab || 'inbox';- const [summary, setSummary] = useState(null);- const [settings, setSettings] = useState(null);- const [loading, setLoading] = useState(true);-const fetchData = useCallback(async () => {- const [summaryData, settingsData] = await Promise.all([+ const [summary, settings] = await Promise.all([api.getBrainSummary().catch(() => null),api.getBrainSettings().catch(() => null)]);- setSummary(summaryData);- setSettings(settingsData);- setLoading(false);- return null;+ return { summary, settings };}, []);- useAutoRefetch(fetchData, 30_000);+ const { data, loading, refetch } = useAutoRefetch(fetchData, 30_000, {+ compare: sameBrainPayload,+ });+ const summary = data?.summary ?? null;+ const settings = data?.settings ?? null;const handleTabChange = (tabId) => {navigate(`/brain/${tabId}`);@@ -50,29 +55,29 @@ export default function Brain() {const renderTabContent = () => {switch (activeTab) {case 'inbox':- return <InboxTab onRefresh={fetchData} settings={settings} />;+ return <InboxTab onRefresh={refetch} settings={settings} />;case 'links':- return <LinksTab onRefresh={fetchData} />;+ return <LinksTab onRefresh={refetch} />;case 'memory':- return <MemoryTab onRefresh={fetchData} />;+ return <MemoryTab onRefresh={refetch} />;case 'notes':- return <NotesTab onRefresh={fetchData} />;+ return <NotesTab onRefresh={refetch} />;case 'daily-log':return <DailyLogTab />;case 'graph':return <BrainGraph />;case 'digest':- return <DigestTab onRefresh={fetchData} />;+ return <DigestTab onRefresh={refetch} />;case 'feeds':- return <FeedsTab onRefresh={fetchData} />;+ return <FeedsTab onRefresh={refetch} />;case 'trust':- return <TrustTab onRefresh={fetchData} />;+ return <TrustTab onRefresh={refetch} />;case 'import':return <ImportTab />;case 'config':- return <ConfigTab onRefresh={fetchData} />;+ return <ConfigTab onRefresh={refetch} />;default:- return <InboxTab onRefresh={fetchData} settings={settings} />;+ return <InboxTab onRefresh={refetch} settings={settings} />;}};diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex bef7fdc4d6..0d1119abcb 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -1,4 +1,4 @@-import { useState, useCallback } from 'react';+import { useCallback } from 'react';import { useParams, useNavigate } from 'react-router-dom';import * as api from '../services/api';import { Heart } from 'lucide-react';@@ -8,6 +8,12 @@ import { useAutoRefetch } from '../hooks/useAutoRefetch';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';@@ -27,22 +33,19 @@ export default function DigitalTwin() {const navigate = useNavigate();const activeTab = tab || 'overview';- const [status, setStatus] = useState(null);- const [settings, setSettings] = useState(null);- const [loading, setLoading] = useState(true);-const fetchData = useCallback(async () => {- const [statusData, settingsData] = await Promise.all([+ const [status, settings] = await Promise.all([api.getDigitalTwinStatus().catch(() => null),api.getDigitalTwinSettings().catch(() => null)]);- setStatus(statusData);- setSettings(settingsData);- setLoading(false);- return null;+ return { status, settings };}, []);- useAutoRefetch(fetchData, 30_000);+ const { data, loading, refetch } = useAutoRefetch(fetchData, 30_000, {+ compare: sameTwinPayload,+ });+ const status = data?.status ?? null;+ const settings = data?.settings ?? null;const handleTabChange = (tabId) => {navigate(`/digital-twin/${tabId}`);@@ -51,33 +54,33 @@ export default function DigitalTwin() {const renderTabContent = () => {switch (activeTab) {case 'overview':- return <OverviewTab status={status} settings={settings} onRefresh={fetchData} />;+ return <OverviewTab status={status} settings={settings} onRefresh={refetch} />;case 'documents':- return <DocumentsTab onRefresh={fetchData} />;+ return <DocumentsTab onRefresh={refetch} />;case 'test':- return <TestTab onRefresh={fetchData} />;+ return <TestTab onRefresh={refetch} />;case 'enrich':- return <EnrichTab onRefresh={fetchData} />;+ return <EnrichTab onRefresh={refetch} />;case 'taste':- return <TasteTab onRefresh={fetchData} />;+ return <TasteTab onRefresh={refetch} />;case 'accounts':return <AccountsTab />;case 'identity':- return <IdentityTab onRefresh={fetchData} />;+ return <IdentityTab onRefresh={refetch} />;case 'goals':- return <GoalsTab onRefresh={fetchData} />;+ return <GoalsTab onRefresh={refetch} />;case 'interview':- return <InterviewTab onRefresh={fetchData} />;+ return <InterviewTab onRefresh={refetch} />;case 'autobiography':- return <AutobiographyTab onRefresh={fetchData} />;+ return <AutobiographyTab onRefresh={refetch} />;case 'import':- return <ImportTab onRefresh={fetchData} />;+ return <ImportTab onRefresh={refetch} />;case 'export':- return <ExportTab onRefresh={fetchData} />;+ return <ExportTab onRefresh={refetch} />;case 'time-capsule':- return <TimeCapsuleTab onRefresh={fetchData} />;+ return <TimeCapsuleTab onRefresh={refetch} />;default:- return <OverviewTab status={status} settings={settings} onRefresh={fetchData} />;+ return <OverviewTab status={status} settings={settings} onRefresh={refetch} />;}};