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

add useAutoRefetch { pollOnly: true } mode + migrate 11 side-effect-only callers (#426)

[._.]/ Adam Eivy6f6f837e9210
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index b5a33e546f..543bcb2a81 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -23,6 +23,7 @@
- **[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.
- **[useautorefetch-compare-caller-rollout-widgets] Five Dashboard widgets stop re-rendering on unchanged poll ticks.** Backup, Chief of Staff, Decision Log, Goal Progress, and Proactive Alerts widgets now pass a `compare` callback to `useAutoRefetch` so a 30s–5min poll that returns the same aggregated state — same backup `lastRun`, same today's task counts, same alert set, same per-goal progress — keeps the prior data reference and skips the React subtree update. Each comparator covers every field the widget actually renders (counts, status flags, per-row tuples, per-cell heatmap distribution) so genuine changes still flow through unchanged. A new shared `useTimeTick(intervalMs)` hook drives wall-clock-derived UI (relative timestamps like "5 min ago", thresholds like the backup health 25h/49h windows, the goal-stall 14-day boundary) so those labels stay accurate across deduped polls — N widgets at the same cadence share one underlying `setInterval`. Sites that own their own state via `setX(...) ; return null` (Brain summary, Digital Twin status, meatspace Overview, MediaJobsQueue, Chief of Staff page, Browser status, AgentsPage, ProcessesTab, Loops, brain LinksTab) get no benefit from `compare` and are tracked under the `useautorefetch-pollonly-mode` plan item instead.
+- **[useautorefetch-pollonly-mode] `useAutoRefetch` gains a `{ pollOnly: true }` option for side-effect-only callers.** Eleven pollers (Chief of Staff, the meatspace Overview tab, Loops, Browser, Image Gen's queue tick, the brain Links tab clone watcher, the apps Update health-check, the cos AgentCard process-stats tick, the media render queue, and the CyberCity HUD's running-agent + system-health sub-fetches) drove all their state through `setState` calls inside `fetchFn` and ignored the hook's returned `data` / `loading` — they now opt in to `pollOnly: true`, which tells the hook to skip the `data` / `loading` state updates on every tick (the `useState` hooks still exist — React requires their call sites to be stable — but no `setData` / `setLoading` fires) and return `{ refetch }` only, removing the `return null;` ceremony and a wasted re-render per tick. No user-visible change.
- **[agents-tab-cooldown-tick-extraction] Internal: collapsed the agents-tabs cooldown ticker into a shared hook.** `OverviewTab`, `ToolsTab`, and `WorldTab` each ran their own 1-second `setInterval` for rate-limit countdown labels with a refetch when every cooldown cleared; the new `useCooldownTick({ cooldownEnds, onAllExpired })` hook owns that pattern in one tested place. No 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.md
index b58fead172..50d0bd6c76 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-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.
- [ ] [extract-compare-helpers-once-eight-callers] **Extract `equalByKeys` / `equalListByKeys` once `useAutoRefetch`'s `compare` reaches ~8 widget callers.** With the dashboard rollout (PR #421) there are now 5 widget callers (Backup, Chief of Staff, Decision Log, Goal Progress, Proactive Alerts) on top of EpisodeVideoStage / Brain / Digital Twin from PR #425, using two emerging shapes — (a) scalar-object key equality (BackupWidget status, DecisionLogWidget last24Hours, ProactiveAlertsWidget counts) and (b) array equality by length + per-item key tuple (BackupWidget snapshots, GoalProgressWidget goals, ProactiveAlertsWidget alerts list, DecisionLogWidget impactfulDecisions). Inline forms are noisy but each has an explanatory comment that an `equalByKeys(prev, next, ['status', 'lastRun', …])` would lose. Defer until enough more callers appear that the abstraction pays for itself, then add helpers to `client/src/lib/compareHelpers.js` (register in `index.js` + `README.md`) and migrate the flat callers — leave CosDashboardWidget's nested-optional-chain shape inline. Surfaced by /simplify reuse review during `[useautorefetch-compare-caller-rollout-widgets]` claim 2026-05-21.
- [ ] [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.
- [ ] [dedupe-hhmm-time-window-helpers] **Dedupe HH:MM time-window helpers across server.** `server/services/voice/proactiveSpeech.js` exports `HHMM_RE` + `parseHHMM` + `isWithinQuietHours` (lines 26–57). `server/services/dashboardLayouts.js#sanitizeActivateWindow` + the inlined `isInTimeWindow` logic (post `[codex5-dashboard-intent-layouts]`) duplicate the same predicate (~25 LOC). Lift the three primitives to `server/lib/timezone.js` (where `getLocalParts` already lives) and have both `proactiveSpeech.js` and `dashboardLayouts.js` import from there. The dashboard route's Zod schema (`TIME_STRING_RE`) can keep aliasing the shared regex. Also evaluate whether `client/src/utils/timeWindow.js` (intentional client mirror) needs a parity test against the server primitive — surfaced by /simplify reuse review during `[codex5-dashboard-intent-layouts]` claim 2026-05-20.
diff --git a/client/src/components/apps/tabs/UpdateTab.jsx b/client/src/components/apps/tabs/UpdateTab.jsx
index 753544b0eb..b343207f57 100644
--- a/client/src/components/apps/tabs/UpdateTab.jsx
+++ b/client/src/components/apps/tabs/UpdateTab.jsx
@@ -116,16 +116,15 @@ export default function UpdateTab() {
setPolling(false);
toast.success(`Updated to v${ok.version}`, { id: 'portos-update-restart' });
setTimeout(() => window.location.reload(), 1000);
- return null;
+ return;
}
if (attemptsRef.current >= 30) {
setPolling(false);
toast.error('Restart timed out — try reloading manually', { id: 'portos-update-restart' });
}
- return null;
}, []);
- useAutoRefetch(pollHealth, 2000, { enabled: polling });
+ useAutoRefetch(pollHealth, 2000, { enabled: polling, pollOnly: true });
const handleCheck = async () => {
setChecking(true);
diff --git a/client/src/components/brain/tabs/LinksTab.jsx b/client/src/components/brain/tabs/LinksTab.jsx
index bd33115b7b..75ee81e150 100644
--- a/client/src/components/brain/tabs/LinksTab.jsx
+++ b/client/src/components/brain/tabs/LinksTab.jsx
@@ -64,7 +64,6 @@ export default function LinksTab({ onRefresh }) {
setLinks(data.links || []);
setTotal(data.total || 0);
setLoading(false);
- return null;
}, [filter]);
useEffect(() => {
@@ -73,7 +72,7 @@ export default function LinksTab({ onRefresh }) {
// 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 });
+ useAutoRefetch(fetchLinks, 3000, { enabled: hasInFlightClone, pollOnly: true });
const handleSubmit = async (e) => {
e.preventDefault();
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsx
index 5b8ea1dd21..96ff81a74f 100644
--- a/client/src/components/cos/tabs/AgentCard.jsx
+++ b/client/src/components/cos/tabs/AgentCard.jsx
@@ -209,10 +209,9 @@ export default function AgentCard({ agent, onKill, onDelete, onResume, completed
const fetchStats = useCallback(async () => {
const stats = await api.getCosAgentStats(agent.id).catch(() => null);
setProcessStats(stats);
- return null;
}, [agent.id]);
- useAutoRefetch(fetchStats, 5000, { enabled: !completed && !remote });
+ useAutoRefetch(fetchStats, 5000, { enabled: !completed && !remote, pollOnly: true });
const handleKill = async () => {
if (!onKill) return;
diff --git a/client/src/components/meatspace/tabs/OverviewTab.jsx b/client/src/components/meatspace/tabs/OverviewTab.jsx
index 58bbb8f002..9e21553f33 100644
--- a/client/src/components/meatspace/tabs/OverviewTab.jsx
+++ b/client/src/components/meatspace/tabs/OverviewTab.jsx
@@ -161,10 +161,9 @@ export default function OverviewTab() {
setEyes(eye);
setCalendar(cal);
setLoading(false);
- return null;
}, []);
- useAutoRefetch(fetchData, 60_000);
+ useAutoRefetch(fetchData, 60_000, { pollOnly: true });
if (loading) {
return (
diff --git a/client/src/components/media/MediaJobsQueue.jsx b/client/src/components/media/MediaJobsQueue.jsx
index f121d21012..a6dfb0dc48 100644
--- a/client/src/components/media/MediaJobsQueue.jsx
+++ b/client/src/components/media/MediaJobsQueue.jsx
@@ -43,10 +43,9 @@ export default function MediaJobsQueue({ kind, recentLimit = 10, className = ''
const data = await listMediaJobs(kind ? { kind } : {}).catch(() => null);
if (data) setJobs(data);
setLoading(false);
- return null;
}, [kind]);
- useAutoRefetch(fetchJobs, 3000);
+ useAutoRefetch(fetchJobs, 3000, { pollOnly: true });
const handleCancel = (id) => cancelMediaJob(id)
.then(() => {
diff --git a/client/src/hooks/README.md b/client/src/hooks/README.md
index 985ecd2b48..046cc343c8 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -62,7 +62,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| Hook | Purpose | Use when |
|---|---|---|
| `useArmedAction` | Two-click-arm `[armed, fire]` confirmation. | Destructive button needing a confirm tap. (Project memory: user finds this less discoverable — prefer inline confirm rows for new UI.) |
-| `useAutoRefetch` | Poll-based refetch on an interval. | Data needs periodic refresh (no socket / SSE available). |
+| `useAutoRefetch` | Poll-based refetch on an interval. `{ pollOnly: true }` skips internal data/loading state for side-effect-only callers (returns `{ refetch }` only). | Data needs periodic refresh (no socket / SSE available). |
| `useClickOutside` | Fire `onOutside` on mousedown outside a ref. | Popovers, menus, drawers. |
| `useCmdKSearch` | `⌘K` open/close state. | Anywhere that needs to toggle the palette. |
| `useContainerWidth` | `[ref, width]` via ResizeObserver. | Layout responds to a specific container's width. |
diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.js
index b03f3ffe8d..1af7dfa91e 100644
--- a/client/src/hooks/useAutoRefetch.js
+++ b/client/src/hooks/useAutoRefetch.js
@@ -6,39 +6,46 @@ import { useVisibilityEvent } from './useVisibilityEvent.js';
* once when it becomes visible again. Replaces the per-component
* useEffect + setInterval pattern for data-fetch polling.
*
- * fetchFn should handle its own errors. Side-effect-only callers that manage
- * their own state via setStates inside fetchFn typically `return null` and
- * ignore the hook's `data` return; that's fine, but be aware the hook will
- * still set `data = null` on each tick.
- *
- * Data-path callers (those reading the returned `data`) should NOT swallow
- * errors with `.catch(() => null)` — the hook will then apply that null and
- * wipe the previously-displayed snapshot on every transient blip. Let the
- * error throw; the hook's catch logs it and preserves the last good data.
+ * The hook catches whatever `fetchFn` throws, warns, and keeps the prior
+ * `data` untouched — so data-path callers (those reading the returned `data`)
+ * should NOT swallow errors with `.catch(() => null)`. Returning `null` here
+ * applies that null and wipes the previously-displayed snapshot on every
+ * transient blip; letting the error throw preserves the last good data.
+ * `pollOnly` (side-effect) callers can also handle errors inside `fetchFn`
+ * for their own logging or recovery; doing so swallows the rejection and
+ * suppresses the hook's warn, so re-throw if you still want the hook log.
*
* `refetch` is intentionally unconditional — it bypasses the hidden-tab
* short-circuit so explicit "Refresh" buttons work regardless of visibility.
* Don't call it from effects that fire on mount/route change without a
* visibility gate, or the "pauses while hidden" guarantee leaks.
*
- * @param {Function} fetchFn - async, returns the new data
- * @param {number} intervalMs - poll cadence; changing restarts the interval
+ * @param {Function} fetchFn - async; returns the new data, or any value if
+ * used purely for its side effects (see `pollOnly`).
+ * @param {number} intervalMs - poll cadence; changing restarts the interval.
* @param {Object} [options]
- * @param {boolean} [options.enabled=true] - when false, no interval and no fetch
- * @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 {boolean} [options.enabled=true] - when false, no interval and no fetch.
+ * @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 }}
+ * Ignored in `pollOnly` mode (no data is tracked to compare).
+ * @param {boolean} [options.pollOnly=false] - when true, the hook is treated
+ * as a side-effect-only poll tick: `data` / `loading` state is not tracked,
+ * no `applyResult` / setState calls run, and the return is `{ refetch }`
+ * only. Use when the caller owns its own state via `fetchFn`'s side
+ * effects and would otherwise `return null` and ignore `data` / `loading`.
+ * @returns {{ refetch: Function, data?: any, loading?: boolean }}
+ * `data` and `loading` are omitted when `pollOnly` is true.
*/
export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
- const { enabled = true, immediate = true, compare } = options;
+ const { enabled = true, immediate = true, compare, pollOnly = false } = options;
const [data, setData] = useState(null);
- const [loading, setLoading] = useState(true);
+ const [loading, setLoading] = useState(!pollOnly);
const fetchRef = useRef(fetchFn);
const compareRef = useRef(compare);
@@ -53,12 +60,13 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
}, [compare]);
const applyResult = useCallback((result) => {
+ if (pollOnly) return;
setData((prev) => {
const cmp = compareRef.current;
if (cmp && prev != null && result != null && cmp(prev, result)) return prev;
return result;
});
- }, []);
+ }, [pollOnly]);
// Stable, unconditional refetch for callers (Refresh buttons, post-mutation
// refresh paths, and key-change effects that need an immediate fetch with
@@ -68,14 +76,14 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
try {
const result = await fetchRef.current();
applyResult(result);
- setLoading(false);
+ if (!pollOnly) setLoading(false);
return result;
} catch (err) {
- console.warn(`⚠️ Auto-refetch failed: ${err.message}`);
- setLoading(false);
+ console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);
+ if (!pollOnly) setLoading(false);
return undefined;
}
- }, [applyResult]);
+ }, [applyResult, pollOnly]);
const loadOnVisibleRef = useRef(null);
@@ -93,10 +101,10 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
const result = await fetchRef.current();
if (cancelled) return;
applyResult(result);
- setLoading(false);
+ if (!pollOnly) setLoading(false);
} catch (err) {
- console.warn(`⚠️ Auto-refetch failed: ${err.message}`);
- if (!cancelled) setLoading(false);
+ console.warn(`⚠️ Auto-refetch failed: ${err?.message ?? String(err)}`);
+ if (!cancelled && !pollOnly) setLoading(false);
}
};
@@ -109,11 +117,12 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
clearInterval(interval);
loadOnVisibleRef.current = null;
};
- }, [intervalMs, enabled, immediate, applyResult]);
+ }, [intervalMs, enabled, immediate, applyResult, pollOnly]);
useVisibilityEvent((state) => {
if (state === 'visible') loadOnVisibleRef.current?.();
});
+ if (pollOnly) return { refetch };
return { data, loading, refetch };
}
diff --git a/client/src/hooks/useAutoRefetch.test.jsx b/client/src/hooks/useAutoRefetch.test.jsx
index fec30efcf6..6c0d05d86b 100644
--- a/client/src/hooks/useAutoRefetch.test.jsx
+++ b/client/src/hooks/useAutoRefetch.test.jsx
@@ -83,6 +83,22 @@ describe('useAutoRefetch', () => {
warn.mockRestore();
});
+ it('survives non-Error rejections (null, string) without throwing inside the catch', async () => {
+ const fetchFn = vi.fn()
+ .mockResolvedValueOnce('first')
+ .mockRejectedValueOnce(null)
+ .mockRejectedValueOnce('plain string')
+ .mockResolvedValue('recovered');
+ 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(4));
+ expect(result.current.data).toBe('recovered');
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
it('skips the on-mount fetch when immediate is false', async () => {
const fetchFn = vi.fn().mockResolvedValue('x');
renderHook(() => useAutoRefetch(fetchFn, 60, { immediate: false }));
@@ -186,6 +202,93 @@ describe('useAutoRefetch', () => {
expect(result.current.data).toBe(snapshot);
});
+ describe('pollOnly mode', () => {
+ it('returns { refetch } only — no data, no loading', async () => {
+ const fetchFn = vi.fn().mockResolvedValue({ ignored: true });
+ const { result } = renderHook(() => useAutoRefetch(fetchFn, 60_000, { pollOnly: true }));
+
+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ expect(result.current).toHaveProperty('refetch');
+ expect(result.current).not.toHaveProperty('data');
+ expect(result.current).not.toHaveProperty('loading');
+ });
+
+ it('still ticks on the interval', async () => {
+ const fetchFn = vi.fn().mockResolvedValue(null);
+ renderHook(() => useAutoRefetch(fetchFn, 30, { pollOnly: true }));
+ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(3));
+ });
+
+ it('skips while hidden and refires on visibility', async () => {
+ const fetchFn = vi.fn().mockResolvedValue(null);
+ renderHook(() => useAutoRefetch(fetchFn, 20, { pollOnly: true }));
+ 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('respects enabled toggling', async () => {
+ const fetchFn = vi.fn().mockResolvedValue(null);
+ const { rerender } = renderHook(
+ ({ enabled }) => useAutoRefetch(fetchFn, 20, { enabled, pollOnly: true }),
+ { initialProps: { enabled: false } },
+ );
+
+ await new Promise((r) => setTimeout(r, 80));
+ expect(fetchFn).not.toHaveBeenCalled();
+
+ rerender({ enabled: true });
+ await waitFor(() => expect(fetchFn).toHaveBeenCalledTimes(1));
+ });
+
+ it('exposes a working refetch that swallows errors via warn', async () => {
+ const fetchFn = vi.fn()
+ .mockResolvedValueOnce('first')
+ .mockRejectedValueOnce(new Error('boom'));
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ const { result } = renderHook(
+ () => useAutoRefetch(fetchFn, 60_000, { pollOnly: true, enabled: false }),
+ );
+
+ expect(fetchFn).not.toHaveBeenCalled();
+
+ let returned;
+ await act(async () => { returned = await result.current.refetch(); });
+ expect(returned).toBe('first');
+
+ await act(async () => { returned = await result.current.refetch(); });
+ expect(returned).toBeUndefined();
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ it('does not re-render on each tick (no data/loading state changes)', async () => {
+ const fetchFn = vi.fn().mockResolvedValue(null);
+ let renders = 0;
+ const { rerender } = renderHook(() => {
+ renders += 1;
+ return useAutoRefetch(fetchFn, 20, { pollOnly: true });
+ });
+
+ await waitFor(() => expect(fetchFn.mock.calls.length).toBeGreaterThanOrEqual(3));
+ const rendersAfterTicks = renders;
+ // Pollster runs three+ times; should not re-render per tick.
+ expect(rendersAfterTicks).toBeLessThanOrEqual(2);
+
+ // Rerendering externally still works normally.
+ rerender();
+ expect(renders).toBe(rendersAfterTicks + 1);
+ });
+ });
+
it('compare is bypassed when the new result is null, replacing prior data', async () => {
const fetchFn = vi.fn()
.mockResolvedValueOnce({ updatedAt: 1 })
diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.js
index 578ce58241..d4d8e5ff97 100644
--- a/client/src/hooks/useCityData.js
+++ b/client/src/hooks/useCityData.js
@@ -58,30 +58,28 @@ 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 null;
+ if (healthInFlightRef.current) return;
healthInFlightRef.current = true;
const health = await api.getSystemHealth({ silent: true }).catch(() => null);
healthInFlightRef.current = false;
- if (!health) return null;
+ if (!health) return;
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;
}, []);
// `immediate: false` — `fetchAll()` (run from the socket-setup effect below
// and from agent socket events) already covers the initial fetch for both
// running agents and system health; the hook then takes over the polling
// cadence without double-fetching at mount.
- useAutoRefetch(fetchRunningAgents, 10_000, { immediate: false });
- useAutoRefetch(fetchHealth, 15_000, { immediate: false });
+ useAutoRefetch(fetchRunningAgents, 10_000, { immediate: false, pollOnly: true });
+ useAutoRefetch(fetchHealth, 15_000, { immediate: false, pollOnly: true });
const agentMap = useMemo(() => {
const map = new Map();
diff --git a/client/src/pages/Browser.jsx b/client/src/pages/Browser.jsx
index b67dee98c0..36ead4d0a4 100644
--- a/client/src/pages/Browser.jsx
+++ b/client/src/pages/Browser.jsx
@@ -49,7 +49,6 @@ export default function BrowserPage() {
setStatus(data);
setLoading(false);
}
- return null;
}, []);
const fetchLogs = useCallback(async () => {
@@ -60,7 +59,7 @@ export default function BrowserPage() {
}
}, []);
- useAutoRefetch(fetchStatus, POLL_INTERVAL);
+ useAutoRefetch(fetchStatus, POLL_INTERVAL, { pollOnly: true });
// Load config when settings panel opens
useEffect(() => {
diff --git a/client/src/pages/ChiefOfStaff.jsx b/client/src/pages/ChiefOfStaff.jsx
index e8b20f471a..844ab0ab1a 100644
--- a/client/src/pages/ChiefOfStaff.jsx
+++ b/client/src/pages/ChiefOfStaff.jsx
@@ -151,7 +151,7 @@ export default function ChiefOfStaff() {
}, [tab, validTabIds, navigate]);
// Reduced polling since most updates come via socket events
- useAutoRefetch(fetchData, 30_000);
+ useAutoRefetch(fetchData, 30_000, { pollOnly: true });
useEffect(() => {
if (!socket) return;
diff --git a/client/src/pages/ImageGen.jsx b/client/src/pages/ImageGen.jsx
index d8e33f7f73..e644d91917 100644
--- a/client/src/pages/ImageGen.jsx
+++ b/client/src/pages/ImageGen.jsx
@@ -539,7 +539,7 @@ export default function ImageGen() {
const lastBusyRef = useRef(0);
const pollQueue = useCallback(async () => {
const jobs = await listMediaJobs({ kind: 'image' }).catch(() => null);
- if (!jobs) return null;
+ if (!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".
@@ -552,9 +552,8 @@ export default function ImageGen() {
// 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 });
+ useAutoRefetch(pollQueue, 4000, { enabled: queueActive, pollOnly: true });
const flux2Issue = isFlux2Model && flux2Status
? (!flux2Status.venvInstalled ? 'venv' : !flux2Status.hfTokenPresent ? 'token' : null)
diff --git a/client/src/pages/Loops.jsx b/client/src/pages/Loops.jsx
index d501a52c93..c0bb3b6c47 100644
--- a/client/src/pages/Loops.jsx
+++ b/client/src/pages/Loops.jsx
@@ -343,7 +343,6 @@ export default function Loops() {
const data = await api.getLoops().catch(() => []);
setLoops(data);
setLoading(false);
- return null;
}, []);
const fetchProviders = useCallback(async () => {
@@ -352,7 +351,7 @@ export default function Loops() {
}, []);
// Fallback poll for iteration count updates (socket events cover state changes)
- useAutoRefetch(fetchLoops, 60_000);
+ useAutoRefetch(fetchLoops, 60_000, { pollOnly: true });
useEffect(() => {
fetchProviders();