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
extract useCooldownTick for the three agents-tabs rate-limit countdowns (#422)
[._.]/ Adam Eivyadc74d3b80b0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 33c5c106e3..4cc43f03d3 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.+- **[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.## Fixeddiff --git a/PLAN.md b/PLAN.mdindex cf251a5d65..a961ba4568 100644--- a/PLAN.md+++ b/PLAN.md@@ -6,7 +6,6 @@ For project goals, see [GOALS.md](./GOALS.md). For completed work, see [.changel- [ ] [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.- [ ] [dashboard-active-layout-revert-tracks-server-confirmed-id] **Active-layout revert should fall back to the last server-confirmed id, not `previousId`.** In `Dashboard.jsx#selectLayout`, two consecutive failed `setActiveDashboardLayout` PUTs revert each to their respective `previousId` snapshot — but `previousId` of the second call may be the optimistic-but-uncommitted id of the first call. So after two consecutive failures the UI snaps to a layout that never landed at the server. Mitigated in practice by single-user Tailscale deployment + write-tail serialization making double-failures rare, but worth a fix: track the last server-confirmed active id (from GET or successful PUT) and revert to that, or refetch on failure. Surfaced by codex iter-4 review during `[codex5-dashboard-intent-layouts]` claim.diff --git a/client/src/components/agents/tabs/OverviewTab.jsx b/client/src/components/agents/tabs/OverviewTab.jsxindex 3771d3f0a8..a5d7b88f56 100644--- a/client/src/components/agents/tabs/OverviewTab.jsx+++ b/client/src/components/agents/tabs/OverviewTab.jsx@@ -6,6 +6,7 @@ import * as api from '../../../services/api';import { filterSelectableModels } from '../../../utils/providers';import BrailleSpinner from '../../BrailleSpinner';import { PERSONALITY_STYLES, DEFAULT_PERSONALITY, DEFAULT_AVATAR, PLATFORM_TYPES, ACCOUNT_STATUSES } from '../constants';+import { useCooldownTick } from '../../../hooks/useCooldownTick';export default function OverviewTab({ agentId, agent, onAgentUpdate }) {const navigate = useNavigate();@@ -42,7 +43,6 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {// Cooldown timer stateconst [cooldownEnds, setCooldownEnds] = useState({});- const [, setTick] = useState(0);// Initialize form from agentuseEffect(() => {@@ -103,18 +103,30 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {const quickAccount = accounts.find(a => a.id === quickAccountId);const quickPlatform = quickAccount?.platform || 'moltbook';+ // Platform-aware rate-limit fetch — moltworld accounts have their own+ // endpoint. Used by the initial load, all four post-action refetches, and+ // the cooldown-expiry refetch so every path stays in sync with the selected+ // account's platform.+ const fetchRateLimitsForQuickAccount = useCallback(() => {+ if (!quickAccountId) return Promise.resolve(null);+ const account = accounts.find(a => a.id === quickAccountId);+ return account?.platform === 'moltworld'+ ? api.moltworldRateLimits(quickAccountId)+ : api.getAgentRateLimits(quickAccountId);+ }, [quickAccountId, accounts]);++ const refetchRateLimits = useCallback(() => {+ fetchRateLimitsForQuickAccount().then(setRateLimits).catch(() => {});+ }, [fetchRateLimitsForQuickAccount]);+// Load rate limits when quick account changesuseEffect(() => {if (!quickAccountId) {setRateLimits(null);return;}- const account = accounts.find(a => a.id === quickAccountId);- const endpoint = account?.platform === 'moltworld'- ? api.moltworldRateLimits(quickAccountId)- : api.getAgentRateLimits(quickAccountId);- endpoint.then(setRateLimits).catch(() => {});- }, [quickAccountId, accounts]);+ refetchRateLimits();+ }, [quickAccountId, refetchRateLimits]);// Calculate cooldown end timestamps from rate limit datauseEffect(() => {@@ -129,23 +141,7 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {setCooldownEnds(ends);}, [rateLimits]);- // Tick cooldown timer every second while any cooldown is active- useEffect(() => {- const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());- if (!hasActive) return;- let refetched = false;- const interval = setInterval(() => {- const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());- setTick(t => t + 1);- if (!stillActive && !refetched) {- refetched = true;- if (quickAccountId) {- api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});- }- }- }, 1000);- return () => clearInterval(interval);- }, [cooldownEnds, quickAccountId]);+ useCooldownTick({ cooldownEnds, onAllExpired: refetchRateLimits });const getModelsForProvider = (providerId) => {const p = providers.find(pr => pr.id === providerId);@@ -198,7 +194,7 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {const result = await api.engageAgent(agentId, quickAccountId, 1, 3);setEngaging(false);toast.success(`Engaged: ${result.votes?.length || 0} votes, ${result.comments?.length || 0} comments`);- api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ refetchRateLimits();};const handleCheckPosts = async () => {@@ -208,7 +204,7 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {setChecking(false);if (!result) return;toast.success(`Checked ${result.postsChecked} posts: ${result.engagement?.upvoted?.length || 0} upvotes, ${result.engagement?.replied?.length || 0} replies`);- api.getAgentRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ refetchRateLimits();};// Moltworld quick actions@@ -219,14 +215,14 @@ export default function OverviewTab({ agentId, agent, onAgentUpdate }) {setExploring(false);if (!result) return;toast.success(`Explored (${result.x}, ${result.y}) — ${result.nearby || 0} agents nearby`);- api.moltworldRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ refetchRateLimits();};const handleBuild = async () => {if (!agentId || !quickAccountId) return;const result = await api.moltworldBuild(quickAccountId, agentId, 0, 0, 0, 'stone', 'place').catch(() => null);if (result) toast.success('Block placed');- api.moltworldRateLimits(quickAccountId).then(setRateLimits).catch(() => {});+ refetchRateLimits();};// Account handlersdiff --git a/client/src/components/agents/tabs/ToolsTab.jsx b/client/src/components/agents/tabs/ToolsTab.jsxindex d6cf9f5823..0b4db79870 100644--- a/client/src/components/agents/tabs/ToolsTab.jsx+++ b/client/src/components/agents/tabs/ToolsTab.jsx@@ -2,6 +2,7 @@ import { useState, useEffect, useCallback } from 'react';import toast from '../../ui/Toast';import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';+import { useCooldownTick } from '../../../hooks/useCooldownTick';export default function ToolsTab({ agentId, agent }) {const [selectedAccountId, setSelectedAccountId] = useState('');@@ -44,7 +45,6 @@ export default function ToolsTab({ agentId, agent }) {// Cooldown timer stateconst [cooldownEnds, setCooldownEnds] = useState({});- const [, setTick] = useState(0);// Auto-resolve the moltbook account for this agentuseEffect(() => {@@ -84,23 +84,14 @@ export default function ToolsTab({ agentId, agent }) {setCooldownEnds(ends);}, [rateLimits]);- // Tick cooldown timer every second while any cooldown is active- useEffect(() => {- const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());- if (!hasActive) return;- let refetched = false;- const interval = setInterval(() => {- const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());- setTick(t => t + 1);- if (!stillActive && !refetched) {- refetched = true;- if (selectedAccountId) {- api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});- }+ useCooldownTick({+ cooldownEnds,+ onAllExpired: () => {+ if (selectedAccountId) {+ api.getAgentRateLimits(selectedAccountId).then(setRateLimits).catch(() => {});}- }, 1000);- return () => clearInterval(interval);- }, [cooldownEnds, selectedAccountId]);+ },+ });const loadDrafts = useCallback(async () => {if (!agentId) return;diff --git a/client/src/components/agents/tabs/WorldTab.jsx b/client/src/components/agents/tabs/WorldTab.jsxindex 0d6b651c30..cbcf685c28 100644--- a/client/src/components/agents/tabs/WorldTab.jsx+++ b/client/src/components/agents/tabs/WorldTab.jsx@@ -4,6 +4,7 @@ import * as api from '../../../services/api';import BrailleSpinner from '../../BrailleSpinner';import socket from '../../../services/socket';import useMoltworldWs from '../../../hooks/useMoltworldWs';+import { useCooldownTick } from '../../../hooks/useCooldownTick';import { timeAgo } from '../../../utils/formatters';const EVENT_ICONS = {@@ -113,7 +114,6 @@ export default function WorldTab({ agentId }) {// Cooldown timer stateconst [cooldownEnds, setCooldownEnds] = useState({});- const [, setTick] = useState(0);// Activity History stateconst [history, setHistory] = useState([]);@@ -237,21 +237,7 @@ export default function WorldTab({ agentId }) {setCooldownEnds(ends);}, [rateLimits]);- // Tick cooldown timer every second while any cooldown is active- useEffect(() => {- const hasActive = Object.values(cooldownEnds).some(end => end > Date.now());- if (!hasActive) return;- let refetched = false;- const interval = setInterval(() => {- const stillActive = Object.values(cooldownEnds).some(end => end > Date.now());- setTick(t => t + 1);- if (!stillActive && !refetched) {- refetched = true;- fetchRateLimits();- }- }, 1000);- return () => clearInterval(interval);- }, [cooldownEnds, fetchRateLimits]);+ useCooldownTick({ cooldownEnds, onAllExpired: fetchRateLimits });const updateFromJoinResponse = (result) => {if (result?.agents) setNearby(result.agents);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex b9739b8a0a..985ecd2b48 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -66,6 +66,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `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. |+| `useCooldownTick` | 1-second ticker over a `{ id: epochMs }` cooldown map; fires `onAllExpired` once when every deadline passes. | Rate-limit countdown labels that need to refetch when the last cooldown clears (agents tabs pattern). || `useFieldDraft` | Local input draft that commits on blur. | Bible-editor-style single-field input that must dedupe sibling races. || `useRowDraft` | Multi-column row draft (analogue of `useFieldDraft`). | Multi-column row that commits as a unit. || `usePendingListRows` | List-of-rows where a new row is held client-side until a required column fills, then promoted to `onChange`. | Editable list whose nameless rows would otherwise be dropped by the server sanitizer (WardrobeSection, CharacterDetailEditor list sections). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex fe44c85cd9..c6408f4331 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -61,6 +61,7 @@ export * from './useVisibilityEvent.js';export * from './useArmedAction.js';export * from './useAutoRefetch.js';export * from './useCmdKSearch.js';+export * from './useCooldownTick.js';export * from './useKeyboardHelp.js';export * from './useLockToggle.js';export * from './useScrollLock.js';diff --git a/client/src/hooks/useCooldownTick.js b/client/src/hooks/useCooldownTick.jsnew file mode 100644index 0000000000..815828cc37--- /dev/null+++ b/client/src/hooks/useCooldownTick.js@@ -0,0 +1,54 @@+import { useRef, useState, useEffect } from 'react';++// Shared 1-second cooldown ticker for the agents tabs. Three near-identical+// implementations (`OverviewTab`, `ToolsTab`, `WorldTab`) each ran their own+// `setInterval` that bumped a local `tick` so countdown labels re-rendered and+// fired a refetch once every cooldown expired. Collapsed into one hook.+//+// `cooldownEnds` is a `{ [actionId]: epochMillis }` map; the interval only runs+// while at least one entry is still in the future. `onAllExpired` fires once,+// the first tick after every entry crosses the deadline, and the interval is+// cleared at that same tick so a missing/no-op callback can't leave us spinning+// forever. When the caller's expiry handler swaps in a fresh `cooldownEnds`+// (new ref, new deadlines), the effect re-runs and a new interval starts.+// Latest-callback is kept in a ref so consumers don't have to memoize it — the+// interval's lifecycle is driven by `cooldownEnds` alone, matching the+// originals where the surrounding account/refetch dep only affected the+// *closure*, not the timer's start/stop.+export function useCooldownTick(options = {}) {+ const { cooldownEnds = {}, onAllExpired } = options;+ const [, setTick] = useState(0);+ // Update the ref during render (not in a useEffect) so the latest callback+ // is always visible to the interval tick — a useEffect-driven ref update+ // can lag one render behind and, if `onAllExpired` changes right before+ // the expiry tick, the interval would fire the previous closure once.+ // Pattern mirrored from usePostSession.js / useCityAudio.js.+ const callbackRef = useRef(onAllExpired);+ callbackRef.current = onAllExpired;++ useEffect(() => {+ const hasActive = Object.values(cooldownEnds).some((end) => end > Date.now());+ if (!hasActive) return;+ let interval = null;+ const stop = () => {+ if (interval !== null) {+ clearInterval(interval);+ interval = null;+ }+ };+ interval = setInterval(() => {+ const stillActive = Object.values(cooldownEnds).some((end) => end > Date.now());+ setTick((t) => t + 1);+ if (!stillActive) {+ // Fire the one-shot expiry signal and stop ticking. If the caller's+ // handler refetches and produces a fresh `cooldownEnds` (different ref+ // with new deadlines), the effect re-runs and a new interval starts.+ // If it doesn't (handler omitted, network error, no new cooldowns),+ // we don't spin forever re-rendering for no reason.+ stop();+ callbackRef.current?.();+ }+ }, 1000);+ return stop;+ }, [cooldownEnds]);+}diff --git a/client/src/hooks/useCooldownTick.test.jsx b/client/src/hooks/useCooldownTick.test.jsxnew file mode 100644index 0000000000..cc5a6bc137--- /dev/null+++ b/client/src/hooks/useCooldownTick.test.jsx@@ -0,0 +1,130 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import { useCooldownTick } from './useCooldownTick';++describe('useCooldownTick', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it('does not start an interval when no cooldowns are active', () => {+ const onAllExpired = vi.fn();+ renderHook(() => useCooldownTick({ cooldownEnds: {}, onAllExpired }));++ act(() => vi.advanceTimersByTime(5_000));+ expect(onAllExpired).not.toHaveBeenCalled();+ });++ it('treats already-elapsed deadlines as no active cooldown', () => {+ const onAllExpired = vi.fn();+ const past = Date.now() - 1_000;+ renderHook(() => useCooldownTick({ cooldownEnds: { x: past }, onAllExpired }));++ act(() => vi.advanceTimersByTime(5_000));+ expect(onAllExpired).not.toHaveBeenCalled();+ });++ it('fires onAllExpired exactly once when every cooldown crosses its deadline', () => {+ const onAllExpired = vi.fn();+ const now = Date.now();+ renderHook(() => useCooldownTick({+ cooldownEnds: { a: now + 2_500, b: now + 1_500 },+ onAllExpired,+ }));++ act(() => vi.advanceTimersByTime(1_000));+ expect(onAllExpired).not.toHaveBeenCalled();++ act(() => vi.advanceTimersByTime(2_000));+ expect(onAllExpired).toHaveBeenCalledTimes(1);++ act(() => vi.advanceTimersByTime(5_000));+ expect(onAllExpired).toHaveBeenCalledTimes(1);+ });++ it('reads the latest onAllExpired closure when it fires', () => {+ const first = vi.fn();+ const second = vi.fn();+ const now = Date.now();+ const props = { cooldownEnds: { a: now + 2_000 }, onAllExpired: first };+ const { rerender } = renderHook((p) => useCooldownTick(p), { initialProps: props });++ rerender({ ...props, onAllExpired: second });++ act(() => vi.advanceTimersByTime(3_000));+ expect(first).not.toHaveBeenCalled();+ expect(second).toHaveBeenCalledTimes(1);+ });++ it('clears the interval on unmount', () => {+ const onAllExpired = vi.fn();+ const now = Date.now();+ const { unmount } = renderHook(() => useCooldownTick({+ cooldownEnds: { a: now + 3_000 },+ onAllExpired,+ }));++ unmount();+ act(() => vi.advanceTimersByTime(5_000));+ expect(onAllExpired).not.toHaveBeenCalled();+ });++ it('restarts the interval when cooldownEnds gains a new active entry', () => {+ const onAllExpired = vi.fn();+ const { rerender } = renderHook(+ (p) => useCooldownTick(p),+ { initialProps: { cooldownEnds: {}, onAllExpired } },+ );++ act(() => vi.advanceTimersByTime(2_000));+ expect(onAllExpired).not.toHaveBeenCalled();++ rerender({ cooldownEnds: { a: Date.now() + 1_500 }, onAllExpired });+ act(() => vi.advanceTimersByTime(2_000));+ expect(onAllExpired).toHaveBeenCalledTimes(1);+ });++ it('does not crash when onAllExpired is omitted', () => {+ renderHook(() => useCooldownTick({ cooldownEnds: { a: Date.now() + 1_000 } }));++ expect(() => act(() => vi.advanceTimersByTime(2_000))).not.toThrow();+ });++ it('does not crash when called with no options (defaults to no active cooldowns)', () => {+ // Regression guard: useCooldownTick() used to destructure required+ // fields and throw before React could surface the misuse. The hook+ // now defaults `options` to `{}` and `cooldownEnds` to `{}`, so a+ // missing-args call is harmless — same steady state as "no active+ // cooldowns" (no interval armed, callback never fires).+ expect(() => renderHook(() => useCooldownTick())).not.toThrow();+ expect(vi.getTimerCount()).toBe(0);+ });++ it('clears the interval after the expiry tick even if the caller never updates cooldownEnds', () => {+ // Regression guard for Copilot review on PR #422: a no-op onAllExpired+ // (or a network error in the caller) must not leave the 1s interval+ // re-rendering forever after the deadline passes. Callers in+ // OverviewTab/ToolsTab/WorldTab hold `cooldownEnds` in useState so the+ // reference is stable across the internal `setTick` re-renders; the+ // expected steady state after expiry is "no live timers."+ const onAllExpired = vi.fn();+ const cooldownEnds = { a: Date.now() + 1_500 };+ renderHook(() => useCooldownTick({ cooldownEnds, onAllExpired }));++ expect(vi.getTimerCount()).toBe(1);++ act(() => vi.advanceTimersByTime(2_000));+ expect(onAllExpired).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);++ // Advance well past any further 1s tick — no second interval armed,+ // callback stays at 1.+ act(() => vi.advanceTimersByTime(30_000));+ expect(onAllExpired).toHaveBeenCalledTimes(1);+ expect(vi.getTimerCount()).toBe(0);+ });+});