Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(ui): reactive NodeSpec/NodeGroups via WS-backed TanStack queries
trohitgb98bf93873b0
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 8c8ec950..4a47ce7a 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -95,8 +95,11 @@ const createNodeTypes = (): Record<string, React.ComponentType<any>> => {types[type] = TeamMonitorNode;} else if (SKILL_NODE_TYPES.includes(type)) {types[type] = ToolkitNode;- } else if (SPECIALIZED_AGENT_TYPES.includes(type)) {+ } else if (type === 'aiAgent' || type === 'chatAgent' || SPECIALIZED_AGENT_TYPES.includes(type)) {// Pre-prefetch fallback so agents render before specs arrive.+ // aiAgent/chatAgent aren't in SPECIALIZED_AGENT_TYPES but still+ // need AIAgentNode rendering; otherwise cold-cache paints them as+ // generic SquareNode with no agent handles.types[type] = AIAgentNode;} else {types[type] = SquareNode;@@ -540,19 +543,17 @@ const DashboardContent: React.FC = () => {// Wave 10.D step 2: nodeTypes is rebuilt once after the NodeSpec// prefetch lands so spec.componentKind dispatch becomes effective.- // The initial value (moduleNodeTypes) is computed at module load- // before any spec is cached, so it falls through to the small legacy- // fallback for every type — fine because most types still render via- // SquareNode and the upgrade to spec-driven dispatch only causes one- // remount when prefetch completes. React Flow's identity check is the- // reason we use a ref + manual setter rather than a useMemo on every- // render.- const nodeTypesRef = React.useRef(moduleNodeTypes);- React.useEffect(() => {- if (!specsReady) return;- nodeTypesRef.current = createNodeTypes();- }, [specsReady]);- const edgeTypesRef = React.useRef(moduleEdgeTypes);+ // Using `useMemo` (not a ref) so React Flow actually sees the new+ // reference and re-mounts nodes with the correct components (e.g.+ // `aiAgent` → AIAgentNode instead of the SquareNode fallback chosen+ // when the spec cache was cold). Before `specsReady`, returns the+ // module-scope map (stable identity). After prefetch: returns the+ // spec-aware map (stable identity for the rest of the session).+ const nodeTypes = React.useMemo(+ () => (specsReady ? createNodeTypes() : moduleNodeTypes),+ [specsReady],+ );+ const edgeTypes = moduleEdgeTypes;// Execute entire workflow from start node to endconst handleRun = async () => {@@ -1202,8 +1203,8 @@ const DashboardContent: React.FC = () => {onDragOver={onDragOver}onDrop={onDrop}onNodeContextMenu={onNodeContextMenu}- nodeTypes={nodeTypesRef.current}- edgeTypes={edgeTypesRef.current}+ nodeTypes={nodeTypes}+ edgeTypes={edgeTypes}connectionMode={ConnectionMode.Loose}deleteKeyCode={isCurrentWorkflowLocked ? [] : ['Delete', 'Backspace']}edgesFocusable={!isCurrentWorkflowLocked}diff --git a/client/src/components/AIAgentNode.tsx b/client/src/components/AIAgentNode.tsxindex 68155fbe..c4f889fd 100644--- a/client/src/components/AIAgentNode.tsx+++ b/client/src/components/AIAgentNode.tsx@@ -134,7 +134,7 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectastyle={{position: 'relative',padding: theme.spacing.lg,- paddingRight: hasRightOutputs ? '60px' : theme.spacing.lg,+ paddingRight: hasRightOutputs ? '72px' : theme.spacing.lg,minWidth: `${width}px`,minHeight: `${height}px`,borderRadius: theme.borderRadius.lg,@@ -287,14 +287,18 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnecta/>)}- {/* Right outputs (multi-output nodes like socialReceive) */}- {!topOutput && hasRightOutputs && rightOutputs.map(h => (+ {/* Right outputs — rendered whenever the spec ships any, independent+ of whether the top output also exists. Agents that expose both+ a top-position Output (team/delegate) and a right-position+ Output (workflow) need both handles visible. */}+ {hasRightOutputs && rightOutputs.map(h => (<React.Fragment key={h.name}><div style={{- position: 'absolute', right: '10px', top: h.offset || '50%',+ position: 'absolute', right: '14px', top: h.offset || '50%',transform: 'translateY(-50%)', fontSize: theme.fontSize.sm,color: theme.colors.text, fontWeight: theme.fontWeight.medium,pointerEvents: 'none', whiteSpace: 'nowrap', textAlign: 'right',+ lineHeight: 1,}}>{h.label || h.name}</div><Handleid={h.name}@@ -305,16 +309,19 @@ const AIAgentNode: React.FC<NodeProps<NodeData>> = ({ id, type, data, isConnectaposition: 'absolute', right: '-6px', top: h.offset || '50%',transform: 'translateY(-50%)',width: theme.nodeSize.handle, height: theme.nodeSize.handle,- backgroundColor: theme.colors.background,- border: `2px solid ${theme.colors.textSecondary}`, borderRadius: '50%',+ backgroundColor: accentColor,+ border: `2px solid ${theme.isDarkMode ? theme.colors.background : '#ffffff'}`,+ borderRadius: '50%', zIndex: 20,}}title={h.label || h.name}/></React.Fragment>))}- {/* Single default right output when the spec declares none explicitly */}- {!topOutput && !hasRightOutputs && (+ {/* Single default right output when the spec declares neither a+ right-position nor a top-position output. Keeps the node+ connectable even if the backend omits an explicit output. */}+ {!hasRightOutputs && !topOutput && (<Handleid="output-main"type="source"diff --git a/client/src/components/ui/ComponentPalette.tsx b/client/src/components/ui/ComponentPalette.tsxindex 42735eb9..0fc9bcd2 100644--- a/client/src/components/ui/ComponentPalette.tsx+++ b/client/src/components/ui/ComponentPalette.tsx@@ -1,5 +1,4 @@import React from 'react';-import { useQuery } from '@tanstack/react-query';import { useAppTheme } from '../../hooks/useAppTheme';import { ComponentPaletteProps } from '../../types/ComponentTypes';import { INodeTypeDescription } from '../../types/INodeProperties';@@ -9,8 +8,7 @@ import { Badge } from '@/components/ui/badge';import { Input } from '@/components/ui/input';import { Search } from 'lucide-react';import { resolveIcon, resolveLibraryIcon, isImageIcon } from '../../assets/icons';-import { nodeGroupsQueryKey, NodeGroupEntry } from '../../lib/nodeSpec';-import { useWebSocket } from '../../contexts/WebSocketContext';+import { useNodeGroups, NodeGroupEntry } from '../../lib/nodeSpec';// Wave 10.B: palette section metadata (icon / label / color / visibility)// is fetched from the backend GET /api/schemas/nodes/groups endpoint.@@ -26,21 +24,11 @@ const ComponentPalette: React.FC<ComponentPaletteProps> = ({proMode = false, // Default to simple mode}) => {const theme = useAppTheme();- const { sendRequest, isConnected } = useWebSocket();-- // Backend-driven group metadata (label / icon / color / visibility).- // Direct WS call — do NOT route through `fetchNodeGroups`, which- // would re-enter `queryClient.fetchQuery` on the same key and leave- // this subscription stuck with `undefined`.- const { data: groupIndex } = useQuery<Record<string, NodeGroupEntry>>({- queryKey: nodeGroupsQueryKey,- queryFn: async () => {- const response = await sendRequest('get_node_groups', {});- return (response?.groups ?? {}) as Record<string, NodeGroupEntry>;- },- staleTime: Infinity,- enabled: isConnected,- });++ // Backend-driven group metadata via the shared WS-in-queryFn hook.+ // `useNodeGroups` auto-fires on WS connect and re-renders the palette+ // with proper icons once the response lands.+ const groupIndex = useNodeGroups();const getCategoryConfig = React.useCallback((category: string) => {const entry = groupIndex?.[category.toLowerCase()] as NodeGroupEntry | undefined;diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex 7859e9ba..62216941 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -14,6 +14,7 @@ import React, { createContext, useContext, useEffect, useState, useCallback, useimport { API_CONFIG } from '../config/api';import { useAppStore } from '../store/useAppStore';import { useAuth } from './AuthContext';+import { queryClient } from '../lib/queryClient';// Generate unique request IDconst generateRequestId = (): string => {@@ -1061,6 +1062,14 @@ 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'] });+// Start ping intervalpingIntervalRef.current = setInterval(() => {if (ws.readyState === WebSocket.OPEN) {diff --git a/client/src/lib/nodeSpec.ts b/client/src/lib/nodeSpec.tsindex 2d7d4411..d22e3338 100644--- a/client/src/lib/nodeSpec.ts+++ b/client/src/lib/nodeSpec.ts@@ -17,6 +17,7 @@ import { nodeSpecToDescription, type NodeSpec } from '../adapters/nodeSpecToDescimport type { INodeTypeDescription } from '../types/INodeProperties';import { featureFlags } from './featureFlags';import { queryClient } from './queryClient';+import { useWebSocket } from '../contexts/WebSocketContext';type SendRequest = (type: string, data?: any) => Promise<any>;@@ -71,21 +72,57 @@ export function getCachedNodeSpec(nodeType: string): NodeSpec | null {}/**- * Reactive spec subscription. Uses TanStack Query so the component- * re-renders when the prefetch warms the cache. No extra network- * traffic — `prefetchAllNodeSpecs` populates the cache at WS connect;- * this hook just subscribes.+ * Reactive spec subscription — tRPC `wsLink` / TanStack-Query+WS pattern.+ *+ * The `queryFn` sends a WS request whose Promise resolves via the+ * correlated response. TanStack auto-fires on mount, so cold-cache+ * renders are self-healing — no dependency on `prefetchAllNodeSpecs`+ * running first. When the prefetch does run (same queryKey), it warms+ * the cache and this hook reads from it instantly.+ *+ * References:+ * - TkDodo: https://tkdodo.eu/blog/using-web-sockets-with-react-query+ * - tRPC wsLink: https://trpc.io/docs/client/links/wsLink*/export function useNodeSpec(nodeType: string | undefined | null): NodeSpec | null {+ const { sendRequest, isConnected } = useWebSocket();const { data } = useQuery<NodeSpec | null>({queryKey: nodeSpecQueryKey(nodeType ?? '__none__'),- queryFn: () => null,- enabled: false,- staleTime: Infinity,+ queryFn: async () => {+ if (!nodeType) return null;+ try {+ const response = await sendRequest('get_node_spec', { node_type: nodeType });+ return (response?.spec ?? null) as NodeSpec | null;+ } catch {+ return null;+ }+ },+ enabled: !!nodeType && isConnected,+ staleTime: 60_000, // 60s — short enough to pick up backend restarts in dev+ refetchOnMount: 'always',});return data ?? null;}+/**+ * Reactive node-groups subscription. Same WS-in-queryFn pattern as+ * `useNodeSpec`. Replaces the old double-wrapped `fetchNodeGroups`+ * call inside `useQuery` (which deadlocked on the shared query key).+ */+export function useNodeGroups(): Record<string, NodeGroupEntry> | undefined {+ const { sendRequest, isConnected } = useWebSocket();+ const { data } = useQuery<Record<string, NodeGroupEntry>>({+ queryKey: nodeGroupsQueryKey,+ queryFn: async () => {+ const response = await sendRequest('get_node_groups', {});+ return (response?.groups ?? {}) as Record<string, NodeGroupEntry>;+ },+ enabled: isConnected,+ staleTime: Infinity,+ });+ return data;+}+/** Wire shape for one entry in the GET /api/schemas/nodes/groups* response (Wave 10.B): per-group palette metadata + member types. */export interface NodeGroupEntry {diff --git a/server/nodes/agents.py b/server/nodes/agents.pyindex 66466eec..aa42ef14 100644--- a/server/nodes/agents.py+++ b/server/nodes/agents.py@@ -32,9 +32,9 @@ _STD_AGENT_HINTS = {**_STD_SIZE, "hasSkills": True}def _std_handles(extra_bottom: list[dict] | None = None) -> list[dict]:- """Skill + Tool + Memory + Task + top Output — the handle set shared- by 16 of the 20 agent variants. Factored out as a local helper in- this module only; not a global lookup. Each register_node call+ """Input + Skill + Tool + Memory + Task + Output — the handle set+ shared by 18 of the 20 agent variants. Factored out as a local helper+ in this module only; not a global lookup. Each register_node callbelow still opts in by name."""bottom = list(extra_bottom) if extra_bottom else [@@ -43,9 +43,11 @@ def _std_handles(extra_bottom: list[dict] | None = None) -> list[dict]:]return [*bottom,- {"name": "input-memory", "kind": "input", "position": "left", "offset": "65%", "label": "Memory", "role": "memory"},- {"name": "input-task", "kind": "input", "position": "left", "offset": "85%", "label": "Task", "role": "task"},- {"name": "output-top", "kind": "output", "position": "top", "label": "Output", "role": "main"},+ {"name": "input-main", "kind": "input", "position": "left", "offset": "25%", "label": "Input", "role": "main"},+ {"name": "input-memory", "kind": "input", "position": "left", "offset": "50%", "label": "Memory", "role": "memory"},+ {"name": "input-task", "kind": "input", "position": "left", "offset": "75%", "label": "Task", "role": "task"},+ {"name": "output-main", "kind": "output", "position": "right", "offset": "50%", "label": "Output", "role": "main"},+ {"name": "output-top", "kind": "output", "position": "top", "label": "Output", "role": "main"},]