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([issue-705]): coalesce CyberCity socket-driven refetch bursts (roadmap 3.8)
[._.]/ Adam Eivy92576d768500
diff --git a/client/src/hooks/useCityData.js b/client/src/hooks/useCityData.jsindex 9fcb53ba55..6d58139d2d 100644--- a/client/src/hooks/useCityData.js+++ b/client/src/hooks/useCityData.js@@ -4,6 +4,7 @@ import socket from '../services/socket';import { useAutoRefetch } from './useAutoRefetch';import { METRICS as HEALTH_TOWER_METRICS } from '../utils/cityHealthTower';import { applyAiStatusEvent } from '../utils/cityAiCore';+import { coalesce } from '../utils/coalesce';// Metric keys the vitals-tower landmark renders — fetched as the latest-value snapshot.const HEALTH_METRIC_KEYS = HEALTH_TOWER_METRICS.map(m => m.key);@@ -153,6 +154,12 @@ export const useCityData = () => {return map;}, [apps, cosAgents]);+ // CoS agent spawn/complete events arrive in bursts (a wave of agents starting fires+ // several within milliseconds), and each one triggers a full `fetchAll`. Coalesce those+ // socket-driven refreshes into a single trailing refetch (~120ms) so a burst costs one+ // round of requests instead of N. The mount fetch below stays immediate.+ const coalescedFetchAll = useMemo(() => coalesce(fetchAll, 120), [fetchAll]);+useEffect(() => {fetchAll();@@ -168,7 +175,7 @@ export const useCityData = () => {const handleAgentSpawned = (data) => {setCosAgents(prev => [...prev, data]);- fetchAll();+ coalescedFetchAll();};socket.on('cos:agent:spawned', handleAgentSpawned);@@ -178,7 +185,7 @@ export const useCityData = () => {socket.on('cos:agent:updated', handleAgentUpdated);const handleAgentCompleted = () => {- fetchAll();+ coalescedFetchAll();};socket.on('cos:agent:completed', handleAgentCompleted);@@ -272,8 +279,9 @@ export const useCityData = () => {socket.off('voice:error', handleVoiceError);socket.off('voice:idle', handleVoiceIdle);socket.off('ai:status', handleAiStatus);+ coalescedFetchAll.cancel(); // drop any pending trailing refetch on unmount};- }, [fetchAll, fetchApps, fetchBackup]);+ }, [fetchAll, fetchApps, fetchBackup, coalescedFetchAll]);return {apps,diff --git a/client/src/utils/coalesce.js b/client/src/utils/coalesce.jsnew file mode 100644index 0000000000..50d9c001d6--- /dev/null+++ b/client/src/utils/coalesce.js@@ -0,0 +1,29 @@+// Collapse a burst of rapid calls into a single trailing invocation on a short tick.+// CyberCity subscribes to many socket events (CoS agent spawn/complete, AI status, task+// changes, …); when several fire at once — e.g. a wave of agents spawning — a handler that+// triggers a full refetch per event would fan out N identical refreshes. Wrapping that+// handler in `coalesce` runs it once on the trailing edge instead.+//+// Trailing-edge by design: the LAST call's effect always runs, so state still converges to+// the freshest value — only the redundant intermediate calls are dropped. Call `.cancel()`+// on teardown so a pending flush can't fire after unmount.+export function coalesce(fn, waitMs = 100) {+ let timer = null;+ let lastArgs = [];+ const wrapped = (...args) => {+ lastArgs = args;+ if (timer) clearTimeout(timer);+ timer = setTimeout(() => {+ timer = null;+ fn(...lastArgs);+ }, waitMs);+ };+ wrapped.cancel = () => {+ if (timer) {+ clearTimeout(timer);+ timer = null;+ }+ };+ wrapped.pending = () => timer !== null;+ return wrapped;+}diff --git a/client/src/utils/coalesce.test.js b/client/src/utils/coalesce.test.jsnew file mode 100644index 0000000000..be6f76461a--- /dev/null+++ b/client/src/utils/coalesce.test.js@@ -0,0 +1,74 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { coalesce } from './coalesce';++beforeEach(() => vi.useFakeTimers());+afterEach(() => vi.useRealTimers());++describe('coalesce', () => {+ it('runs once on the trailing edge for a burst of calls', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ c(); c(); c();+ expect(fn).not.toHaveBeenCalled(); // nothing fires synchronously+ vi.advanceTimersByTime(100);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('passes the LAST call\'s arguments through', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ c('a'); c('b'); c('c');+ vi.advanceTimersByTime(100);+ expect(fn).toHaveBeenCalledWith('c');+ });++ it('fires again for a new burst after the window elapses', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ c();+ vi.advanceTimersByTime(100);+ c();+ vi.advanceTimersByTime(100);+ expect(fn).toHaveBeenCalledTimes(2);+ });++ it('each call within the window resets the timer (debounce semantics)', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ c();+ vi.advanceTimersByTime(80);+ c(); // resets — should not fire at the original 100ms mark+ vi.advanceTimersByTime(80);+ expect(fn).not.toHaveBeenCalled();+ vi.advanceTimersByTime(20);+ expect(fn).toHaveBeenCalledTimes(1);+ });++ it('cancel() prevents a pending flush from firing', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ c();+ expect(c.pending()).toBe(true);+ c.cancel();+ expect(c.pending()).toBe(false);+ vi.advanceTimersByTime(200);+ expect(fn).not.toHaveBeenCalled();+ });++ it('cancel() is a no-op when nothing is pending', () => {+ const fn = vi.fn();+ const c = coalesce(fn, 100);+ expect(() => c.cancel()).not.toThrow();+ expect(c.pending()).toBe(false);+ });++ it('defaults to a 100ms window', () => {+ const fn = vi.fn();+ const c = coalesce(fn);+ c();+ vi.advanceTimersByTime(99);+ expect(fn).not.toHaveBeenCalled();+ vi.advanceTimersByTime(1);+ expect(fn).toHaveBeenCalledTimes(1);+ });+});