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

share one visibilitychange listener across useAutoRefetch consumers (#423)

[._.]/ Adam Eivyc3947c6f6199
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fc4ee0aa49..1338badc92 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-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.
## Fixed
diff --git a/PLAN.md b/PLAN.md
index 31605ad6e3..05441f20ce 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -5,7 +5,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-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-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/hooks/README.md b/client/src/hooks/README.md
index 440ccd5192..ec6c8fc319 100644
--- a/client/src/hooks/README.md
+++ b/client/src/hooks/README.md
@@ -54,6 +54,7 @@ grep -i "what you want to do" client/src/hooks/README.md
| `useSocket` | Shared socket instance + connection status. | You need to subscribe to a socket event. |
| `useUpdateChecker` | Detect stale client bundle; show reload toast. | Wire once at app root. |
| `useMounted` | `mountedRef` whose `.current` is true while mounted. | Async deferred work that must abort on unmount. |
+| `useVisibilityEvent` | Singleton-backed `document.visibilitychange` subscription (N subscribers share one listener). | Reacting to tab show/hide without spawning a per-component listener. `useAutoRefetch` already builds on this. |
## UI / interaction
diff --git a/client/src/hooks/index.js b/client/src/hooks/index.js
index 3e1e309088..99bdf873b3 100644
--- a/client/src/hooks/index.js
+++ b/client/src/hooks/index.js
@@ -54,6 +54,7 @@ export * from './useOpenClawAttachments.js';
// === Sockets & lifecycle ===
export * from './useSocket.js';
export * from './useUpdateChecker.jsx';
+export * from './useVisibilityEvent.js';
// === UI / interaction ===
export * from './useArmedAction.js';
diff --git a/client/src/hooks/useAutoRefetch.js b/client/src/hooks/useAutoRefetch.js
index 8b3f945f17..892b0f52d6 100644
--- a/client/src/hooks/useAutoRefetch.js
+++ b/client/src/hooks/useAutoRefetch.js
@@ -1,4 +1,5 @@
import { useState, useEffect, useRef, useCallback } from 'react';
+import { useVisibilityEvent } from './useVisibilityEvent.js';
/**
* Auto-refetch on an interval, pausing while the tab is hidden and re-firing
@@ -66,8 +67,13 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
}
}, [applyResult]);
+ const loadOnVisibleRef = useRef(null);
+
useEffect(() => {
- if (!enabled) return undefined;
+ if (!enabled) {
+ loadOnVisibleRef.current = null;
+ return undefined;
+ }
let cancelled = false;
@@ -84,24 +90,20 @@ export function useAutoRefetch(fetchFn, intervalMs, options = {}) {
}
};
- const handleVisibilityChange = () => {
- if (document.visibilityState === 'visible') loadData();
- };
-
+ loadOnVisibleRef.current = loadData;
if (immediate) 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);
- }
+ loadOnVisibleRef.current = null;
};
}, [intervalMs, enabled, immediate, applyResult]);
+ useVisibilityEvent((state) => {
+ if (state === 'visible') loadOnVisibleRef.current?.();
+ });
+
return { data, loading, refetch };
}
diff --git a/client/src/hooks/useVisibilityEvent.js b/client/src/hooks/useVisibilityEvent.js
new file mode 100644
index 0000000000..996f6fd38c
--- /dev/null
+++ b/client/src/hooks/useVisibilityEvent.js
@@ -0,0 +1,57 @@
+import { useEffect, useRef } from 'react';
+
+// Singleton emitter so N subscribers share one document-level
+// `visibilitychange` listener. With 20+ widgets on the Dashboard, a per-hook
+// listener fires 20+ near-simultaneous handlers on every tab show/hide; this
+// keeps the listener count to one regardless of subscriber count.
+
+const subscribers = new Set();
+let attached = false;
+
+const dispatch = () => {
+ const state = typeof document !== 'undefined' ? document.visibilityState : 'visible';
+ for (const fn of subscribers) fn(state);
+};
+
+const ensureAttached = () => {
+ if (attached || typeof document === 'undefined') return;
+ document.addEventListener('visibilitychange', dispatch);
+ attached = true;
+};
+
+const detachIfEmpty = () => {
+ if (!attached || subscribers.size > 0 || typeof document === 'undefined') return;
+ document.removeEventListener('visibilitychange', dispatch);
+ attached = false;
+};
+
+/**
+ * Subscribe to `document.visibilitychange` via a shared singleton listener.
+ * The handler receives the new `document.visibilityState` string.
+ *
+ * @param {(state: 'visible' | 'hidden') => void} handler
+ */
+export function useVisibilityEvent(handler) {
+ const handlerRef = useRef(handler);
+ useEffect(() => { handlerRef.current = handler; }, [handler]);
+
+ useEffect(() => {
+ const fn = (state) => handlerRef.current?.(state);
+ subscribers.add(fn);
+ ensureAttached();
+ return () => {
+ subscribers.delete(fn);
+ detachIfEmpty();
+ };
+ }, []);
+}
+
+// Test-only escape hatch. Lets the test reset module-scope state between
+// runs without exposing it as a public API.
+export function __resetVisibilityEventForTests() {
+ subscribers.clear();
+ if (attached && typeof document !== 'undefined') {
+ document.removeEventListener('visibilitychange', dispatch);
+ }
+ attached = false;
+}
diff --git a/client/src/hooks/useVisibilityEvent.test.jsx b/client/src/hooks/useVisibilityEvent.test.jsx
new file mode 100644
index 0000000000..a22ad14140
--- /dev/null
+++ b/client/src/hooks/useVisibilityEvent.test.jsx
@@ -0,0 +1,90 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { useVisibilityEvent, __resetVisibilityEventForTests } from './useVisibilityEvent';
+
+const setVisibility = (state) => {
+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });
+};
+
+const fireVisibilityChange = () => {
+ document.dispatchEvent(new Event('visibilitychange'));
+};
+
+describe('useVisibilityEvent', () => {
+ let addSpy;
+ let removeSpy;
+
+ beforeEach(() => {
+ setVisibility('visible');
+ __resetVisibilityEventForTests();
+ addSpy = vi.spyOn(document, 'addEventListener');
+ removeSpy = vi.spyOn(document, 'removeEventListener');
+ });
+
+ afterEach(() => {
+ addSpy.mockRestore();
+ removeSpy.mockRestore();
+ __resetVisibilityEventForTests();
+ setVisibility('visible');
+ });
+
+ const visibilityListenerCount = (spy) =>
+ spy.mock.calls.filter(([type]) => type === 'visibilitychange').length;
+
+ it('attaches exactly one document listener regardless of subscriber count', () => {
+ const a = renderHook(() => useVisibilityEvent(() => {}));
+ const b = renderHook(() => useVisibilityEvent(() => {}));
+ const c = renderHook(() => useVisibilityEvent(() => {}));
+
+ expect(visibilityListenerCount(addSpy)).toBe(1);
+ expect(visibilityListenerCount(removeSpy)).toBe(0);
+
+ a.unmount();
+ b.unmount();
+ expect(visibilityListenerCount(removeSpy)).toBe(0);
+
+ c.unmount();
+ expect(visibilityListenerCount(removeSpy)).toBe(1);
+ });
+
+ it('fans out visibility changes to every subscriber', () => {
+ const a = vi.fn();
+ const b = vi.fn();
+ renderHook(() => useVisibilityEvent(a));
+ renderHook(() => useVisibilityEvent(b));
+
+ setVisibility('hidden');
+ act(() => fireVisibilityChange());
+ expect(a).toHaveBeenLastCalledWith('hidden');
+ expect(b).toHaveBeenLastCalledWith('hidden');
+
+ setVisibility('visible');
+ act(() => fireVisibilityChange());
+ expect(a).toHaveBeenLastCalledWith('visible');
+ expect(b).toHaveBeenLastCalledWith('visible');
+ });
+
+ it('calls the latest handler when the caller re-renders with a new function', () => {
+ const first = vi.fn();
+ const second = vi.fn();
+ const { rerender } = renderHook(({ fn }) => useVisibilityEvent(fn), { initialProps: { fn: first } });
+
+ rerender({ fn: second });
+ setVisibility('hidden');
+ act(() => fireVisibilityChange());
+
+ expect(first).not.toHaveBeenCalled();
+ expect(second).toHaveBeenCalledWith('hidden');
+ });
+
+ it('detaches when the last subscriber unmounts and re-attaches on the next mount', () => {
+ const a = renderHook(() => useVisibilityEvent(() => {}));
+ expect(visibilityListenerCount(addSpy)).toBe(1);
+
+ a.unmount();
+ expect(visibilityListenerCount(removeSpy)).toBe(1);
+
+ renderHook(() => useVisibilityEvent(() => {}));
+ expect(visibilityListenerCount(addSpy)).toBe(2);
+ });
+});