Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
perf: drive the agent card's elapsed clock from the shared ticker
[._.]/ Adam Eivyf0382446399f
diff --git a/client/src/components/cos/tabs/AgentCard.jsx b/client/src/components/cos/tabs/AgentCard.jsxindex 891249af66..53d1d33735 100644--- a/client/src/components/cos/tabs/AgentCard.jsx+++ b/client/src/components/cos/tabs/AgentCard.jsx@@ -37,6 +37,7 @@ import AuditSourceEvidence from '../AuditSourceEvidence';import { DEFAULT_REVIEWER, normalizeReviewers } from '../constants';import { formatBytes, formatCount, formatDurationMs, formatDateTime, formatTimeOfDay, shortClaudeModelName } from '../../../utils/formatters';import { useSocketResource } from '../../../hooks/useSocketResource';+import { useTimeTick } from '../../../hooks/useTimeTick';import ConfirmButtonPair from '../../ui/ConfirmButtonPair';import { useConfirmDelete } from '../../../hooks/useConfirmDelete';@@ -406,7 +407,6 @@ function GoalFidelityFollowUp({ followUp }) {export default function AgentCard({ agent, onPause, onKill, onDelete, onResume, onRelaunch, completed, paused = false, liveOutput, durations, onFeedbackChange, remote, peerName, initiallyExpanded = false }) {const [expanded, setExpanded] = useState(initiallyExpanded);const [transcriptExpanded, setTranscriptExpanded] = useState(false);- const [now, setNow] = useState(Date.now());// Every surface of this card that renders the agent's own prose resolves a// bare `#7640` against the run's tracker through the one resolver.const linkifyIssues = useMemo(() => agentIssueLinkifier(agent), [agent]);@@ -512,12 +512,10 @@ export default function AgentCard({ agent, onPause, onKill, onDelete, onResume,}}, [agent.id, btwInput, sendingBtw]);- // Update duration display for running agents- useEffect(() => {- if (inactive) return;- const interval = setInterval(() => setNow(Date.now()), 1000);- return () => clearInterval(interval);- }, [inactive]);+ // The elapsed-time display shares the app-wide one-second ticker (one timer+ // for N running cards, paused in a hidden tab) and unsubscribes once the run+ // is finished or paused, where the duration no longer moves.+ const now = useTimeTick(1000, { enabled: !inactive });// Read only for an expanded, active local agent. The resource key discards// in-flight responses after collapsing, switching agents, or going inactive.diff --git a/client/src/components/cos/tabs/AgentCard.test.jsx b/client/src/components/cos/tabs/AgentCard.test.jsxindex 711853cf0d..4d7649a80d 100644--- a/client/src/components/cos/tabs/AgentCard.test.jsx+++ b/client/src/components/cos/tabs/AgentCard.test.jsx@@ -104,6 +104,34 @@ describe('AgentCard runtime presentation', () => {expect(screen.queryByText(/left$/)).not.toBeInTheDocument();});+ // Running cards share the app-wide one-second ticker (#12031): N cards cost+ // one timer, and a finished card costs none.+ it('advances the elapsed time of running cards from one shared ticker and none for finished ones', () => {+ vi.useFakeTimers();+ vi.setSystemTime(now);+ const intervalSpy = vi.spyOn(window, 'setInterval');++ render(+ <MemoryRouter>+ <AgentCard agent={runningAt(30_000)} />+ <AgentCard agent={{ ...runningAt(45_000), id: 'agent-two' }} />+ <AgentCard agent={agent} completed />+ </MemoryRouter>+ );+ expect(screen.getByText('30s')).toBeInTheDocument();+ expect(screen.getByText('45s')).toBeInTheDocument();+ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 1000)).toHaveLength(1);++ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(screen.getByText('31s')).toBeInTheDocument();+ expect(screen.getByText('46s')).toBeInTheDocument();+ expect(screen.getByText('1h 0m')).toBeInTheDocument();++ intervalSpy.mockRestore();+ });+// The run this card is for, and the execution-scoped history that describes it// (#8001). Same task type as `durationHistory` above, but four times slower —// so a card that fell back to the task-type average would show the wrong ETA.diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 7bcbf630d5..f043125976 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -110,7 +110,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `usePortosRestartWatch` | Watches PortOS restarting ITSELF and reloads the page once it answers again: arms on the update stream's restart step, on `portos:update:complete`, or on a socket disconnect confirmed unreachable, then polls `/api/system/health` for a version change, a down→up dip, or an uptime reset. `update.sh` pm2-deletes the server mid-run, so there is no completion event to await. | Only a surface that launches a PortOS self-update WITHOUT going through an app operation — today just the Update page. `useAppOperation` already wires it, so App Management surfaces read `restarting` from there instead. || `usePrevious` | Returns the value from the previous render — snapshot updated in a `useEffect`. | Compare-and-act on prop/state change from inside a `useEffect`. || `usePreviousSync` | Same shape, but snapshot updated *during* render. | The prior value gates an in-render `setState` (React's "adjusting state on prop change" pattern); the during-render update avoids an extra discard/rerun cycle. |-| `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. |+| `useTimeTick` | Singleton-backed wall-clock tick (`Date.now()`); N subscribers at the same cadence share one `setInterval`; `{ enabled: false }` unsubscribes a counter whose subject has stopped. | 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/useTimeTick.js b/client/src/hooks/useTimeTick.jsindex 806f421737..f410d3aaed 100644--- a/client/src/hooks/useTimeTick.js+++ b/client/src/hooks/useTimeTick.js@@ -86,13 +86,17 @@ const releaseVisibilityIfIdle = () => {* @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.+ * @param {{ enabled?: boolean }} [options] - `enabled: false` leaves the+ * ticker unsubscribed (the returned snapshot freezes at its last value), for+ * a counter that only runs while its subject does, e.g. a finished agent's+ * card. Hooks cannot be called conditionally, so the gate lives here.* @returns {number} the latest `Date.now()` snapshot at the most recent tick.*/-export function useTimeTick(intervalMs = 60000) {+export function useTimeTick(intervalMs = 60000, { enabled = true } = {}) {const [now, setNow] = useState(() => Date.now());useEffect(() => {- if (typeof window === 'undefined') return undefined;+ if (typeof window === 'undefined' || !enabled) return undefined;let entry = tickers.get(intervalMs);if (!entry) entry = startTicker(intervalMs);entry.subscribers.add(setNow);@@ -105,7 +109,7 @@ export function useTimeTick(intervalMs = 60000) {releaseVisibilityIfIdle();}};- }, [intervalMs]);+ }, [intervalMs, enabled]);return now;}diff --git a/client/src/hooks/useTimeTick.test.jsx b/client/src/hooks/useTimeTick.test.jsxindex 917c62ddc2..089bf1ebfb 100644--- a/client/src/hooks/useTimeTick.test.jsx+++ b/client/src/hooks/useTimeTick.test.jsx@@ -44,6 +44,35 @@ describe('useTimeTick', () => {expect(result.current).toBe(initial + 60000);});+ it('does not subscribe while disabled and resumes ticking once enabled', () => {+ vi.setSystemTime(new Date('2026-05-21T12:00:00Z'));+ const intervalSpy = vi.spyOn(window, 'setInterval');+ const { result, rerender } = renderHook(({ enabled }) => useTimeTick(1000, { enabled }), {+ initialProps: { enabled: false },+ });+ const initial = result.current;++ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(intervalSpy.mock.calls.filter(([, ms]) => ms === 1000)).toHaveLength(0);+ expect(result.current).toBe(initial);++ rerender({ enabled: true });+ act(() => {+ vi.advanceTimersByTime(1000);+ });+ expect(result.current).toBe(initial + 6000);++ rerender({ enabled: false });+ act(() => {+ vi.advanceTimersByTime(5000);+ });+ expect(result.current).toBe(initial + 6000);++ intervalSpy.mockRestore();+ });+it('subscribers at the same intervalMs share one underlying setInterval', () => {const intervalSpy = vi.spyOn(window, 'setInterval');diff --git a/client/src/pollingConventions.test.js b/client/src/pollingConventions.test.jsindex 97d16e28b3..421b9b0c58 100644--- a/client/src/pollingConventions.test.js+++ b/client/src/pollingConventions.test.js@@ -64,7 +64,6 @@ const TIMER_CALL = /\bsetInterval\s*\(/;const ALLOWED = {'src/components/BrailleSpinner.jsx': 'advances the spinner glyph; no I/O','src/components/calendar/DayView.jsx': 'moves the "now" line down the day grid; no I/O',- 'src/components/cos/tabs/AgentCard.jsx': 'elapsed-time clock tick (the card polls stats via useAutoRefetch)','src/components/meatspace/post/PostDrillRunner.jsx': 'drill countdown timer; no I/O','src/components/meatspace/post/PostLlmDrillRunner.jsx': 'drill countdown timer; no I/O','src/components/meatspace/post/WordplayDrillUI.jsx': 'elapsed-time clock tick; no I/O',