Skip to content

Self-improving AI Employees for everyone

fix(perf): tab-return unresponsiveness — passive mouseover + pause animations on hidden + immediate isReady (Waves 32 + 33)

trohitg09375e137787
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 222ded29..80361760 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -292,6 +292,41 @@ const DashboardContent: React.FC = () => {
// in lockstep with the active theme + user preference.
useSoundSync();
+ // Wave 33: pause CSS animations while the tab is in the background.
+ //
+ // Without this, browsers continue advancing CSS animation timing on
+ // hidden tabs (RAF is throttled to ~1Hz but `animation` keyframes
+ // accumulate paused frames in the compositor's queue). When the user
+ // returns, all 50+ executing nodes' three-layer box-shadow `node-pulse`
+ // animations resume simultaneously and the GPU compositor stalls for
+ // 100-200ms blending the paused frames + Cyber theme's full-viewport
+ // `cyber-flicker` / `cyber-roll` decorations. During the stall, input
+ // events queue but don't dispatch — first click on tab return appears
+ // unresponsive until the composite pass finishes (then the second
+ // click works, hence the "wakes up on interaction" pattern).
+ //
+ // Setting `animation-play-state: paused` on every element via a CSS
+ // rule keyed off `<html data-page-hidden>` flushes the queue. The
+ // requestAnimationFrame on resume defers the unpause until after the
+ // first input is ready to dispatch (one frame's delay, imperceptible).
+ useEffect(() => {
+ const handleVisibility = () => {
+ const root = document.documentElement;
+ if (document.hidden) {
+ root.setAttribute('data-page-hidden', '');
+ } else {
+ // Defer unpause to the next frame so the browser has a chance
+ // to clear the input queue before animations resume their
+ // composite work.
+ requestAnimationFrame(() => {
+ root.removeAttribute('data-page-hidden');
+ });
+ }
+ };
+ document.addEventListener('visibilitychange', handleVisibility);
+ return () => document.removeEventListener('visibilitychange', handleVisibility);
+ }, []);
+
// Context menu state for node right-click
const [contextMenu, setContextMenu] = React.useState<{
nodeId: string;
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index dee0c5e4..26ad8eb7 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -1379,13 +1379,53 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
}
}, 30000);
- // Init burst — every probe / history fetch below is independent
- // (no handler reads results from a sibling), so we run them in
- // parallel via Promise.allSettled. Time-to-isReady drops from
- // ~8 × roundtrip (serial) to one wide round-trip. Each helper
- // owns its own request_id, message handler, timeout, and state
- // write — failure in one does not abort the others.
+ // Drain any sends that were queued while the socket was reconnecting.
+ // Runs BEFORE setIsReady(true) so isReady-gated callers don't race
+ // an empty pendingRequestsRef. Mirrors socket.io-client's offline
+ // buffer + Apollo RetryLink semantics.
+ drainPendingSends(ws);
+
+ // Wave 32: flip `isReady` IMMEDIATELY on socket open + queue drain.
+ // The page-state restore (terminal / chat / console history) fires
+ // in the BACKGROUND below — its results trickle into state writes
+ // when each request settles, but UI interaction is no longer blocked
+ // behind a serial 5-up-to-25-second `Promise.allSettled` await.
+ //
+ // Why this matters: tab-blur + WS reconnect previously left the user
+ // staring at an unresponsive workflow until init-burst finished.
+ // First click "did nothing" because catalogue / nodeSpec / credentials
+ // queries gate on `isReady` and stayed disabled. The cache (warmed
+ // from localStorage via PersistQueryClientProvider for `nodeSpec` /
+ // `nodeGroups` / `pluginCatalogue` / `skillContent`) carries the
+ // visible state until refreshes land.
+ //
+ // Wave 32 also dropped the legacy hardcoded `probeApiKey` loop over
+ // `['openai', 'anthropic', 'gemini', 'google_maps', 'android_remote']`.
+ // Those probes were redundant — credential state has TWO authoritative
+ // sources already:
+ // 1. The backend's `initial_status` broadcast (handled at line ~638)
+ // pushes the full `api_keys` map on every reconnect.
+ // 2. The catalogue (TanStack Query `useCatalogueQuery`) carries the
+ // `provider.stored` flag for every provider; refetched via the
+ // debounced `invalidateCatalogue(queryClient)` helper that 8+
+ // credential CloudEvent handlers already fire (`api_key_status`,
+ // `credential_catalogue_updated`, `whatsapp_status`,
+ // `twitter_oauth_complete`, `google_oauth_complete`,
+ // `google_status`, `telegram_status`, `initial_status`).
+ // No frontend should hardcode a provider list — adding a new
+ // provider should be a backend-only edit.
+ setIsReady(true);
+
+ // Single-shot catalogue invalidate so any credential mutations that
+ // landed on the server while the socket was disconnected propagate
+ // to the in-memory cache immediately. Debounced (300ms trailing) so
+ // it coalesces with other broadcast-driven invalidations.
+ invalidateCatalogue(queryClient);
+ // Page-state restore (background). Fire-and-forget — these writes
+ // hydrate panels that PersistQueryClient doesn't cache (terminal /
+ // chat / console history come straight from the server's per-request
+ // log read, not from a query cache).
const sendBurstRequest = <T = any>(payload: object, idPrefix: string): Promise<T> =>
new Promise<T>((resolve, reject) => {
const requestId = `${idPrefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;
@@ -1407,26 +1447,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
ws.send(JSON.stringify({ ...payload, request_id: requestId }));
});
- const probeApiKey = async (provider: string) => {
- try {
- const response = await sendBurstRequest<any>(
- { type: 'get_stored_api_key', provider },
- `init_${provider}`,
- );
- if (response.hasKey) {
- // Only seed the validation cache; "is stored" lives on
- // the catalogue's `provider.stored` flag (single source).
- setApiKeyStatuses(prev => ({
- ...prev,
- [provider]: { valid: true },
- }));
- }
- } catch {
- // Ignore errors during initial check
- }
- };
-
- const loadTerminalLogs = async () => {
+ void (async () => {
try {
const terminalResponse = await sendBurstRequest<any>(
{ type: 'get_terminal_logs' },
@@ -1439,20 +1460,16 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
message: log.message || '',
source: log.source,
details: log.details,
- })).reverse(); // Server stores oldest first, we want newest first
+ })).reverse();
setTerminalLogs(logs);
}
} catch {
// Ignore errors loading terminal logs
}
- };
+ })();
- const loadChatHistory = async () => {
+ void (async () => {
try {
- // Scope to the currently-open workflow if any. session_id is
- // re-used as the workflow identifier on the chat side so the
- // panel only shows messages tied to this workflow. Falls
- // back to "default" when no workflow is selected.
const workflowId = useAppStore.getState().currentWorkflow?.id || 'default';
const chatResponse = await sendBurstRequest<any>(
{ type: 'get_chat_messages', session_id: workflowId },
@@ -1469,12 +1486,10 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
} catch {
// Ignore errors loading chat messages
}
- };
+ })();
- const loadConsoleLogs = async () => {
+ void (async () => {
try {
- // Scope to the currently-open workflow so the panel only
- // shows console output from this workflow's runs.
const consoleWorkflowId = useAppStore.getState().currentWorkflow?.id;
const consoleResponse = await sendBurstRequest<any>(
{ type: 'get_console_logs', limit: 100, workflow_id: consoleWorkflowId },
@@ -1498,27 +1513,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
} catch {
// Ignore errors loading console logs
}
- };
-
- const providers = ['openai', 'anthropic', 'gemini', 'google_maps', 'android_remote'];
- await Promise.allSettled([
- ...providers.map(probeApiKey),
- loadTerminalLogs(),
- loadChatHistory(),
- loadConsoleLogs(),
- ]);
-
- // Drain any sends that were queued while the socket was reconnecting.
- // Must run BEFORE setIsReady(true) so isReady-gated callers don't race
- // an empty pendingRequestsRef. Mirrors socket.io-client's offline buffer
- // and Apollo RetryLink semantics.
- drainPendingSends(ws);
-
- // Init burst complete — flip `isReady` so queries that gate on
- // it (catalogue, node specs, node parameters, user settings,
- // credential panels) fire once against a stable socket instead
- // of racing the serial init awaits above.
- setIsReady(true);
+ })();
};
ws.onmessage = handleMessage;
diff --git a/client/src/hooks/useSound.ts b/client/src/hooks/useSound.ts
index 184c3b71..66b39991 100644
--- a/client/src/hooks/useSound.ts
+++ b/client/src/hooks/useSound.ts
@@ -123,7 +123,21 @@ export function useSoundSync(): void {
if (related && matched.contains(related)) return;
Sounds.play('hover');
};
- document.addEventListener('mouseover', handleMouseOver, true);
+ // Wave 33: PASSIVE listener so the handler can never block scroll /
+ // input dispatch. The handler doesn't call preventDefault, so passive
+ // is safe. Bare `true` (capture-only) registers an ACTIVE listener,
+ // which means the browser must wait for the handler to finish before
+ // dispatching the next input event — on tab return, when a burst of
+ // queued mouseover events fires while the mouse is over the canvas,
+ // the active handler's closest() DOM-walks blocked first-click input
+ // dispatch by 5-15ms. Passive removes that block.
+ //
+ // removeEventListener's options bag only consults `capture` for
+ // matching (W3C spec — passive isn't part of the listener identity),
+ // so the cleanup pair below uses the same shape but TypeScript's
+ // EventListenerOptions doesn't include `passive` — pass `true` for
+ // capture-only removal which matches both add registrations.
+ document.addEventListener('mouseover', handleMouseOver, { capture: true, passive: true });
document.addEventListener('touchstart', handleHover, { capture: true, passive: true });
return () => {
document.removeEventListener('mouseover', handleMouseOver, true);
diff --git a/client/src/themes/base.css b/client/src/themes/base.css
index e2ece42a..5d2269c8 100644
--- a/client/src/themes/base.css
+++ b/client/src/themes/base.css
@@ -71,6 +71,33 @@
* → Sound effects is the user-facing audio toggle.
* ============================================================================ */
+/* ============================================================================
+ * Wave 33: pause every CSS animation when the tab is hidden.
+ *
+ * Browsers continue advancing CSS keyframe timing on background tabs (RAF
+ * is throttled to ~1Hz but `animation` keyframes still accumulate paused
+ * frames in the compositor queue). When the tab becomes visible, all
+ * paused frames flush at once — with W30's three-layer box-shadow
+ * `node-pulse` (peak `0 0 56px 16px color-mix(...)` × 3 layers) running
+ * on every executing node, plus Cyber theme's full-viewport
+ * `cyber-flicker` (5s opacity) + `cyber-roll` (8s viewport-height
+ * translateY), the GPU compositor stalls for 100-200ms. During the stall
+ * input events queue but don't dispatch — first click on tab return
+ * appears unresponsive.
+ *
+ * The Dashboard mounts a small `visibilitychange` listener that toggles
+ * this attribute on `<html>`. Setting `animation-play-state: paused`
+ * flushes the keyframe queue so resume has nothing to catch up on. The
+ * dashboard defers the unpause via `requestAnimationFrame` so input
+ * dispatch happens before composite.
+ * ============================================================================ */
+
+html[data-page-hidden] *,
+html[data-page-hidden] *::before,
+html[data-page-hidden] *::after {
+ animation-play-state: paused !important;
+}
+
@media (prefers-reduced-motion: reduce) {
/* Cyber */
:root[data-theme="cyber"] .app-frame,