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
perf([codex5-polling-consolidation]): pause polling while tab is hidden across 20 surfaces
[._.]/ Adam Eivy1e6537ebc605
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex bf6e544e8e..f834b6ffe5 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -14,6 +14,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.+- **[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 20987175b5..0473ee55b2 100644--- a/PLAN.md+++ b/PLAN.md@@ -5,7 +5,10 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel## Next Up- [ ] [bump-stale-shipped-md5-on-settled-migrations] **Bump stale `NEW_SHIPPED_MD5` entries on settled migrations + add `runPromptMigrationTests` coverage.** Migrations 003 / 004 / 005 / 013 still record their original NEW hash, but downstream migrations have since evolved the same files (e.g. 003's `pipeline-idea-expansion.md` is at the post-025 hash today, 005's `pipeline-arc-overview.md` is at the post-019 hash, 013's `pipeline-comic-script.md` is past `133d200d069c2e8173b7c129eea58f53`). That's a latent bug: a fresh install with `data/migrations.applied.json` cleared misclassifies every shipped file as "customized" instead of "already current," and `runPromptMigrationTests`'s drift-catch can't be wired up. Per the 019 convention, bump each migration's `NEW_SHIPPED_MD5` entry to the current `data.sample` hash and append the intermediate hash(es) to `ACCEPTED_OLD_MD5`; then add a `<num>.test.js` that calls `runPromptMigrationTests`. Skipped from `[backport-pre-023-migrations-to-_lib]` because that PR was scoped to a pure refactor.-- [ ] [codex5-polling-consolidation] **[P2][PERF]** Migrate remaining `setInterval` callers to `useAutoRefetch`. The shared hook at `client/src/hooks/useAutoRefetch.js` exists; 20+ pages/components still spin local `setInterval`s — ChiefOfStaff, Brain, DigitalTwin, Loops, Browser, CyberCity, ImageGen, Ambient, AgentsPage, calendar, meatspace, city tabs. Migrate each to `useAutoRefetch` (which already provides the `document.visibilityState === 'hidden'` short-circuit); for domains with a Socket.IO event stream, switch to event-driven refetch instead of polling.+- [ ] [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-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]`.- [ ] [codex5-dashboard-intent-layouts] **[P2][DASHBOARD]** Finish intent-named layouts + morning default + widget suggestions. `server/services/dashboardLayouts.js` seeds `morning-review` and `ops` already; still missing `Deep Work`, `Health`, `Agent Watch`. Add the three remaining seeded layouts, a "make this my morning default" toggle that activates a layout in a configured time window, and a "widget suggestion" hint: when a layout omits a widget whose data source is populated (e.g. layout has no calendar widget but calendar is connected), surface an inline "Add Calendar?" affordance.- [ ] [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.- [ ] [migrate-two-remaining-local-formatters] **Migrate two remaining local formatters surfaced during the module-discovery PR.** Two additional local format definitions were found that aren't in the original tracker: (1) `client/src/components/calendar/EventDetail.jsx:10` defines `formatDateTime(dateStr, isAllDay)` with an all-day branch the shared `formatDateTime` lacks — extend the shared helper to take `{ allDay: true }` or keep this local and rename to `formatEventDateTime`. (2) `client/src/components/cos/tabs/TaskItem.jsx:78` defines `formatDurationMin(mins)` with a `~` approximation prefix (`~3h 30m`) — extend shared `formatDurationMin` with an `{ approximate: true }` option. Low priority; visual semantics need to be preserved exactly.diff --git a/client/src/components/apps/tabs/ProcessesTab.jsx b/client/src/components/apps/tabs/ProcessesTab.jsxindex 7c9c336dc5..9e7b03ef4b 100644--- a/client/src/components/apps/tabs/ProcessesTab.jsx+++ b/client/src/components/apps/tabs/ProcessesTab.jsx@@ -3,6 +3,7 @@ import { Maximize2, X } from 'lucide-react';import * as api from '../../../services/api';import socket from '../../../services/socket';import BrailleSpinner from '../../BrailleSpinner';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';const formatMemory = (bytes) => {if (!bytes) return '0 MB';@@ -29,8 +30,6 @@ const getStatusClasses = (status) => {};export default function ProcessesTab({ pm2ProcessNames, filterFn }) {- const [processes, setProcesses] = useState([]);- const [loading, setLoading] = useState(true);const [expandedProcess, setExpandedProcess] = useState(null);const [logs, setLogs] = useState([]);const [restarting, setRestarting] = useState({});@@ -40,17 +39,11 @@ export default function ProcessesTab({ pm2ProcessNames, filterFn }) {const logsRef = useRef(null);const fullscreenLogsRef = useRef(null);- const loadProcesses = async () => {- const data = await api.getProcessesList().catch(() => []);- setProcesses(data);- setLoading(false);- };-- useEffect(() => {- loadProcesses();- const interval = setInterval(loadProcesses, 5000);- return () => clearInterval(interval);- }, []);+ const { data, loading } = useAutoRefetch(+ () => api.getProcessesList().catch(() => []),+ 5000,+ );+ const processes = data ?? [];useEffect(() => {if (!expandedProcess) {diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsxindex 6853555257..753544b0eb 100644--- a/client/src/components/apps/tabs/UpdateTab.jsx+++ b/client/src/components/apps/tabs/UpdateTab.jsx@@ -5,6 +5,7 @@ import BrailleSpinner from '../../BrailleSpinner';import MarkdownOutput from '../../cos/MarkdownOutput';import * as api from '../../../services/api';import socket from '../../../services/socket';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';const STEP_LABELS = {starting: 'Starting update',@@ -34,7 +35,7 @@ export default function UpdateTab() {const [steps, setSteps] = useState([]);const [updateError, setUpdateError] = useState(null);const [polling, setPolling] = useState(false);- const pollRef = useRef(null);+ const attemptsRef = useRef(0);const targetVersionRef = useRef(null);const preUpdateVersionRef = useRef(null);@@ -85,7 +86,6 @@ export default function UpdateTab() {const handleError = ({ message }) => {setUpdating(false);setPolling(false);- if (pollRef.current) clearInterval(pollRef.current);toast.dismiss('portos-update-restart');setUpdateError(message);};@@ -101,41 +101,31 @@ export default function UpdateTab() {};}, []);- // Poll health endpoint after restart to detect new version+ // Poll health endpoint after restart to detect new version. The hook's+ // `enabled: polling` gate handles teardown automatically when polling flips+ // off; attemptsRef resets on every fresh polling cycle.useEffect(() => {- if (!polling) return;-- let attempts = 0;- const maxAttempts = 30;-- pollRef.current = setInterval(async () => {- attempts++;- const ok = await api.checkHealth()- .catch(() => null);-- // Accept either an exact target match or any version different from- // the pre-update version (git pull may land on a newer version than- // the release tag that triggered the update)- const preUpdateVersion = preUpdateVersionRef.current;- if (ok?.version && (ok.version === targetVersionRef.current || (preUpdateVersion && ok.version !== preUpdateVersion))) {- clearInterval(pollRef.current);- setPolling(false);- toast.success(`Updated to v${ok.version}`, { id: 'portos-update-restart' });- setTimeout(() => window.location.reload(), 1000);- return;- }+ if (polling) attemptsRef.current = 0;+ }, [polling]);- if (attempts >= maxAttempts) {- clearInterval(pollRef.current);- setPolling(false);- toast.error('Restart timed out — try reloading manually', { id: 'portos-update-restart' });- }- }, 2000);+ const pollHealth = useCallback(async () => {+ attemptsRef.current += 1;+ const ok = await api.checkHealth().catch(() => null);+ const preUpdateVersion = preUpdateVersionRef.current;+ if (ok?.version && (ok.version === targetVersionRef.current || (preUpdateVersion && ok.version !== preUpdateVersion))) {+ setPolling(false);+ toast.success(`Updated to v${ok.version}`, { id: 'portos-update-restart' });+ setTimeout(() => window.location.reload(), 1000);+ return null;+ }+ if (attemptsRef.current >= 30) {+ setPolling(false);+ toast.error('Restart timed out — try reloading manually', { id: 'portos-update-restart' });+ }+ return null;+ }, []);- return () => {- if (pollRef.current) clearInterval(pollRef.current);- };- }, [polling]);+ useAutoRefetch(pollHealth, 2000, { enabled: polling });const handleCheck = async () => {setChecking(true);diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsxindex 0f49cbf80e..bd33115b7b 100644--- a/client/src/components/brain/tabs/LinksTab.jsx+++ b/client/src/components/brain/tabs/LinksTab.jsx@@ -20,6 +20,7 @@ import {import BrailleSpinner from '../../BrailleSpinner';import toast from '../../ui/Toast';import { timeAgo } from '../../../utils/formatters';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';const LINK_TYPE_COLORS = {github: 'bg-purple-500/20 text-purple-400 border-purple-500/30',@@ -63,20 +64,16 @@ export default function LinksTab({ onRefresh }) {setLinks(data.links || []);setTotal(data.total || 0);setLoading(false);+ return null;}, [filter]);useEffect(() => {fetchLinks();}, [fetchLinks]);- // Poll for clone status updates- useEffect(() => {- const cloningLinks = links.filter(l => l.cloneStatus === 'cloning' || l.cloneStatus === 'pending');- if (cloningLinks.length === 0) return;-- const interval = setInterval(fetchLinks, 3000);- return () => clearInterval(interval);- }, [links, fetchLinks]);+ // Poll for clone status updates while at least one link is in flight.+ const hasInFlightClone = links.some(l => l.cloneStatus === 'cloning' || l.cloneStatus === 'pending');+ useAutoRefetch(fetchLinks, 3000, { enabled: hasInFlightClone });const handleSubmit = async (e) => {e.preventDefault();diff --git a/client/src/components/cos/ActionableInsightsBanner.jsx b/client/src/components/cos/ActionableInsightsBanner.jsxindex e174976adf..3bd517d9ba 100644--- a/client/src/components/cos/ActionableInsightsBanner.jsx+++ b/client/src/components/cos/ActionableInsightsBanner.jsx@@ -1,5 +1,6 @@-import { useState, useEffect } from 'react';+import { useState } from 'react';import { useNavigate } from 'react-router-dom';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';import toast from '../ui/Toast';import {AlertCircle,@@ -60,23 +61,14 @@ const PRIORITY_STYLES = {};export default function ActionableInsightsBanner({ onTaskUnblocked }) {- const [data, setData] = useState(null);const [dismissed, setDismissed] = useState([]);const [expanded, setExpanded] = useState({});- const [loading, setLoading] = useState(true);const navigate = useNavigate();- const loadInsights = async () => {- const result = await api.getCosActionableInsights().catch(() => null);- setData(result);- setLoading(false);- };-- useEffect(() => {- loadInsights();- const interval = setInterval(loadInsights, 60000);- return () => clearInterval(interval);- }, []);+ const { data, loading } = useAutoRefetch(+ () => api.getCosActionableInsights().catch(() => null),+ 60_000,+ );const handleDismiss = (type) => {setDismissed(prev => [...prev, type]);diff --git a/client/src/components/cos/QuickSummary.jsx b/client/src/components/cos/QuickSummary.jsxindex eef8c54a96..a1d33f949c 100644--- a/client/src/components/cos/QuickSummary.jsx+++ b/client/src/components/cos/QuickSummary.jsx@@ -1,4 +1,4 @@-import { useState, useEffect } from 'react';+import { useState } from 'react';import {CheckCircle,Flame,@@ -17,28 +17,18 @@ import {Sunset} from 'lucide-react';import * as api from '../../services/api';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';/*** QuickSummary - At-a-glance dashboard widget for CoS status* Shows today's progress, streak status, next job, and pending work*/export default function QuickSummary() {- const [summary, setSummary] = useState(null);- const [loading, setLoading] = useState(true);const [showAccomplishments, setShowAccomplishments] = useState(false);-- useEffect(() => {- const loadSummary = async () => {- const data = await api.getCosQuickSummary().catch(() => null);- setSummary(data);- setLoading(false);- };-- loadSummary();- // Refresh every 30 seconds- const interval = setInterval(loadSummary, 30000);- return () => clearInterval(interval);- }, []);+ const { data: summary, loading } = useAutoRefetch(+ () => api.getCosQuickSummary().catch(() => null),+ 30_000,+ );if (loading || !summary) {return null;diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex e3342e5891..5b8ea1dd21 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -29,6 +29,7 @@ import Modal from '../../ui/Modal';import toast from '../../ui/Toast';import { copyToClipboard } from '../../../lib/clipboard';import { DEFAULT_REVIEWER } from '../constants';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';// Extract task type from description (matches server-side extractTaskType)function extractTaskType(description) {@@ -205,18 +206,13 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed}, [completed]);// Fetch process stats for running agents (skip for remote peers)- useEffect(() => {- if (completed || remote) return;-- const fetchStats = async () => {- const stats = await api.getCosAgentStats(agent.id).catch(() => null);- setProcessStats(stats);- };+ const fetchStats = useCallback(async () => {+ const stats = await api.getCosAgentStats(agent.id).catch(() => null);+ setProcessStats(stats);+ return null;+ }, [agent.id]);- fetchStats();- const interval = setInterval(fetchStats, 5000); // Update every 5 seconds- return () => clearInterval(interval);- }, [completed, agent.id, remote]);+ useAutoRefetch(fetchStats, 5000, { enabled: !completed && !remote });const handleKill = async () => {if (!onKill) return;diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsxindex 1433474271..58bbb8f002 100644--- a/client/src/components/meatspace/tabs/OverviewTab.jsx+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx@@ -1,9 +1,10 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useCallback } from 'react';import { useNavigate } from 'react-router-dom';import { Beer, Scale, HeartPulse, Dna, Eye, Dumbbell, Database, Rocket, Calendar } from 'lucide-react';import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import DeathClockCountdown from '../../DeathClockCountdown';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';function HealthTile({ icon: Icon, iconColor, label, metrics, onClick }) {return (@@ -160,13 +161,10 @@ export default function OverviewTab() {setEyes(eye);setCalendar(cal);setLoading(false);+ return null;}, []);- useEffect(() => {- fetchData();- const interval = setInterval(fetchData, 60000);- return () => clearInterval(interval);- }, [fetchData]);+ useAutoRefetch(fetchData, 60_000);if (loading) {return (diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsxindex 59b4891b19..f121d21012 100644--- a/client/src/components/media/MediaJobsQueue.jsx+++ b/client/src/components/media/MediaJobsQueue.jsx@@ -1,8 +1,9 @@-import { useEffect, useMemo, useState, useCallback } from 'react';+import { useMemo, useState, useCallback } from 'react';import { ListOrdered, Image as ImageIcon, Film, X, RefreshCw, ChevronDown, ChevronRight, Trash2, RotateCw, Zap, Pencil } from 'lucide-react';import toast from '../ui/Toast';import { listMediaJobs, cancelMediaJob, cancelQueuedMediaJobs, deleteMediaJob, retryMediaJob, runMediaJobNow } from '../../services/apiMediaJobs.js';import { IMAGE_GEN_MODE } from '../../lib/imageGenBackends';+import { useAutoRefetch } from '../../hooks/useAutoRefetch';const STATUS_BADGE = {queued: 'bg-port-border text-port-text-muted',@@ -38,17 +39,14 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''const [loading, setLoading] = useState(true);const [showRecent, setShowRecent] = useState(false);- const fetchJobs = useCallback(() => {- listMediaJobs(kind ? { kind } : {})- .then((data) => { setJobs(data || []); setLoading(false); })- .catch(() => setLoading(false));+ const fetchJobs = useCallback(async () => {+ const data = await listMediaJobs(kind ? { kind } : {}).catch(() => null);+ if (data) setJobs(data);+ setLoading(false);+ return null;}, [kind]);- useEffect(() => {- fetchJobs();- const t = setInterval(fetchJobs, 3000);- return () => clearInterval(t);- }, [fetchJobs]);+ useAutoRefetch(fetchJobs, 3000);const handleCancel = (id) => cancelMediaJob(id).then(() => {diff --git a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx b/client/src/components/pipeline/stages/EpisodeVideoStage.jsxindex 083ad0d381..98bd33c3bf 100644--- a/client/src/components/pipeline/stages/EpisodeVideoStage.jsx+++ b/client/src/components/pipeline/stages/EpisodeVideoStage.jsx@@ -1,4 +1,4 @@-import { useEffect, useMemo, useRef, useState } from 'react';+import { useEffect, useMemo, useState } from 'react';import { Link } from 'react-router-dom';import { Film, ExternalLink, Loader2, Sparkles, AlertCircle, CheckCircle2 } from 'lucide-react';import toast from '../../ui/Toast';@@ -7,6 +7,7 @@ import { getCreativeDirectorProject } from '../../../services/apiCreativeDirectoimport { getSceneStatusBadge, PROJECT_STATUS_LABEL } from '../../creative-director/sceneStatus';import ScenePreview from '../../creative-director/ScenePreview';import { useAsyncAction } from '../../../hooks/useAsyncAction';+import { useAutoRefetch } from '../../../hooks/useAutoRefetch';const POLL_INTERVAL_MS = 4000;@@ -35,45 +36,32 @@ 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');- const intervalRef = useRef(null);- // Single polling effect keyed only on cdProjectId so a status flip doesn't- // tear down and rebuild the interval (each tear-down fired an immediate- // fetch → setState → effect re-run, producing a fetch storm at every- // transition). The interval clears itself once status becomes terminal.+ // Clear the displayed project when the cdProjectId itself goes away+ // (stage reset). Fresh project ids flow in via the poll below.useEffect(() => {- if (!cdProjectId) {- setCdProject(null);- return undefined;- }- let cancelled = false;- const stop = () => {- if (intervalRef.current) {- clearInterval(intervalRef.current);- intervalRef.current = null;- }- };- const fetchOnce = async () => {- if (document.hidden) return;+ if (!cdProjectId) setCdProject(null);+ }, [cdProjectId]);++ // Poll while the project could still mutate. Pauses on hidden tab via+ // useAutoRefetch's visibility short-circuit and stops once status is terminal.+ useAutoRefetch(+ async () => {const p = await getCreativeDirectorProject(cdProjectId, { slim: true }).catch((err) => {- if (!cancelled) console.log(`pipeline:episode poll error ${err.message}`);+ console.log(`pipeline:episode poll error ${err.message}`);return null;});- if (cancelled || !p) return;+ 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));- if (isTerminalProjectStatus(p.status)) stop();- };- fetchOnce();- intervalRef.current = setInterval(fetchOnce, POLL_INTERVAL_MS);- return () => {- cancelled = true;- stop();- };- }, [cdProjectId]);+ return null;+ },+ POLL_INTERVAL_MS,+ { enabled: !!cdProjectId && !isTerminalProjectStatus(cdProject?.status) },+ );const [runSubmit, submitting] = useAsyncAction(async ({ force }) => {diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.jsindex 75da260dce..315e8f25d9 100644--- a/client/src/hooks/useAutoRefetch.js+++ b/client/src/hooks/useAutoRefetch.js@@ -1,46 +1,83 @@-import { useState, useEffect, useRef } from 'react';+import { useState, useEffect, useRef, useCallback } from 'react';/**- * Hook for auto-refetching data on an interval.- * Eliminates the repeated useEffect + setInterval pattern across dashboard widgets.+ * Auto-refetch on an interval, pausing while the tab is hidden and re-firing+ * once when it becomes visible again. Replaces the per-component+ * useEffect + setInterval pattern for data-fetch polling.*- * @param {Function} fetchFn - Async function that returns data (should handle its own errors)- * @param {number} intervalMs - Refetch interval in milliseconds (changing this will restart the interval with the new value)- * @returns {{ data: any, loading: boolean }}+ * fetchFn should handle its own errors and return either the new data or+ * `null` (the documented "no change / use prior" sentinel — returning+ * `undefined` would set data to undefined and lose prior state).+ * Side-effect-only callers that manage their own state should `return null`.+ *+ * @param {Function} fetchFn - async, returns the new data or null+ * @param {number} intervalMs - poll cadence; changing restarts the interval+ * @param {Object} [options]+ * @param {boolean} [options.enabled=true] - when false, no interval and no fetch+ * @returns {{ data: any, loading: boolean, refetch: Function }}*/-export function useAutoRefetch(fetchFn, intervalMs) {+export function useAutoRefetch(fetchFn, intervalMs, options = {}) {+ const { enabled = true } = options;const [data, setData] = useState(null);const [loading, setLoading] = useState(true);const fetchRef = useRef(fetchFn);- // Keep ref current so interval callbacks don't capture stale closuresuseEffect(() => {fetchRef.current = fetchFn;}, [fetchFn]);+ // Stable, unconditional refetch for callers (Refresh buttons, post-mutation+ // refresh paths). Bypasses the visibility short-circuit — when a user+ // clicks Refresh the tab is by definition visible.+ const refetch = useCallback(async () => {+ try {+ const result = await fetchRef.current();+ setData(result);+ setLoading(false);+ return result;+ } catch (err) {+ console.warn(`⚠️ Auto-refetch failed: ${err.message}`);+ setLoading(false);+ return undefined;+ }+ }, []);+useEffect(() => {+ if (!enabled) return undefined;+let cancelled = false;const loadData = async () => {+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;try {const result = await fetchRef.current();if (cancelled) return;setData(result);setLoading(false);} catch (err) {- // Keep prior data on failure, just clear loading stateconsole.warn(`⚠️ Auto-refetch failed: ${err.message}`);if (!cancelled) setLoading(false);}};+ const handleVisibilityChange = () => {+ if (document.visibilityState === 'visible') loadData();+ };+loadData();const interval = setInterval(loadData, intervalMs);+ if (typeof document !== 'undefined') {+ document.addEventListener('visibilitychange', handleVisibilityChange);+ }+return () => {cancelled = true;clearInterval(interval);+ if (typeof document !== 'undefined') {+ document.removeEventListener('visibilitychange', handleVisibilityChange);+ }};- }, [intervalMs]);+ }, [intervalMs, enabled]);- return { data, loading };+ return { data, loading, refetch };}diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsxnew file mode 100644index 0000000000..caf1a00815--- /dev/null+++ b/client/src/hooks/useAutoRefetch.test.jsx@@ -0,0 +1,115 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act, waitFor } from '@testing-library/react';+import { useAutoRefetch } from './useAutoRefetch';++const setVisibility = (state) => {+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });+};++const fireVisibilityChange = () => {+ document.dispatchEvent(new Event('visibilitychange'));+};++describe('useAutoRefetch', () => {+ beforeEach(() => {+ setVisibility('visible');+ });++ afterEach(() => {+ setVisibility('visible');+ });++ it('fetches immediately on mount and exposes data + loading', async () => {+ const fetchFn = vi.fn().mockResolvedValue({ ok: true });+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 10_000));++ expect(result.current.loading).toBe(true);+ await waitFor(() => expect(result.current.loading).toBe(false));+ expect(fetchFn).toHaveBeenCalledTimes(1);+ expect(result.current.data).toEqual({ ok: true });+ });++ it('refetches on the configured interval', async () => {+ const fetchFn = vi.fn().mockResolvedValue('x');+ renderHook(() => useAutoRefetch(fetchFn, 30));+ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(3));+ });++ it('skips fetches while the tab is hidden and refires when visible', async () => {+ const fetchFn = vi.fn().mockResolvedValue('x');+ renderHook(() => useAutoRefetch(fetchFn, 20));+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));++ setVisibility('hidden');+ await new Promise((r) => setTimeout(r, 80));+ const callsWhileHidden = fetchFn.mock.calls.length;+ expect(callsWhileHidden).toBe(1);++ setVisibility('visible');+ act(() => fireVisibilityChange());+ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThan(callsWhileHidden));+ });++ it('skips entirely when enabled is false and starts/stops on toggle', async () => {+ const fetchFn = vi.fn().mockResolvedValue('x');+ const { rerender } = renderHook(+ ({ enabled }) => useAutoRefetch(fetchFn, 20, { enabled }),+ { initialProps: { enabled: false } },+ );++ await new Promise((r) => setTimeout(r, 80));+ expect(fetchFn).not.toHaveBeenCalled();++ rerender({ enabled: true });+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));++ rerender({ enabled: false });+ const callsAfterDisable = fetchFn.mock.calls.length;+ await new Promise((r) => setTimeout(r, 80));+ expect(fetchFn).toHaveBeenCalledTimes(callsAfterDisable);+ });++ it('keeps prior data and clears loading when fetchFn throws', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce('first')+ .mockRejectedValue(new Error('boom'));+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});++ const { result } = renderHook(() => useAutoRefetch(fetchFn, 20));+ await waitFor(() => expect(result.current.data).toBe('first'));+ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(2));+ expect(result.current.data).toBe('first');+ expect(result.current.loading).toBe(false);+ warn.mockRestore();+ });++ it('exposes a refetch handle that fetches on demand and updates data', async () => {+ const fetchFn = vi.fn()+ .mockResolvedValueOnce('first')+ .mockResolvedValueOnce('second');+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 60_000, { enabled: false }));++ expect(fetchFn).not.toHaveBeenCalled();+ expect(result.current.data).toBeNull();++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toBe('first');++ await act(async () => { await result.current.refetch(); });+ expect(result.current.data).toBe('second');+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });++ it('does not capture a stale fetchFn closure across renders', async () => {+ const first = vi.fn().mockResolvedValue('first');+ const second = vi.fn().mockResolvedValue('second');+ const { rerender } = renderHook(+ ({ fn }) => useAutoRefetch(fn, 20),+ { initialProps: { fn: first } },+ );+ await waitFor(() => expect(first).toHaveBeenCalledTimes(1));++ rerender({ fn: second });+ await waitFor(() => expect(second.mock.calls.length).toBeGreaterThanOrEqual(1));+ });+});diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex aa22356c18..988c3e4350 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -1,6 +1,7 @@import { useState, useEffect, useCallback, useMemo, useRef } from 'react';import * as api from '../services/api';import socket from '../services/socket';+import { useAutoRefetch } from './useAutoRefetch';const healthSignature = (h) => {const warnings = (h?.warnings || []).map(w => `${w.type}:${w.message}`).join(';');@@ -18,8 +19,6 @@ export const useCityData = () => {const [systemHealth, setSystemHealth] = useState(null);const [notificationCounts, setNotificationCounts] = useState({ unread: 0 });const [loading, setLoading] = useState(true);- const pollRef = useRef(null);- const healthPollRef = useRef(null);const logIdRef = useRef(0);const fetchApps = useCallback(async () => {@@ -59,17 +58,27 @@ export const useCityData = () => {// In-flight guard: a slow /system/health/details (>15s) would otherwise// let the next interval tick fire a concurrent request. Drop the new tick// when one is already pending; the next interval picks up fresh state.- if (healthInFlightRef.current) return;+ if (healthInFlightRef.current) return null;healthInFlightRef.current = true;const health = await api.getSystemHealth({ silent: true }).catch(() => null);healthInFlightRef.current = false;- if (!health) return;+ if (!health) return null;setSystemHealth(prev => {if (prev && healthSignature(prev) === healthSignature(health)) return prev;return health;});+ return null;}, []);+ const fetchRunningAgents = useCallback(async () => {+ const agents = await api.getRunningAgents().catch(() => []);+ setRunningAgents(agents);+ return null;+ }, []);++ useAutoRefetch(fetchRunningAgents, 10_000);+ useAutoRefetch(fetchHealth, 15_000);+const agentMap = useMemo(() => {const map = new Map();const allAgents = [...(cosAgents || [])];@@ -139,13 +148,6 @@ export const useCityData = () => {socket.on('notifications:count', handleNotifCount);socket.on('notifications:cleared', handleNotifCleared);- pollRef.current = setInterval(async () => {- const agents = await api.getRunningAgents().catch(() => []);- setRunningAgents(agents);- }, 10000);-- healthPollRef.current = setInterval(fetchHealth, 15000);-// Subscribe but do NOT unsubscribe on cleanup. The cos:* and notifications:*// namespaces are shared (useNotifications in Layout, useAgentFeedbackToast).// Server uses a per-socket Set, so unsubscribing here would yank the@@ -161,10 +163,8 @@ export const useCityData = () => {socket.off('cos:status', handleCosStatus);socket.off('notifications:count', handleNotifCount);socket.off('notifications:cleared', handleNotifCleared);- clearInterval(pollRef.current);- clearInterval(healthPollRef.current);};- }, [fetchAll, fetchApps, fetchHealth]);+ }, [fetchAll, fetchApps]);return {apps,diff --git a/client/src/pages/AgentsPage.jsx b/client/src/pages/AgentsPage.jsxindex 1c8827b9f3..a82406140d 100644--- a/client/src/pages/AgentsPage.jsx+++ b/client/src/pages/AgentsPage.jsx@@ -1,32 +1,23 @@-import { useState, useEffect, Fragment } from 'react';+import { useState, useCallback, Fragment } from 'react';import { RefreshCw, Activity, XCircle, Cpu, MemoryStick, Terminal } from 'lucide-react';import * as api from '../services/api';+import { useAutoRefetch } from '../hooks/useAutoRefetch';export function AgentsPage() {- const [agents, setAgents] = useState([]);- const [loading, setLoading] = useState(true);const [killing, setKilling] = useState({});const [expandedPid, setExpandedPid] = useState(null);const REFRESH_INTERVAL = 3;- useEffect(() => {- loadAgents();- const interval = setInterval(loadAgents, REFRESH_INTERVAL * 1000);- return () => clearInterval(interval);- }, []);-- const loadAgents = async () => {- const data = await api.getAgents().catch(() => []);- setAgents(data);- setLoading(false);- };+ const loadAgents = useCallback(() => api.getAgents().catch(() => []), []);+ const { data, loading, refetch } = useAutoRefetch(loadAgents, REFRESH_INTERVAL * 1000);+ const agents = data ?? [];const handleKill = async (pid) => {setKilling(prev => ({ ...prev, [pid]: true }));await api.killAgent(pid).catch(() => null);setTimeout(() => {setKilling(prev => ({ ...prev, [pid]: false }));- loadAgents();+ refetch();}, 1000);};@@ -55,7 +46,7 @@ export function AgentsPage() {<span className="hidden sm:inline text-gray-500 text-sm">({REFRESH_INTERVAL}s)</span></div><button- onClick={loadAgents}+ onClick={refetch}className="flex items-center justify-center gap-2 px-3 py-1.5 sm:px-4 sm:py-2 bg-port-card border border-port-border hover:border-gray-500 text-white text-sm rounded-lg transition-colors"><RefreshCw size={14} className="sm:w-4 sm:h-4" />diff --git a/client/src/pages/Brain.jsx b/client/src/pages/Brain.jsxindex 11ddc409ea..10da549dae 100644--- a/client/src/pages/Brain.jsx+++ b/client/src/pages/Brain.jsx@@ -1,9 +1,10 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useCallback } from 'react';import { useParams, useNavigate } from 'react-router-dom';import * as api from '../services/api';import {Brain as BrainIcon} from 'lucide-react';import BrailleSpinner from '../components/BrailleSpinner';import TabPills from '../components/ui/TabPills';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import { TABS } from '../components/brain/constants';import { timeAgo } from '../utils/formatters';@@ -37,13 +38,10 @@ export default function Brain() {setSummary(summaryData);setSettings(settingsData);setLoading(false);+ return null;}, []);- useEffect(() => {- fetchData();- const interval = setInterval(fetchData, 30000);- return () => clearInterval(interval);- }, [fetchData]);+ useAutoRefetch(fetchData, 30_000);const handleTabChange = (tabId) => {navigate(`/brain/${tabId}`);diff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsxindex 6a34a27140..b67dee98c0 100644--- a/client/src/pages/Browser.jsx+++ b/client/src/pages/Browser.jsx@@ -1,4 +1,5 @@import { useState, useEffect, useCallback } from 'react';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import {Globe, Play, Square, RefreshCw, Settings, Activity,Monitor, Wifi, WifiOff, Clock, Cpu, MemoryStick,@@ -48,6 +49,7 @@ export default function BrowserPage() {setStatus(data);setLoading(false);}+ return null;}, []);const fetchLogs = useCallback(async () => {@@ -58,16 +60,7 @@ export default function BrowserPage() {}}, []);- // Initial load- useEffect(() => {- fetchStatus();- }, [fetchStatus]);-- // Poll for status updates- useEffect(() => {- const interval = setInterval(fetchStatus, POLL_INTERVAL);- return () => clearInterval(interval);- }, [fetchStatus]);+ useAutoRefetch(fetchStatus, POLL_INTERVAL);// Load config when settings panel opensuseEffect(() => {diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsxindex f19494cd0a..e8b20f471a 100644--- a/client/src/pages/ChiefOfStaff.jsx+++ b/client/src/pages/ChiefOfStaff.jsx@@ -3,6 +3,7 @@ import { useParams, useNavigate } from 'react-router-dom';import { useSocket } from '../hooks/useSocket';import { useLocalStorageBool } from '../hooks/useLocalStorageBool';import useNextEvalCountdown from '../hooks/useNextEvalCountdown';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import * as api from '../services/api';import { Play, Square, Clock, CheckCircle, AlertCircle, Cpu, ChevronDown, ChevronUp, ChevronLeft, ChevronRight, Brain, PanelLeftClose, PanelLeftOpen } from 'lucide-react';import toast from '../components/ui/Toast';@@ -149,12 +150,8 @@ export default function ChiefOfStaff() {}}, [tab, validTabIds, navigate]);- useEffect(() => {- fetchData();- // Reduced polling since most updates come via socket events- const interval = setInterval(fetchData, 30000);- return () => clearInterval(interval);- }, [fetchData]);+ // Reduced polling since most updates come via socket events+ useAutoRefetch(fetchData, 30_000);useEffect(() => {if (!socket) return;diff --git a/client/src/pages/CreativeDirectorDetail.jsx b/client/src/pages/CreativeDirectorDetail.jsxindex 81a2df28af..a244f893e9 100644--- a/client/src/pages/CreativeDirectorDetail.jsx+++ b/client/src/pages/CreativeDirectorDetail.jsx@@ -14,6 +14,9 @@ import SegmentsTab from '../components/creative-director/SegmentsTab.jsx';import RunsTab from '../components/creative-director/RunsTab.jsx';import ActiveAgentsBanner from '../components/creative-director/ActiveAgentsBanner.jsx';import { getCosAgents } from '../services/apiAgents.js';+import { useAutoRefetch } from '../hooks/useAutoRefetch';++const TERMINAL_PROJECT_STATUSES = new Set(['complete', 'failed', 'paused', 'draft']);const TABS = [{ id: 'overview', label: 'Overview' },@@ -32,10 +35,11 @@ export default function CreativeDirectorDetail() {const [loading, setLoading] = useState(true);const [activeAgents, setActiveAgents] = useState([]);- const fetchProject = useCallback(() => {- getCreativeDirectorProject(id)- .then((p) => { setProject(p); setLoading(false); })- .catch(() => { setProject(null); setLoading(false); });+ const fetchProject = useCallback(async () => {+ const p = await getCreativeDirectorProject(id).catch(() => null);+ setProject(p);+ setLoading(false);+ return null;}, [id]);// Reset state ONLY when the route id changes, so navigating between@@ -51,27 +55,22 @@ export default function CreativeDirectorDetail() {// Poll CoS agents in parallel so the Segments tab can flag the scene that's// currently being worked on, even before the agent PATCHes its status.// Filter by `taskId` prefix `cd-<projectId>-` (agentBridge's id scheme).- const fetchAgents = useCallback(() => {- getCosAgents()- .then((data) => {- const prefix = `cd-${id}-`;- const mine = (data || []).filter((a) => a.status === 'running' && (a.taskId || '').startsWith(prefix));- setActiveAgents(mine);- })- .catch(() => setActiveAgents([]));+ const fetchAgents = useCallback(async () => {+ const data = await getCosAgents().catch(() => []);+ const prefix = `cd-${id}-`;+ const mine = (data || []).filter((a) => a.status === 'running' && (a.taskId || '').startsWith(prefix));+ setActiveAgents(mine);+ return null;}, [id]);- useEffect(() => {- fetchProject();- fetchAgents();- // Only poll while the agent could still mutate the project. Once the- // status reaches a terminal state, skip the interval entirely so we're- // not constantly tearing down and rebuilding it on every refetch.- const status = project?.status;- if (status && ['complete', 'failed', 'paused', 'draft'].includes(status)) return;- const interval = setInterval(() => { fetchProject(); fetchAgents(); }, 5000);- return () => clearInterval(interval);- }, [fetchProject, fetchAgents, project?.status]);+ // Only poll while the agent could still mutate the project. Once the+ // status reaches a terminal state, the visibility-paused hook stops firing.+ const pollEnabled = !project?.status || !TERMINAL_PROJECT_STATUSES.has(project.status);+ const poll = useCallback(async () => {+ await Promise.all([fetchProject(), fetchAgents()]);+ return null;+ }, [fetchProject, fetchAgents]);+ useAutoRefetch(poll, 5000, { enabled: pollEnabled });const handleAction = async (kind) => {// Map action → past-tense label and optimistic status up-front.diff --git a/client/src/pages/CyberCity.jsx b/client/src/pages/CyberCity.jsxindex 4f12ffbde7..e0d2f0bd28 100644--- a/client/src/pages/CyberCity.jsx+++ b/client/src/pages/CyberCity.jsx@@ -3,6 +3,7 @@ import { useNavigate, useLocation } from 'react-router-dom';import { useCityData } from '../hooks/useCityData';import useCityAudio from '../hooks/useCityAudio';import useKeyboardControls from '../hooks/useKeyboardControls';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import * as api from '../services/api';import CityScene from '../components/city/CityScene';import CityHud from '../components/city/CityHud';@@ -17,7 +18,6 @@ function CyberCityInner() {const { playSfx } = useCityAudio(settings);const navigate = useNavigate();const location = useLocation();- const [productivityData, setProductivityData] = useState(null);const [filter, setFilter] = useState(() => {// try/catch is necessary because sessionStorage values are external state// a corrupted/older-schema entry would throw and crash the page render.@@ -61,16 +61,11 @@ function CyberCityInner() {const keysRef = useKeyboardControls(handleToggleExploration);- // Fetch productivity data for HUD vitals and billboards- useEffect(() => {- const fetchProductivity = async () => {- const data = await api.getCosQuickSummary().catch(() => null);- setProductivityData(data);- };- fetchProductivity();- const interval = setInterval(fetchProductivity, 60000);- return () => clearInterval(interval);- }, []);+ // Productivity data for HUD vitals and billboards+ const { data: productivityData } = useAutoRefetch(+ () => api.getCosQuickSummary().catch(() => null),+ 60_000,+ );const handleBuildingClick = useCallback((app) => {if (app?.id) {diff --git a/client/src/pages/DigitalTwin.jsx b/client/src/pages/DigitalTwin.jsxindex a21a713452..bef7fdc4d6 100644--- a/client/src/pages/DigitalTwin.jsx+++ b/client/src/pages/DigitalTwin.jsx@@ -1,9 +1,10 @@-import { useState, useEffect, useCallback } from 'react';+import { useState, useCallback } from 'react';import { useParams, useNavigate } from 'react-router-dom';import * as api from '../services/api';import { Heart } from 'lucide-react';import BrailleSpinner from '../components/BrailleSpinner';import TabPills from '../components/ui/TabPills';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import { TABS, getHealthColor, getHealthLabel } from '../components/digital-twin/constants';@@ -38,13 +39,10 @@ export default function DigitalTwin() {setStatus(statusData);setSettings(settingsData);setLoading(false);+ return null;}, []);- useEffect(() => {- fetchData();- const interval = setInterval(fetchData, 30000);- return () => clearInterval(interval);- }, [fetchData]);+ useAutoRefetch(fetchData, 30_000);const handleTabChange = (tabId) => {navigate(`/digital-twin/${tabId}`);diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsxindex 70490973a7..d8e33f7f73 100644--- a/client/src/pages/ImageGen.jsx+++ b/client/src/pages/ImageGen.jsx@@ -26,6 +26,7 @@ import LoraPicker from '../components/imageGen/LoraPicker';import MediaJobsQueue from '../components/media/MediaJobsQueue';import { useMediaCompletionRefresh } from '../hooks/useMediaCompletionRefresh';import { useMediaAnnotations } from '../hooks/useMediaAnnotations';+import { useAutoRefetch } from '../hooks/useAutoRefetch';import usePreviewRoute from '../hooks/usePreviewRoute';import {Image as ImageIcon, Sparkles, Download, RefreshCw, Settings as SettingsIcon,@@ -536,29 +537,24 @@ export default function ImageGen() {// 4s clock settle.const queueActive = pendingQueued > 0;const lastBusyRef = useRef(0);- useEffect(() => {- if (!queueActive) return;- let cancelled = false;- const tick = async () => {- const jobs = await listMediaJobs({ kind: 'image' }).catch(() => null);- if (cancelled || !jobs) return;- const stillBusy = jobs.filter((j) => j.status === 'queued' || j.status === 'running').length;- // Subtract 1 for the actively-tracked render (when generating). Floor- // at 0 so a transient counting glitch doesn't show "−1 queued".- const next = Math.max(0, stillBusy - (generating ? 1 : 0));- // Only refresh gallery on a busy-count drop — that's the signal a- // queued job just completed. Otherwise polling re-fetches the gallery- // every 4s for nothing.- if (stillBusy < lastBusyRef.current) refreshGallery();- lastBusyRef.current = stillBusy;- // No-op guard: same value setState would still trigger a render, so- // explicitly skip when nothing changed.- setPendingQueued((prev) => (prev === next ? prev : next));- };- tick();- const interval = setInterval(tick, 4000);- return () => { cancelled = true; clearInterval(interval); };- }, [queueActive, generating]); // eslint-disable-line react-hooks/exhaustive-deps+ const pollQueue = useCallback(async () => {+ const jobs = await listMediaJobs({ kind: 'image' }).catch(() => null);+ if (!jobs) return null;+ const stillBusy = jobs.filter((j) => j.status === 'queued' || j.status === 'running').length;+ // Subtract 1 for the actively-tracked render (when generating). Floor+ // at 0 so a transient counting glitch doesn't show "−1 queued".+ const next = Math.max(0, stillBusy - (generating ? 1 : 0));+ // Only refresh gallery on a busy-count drop — that's the signal a+ // queued job just completed. Otherwise polling re-fetches the gallery+ // every 4s for nothing.+ if (stillBusy < lastBusyRef.current) refreshGallery();+ lastBusyRef.current = stillBusy;+ // No-op guard: same value setState would still trigger a render, so+ // explicitly skip when nothing changed.+ setPendingQueued((prev) => (prev === next ? prev : next));+ return null;+ }, [generating, refreshGallery]);+ useAutoRefetch(pollQueue, 4000, { enabled: queueActive });const flux2Issue = isFlux2Model && flux2Status? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsxindex febbaab616..d501a52c93 100644--- a/client/src/pages/Loops.jsx+++ b/client/src/pages/Loops.jsx@@ -9,6 +9,7 @@ import toast from '../components/ui/Toast';import { timeAgo } from '../components/feature-agents/constants';import { formatInterval } from '../components/cos/constants';import BrailleSpinner from '../components/BrailleSpinner';+import { useAutoRefetch } from '../hooks/useAutoRefetch';const INTERVAL_PRESETS = [{ label: '30s', value: '30s' },@@ -342,6 +343,7 @@ export default function Loops() {const data = await api.getLoops().catch(() => []);setLoops(data);setLoading(false);+ return null;}, []);const fetchProviders = useCallback(async () => {@@ -349,24 +351,20 @@ export default function Loops() {setProviders(data.providers || []);}, []);+ // Fallback poll for iteration count updates (socket events cover state changes)+ useAutoRefetch(fetchLoops, 60_000);+useEffect(() => {- fetchLoops();fetchProviders();- // Subscribe to loop eventssocket.emit('loops:subscribe');-const refreshEvents = ['loop:created', 'loop:stopped', 'loop:resumed', 'loop:deleted', 'loop:updated'];const handleRefresh = () => fetchLoops();refreshEvents.forEach(e => socket.on(e, handleRefresh));- // Fallback poll for iteration count updates (socket events cover state changes)- const poll = setInterval(fetchLoops, 60000);-return () => {socket.emit('loops:unsubscribe');refreshEvents.forEach(e => socket.off(e, handleRefresh));- clearInterval(poll);};}, [fetchLoops, fetchProviders]);diff --git a/client/src/pages/SystemHealthPage.jsx b/client/src/pages/SystemHealthPage.jsxindex 2a553385f9..d26fa25803 100644--- a/client/src/pages/SystemHealthPage.jsx+++ b/client/src/pages/SystemHealthPage.jsx@@ -1,9 +1,10 @@-import { useEffect, useState } from 'react';+import { useEffect, useState, useRef } from 'react';import { Link } from 'react-router-dom';import { Activity, AlertTriangle, CheckCircle, XCircle, HardDrive, Cpu, Database, ServerCog, Zap } from 'lucide-react';import * as api from '../services/api';import toast from '../components/ui/Toast';import BrailleSpinner from '../components/BrailleSpinner';+import { useAutoRefetch } from '../hooks/useAutoRefetch';const HEALTH_STYLE = {healthy: { color: 'text-port-success', bg: 'bg-port-success/10', icon: CheckCircle, label: 'Healthy' },@@ -24,23 +25,24 @@ function barTone(pct, warn, critical) {}export default function SystemHealthPage() {- const [health, setHealth] = useState(null);- const [loading, setLoading] = useState(true);const [draft, setDraft] = useState(null);const [saving, setSaving] = useState(false);+ // Tracks whether the user has acquired an editable draft. Cleared after a+ // successful save so the next refetch re-seeds with the persisted thresholds.+ const draftSeededRef = useRef(false);- const load = async ({ seedDraft = false } = {}) => {- const data = await api.getSystemHealth({ silent: true }).catch(() => null);- setHealth(data);- if (data?.thresholds && seedDraft) setDraft(data.thresholds);- setLoading(false);- };+ const { data: health, loading, refetch } = useAutoRefetch(+ () => api.getSystemHealth({ silent: true }).catch(() => null),+ 15_000,+ );+ // Seed the editable draft from server state on first load and after each save.useEffect(() => {- load({ seedDraft: true });- const interval = setInterval(() => load(), 15000);- return () => clearInterval(interval);- }, []);+ if (health?.thresholds && !draftSeededRef.current) {+ setDraft(health.thresholds);+ draftSeededRef.current = true;+ }+ }, [health]);const handleSaveThresholds = async () => {if (!draft) return;@@ -52,7 +54,8 @@ export default function SystemHealthPage() {setSaving(false);if (result) {toast.success('Thresholds saved');- load({ seedDraft: true });+ draftSeededRef.current = false;+ refetch();}};