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
dedup polls on five dashboard widgets via useAutoRefetch compare (#421)
[._.]/ Adam Eivy2382059f8de8
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3fee9e739f..33c5c106e3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -22,6 +22,7 @@- **[useautorefetch-poll-result-dedup] `useAutoRefetch` callers can now opt into skipping re-renders when the poll result is logically unchanged.** The hook accepts an optional `compare(prev, next)` callback; when it returns true the previous data reference is preserved, so React's set-state bail-out kicks in and the subtree doesn't re-render. The first fetch always sets data (the comparator only runs when both sides are non-null). Useful for monotonic snapshots like `(a, b) => a.updatedAt === b.updatedAt` on widgets that poll every few seconds. No behavior change for existing callers; rollout to individual widgets tracked separately.- **[useautorefetch-compare-caller-rollout] Brain, Digital Twin, and the pipeline Episode Video stage skip wasted re-renders when their polls return unchanged data.** Brain (30s) and Digital Twin (30s) headers now stay stable through identical poll ticks instead of flashing through a fresh render every interval. The Episode Video stage's bespoke "skip if updatedAt/status match" check inside `setCdProject` is gone — that dedup now lives in the shared hook alongside the rest of the polling surface, 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.- **[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 258583b57d..cf251a5d65 100644--- a/PLAN.md+++ b/PLAN.md@@ -5,6 +5,7 @@ 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.- [ ] [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.- [ ] [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/BackupWidget.jsx b/client/src/components/BackupWidget.jsxindex 48e2f88004..b39d237824 100644--- a/client/src/components/BackupWidget.jsx+++ b/client/src/components/BackupWidget.jsx@@ -14,6 +14,7 @@ import BrailleSpinner from './BrailleSpinner';import toast from './ui/Toast';import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useTimeTick } from '../hooks/useTimeTick';// ---------------------------------------------------------------------------// Pure helpers@@ -200,9 +201,26 @@ function RestorePanel({ snapshot, onClose }) {// ---------------------------------------------------------------------------function SnapshotList() {+ // Let errors throw — `useAutoRefetch` preserves the last-good data on+ // transient failures. A `.catch(() => null)` here would wipe the snapshot+ // list on every blip per the hook's documented gotcha.const { data: snapshots, loading } = useAutoRefetch(- () => api.getBackupSnapshots({ silent: true }).catch(() => null),- 120000+ () => api.getBackupSnapshots({ silent: true }),+ 120000,+ {+ // Snapshots only change when a new backup lands or the rotation prunes+ // the oldest — walk every rendered tuple (id + fileCount) so a stale+ // server-side fileCount recount or a middle-row mutation can't hide+ // behind the head/tail id check.+ compare: (prev, next) => {+ if (prev.length !== next.length) return false;+ for (let i = 0; i < prev.length; i++) {+ if (prev[i]?.id !== next[i]?.id) return false;+ if (prev[i]?.fileCount !== next[i]?.fileCount) return false;+ }+ return true;+ },+ },);const [selectedId, setSelectedId] = useState(null);@@ -254,12 +272,33 @@ function SnapshotList() {// ---------------------------------------------------------------------------const BackupWidget = memo(function BackupWidget() {+ // Let errors throw — `useAutoRefetch` preserves the last-good status on+ // transient failures so a blip doesn't drop the widget to its loading state.const { data: status } = useAutoRefetch(- () => api.getBackupStatus({ silent: true }).catch(() => null),- 60000+ () => api.getBackupStatus({ silent: true }),+ 60000,+ {+ // Backup state only flips when a new run starts/finishes — comparing the+ // monotonic timestamps + status + error + destPath captures every+ // visible change at the widget's resolution. Avoids per-poll re-renders+ // that would re-compute relative-time labels for no visual benefit.+ compare: (prev, next) => (+ prev.status === next.status+ && prev.lastRun === next.lastRun+ && prev.nextRun === next.nextRun+ && prev.error === next.error+ && prev.filesChanged === next.filesChanged+ && prev.destPath === next.destPath+ ),+ },);const [triggering, setTriggering] = useState(false);const [snapshotsOpen, setSnapshotsOpen] = useState(false);+ // Tick every minute so the dedup-skipped widget still recomputes+ // `relativeTime(lastRun/nextRun)` labels and the `computeHealth` 25h/49h+ // thresholds when wall-clock time crosses a boundary even though the poll+ // payload is unchanged.+ useTimeTick(60000);const health = computeHealth(status);const { dot, text, icon: HealthIcon } = HEALTH_STYLES[health];diff --git a/client/src/components/CosDashboardWidget.jsx b/client/src/components/CosDashboardWidget.jsxindex 41ad7e4188..cd07fb12b8 100644--- a/client/src/components/CosDashboardWidget.jsx+++ b/client/src/components/CosDashboardWidget.jsx@@ -16,6 +16,8 @@ import {} from 'lucide-react';import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useTimeTick } from '../hooks/useTimeTick';+import { timeAgo } from '../utils/formatters';/*** CosDashboardWidget - Compact CoS status widget for the main Dashboard@@ -23,18 +25,116 @@ import { useAutoRefetch } from '../hooks/useAutoRefetch';*/const CosDashboardWidget = memo(function CosDashboardWidget() {const { data: dashData, loading } = useAutoRefetch(async () => {+ // Let errors throw — `useAutoRefetch` preserves the last-good batch on+ // transient failures. Without this, a per-endpoint `.catch(() => null)`+ // could mix fresh and stale sections (e.g. summary=null but+ // learningSummary holding its prior value) and the widget would flicker+ // sections off-screen on every blip.const silent = { silent: true };const [summary, learningSummary, recentTasks, activityCalendar] = await Promise.all([- api.getCosQuickSummary(silent).catch(() => null),- api.getCosLearningSummary(silent).catch(() => null),- api.getCosRecentTasks(5, silent).catch(() => null),- api.getCosActivityCalendar(8, silent).catch(() => null)+ api.getCosQuickSummary(silent),+ api.getCosLearningSummary(silent),+ api.getCosRecentTasks(5, silent),+ api.getCosActivityCalendar(8, silent)]);return { summary, learningSummary, recentTasks, activityCalendar };- }, 30000);+ }, 30000, {+ // Re-render only when one of the aggregated counts actually moves —+ // running agents, completed/failed counts, streak, queue depth, learning+ // success rate, every visible recent-task field, every per-day heatmap+ // cell, and the heatmap summary. The poll fires every 30s; without this+ // guard each tick re-renders the activity heatmap + recent tasks list+ // even when nothing changed.+ //+ // Recent-tasks comparison walks every rendered field per row (id,+ // description, taskType, app, durationFormatted, success). The relative-+ // time label is rendered client-side from `task.completedAt` via timeAgo+ // and refreshed by the useTimeTick(60000) below, so the server's+ // `task.completedRelative` string is intentionally ignored — it ships in+ // the payload but would freeze across deduped polls if we used it.+ //+ // Heatmap comparison walks every cell's (date, tasks, successRate) tuple+ // plus summary totals — per-day tasks/successRate distribution can shift+ // without changing top-level totals (e.g. a task moving from one day to+ // another in late-arriving telemetry).+ compare: (prev, next) => {+ const prevTasks = prev.recentTasks?.tasks;+ const nextTasks = next.recentTasks?.tasks;+ const prevLen = prevTasks?.length ?? 0;+ const nextLen = nextTasks?.length ?? 0;+ if (prevLen !== nextLen) return false;+ for (let i = 0; i < prevLen; i++) {+ const a = prevTasks[i];+ const b = nextTasks[i];+ if (+ a?.id !== b?.id+ || a?.success !== b?.success+ || a?.description !== b?.description+ || a?.taskType !== b?.taskType+ || a?.app !== b?.app+ || a?.durationFormatted !== b?.durationFormatted+ // completedAt is the input to timeAgo(...) below — if the server+ // corrects a task's completion time without changing other fields+ // (rare but possible) we want the relative-time label to refresh+ // immediately, not on the next minute tick.+ || a?.completedAt !== b?.completedAt+ ) return false;+ }+ // Heatmap weeks: array of arrays of {date, tasks, successRate, isToday,+ // isFuture}. Compare every cell — single boundary-cross (isToday rolls+ // from one date to the next) flips the comparator naturally because+ // (date, isToday) on the prior+next today differ.+ const prevWeeks = prev.activityCalendar?.weeks;+ const nextWeeks = next.activityCalendar?.weeks;+ const prevWeeksLen = prevWeeks?.length ?? 0;+ const nextWeeksLen = nextWeeks?.length ?? 0;+ if (prevWeeksLen !== nextWeeksLen) return false;+ for (let w = 0; w < prevWeeksLen; w++) {+ const pw = prevWeeks[w];+ const nw = nextWeeks[w];+ if ((pw?.length ?? 0) !== (nw?.length ?? 0)) return false;+ for (let d = 0; d < pw.length; d++) {+ const pd = pw[d];+ const nd = nw[d];+ if (+ pd?.date !== nd?.date+ || pd?.tasks !== nd?.tasks+ || pd?.successRate !== nd?.successRate+ || pd?.isToday !== nd?.isToday+ ) return false;+ }+ }+ return (+ prev.summary?.status?.running === next.summary?.status?.running+ && prev.summary?.status?.paused === next.summary?.status?.paused+ && prev.summary?.today?.succeeded === next.summary?.today?.succeeded+ && prev.summary?.today?.failed === next.summary?.today?.failed+ && prev.summary?.today?.running === next.summary?.today?.running+ && prev.summary?.today?.completed === next.summary?.today?.completed+ && prev.summary?.today?.timeWorked === next.summary?.today?.timeWorked+ && prev.summary?.streak?.current === next.summary?.streak?.current+ && prev.summary?.queue?.total === next.summary?.queue?.total+ && prev.summary?.queue?.pendingApprovals === next.summary?.queue?.pendingApprovals+ && prev.learningSummary?.overallSuccessRate === next.learningSummary?.overallSuccessRate+ && prev.learningSummary?.skipped === next.learningSummary?.skipped+ && prev.learningSummary?.status === next.learningSummary?.status+ && prev.learningSummary?.totalCompleted === next.learningSummary?.totalCompleted+ && prev.recentTasks?.summary?.total === next.recentTasks?.summary?.total+ && prev.recentTasks?.summary?.succeeded === next.recentTasks?.summary?.succeeded+ && prev.activityCalendar?.summary?.totalTasks === next.activityCalendar?.summary?.totalTasks+ && prev.activityCalendar?.summary?.successRate === next.activityCalendar?.summary?.successRate+ && prev.activityCalendar?.summary?.activeDays === next.activityCalendar?.summary?.activeDays+ && prev.activityCalendar?.maxTasks === next.activityCalendar?.maxTasks+ && prev.activityCalendar?.currentStreak === next.activityCalendar?.currentStreak+ );+ },+ });const { summary, learningSummary, recentTasks, activityCalendar } = dashData ?? {};const [tasksExpanded, setTasksExpanded] = useState(false);+ // Tick every minute so the client-side `timeAgo(task.completedAt)` labels+ // recompute against the latest wall-clock time across deduped polls.+ useTimeTick(60000);// Don't render while loadingif (loading) {@@ -228,7 +328,13 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {<span>•</span><span>{task.durationFormatted}</span><span>•</span>- <span>{task.completedRelative}</span>+ {/* Compute relative time client-side from `completedAt`+ so the useTimeTick(60000) above can refresh the+ label without help from the server. The server's+ `completedRelative` string ships in the payload but+ we intentionally ignore it — it goes stale across+ deduped polls. */}+ <span>{timeAgo(task.completedAt)}</span></div></div></Link>@@ -242,7 +348,7 @@ const CosDashboardWidget = memo(function CosDashboardWidget() {<divkey={task.id}className={`w-2 h-2 rounded-full ${task.success ? 'bg-port-success' : 'bg-port-error'}`}- title={`${task.description.substring(0, 50)}... (${task.completedRelative})`}+ title={`${task.description.substring(0, 50)}... (${timeAgo(task.completedAt)})`}/>))}</div>diff --git a/client/src/components/DecisionLogWidget.jsx b/client/src/components/DecisionLogWidget.jsxindex 57beb0071b..bd481db14d 100644--- a/client/src/components/DecisionLogWidget.jsx+++ b/client/src/components/DecisionLogWidget.jsx@@ -16,6 +16,7 @@ import {} from 'lucide-react';import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useTimeTick } from '../hooks/useTimeTick';import { timeAgo } from '../utils/formatters';/**@@ -25,11 +26,73 @@ import { timeAgo } from '../utils/formatters';* exactly why the CoS took (or didn't take) action.*/const DecisionLogWidget = memo(function DecisionLogWidget() {+ // Let errors throw — `useAutoRefetch` preserves the last-good summary on+ // transient failures instead of dropping the widget back to its loading+ // state on every blip.const { data: summary, loading } = useAutoRefetch(- () => api.getCosDecisionSummary({ silent: true }).catch(() => null),- 60000+ () => api.getCosDecisionSummary({ silent: true }),+ 60000,+ {+ // Decision stream is append-only; same 24h totals + same per-decision+ // tuple of every rendered field means nothing visible advanced this+ // minute. Comparator walks: id (key + dedup), type (icon + label),+ // reason (body + tooltip), count (×N badge), and the context fields+ // that renderContextDetails surfaces (running/max/project/limit, appId/+ // cooldownMs, fromTask/toTask, attempts, runningAgents/awaitingApproval,+ // taskType, successRate). The `timeAgo(decision.lastTimestamp ||+ // decision.timestamp)` label is re-rendered by the useTimeTick(60000)+ // below — including the timestamp fields in this comparator would+ // pointlessly break dedup on every backend mtime nudge. Keep this tuple+ // in sync with the JSX above.+ compare: (prev, next) => {+ if (prev.last24Hours?.total !== next.last24Hours?.total+ || prev.last24Hours?.skipped !== next.last24Hours?.skipped+ || prev.last24Hours?.switched !== next.last24Hours?.switched+ || prev.last24Hours?.capacityFull !== next.last24Hours?.capacityFull+ || prev.last24Hours?.cooldownActive !== next.last24Hours?.cooldownActive+ || prev.last24Hours?.selected !== next.last24Hours?.selected+ || prev.last24Hours?.adjusted !== next.last24Hours?.adjusted+ || prev.transparencyScore !== next.transparencyScore) return false;+ const a = Array.isArray(prev.impactfulDecisions) ? prev.impactfulDecisions : null;+ const b = Array.isArray(next.impactfulDecisions) ? next.impactfulDecisions : null;+ if (a === null || b === null) return a === b;+ if (a.length !== b.length) return false;+ for (let i = 0; i < a.length; i++) {+ const da = a[i];+ const db = b[i];+ if (+ da.id !== db?.id+ || da.type !== db?.type+ || da.reason !== db?.reason+ || (da.count ?? 1) !== (db?.count ?? 1)+ ) return false;+ const ca = da.context;+ const cb = db?.context;+ if (+ ca?.running !== cb?.running+ || ca?.max !== cb?.max+ || ca?.project !== cb?.project+ || ca?.limit !== cb?.limit+ || ca?.appId !== cb?.appId+ || ca?.cooldownMs !== cb?.cooldownMs+ || ca?.fromTask !== cb?.fromTask+ || ca?.toTask !== cb?.toTask+ || ca?.attempts !== cb?.attempts+ || ca?.runningAgents !== cb?.runningAgents+ || ca?.awaitingApproval !== cb?.awaitingApproval+ || ca?.taskType !== cb?.taskType+ || ca?.successRate !== cb?.successRate+ ) return false;+ }+ return true;+ },+ },);const [expanded, setExpanded] = useState(false);+ // Tick every minute so the `timeAgo(...)` relative-time labels on each+ // decision row roll over even when the poll payload is unchanged by the+ // comparator.+ useTimeTick(60000);// Don't render while loading or if no dataif (loading || !summary) {diff --git a/client/src/components/GoalProgressWidget.jsx b/client/src/components/GoalProgressWidget.jsxindex 01b44a69da..55576dd000 100644--- a/client/src/components/GoalProgressWidget.jsx+++ b/client/src/components/GoalProgressWidget.jsx@@ -3,6 +3,7 @@ import { Link } from 'react-router-dom';import { ChevronRight, AlertTriangle, Target } from 'lucide-react';import * as api from '../services/api';import { useAutoRefetch } from '../hooks/useAutoRefetch';+import { useTimeTick } from '../hooks/useTimeTick';import { CATEGORY_CONFIG, GOAL_TYPE_CONFIG } from './goals/GoalDetailPanel';const HORIZON_LABELS = {@@ -24,11 +25,47 @@ const getDaysSince = (dateStr) => {};const GoalProgressWidget = memo(function GoalProgressWidget() {+ // Let errors throw — `useAutoRefetch` preserves the last-good goal set on+ // transient failures rather than wiping the widget.const { data: goalsData, loading } = useAutoRefetch(- () => api.getGoals({ silent: true }).catch(() => null),- 300000+ () => api.getGoals({ silent: true }),+ 300000,+ {+ // Goals rarely change at 5-minute cadence. Skip the re-render (and the+ // useMemo recompute that re-derives stalled goals + avg progress) when+ // the goal set and every rendered/derived per-goal field are unchanged.+ // Covers: title, category, horizon, goalType (rendered as labels/icons),+ // progress (bar + % label), status + parentId + urgency (filter/sort+ // inputs), and the last-progress timestamp + createdAt fallback that+ // drive `daysSinceUpdate` / `isStalled` (a backfilled or corrected+ // progressHistory entry mutates the latest timestamp without changing+ // array length).+ compare: (prev, next) => {+ const a = Array.isArray(prev.goals) ? prev.goals : null;+ const b = Array.isArray(next.goals) ? next.goals : null;+ if (a === null || b === null) return a === b;+ return a.length === b.length && a.every((g, i) => (+ g.id === b[i]?.id+ && g.title === b[i]?.title+ && g.category === b[i]?.category+ && g.horizon === b[i]?.horizon+ && g.goalType === b[i]?.goalType+ && g.progress === b[i]?.progress+ && g.status === b[i]?.status+ && g.parentId === b[i]?.parentId+ && g.urgency === b[i]?.urgency+ && g.createdAt === b[i]?.createdAt+ && getLastProgressDate(g) === getLastProgressDate(b[i])+ ));+ },+ },);+ // Tick hourly so `daysSinceUpdate` / `isStalled` derivations cross the+ // 14-day stall boundary without waiting for an unrelated payload change to+ // re-render. Day-level precision doesn't need a per-minute tick.+ const tick = useTimeTick(3600000);+const { goals, stalledCount, avgProgress } = useMemo(() => {if (!goalsData?.goals?.length) return { goals: [], stalledCount: 0, avgProgress: 0 };@@ -49,7 +86,10 @@ const GoalProgressWidget = memo(function GoalProgressWidget() {stalledCount: topLevel.filter(g => g.isStalled).length,avgProgress: topLevel.length ? Math.round(topLevel.reduce((sum, g) => sum + (g.progress || 0), 0) / topLevel.length) : 0};- }, [goalsData]);+ // `tick` is in the dep array on purpose — when the wall-clock hour rolls+ // over the derivation re-runs so a goal can cross the stall threshold+ // without needing a new poll payload.+ }, [goalsData, tick]);if (loading || !goals.length) return null;diff --git a/client/src/components/ProactiveAlertsWidget.jsx b/client/src/components/ProactiveAlertsWidget.jsxindex bcb3e8389c..a29a2a6389 100644--- a/client/src/components/ProactiveAlertsWidget.jsx+++ b/client/src/components/ProactiveAlertsWidget.jsx@@ -31,9 +31,33 @@ const TYPE_ICONS = {};const ProactiveAlertsWidget = memo(function ProactiveAlertsWidget() {+ // Let errors throw — `useAutoRefetch` preserves the last-good alert+ // snapshot on transient failures instead of dropping the widget.const { data, loading } = useAutoRefetch(- () => api.getAlertsSummary({ silent: true }).catch(() => null),- 120000 // Refresh every 2 minutes+ () => api.getAlertsSummary({ silent: true }),+ 120000, // Refresh every 2 minutes+ {+ // Skip the re-render when the summary counts and every rendered per-row+ // field are unchanged. Each alert row renders title, detail, severity+ // (style class), type (icon), and link (href), so all five participate+ // in the comparison — keep this list in sync with the JSX below.+ compare: (prev, next) => {+ if (prev.counts?.total !== next.counts?.total+ || prev.counts?.critical !== next.counts?.critical+ || prev.counts?.high !== next.counts?.high+ || prev.counts?.medium !== next.counts?.medium) return false;+ const a = Array.isArray(prev.alerts) ? prev.alerts : null;+ const b = Array.isArray(next.alerts) ? next.alerts : null;+ if (a === null || b === null) return a === b;+ return a.length === b.length && a.every((al, i) => (+ al.title === b[i]?.title+ && al.severity === b[i]?.severity+ && al.detail === b[i]?.detail+ && al.type === b[i]?.type+ && al.link === b[i]?.link+ ));+ },+ },);if (loading) return null;diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ec6c8fc319..b9739b8a0a 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. |+| `useTimeTick` | Singleton-backed wall-clock tick (`Date.now()`); N subscribers at the same cadence share one `setInterval`. | A widget renders something derived from `Date.now()` (relative timestamps, threshold-based health labels, countdowns) and is also fed by a deduped `useAutoRefetch` — without this the label goes stale until the data changes. || `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 / interactiondiff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 99bdf873b3..fe44c85cd9 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -53,6 +53,7 @@ export * from './useOpenClawAttachments.js';// === Sockets & lifecycle ===export * from './useSocket.js';+export * from './useTimeTick.js';export * from './useUpdateChecker.jsx';export * from './useVisibilityEvent.js';diff --git a/client/src/hooks/useTimeTick.js b/client/src/hooks/useTimeTick.jsnew file mode 100644index 0000000000..806f421737--- /dev/null+++ b/client/src/hooks/useTimeTick.js@@ -0,0 +1,122 @@+import { useEffect, useState } from 'react';+import { subscribeVisibility } from './useVisibilityEvent.js';++// Singleton tickers keyed by intervalMs so N subscribers at the same cadence+// share one timer instead of spawning a setInterval per widget. A page with+// six widgets all asking for a minute tick should run one minute-interval+// timer, not six.+//+// Tickers also pause while the tab is hidden — there's no UI to refresh, so+// running the interval just burns CPU/battery in the background. Visibility+// orchestration piggybacks on `useVisibilityEvent`'s singleton emitter+// (`subscribeVisibility`) so the document-level listener count stays at one+// across this hook + every `useVisibilityEvent` consumer + `useAutoRefetch`.+// On tab show we fire once immediately so labels are correct before the+// next scheduled tick lands.+const tickers = new Map(); // intervalMs -> { handle, subscribers: Set<fn> }++const isHidden = () =>+ typeof document !== 'undefined' && document.visibilityState === 'hidden';++const fire = (entry) => {+ const now = Date.now();+ for (const fn of entry.subscribers) fn(now);+};++const startTimer = (entry, intervalMs) => {+ if (entry.handle != null) return;+ entry.handle = setInterval(() => fire(entry), intervalMs);+};++const stopTimer = (entry) => {+ if (entry.handle == null) return;+ clearInterval(entry.handle);+ entry.handle = null;+};++const startTicker = (intervalMs) => {+ const entry = { handle: null, subscribers: new Set() };+ tickers.set(intervalMs, entry);+ if (!isHidden()) startTimer(entry, intervalMs);+ return entry;+};++// Lazy-attached subscription to the shared visibility emitter. We only+// subscribe while at least one ticker is alive — when the last subscriber+// unmounts we unsubscribe so the visibility singleton can detach its+// document-level listener if nothing else is using it.+let unsubscribeVisibility = null;++const handleVisibility = (state) => {+ if (state === 'hidden') {+ for (const entry of tickers.values()) stopTimer(entry);+ } else {+ for (const [intervalMs, entry] of tickers) {+ startTimer(entry, intervalMs);+ fire(entry);+ }+ }+};++const ensureVisibilitySubscribed = () => {+ if (unsubscribeVisibility) return;+ unsubscribeVisibility = subscribeVisibility(handleVisibility);+};++const releaseVisibilityIfIdle = () => {+ if (!unsubscribeVisibility || tickers.size > 0) return;+ unsubscribeVisibility();+ unsubscribeVisibility = null;+};++/**+ * Re-render at a fixed cadence so derived-from-`Date.now()` UI (relative+ * timestamps, threshold-based health labels, countdowns) stays accurate even+ * when the underlying data is deduped by `useAutoRefetch`'s `compare` option.+ *+ * Returns the current `Date.now()` snapshot, which is also useful as a+ * dependency for `useMemo` callers that derive labels from a base timestamp.+ *+ * Subscribers grouped by `intervalMs` share one underlying `setInterval` (so+ * a Dashboard with six widgets calling `useTimeTick(60000)` runs one timer,+ * not six). Tickers also pause while the tab is hidden and fire once on+ * tab-visible so deduped labels catch up — the visibility listener is shared+ * with `useVisibilityEvent` so we don't grow the document-listener count.+ *+ * @param {number} intervalMs - tick cadence. 60000 (one minute) is the right+ * default for "X min ago" labels; bump to 3600000 for hourly "X hours ago"+ * surfaces; 1000 only for true seconds-precision counters.+ * @returns {number} the latest `Date.now()` snapshot at the most recent tick.+ */+export function useTimeTick(intervalMs = 60000) {+ const [now, setNow] = useState(() => Date.now());++ useEffect(() => {+ if (typeof window === 'undefined') return undefined;+ let entry = tickers.get(intervalMs);+ if (!entry) entry = startTicker(intervalMs);+ entry.subscribers.add(setNow);+ ensureVisibilitySubscribed();+ return () => {+ entry.subscribers.delete(setNow);+ if (entry.subscribers.size === 0) {+ stopTimer(entry);+ tickers.delete(intervalMs);+ releaseVisibilityIfIdle();+ }+ };+ }, [intervalMs]);++ return now;+}++// Test-only escape hatch — lets tests reset the singleton tickers between+// runs without exposing it as a public API.+export function __resetTimeTickForTests() {+ for (const entry of tickers.values()) stopTimer(entry);+ tickers.clear();+ if (unsubscribeVisibility) {+ unsubscribeVisibility();+ unsubscribeVisibility = null;+ }+}diff --git a/client/src/hooks/useTimeTick.test.jsx b/client/src/hooks/useTimeTick.test.jsxnew file mode 100644index 0000000000..917c62ddc2--- /dev/null+++ b/client/src/hooks/useTimeTick.test.jsx@@ -0,0 +1,154 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { useTimeTick, __resetTimeTickForTests } from './useTimeTick';+import { __resetVisibilityEventForTests } from './useVisibilityEvent';++const setVisibility = (state) => {+ Object.defineProperty(document, 'visibilityState', { value: state, configurable: true });+};++const fireVisibilityChange = () => {+ document.dispatchEvent(new Event('visibilitychange'));+};++describe('useTimeTick', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ setVisibility('visible');+ __resetVisibilityEventForTests();+ __resetTimeTickForTests();+ });++ afterEach(() => {+ __resetTimeTickForTests();+ __resetVisibilityEventForTests();+ setVisibility('visible');+ vi.useRealTimers();+ });++ it('returns the current Date.now() initially', () => {+ vi.setSystemTime(new Date('2026-05-21T12:00:00Z'));+ const { result } = renderHook(() => useTimeTick(60000));+ expect(result.current).toBe(Date.parse('2026-05-21T12:00:00Z'));+ });++ it('re-renders at the configured interval with a fresh now value', () => {+ vi.setSystemTime(new Date('2026-05-21T12:00:00Z'));+ const { result } = renderHook(() => useTimeTick(60000));+ const initial = result.current;++ act(() => {+ vi.advanceTimersByTime(60000);+ });+ expect(result.current).toBeGreaterThan(initial);+ expect(result.current).toBe(initial + 60000);+ });++ it('subscribers at the same intervalMs share one underlying setInterval', () => {+ const intervalSpy = vi.spyOn(window, 'setInterval');++ const a = renderHook(() => useTimeTick(60000));+ const b = renderHook(() => useTimeTick(60000));+ const c = renderHook(() => useTimeTick(60000));++ const calls60s = intervalSpy.mock.calls.filter(([, ms]) => ms === 60000);+ expect(calls60s).toHaveLength(1);++ a.unmount();+ b.unmount();+ c.unmount();++ intervalSpy.mockRestore();+ });++ it('subscribers at different intervalMs each get their own timer', () => {+ const intervalSpy = vi.spyOn(window, 'setInterval');++ renderHook(() => useTimeTick(60000));+ renderHook(() => useTimeTick(1000));++ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 60000)).toHaveLength(1);+ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 1000)).toHaveLength(1);++ intervalSpy.mockRestore();+ });++ it('clears the underlying timer when the last subscriber unmounts', () => {+ const clearSpy = vi.spyOn(window, 'clearInterval');++ const a = renderHook(() => useTimeTick(60000));+ const b = renderHook(() => useTimeTick(60000));++ a.unmount();+ expect(clearSpy).not.toHaveBeenCalled();++ b.unmount();+ expect(clearSpy).toHaveBeenCalledTimes(1);++ clearSpy.mockRestore();+ });++ it('pauses the timer while the tab is hidden and resumes on visible', () => {+ const intervalSpy = vi.spyOn(window, 'setInterval');+ const clearSpy = vi.spyOn(window, 'clearInterval');++ renderHook(() => useTimeTick(60000));+ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 60000)).toHaveLength(1);++ setVisibility('hidden');+ act(() => fireVisibilityChange());+ expect(clearSpy).toHaveBeenCalledTimes(1);++ setVisibility('visible');+ act(() => fireVisibilityChange());+ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 60000)).toHaveLength(2);++ intervalSpy.mockRestore();+ clearSpy.mockRestore();+ });++ it('fires once on tab-visible so deduped labels catch up immediately', () => {+ vi.setSystemTime(new Date('2026-05-21T12:00:00Z'));+ const { result } = renderHook(() => useTimeTick(60000));+ const initial = result.current;++ setVisibility('hidden');+ act(() => fireVisibilityChange());+ // Advance wall-clock while hidden — the timer is paused so result.current+ // should not advance from background ticks.+ vi.setSystemTime(new Date('2026-05-21T12:05:00Z'));++ setVisibility('visible');+ act(() => fireVisibilityChange());++ expect(result.current).toBeGreaterThan(initial);+ expect(result.current).toBe(Date.parse('2026-05-21T12:05:00Z'));+ });++ it('starts paused if the tab is already hidden at mount', () => {+ const intervalSpy = vi.spyOn(window, 'setInterval');+ setVisibility('hidden');++ renderHook(() => useTimeTick(60000));++ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 60000)).toHaveLength(0);++ intervalSpy.mockRestore();+ });++ it('shares the document visibilitychange listener with useVisibilityEvent', async () => {+ const addSpy = vi.spyOn(document, 'addEventListener');++ // Mount useTimeTick first, then a useVisibilityEvent consumer.+ renderHook(() => useTimeTick(60000));+ // Lazy import the hook here so the singleton state isn't bridged in+ // the imports at the top of the test file.+ const { useVisibilityEvent } = await import('./useVisibilityEvent');+ renderHook(() => useVisibilityEvent(() => {}));++ const visListeners = addSpy.mock.calls.filter(([type]) => type === 'visibilitychange');+ expect(visListeners).toHaveLength(1);++ addSpy.mockRestore();+ });+});diff --git a/client/src/hooks/useVisibilityEvent.js b/client/src/hooks/useVisibilityEvent.jsindex 996f6fd38c..4daa55bacc 100644--- a/client/src/hooks/useVisibilityEvent.js+++ b/client/src/hooks/useVisibilityEvent.js@@ -4,6 +4,10 @@ import { useEffect, useRef } from 'react';// `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.+//+// The non-hook `subscribeVisibility(fn)` export lets other singletons+// (e.g. useTimeTick's ticker registry) reuse this listener without paying+// for a per-component `useEffect`.const subscribers = new Set();let attached = false;@@ -25,24 +29,36 @@ const detachIfEmpty = () => {attached = false;};+/**+ * Subscribe to `document.visibilitychange` from non-hook code (other+ * singletons, services). Returns an unsubscribe function. Reuses the same+ * document-level listener as `useVisibilityEvent` so the listener count+ * stays at one regardless of how many hooks AND singletons subscribe.+ *+ * @param {(state: DocumentVisibilityState) => void} fn+ * @returns {() => void} unsubscribe+ */+export function subscribeVisibility(fn) {+ subscribers.add(fn);+ ensureAttached();+ return () => {+ subscribers.delete(fn);+ detachIfEmpty();+ };+}+/*** Subscribe to `document.visibilitychange` via a shared singleton listener.* The handler receives the new `document.visibilityState` string.*- * @param {(state: 'visible' | 'hidden') => void} handler+ * @param {(state: DocumentVisibilityState) => 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();- };+ return subscribeVisibility((state) => handlerRef.current?.(state));}, []);}