Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
perf(ws): memoize provider value, move nodeStatuses to Zustand, split isOpen/isReady, reject pending on close (Phase 2)
trohitg918f3c39189d
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 69dbcd97..77f8bb32 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -18,6 +18,11 @@ import { queryClient } from '../lib/queryClient';import { queryKeys } from '../lib/queryConfig';import { CATALOGUE_QUERY_KEY } from '../hooks/useCatalogueQuery';import { nodeParamsQueryKey } from '../hooks/useNodeParamsQuery';+import {+ useNodeStatusStore,+ useNodeStatusForId,+ useCurrentWorkflowStatuses,+} from '../stores/nodeStatusStore';// Generate unique request IDconst generateRequestId = (): string => {@@ -244,6 +249,13 @@ export interface FullStatus {interface WebSocketContextValue {// Connection stateisConnected: boolean;+ /**+ * `true` once the socket is open AND the post-open init burst has+ * settled (api-key probes, terminal/chat/console history). Queries+ * that depend on backend-served data should gate on this rather+ * than `isConnected` so they fire once instead of racing the burst.+ */+ isReady: boolean;reconnecting: boolean;// Status data@@ -429,6 +441,14 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiconst currentWorkflowId = currentWorkflow?.id;const [isConnected, setIsConnected] = useState(false);+ // `isReady` flips true only AFTER the init burst inside `ws.onopen`+ // completes (api-key probes, terminal/chat/console history). Queries+ // that depend on backend-served catalogue data (NodeSpec catalogue,+ // node groups, node parameters, user settings, credential panels)+ // gate on `isReady` instead of `isConnected` so they fire once,+ // post-burst, instead of racing the serial awaits and arriving in+ // arbitrary order.+ const [isReady, setIsReady] = useState(false);const [reconnecting, setReconnecting] = useState(false);const [androidStatus, setAndroidStatus] = useState<AndroidStatus>(defaultAndroidStatus);const [whatsappStatus, setWhatsappStatus] = useState<WhatsAppStatus>(defaultWhatsAppStatus);@@ -441,8 +461,12 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiconst [consoleLogs, setConsoleLogs] = useState<ConsoleLogEntry[]>([]);const [terminalLogs, setTerminalLogs] = useState<TerminalLogEntry[]>([]);const [chatMessages, setChatMessages] = useState<ChatMessage[]>([]);- // Per-workflow node statuses: workflow_id -> node_id -> NodeStatus (n8n pattern)- const [allNodeStatuses, setAllNodeStatuses] = useState<Record<string, Record<string, NodeStatus>>>({});+ // Per-workflow node statuses live in a dedicated Zustand store+ // (`stores/nodeStatusStore.ts`). The store is built on+ // useSyncExternalStore so consumers can subscribe to a single+ // node's slot without re-rendering on unrelated status updates.+ // The derived `nodeStatuses` and `getNodeStatus` exposed below read+ // through to the store for backward compatibility.const [nodeParameters, setNodeParameters] = useState<Record<string, NodeParameters>>({});// Per-workflow variables: workflow_id -> variable_name -> value (n8n pattern)const [allVariables, setAllVariables] = useState<Record<string, Record<string, any>>>({});@@ -464,6 +488,9 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiuseEffect(() => {const previousWorkflowId = currentWorkflowIdRef.current;currentWorkflowIdRef.current = currentWorkflowId;+ // Mirror into the node-status store so its slice selectors stay+ // scoped to the same workflow as the rest of the app.+ useNodeStatusStore.getState().setCurrentWorkflowId(currentWorkflowId);// No need to clear node statuses - they are now stored per-workflow (n8n pattern)// Each workflow's statuses are isolated in allNodeStatuses[workflow_id]@@ -569,7 +596,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiif (!groupedStatuses[wfId]) groupedStatuses[wfId] = {};groupedStatuses[wfId][nodeId] = nodeStatus;}- setAllNodeStatuses(prev => ({ ...prev, ...groupedStatuses }));+ useNodeStatusStore.getState().mergeStatuses(groupedStatuses);}if (data.node_parameters) {setNodeParameters(data.node_parameters);@@ -731,13 +758,11 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Flatten the structure: merge inner data with outer data for easier accessconst flattenedData = { ...data, ...innerData, workflow_id: statusWorkflowId };- setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => ({- ...prev,- [statusWorkflowId]: {- ...(prev[statusWorkflowId] || {}),- [node_id]: flattenedData- }- }));+ useNodeStatusStore.getState().setStatus(+ statusWorkflowId,+ node_id,+ flattenedData,+ );}break;@@ -745,17 +770,14 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Per-workflow node output storage (n8n pattern)if (node_id) {const outputWorkflowId = message.workflow_id || 'unknown';- setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => ({- ...prev,- [outputWorkflowId]: {- ...(prev[outputWorkflowId] || {}),- [node_id]: {- ...(prev[outputWorkflowId]?.[node_id] || {}),- output,- workflow_id: outputWorkflowId- }- }- }));+ const store = useNodeStatusStore.getState();+ const previous =+ store.allStatuses[outputWorkflowId]?.[node_id] || ({} as NodeStatus);+ store.setStatus(outputWorkflowId, node_id, {+ ...previous,+ output,+ workflow_id: outputWorkflowId,+ });}break;@@ -764,22 +786,15 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiif (node_id || message.node_id) {const clearedNodeId = node_id || message.node_id;const clearWorkflowId = message.workflow_id;- setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => {- // If workflow_id specified, only clear from that workflow- if (clearWorkflowId && prev[clearWorkflowId]) {- const workflowStatuses = { ...prev[clearWorkflowId] };- delete workflowStatuses[clearedNodeId];- return { ...prev, [clearWorkflowId]: workflowStatuses };- }- // Otherwise clear from all workflows- const newStatuses: Record<string, Record<string, NodeStatus>> = {};- for (const [wfId, nodes] of Object.entries(prev)) {- const filteredNodes = { ...nodes };- delete filteredNodes[clearedNodeId];- newStatuses[wfId] = filteredNodes;+ const store = useNodeStatusStore.getState();+ if (clearWorkflowId) {+ store.clearStatus(clearWorkflowId, clearedNodeId);+ } else {+ // Clear from every workflow's slot+ for (const wfId of Object.keys(store.allStatuses)) {+ store.clearStatus(wfId, clearedNodeId);}- return newStatuses;- });+ }}break;@@ -1101,13 +1116,13 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chisetIsConnected(true);setReconnecting(false);- // Reconnect invalidation (TkDodo / tRPC wsLink pattern):- // any WS-backed TanStack query should refetch after a drop so- // state can't silently diverge from the server. Node specs and- // group metadata are keyed explicitly; other WS-backed queries- // can opt in by sharing these key prefixes.- queryClient.invalidateQueries({ queryKey: ['nodeSpec'] });- queryClient.invalidateQueries({ queryKey: ['nodeGroups'] });+ // NodeSpec + NodeGroups are immutable for the life of a page —+ // they only change on a backend redeploy, and a redeploy+ // bumps the build version which busts the persisted cache on+ // the next hard refresh (see lib/queryPersist.ts). Reconnects+ // alone (transient network drops, server restarts mid-deploy)+ // do not invalidate them, so canvas / palette icons no longer+ // flash back to fallback on every reconnect.// Start ping intervalpingIntervalRef.current = setInterval(() => {@@ -1258,6 +1273,12 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi} catch {// Ignore errors loading console logs}++ // 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;@@ -1265,8 +1286,26 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiws.onclose = (event) => {console.log('[WebSocket] Disconnected:', event.code, event.reason);setIsConnected(false);+ setIsReady(false);wsRef.current = null;+ // Reject every in-flight request so TanStack Query's retry ++ // any awaiters fail fast on the dead socket instead of waiting+ // for the 30s REQUEST_TIMEOUT. Trigger-node waiters that deliberately+ // had no timeout are still cleared — the next reconnect will+ // re-register them when the user re-runs the trigger.+ if (pendingRequestsRef.current.size > 0) {+ for (const [, pending] of pendingRequestsRef.current) {+ if (pending.timeout) clearTimeout(pending.timeout);+ try {+ pending.reject(new Error('WebSocket closed'));+ } catch {+ // Ignore — caller may have already settled.+ }+ }+ pendingRequestsRef.current.clear();+ }+// Clear ping intervalif (pingIntervalRef.current) {clearInterval(pingIntervalRef.current);@@ -1301,14 +1340,17 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}}, []);- // Get node status for current workflow (n8n pattern)- // IMPORTANT: Use currentWorkflowId state directly (not ref) to ensure reactivity on workflow switch+ // Get node status for current workflow (n8n pattern). Reads from the+ // node-status Zustand store which is the source of truth post Phase+ // 2.2; non-reactive snapshot read so this callback identity stays+ // stable across status writes. Components that need reactivity+ // should use the `useNodeStatus(id)` slice hook instead.const getNodeStatus = useCallback((nodeId: string) => {- if (!currentWorkflowId) {- return undefined;- }- return allNodeStatuses[currentWorkflowId]?.[nodeId];- }, [allNodeStatuses, currentWorkflowId]);+ if (!currentWorkflowId) return undefined;+ return useNodeStatusStore+ .getState()+ .allStatuses[currentWorkflowId]?.[nodeId];+ }, [currentWorkflowId]);// Get API key statusconst getApiKeyStatus = useCallback((provider: string) => {@@ -1326,13 +1368,9 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Also clears the backend node_outputs storageconst clearNodeStatus = useCallback(async (nodeId: string) => {const workflowId = currentWorkflowIdRef.current;- // Clear local state for current workflow- setAllNodeStatuses((prev: Record<string, Record<string, NodeStatus>>) => {- if (!workflowId || !prev[workflowId]) return prev;- const workflowStatuses = { ...prev[workflowId] };- delete workflowStatuses[nodeId];- return { ...prev, [workflowId]: workflowStatuses };- });+ if (workflowId) {+ useNodeStatusStore.getState().clearStatus(workflowId, nodeId);+ }// Clear backend storagetry {if (wsRef.current && wsRef.current.readyState === WebSocket.OPEN) {@@ -1381,13 +1419,12 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi}}, []);- // Derive current workflow's node statuses (n8n pattern)- // This provides a flat Record<nodeId, NodeStatus> for the current workflow- // IMPORTANT: Use currentWorkflowId state directly, not ref, to ensure re-render on workflow switch- const nodeStatuses = useMemo(() => {- if (!currentWorkflowId) return {};- return allNodeStatuses[currentWorkflowId] || {};- }, [allNodeStatuses, currentWorkflowId]);+ // Derive current workflow's node statuses (n8n pattern). Subscribes+ // to the Zustand store so context consumers still re-render on+ // status changes; per-node consumers should prefer the `useNodeStatus`+ // slice hook (`useNodeStatusForId`) which only re-renders for its+ // specific slot.+ const nodeStatuses = useCurrentWorkflowStatuses();// Derive current workflow's variables (n8n pattern)// This provides a flat Record<varName, value> for the current workflow@@ -2228,6 +2265,7 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiwsRef.current.close(1000, 'User logged out');wsRef.current = null;setIsConnected(false);+ setIsReady(false);}}, [isAuthenticated]);@@ -2243,9 +2281,16 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi};}, []);- const value: WebSocketContextValue = {+ // Memoized provider value: spreading a fresh object each render forces+ // every useContext consumer to re-render on any state change. Wrapping+ // in useMemo with the actual state deps keeps consumers stable when+ // unrelated slices change. Async methods are useCallback-wrapped+ // upstream, so their identities are stable across renders.+ // Reference: https://overreacted.io/before-you-memo/+ const value: WebSocketContextValue = useMemo(() => ({// Connection stateisConnected,+ isReady,reconnecting,// Status data@@ -2341,8 +2386,37 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Memory and Skill OperationsclearMemory: clearMemoryAsync,- resetSkill: resetSkillAsync- };+ resetSkill: resetSkillAsync,+ }), [+ isConnected, isReady, reconnecting,+ androidStatus, setAndroidStatus,+ whatsappStatus, twitterStatus, googleStatus, telegramStatus,+ whatsappMessages, lastWhatsAppMessage,+ apiKeyStatuses,+ consoleLogs, terminalLogs, chatMessages,+ nodeStatuses, nodeParameters,+ variables, workflowStatus, deploymentStatus, workflowLock,+ compactionStats, updateCompactionStats,+ getNodeStatus, getApiKeyStatus, getVariable,+ requestStatus, clearNodeStatus,+ clearWhatsAppMessages, clearConsoleLogs, clearTerminalLogs, clearChatMessages,+ sendChatMessageAsync, sendRequest,+ getNodeParametersAsync, getAllNodeParametersAsync,+ saveNodeParametersAsync, deleteNodeParametersAsync,+ executeNodeAsync, executeWorkflowAsync, getNodeOutputAsync,+ cancelEventWaitAsync,+ deployWorkflowAsync, cancelDeploymentAsync, getDeploymentStatusAsync,+ executeAiNodeAsync, getAiModelsAsync,+ validateApiKeyAsync, getStoredApiKeyAsync, saveApiKeyAsync, deleteApiKeyAsync,+ getAndroidDevicesAsync, executeAndroidActionAsync,+ validateMapsKeyAsync, validateApifyKeyAsync,+ getWhatsAppStatusAsync, getWhatsAppQRAsync, sendWhatsAppMessageAsync,+ startWhatsAppConnectionAsync, restartWhatsAppConnectionAsync,+ getWhatsAppGroupsAsync, getWhatsAppChannelsAsync, getWhatsAppGroupInfoAsync,+ getWhatsAppRateLimitConfigAsync, setWhatsAppRateLimitConfigAsync,+ getWhatsAppRateLimitStatsAsync, unpauseWhatsAppRateLimitAsync,+ clearMemoryAsync, resetSkillAsync,+ ]);return (<WebSocketContext.Provider value={value}>@@ -2369,10 +2443,12 @@ export const useAndroidStatus = (): AndroidStatus & { isConnected: boolean } =>};};-// Hook specifically for node status+// Hook specifically for node status. Subscribes directly to the+// node-status Zustand store so a single node's consumers re-render+// only when *that node's* slot changes — not on every status tick+// for every other node on the canvas.export const useNodeStatus = (nodeId: string): NodeStatus | undefined => {- const { getNodeStatus } = useWebSocket();- return getNodeStatus(nodeId);+ return useNodeStatusForId(nodeId);};// Hook specifically for workflow statusdiff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex dda7fdd4..ecb337e3 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -234,7 +234,7 @@ export type UseCatalogueQueryResult = UseQueryResult<CatalogueResponse, Error> &*/export function useCatalogueQuery(): UseCatalogueQueryResult {const queryClient = useQueryClient();- const { sendRequest, isConnected } = useWebSocket();+ const { sendRequest, isReady } = useWebSocket();const hydratedFromIdbRef = useRef(false);// Warm start: on first mount, hydrate the TanStack Query cache from IDB.@@ -290,7 +290,7 @@ export function useCatalogueQuery(): UseCatalogueQueryResult {gcTime: 10 * 60_000,// Only fetch once the WebSocket is actually connected. Prevents a// failed fetch during the initial reconnect window.- enabled: isConnected,+ enabled: isReady,// Placeholder so the first render can show the warm-start data.placeholderData: (prev) => prev,});diff --git a/client/src/hooks/useNodeParamsQuery.ts b/client/src/hooks/useNodeParamsQuery.tsindex 60638230..d28e27c3 100644--- a/client/src/hooks/useNodeParamsQuery.ts+++ b/client/src/hooks/useNodeParamsQuery.ts@@ -26,11 +26,11 @@ export const nodeParamsQueryKey = (nodeId: string) =>export function useNodeParamsQuery(nodeId: string | null | undefined,): UseQueryResult<NodeParametersResponse | null, Error> {- const { getNodeParameters, isConnected } = useWebSocket();+ const { getNodeParameters, isReady } = useWebSocket();return useQuery<NodeParametersResponse | null, Error>({queryKey: nodeId ? nodeParamsQueryKey(nodeId) : ['nodeParams', 'none'],queryFn: () => (nodeId ? getNodeParameters(nodeId) : Promise.resolve(null)),- enabled: !!nodeId && isConnected,+ enabled: !!nodeId && isReady,staleTime: 60_000,});}diff --git a/client/src/hooks/useUserSettingsQuery.ts b/client/src/hooks/useUserSettingsQuery.tsindex 370dbe2f..d6f1732c 100644--- a/client/src/hooks/useUserSettingsQuery.ts+++ b/client/src/hooks/useUserSettingsQuery.ts@@ -20,7 +20,7 @@ export type UserSettings = Record<string, any>;export const USER_SETTINGS_QUERY_KEY = ['userSettings'] as const;export function useUserSettingsQuery(): UseQueryResult<UserSettings, Error> {- const { sendRequest, isConnected } = useWebSocket();+ const { sendRequest, isReady } = useWebSocket();return useQuery<UserSettings, Error>({queryKey: USER_SETTINGS_QUERY_KEY,queryFn: async () => {@@ -30,7 +30,7 @@ export function useUserSettingsQuery(): UseQueryResult<UserSettings, Error> {);return response?.settings ?? {};},- enabled: isConnected,+ enabled: isReady,staleTime: 60_000,});}diff --git a/client/src/stores/nodeStatusStore.ts b/client/src/stores/nodeStatusStore.tsnew file mode 100644index 00000000..e01cab35--- /dev/null+++ b/client/src/stores/nodeStatusStore.ts@@ -0,0 +1,134 @@+/**+ * Per-workflow node status store.+ *+ * Replaces the `useState<Record<workflowId, Record<nodeId, NodeStatus>>>`+ * that previously lived inside WebSocketContext. Status writes there+ * forced every `useWebSocket()` consumer to re-render — at 50 canvas+ * nodes + 1 status tick that produced ~200 component re-renders.+ *+ * Zustand stores are built on `useSyncExternalStore`, so a slice+ * selector like `useNodeStatus(nodeId)` only re-renders when *that+ * specific* slot changes. Status writes for other nodes are invisible+ * to consumers of this slot.+ *+ * Reference: https://react.dev/reference/react/useSyncExternalStore+ */++import { create } from 'zustand';+import type { NodeStatus } from '../contexts/WebSocketContext';++interface NodeStatusState {+ /** workflowId -> nodeId -> NodeStatus */+ allStatuses: Record<string, Record<string, NodeStatus>>;+ /** Currently-focused workflow id (mirrored from useAppStore). */+ currentWorkflowId: string | undefined;++ setCurrentWorkflowId: (id: string | undefined) => void;+ /** Replace one node's status atomically. */+ setStatus: (workflowId: string, nodeId: string, status: NodeStatus) => void;+ /** Replace one workflow's full status map (used by initial-status broadcast). */+ setStatusesForWorkflow: (+ workflowId: string,+ statuses: Record<string, NodeStatus>,+ ) => void;+ /** Merge a multi-workflow batch into the store. */+ mergeStatuses: (+ grouped: Record<string, Record<string, NodeStatus>>,+ ) => void;+ /** Drop a single node's status entry. */+ clearStatus: (workflowId: string, nodeId: string) => void;+ /** Drop every status entry for a workflow (used on workflow delete). */+ clearWorkflow: (workflowId: string) => void;+}++export const useNodeStatusStore = create<NodeStatusState>((set) => ({+ allStatuses: {},+ currentWorkflowId: undefined,++ setCurrentWorkflowId: (id) =>+ set((state) =>+ state.currentWorkflowId === id ? state : { currentWorkflowId: id },+ ),++ setStatus: (workflowId, nodeId, status) =>+ set((state) => {+ const workflowSlot = state.allStatuses[workflowId] ?? {};+ const previous = workflowSlot[nodeId];+ // Reference equality short-circuit so identical status payloads+ // do not trigger a store-wide notify (which would wake every+ // selector). Caller is expected to pass a fresh object only when+ // something actually changed.+ if (previous === status) return state;+ return {+ allStatuses: {+ ...state.allStatuses,+ [workflowId]: { ...workflowSlot, [nodeId]: status },+ },+ };+ }),++ setStatusesForWorkflow: (workflowId, statuses) =>+ set((state) => ({+ allStatuses: { ...state.allStatuses, [workflowId]: statuses },+ })),++ mergeStatuses: (grouped) =>+ set((state) => ({+ allStatuses: { ...state.allStatuses, ...grouped },+ })),++ clearStatus: (workflowId, nodeId) =>+ set((state) => {+ const slot = state.allStatuses[workflowId];+ if (!slot || !(nodeId in slot)) return state;+ const next = { ...slot };+ delete next[nodeId];+ return { allStatuses: { ...state.allStatuses, [workflowId]: next } };+ }),++ clearWorkflow: (workflowId) =>+ set((state) => {+ if (!(workflowId in state.allStatuses)) return state;+ const next = { ...state.allStatuses };+ delete next[workflowId];+ return { allStatuses: next };+ }),+}));++/**+ * Slice selector: returns the NodeStatus for `nodeId` in the currently+ * focused workflow. Re-renders only when *that specific* slot changes.+ */+export function useNodeStatusForId(+ nodeId: string,+): NodeStatus | undefined {+ return useNodeStatusStore((s) => {+ const wf = s.currentWorkflowId;+ return wf ? s.allStatuses[wf]?.[nodeId] : undefined;+ });+}++/**+ * Slice selector: returns the flat statuses map for the currently+ * focused workflow. Re-renders only when that workflow's slot changes.+ * Use this where the consumer genuinely needs the full map (e.g. the+ * `useIsToolExecuting` matcher); prefer `useNodeStatusForId` for+ * single-node consumers.+ */+export function useCurrentWorkflowStatuses(): Record<string, NodeStatus> {+ return useNodeStatusStore((s) => {+ const wf = s.currentWorkflowId;+ return wf ? (s.allStatuses[wf] ?? EMPTY) : EMPTY;+ });+}++const EMPTY: Record<string, NodeStatus> = Object.freeze({});++/** Non-reactive snapshot for imperative reads (e.g. event handlers). */+export function getNodeStatusSnapshot(+ nodeId: string,+): NodeStatus | undefined {+ const { allStatuses, currentWorkflowId } = useNodeStatusStore.getState();+ if (!currentWorkflowId) return undefined;+ return allStatuses[currentWorkflowId]?.[nodeId];+}