Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
feat(agent_builder): runtime broadcast + frontend listener
trohitg97ca25e7b4bf
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsxindex 051eca2e..53a93f57 100644--- a/client/src/Dashboard.tsx+++ b/client/src/Dashboard.tsx@@ -44,6 +44,7 @@ import { useDragAndDrop } from './hooks/useDragAndDrop';import { useComponentPalette } from './hooks/useComponentPalette';import { useReactFlowNodes } from './hooks/useReactFlowNodes';import { useAutoSkillEdges } from './hooks/useAutoSkillEdges';+import { useWorkflowOpsListener } from './hooks/useWorkflowOpsListener';import { useCopyPaste } from './hooks/useCopyPaste';import { useWebSocket } from './contexts/WebSocketContext';import { useNodeStatusStore } from './stores/nodeStatusStore';@@ -220,6 +221,9 @@ const DashboardContent: React.FC = () => {setNodes,setEdges,});+ // Apply runtime canvas mutations pushed from the backend (e.g.,+ // Agent Builder tools called by the LLM mid-execution).+ useWorkflowOpsListener({ nodes, edges, setNodes, setEdges });const { copySelectedNodes, pasteNodes } = useCopyPaste({ nodes, edges, setNodes, setEdges, saveNodeParameters });// Override all agent nodes to use the global model. Agent membership isdiff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsxindex df561ac3..f3a3e419 100644--- a/client/src/contexts/WebSocketContext.tsx+++ b/client/src/contexts/WebSocketContext.tsx@@ -322,6 +322,12 @@ interface WebSocketContextValue {// Generic request methodsendRequest: <T = any>(type: string, data?: Record<string, any>) => Promise<T>;+ // Generic broadcast subscription. Returns an unsubscribe fn.+ // Use for ad-hoc backend-pushed events like `workflow_ops_apply`+ // (see server/services/status_broadcaster.send_custom_event) so a+ // new listener doesn't require a new switch case + state slice.+ addEventListener: (type: string, handler: (data: any) => void) => () => void;+// Node ParametersgetNodeParameters: (nodeId: string) => Promise<NodeParameters | null>;getAllNodeParameters: (nodeIds: string[]) => Promise<Record<string, NodeParameters>>;@@ -512,6 +518,11 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiconst wsRef = useRef<ReconnectingWebSocket | null>(null);const pingIntervalRef = useRef<NodeJS.Timeout | null>(null);const pendingRequestsRef = useRef<Map<string, PendingRequest>>(new Map());+ // Generic broadcast subscribers ({type -> Set<handler>}) for events+ // surfaced via send_custom_event on the backend. Lets new features+ // listen for ad-hoc broadcasts without growing the switch statement+ // or the context state shape.+ const eventListenersRef = useRef<Map<string, Set<(data: any) => void>>>(new Map());// Pending-send queue for backpressure + replay across reconnects.// Drained inside `ws.onopen` after the init burst. Source of truth// for currentWorkflowId is `useAppStore.getState().currentWorkflow?.id`@@ -1167,8 +1178,21 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chiconsole.error('[WebSocket] Server error:', message.code, message.message);break;- default:+ default: {+ // Generic broadcast dispatch -- any listener registered via+ // addEventListener(type, handler) gets the message data. Lets+ // backend-only features (e.g. workflow_ops_apply) ship without+ // adding a switch case + state slice every time.+ const listeners = eventListenersRef.current.get(type);+ if (listeners && listeners.size > 0) {+ for (const handler of listeners) {+ try { handler(data); } catch (err) {+ console.error(`[WebSocket] Listener for '${type}' threw:`, err);+ }+ }+ }break;+ }}} catch (error) {console.error('[WebSocket] Failed to parse message:', error);@@ -2669,6 +2693,23 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi// Generic request methodsendRequest,+ // Generic broadcast subscription+ addEventListener: (type: string, handler: (data: any) => void) => {+ let set = eventListenersRef.current.get(type);+ if (!set) {+ set = new Set();+ eventListenersRef.current.set(type, set);+ }+ set.add(handler);+ return () => {+ const current = eventListenersRef.current.get(type);+ if (current) {+ current.delete(handler);+ if (current.size === 0) eventListenersRef.current.delete(type);+ }+ };+ },+// Node ParametersgetNodeParameters: getNodeParametersAsync,getAllNodeParameters: getAllNodeParametersAsync,diff --git a/client/src/hooks/__tests__/useWorkflowOpsListener.test.ts b/client/src/hooks/__tests__/useWorkflowOpsListener.test.tsnew file mode 100644index 00000000..8ee56f23--- /dev/null+++ b/client/src/hooks/__tests__/useWorkflowOpsListener.test.ts@@ -0,0 +1,142 @@+/**+ * Tests for useWorkflowOpsListener.+ *+ * Locks the runtime broadcast contract:+ * - subscribes to `workflow_ops_apply` via the WS context+ * addEventListener API+ * - applies events scoped to the current workflow via applyOperations+ * - other-workflow events trigger a sonner toast (no canvas mutation)+ * - unsubscribes on unmount+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import type { Node, Edge } from 'reactflow';++import { useWorkflowOpsListener } from '../useWorkflowOpsListener';++// --- mocks (must come before importing modules that read them) ----------++const wsMock = {+ addEventListener: vi.fn<(type: string, handler: (data: any) => void) => () => void>(),+ saveNodeParameters: vi.fn().mockResolvedValue(true),+};++const storeMock = {+ currentWorkflowId: 'wf-current',+ loadWorkflow: vi.fn(),+};++vi.mock('../../contexts/WebSocketContext', () => ({+ useWebSocket: () => wsMock,+}));++vi.mock('../../store/useAppStore', () => ({+ useAppStore: (selector: any) => selector({+ currentWorkflow: { id: storeMock.currentWorkflowId },+ loadWorkflow: storeMock.loadWorkflow,+ }),+}));++const applyOpsMock = vi.fn().mockResolvedValue({ applied: 0, errors: [], refMap: {} });+vi.mock('../../lib/workflowOps', () => ({+ applyOperations: (...args: any[]) => applyOpsMock(...args),+}));++const toastMessageMock = vi.fn();+vi.mock('sonner', () => ({+ toast: { message: (...args: any[]) => toastMessageMock(...args) },+}));++// --- test scaffolding ---------------------------------------------------++function _ctx(overrides: Partial<{ nodes: Node[]; edges: Edge[] }> = {}) {+ return {+ nodes: overrides.nodes ?? [],+ edges: overrides.edges ?? [],+ setNodes: vi.fn(),+ setEdges: vi.fn(),+ };+}++let registeredHandler: ((data: any) => void) | null = null;+let unsubscribeMock = vi.fn();++beforeEach(() => {+ vi.clearAllMocks();+ registeredHandler = null;+ unsubscribeMock = vi.fn();+ wsMock.addEventListener.mockImplementation((type, handler) => {+ if (type === 'workflow_ops_apply') registeredHandler = handler;+ return unsubscribeMock;+ });+ storeMock.currentWorkflowId = 'wf-current';+});++// ---------------------------------------------------------------------------++describe('useWorkflowOpsListener', () => {+ it('subscribes to workflow_ops_apply on mount', () => {+ renderHook(() => useWorkflowOpsListener(_ctx()));+ expect(wsMock.addEventListener).toHaveBeenCalledWith(+ 'workflow_ops_apply',+ expect.any(Function),+ );+ });++ it('unsubscribes on unmount', () => {+ const { unmount } = renderHook(() => useWorkflowOpsListener(_ctx()));+ expect(unsubscribeMock).not.toHaveBeenCalled();+ unmount();+ expect(unsubscribeMock).toHaveBeenCalledTimes(1);+ });++ it('applies operations scoped to the current workflow', async () => {+ renderHook(() => useWorkflowOpsListener(_ctx()));+ expect(registeredHandler).not.toBeNull();++ const ops = [{ type: 'add_node', client_ref: 'n', node_type: 'x', parameters: {} }];+ await act(async () => {+ registeredHandler!({+ workflow_id: 'wf-current',+ caller_node_id: 'agent-1',+ operations: ops,+ });+ });++ expect(applyOpsMock).toHaveBeenCalledTimes(1);+ expect(applyOpsMock.mock.calls[0][0]).toEqual(ops);+ expect(toastMessageMock).not.toHaveBeenCalled();+ });++ it('toasts (not applies) when event targets a different workflow', () => {+ renderHook(() => useWorkflowOpsListener(_ctx()));+ expect(registeredHandler).not.toBeNull();++ act(() => {+ registeredHandler!({+ workflow_id: 'wf-other',+ caller_node_id: 'agent-1',+ operations: [{ type: 'add_node', client_ref: 'n', node_type: 'x', parameters: {} }],+ });+ });++ expect(applyOpsMock).not.toHaveBeenCalled();+ expect(toastMessageMock).toHaveBeenCalledTimes(1);+ const [title, opts] = toastMessageMock.mock.calls[0];+ expect(title).toMatch(/workflow created/i);+ expect(opts.action.label).toBe('Switch');+ // Switch handler triggers loadWorkflow with the foreign id.+ opts.action.onClick();+ expect(storeMock.loadWorkflow).toHaveBeenCalledWith('wf-other');+ });++ it('ignores empty-ops events that target the current workflow', async () => {+ renderHook(() => useWorkflowOpsListener(_ctx()));+ await act(async () => {+ registeredHandler!({ workflow_id: 'wf-current', operations: [] });+ });+ expect(applyOpsMock).not.toHaveBeenCalled();+ expect(toastMessageMock).not.toHaveBeenCalled();+ });+});diff --git a/client/src/hooks/useWorkflowOpsListener.ts b/client/src/hooks/useWorkflowOpsListener.tsnew file mode 100644index 00000000..fad83f0c--- /dev/null+++ b/client/src/hooks/useWorkflowOpsListener.ts@@ -0,0 +1,90 @@+/**+ * Listens for backend-pushed `workflow_ops_apply` events and applies+ * them to the live React Flow canvas via the standard+ * `applyOperations` reconciler.+ *+ * Source of events: `services/status_broadcaster.send_custom_event`+ * called by the Agent Builder's tool functions+ * (`server/nodes/tool/agent_builder.py`) after a successful mutation.+ *+ * Filtering:+ * - Events whose `workflow_id` matches the current workflow apply+ * to the canvas in-place.+ * - Events for OTHER workflows (e.g. `create_workflow` returning a+ * fresh id) surface as a sonner toast with a Switch action so the+ * user can jump to the new workflow without losing their place.+ *+ * Mounted once in Dashboard.+ */++import { useEffect } from 'react';+import type { Node, Edge } from 'reactflow';+import { toast } from 'sonner';++import { useWebSocket } from '../contexts/WebSocketContext';+import { useAppStore } from '../store/useAppStore';+import { applyOperations, type WorkflowOperation } from '../lib/workflowOps';++interface WorkflowOpsApplyEvent {+ workflow_id?: string | null;+ caller_node_id?: string | null;+ operations?: WorkflowOperation[];+}++interface UseWorkflowOpsListenerProps {+ nodes: Node[];+ edges: Edge[];+ setNodes: (updater: (ns: Node[]) => Node[]) => void;+ setEdges: (updater: (es: Edge[]) => Edge[]) => void;+}++export function useWorkflowOpsListener({+ nodes,+ edges,+ setNodes,+ setEdges,+}: UseWorkflowOpsListenerProps) {+ const { addEventListener, saveNodeParameters } = useWebSocket();+ const currentWorkflowId = useAppStore(s => s.currentWorkflow?.id);+ const loadWorkflow = useAppStore(s => s.loadWorkflow);++ useEffect(() => {+ const unsubscribe = addEventListener('workflow_ops_apply', (raw: WorkflowOpsApplyEvent) => {+ const ops = raw?.operations ?? [];+ if (ops.length === 0 && !raw?.workflow_id) return;++ // Different workflow -- surface a toast with a switch action.+ // Used by `create_workflow`, which persists a new workflow but+ // doesn't try to mutate the canvas the user is currently on.+ if (raw.workflow_id && raw.workflow_id !== currentWorkflowId) {+ toast.message('New workflow created', {+ description: `Workflow ${raw.workflow_id} is ready.`,+ action: {+ label: 'Switch',+ onClick: () => loadWorkflow(raw.workflow_id!),+ },+ });+ return;+ }++ if (ops.length === 0) return;++ void applyOperations(ops, {+ nodes,+ edges,+ setNodes,+ setEdges,+ saveNodeParameters,+ }).then(result => {+ if (result.errors.length > 0) {+ console.warn('[workflow_ops_apply] some ops failed:', result.errors);+ }+ });+ });++ return unsubscribe;+ }, [+ addEventListener, currentWorkflowId, loadWorkflow,+ nodes, edges, setNodes, setEdges, saveNodeParameters,+ ]);+}