Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | /** * useAutomationEvents - WebSocket Event Hook for Automation System * * Subscribes to hand and workflow events from OpenFang WebSocket * and updates the corresponding stores. * * @module hooks/useAutomationEvents */ import { useEffect, useRef } from 'react'; import { useHandStore } from '../store/handStore'; import { useWorkflowStore } from '../store/workflowStore'; import { useChatStore } from '../store/chatStore'; import type { GatewayClient } from '../lib/gateway-client'; // === Event Types === interface HandEventData { hand_name: string; hand_status: 'triggered' | 'running' | 'completed' | 'failed' | 'needs_approval'; hand_result?: unknown; hand_error?: string; run_id?: string; timestamp?: number; } interface WorkflowEventData { workflow_id: string; workflow_status: 'started' | 'step_completed' | 'completed' | 'failed' | 'paused'; current_step?: number; total_steps?: number; step_name?: string; result?: unknown; error?: string; run_id?: string; timestamp?: number; } interface ApprovalEventData { approval_id: string; hand_name?: string; workflow_id?: string; run_id?: string; status: 'requested' | 'approved' | 'rejected' | 'expired'; reason?: string; requested_by?: string; timestamp?: number; } // === Hook Options === export interface UseAutomationEventsOptions { /** Whether to inject hand results into chat as messages */ injectResultsToChat?: boolean; /** Whether to auto-refresh hands on status change */ refreshOnStatusChange?: boolean; /** Custom event handlers */ onHandEvent?: (data: HandEventData) => void; onWorkflowEvent?: (data: WorkflowEventData) => void; onApprovalEvent?: (data: ApprovalEventData) => void; } // === Helper Functions === function isHandEvent(data: unknown): data is HandEventData { return typeof data === 'object' && data !== null && 'hand_name' in data && 'hand_status' in data; } function isWorkflowEvent(data: unknown): data is WorkflowEventData { return typeof data === 'object' && data !== null && 'workflow_id' in data && 'workflow_status' in data; } function isApprovalEvent(data: unknown): data is ApprovalEventData { return typeof data === 'object' && data !== null && 'approval_id' in data && 'status' in data; } // === Main Hook === /** * Hook for subscribing to automation-related WebSocket events. * * @param client - The GatewayClient instance (optional, will try to get from store if not provided) * @param options - Configuration options * * @example * ```tsx * function AutomationPanel() { * const client = useConnectionStore(s => s.client); * useAutomationEvents(client, { * injectResultsToChat: true, * refreshOnStatusChange: true, * }); * // ... * } * ``` */ export function useAutomationEvents( client: GatewayClient | null, options: UseAutomationEventsOptions = {} ): void { const { injectResultsToChat = true, refreshOnStatusChange = true, onHandEvent, onWorkflowEvent, onApprovalEvent, } = options; // Store references const loadHands = useHandStore(s => s.loadHands); const loadHandRuns = useHandStore(s => s.loadHandRuns); const loadApprovals = useHandStore(s => s.loadApprovals); const loadWorkflows = useWorkflowStore(s => s.loadWorkflows); const loadWorkflowRuns = useWorkflowStore(s => s.loadWorkflowRuns); const addMessage = useChatStore(s => s.addMessage); // Track subscriptions for cleanup const unsubscribersRef = useRef<Array<() => void>>([]); useEffect(() => { if (!client) { return; } // Clean up any existing subscriptions unsubscribersRef.current.forEach(unsub => unsub()); unsubscribersRef.current = []; // === Hand Event Handler === const handleHandEvent = (data: unknown) => { if (!isHandEvent(data)) return; const eventData = data as HandEventData; console.log('[useAutomationEvents] Hand event:', eventData); // Refresh hands if status changed if (refreshOnStatusChange) { loadHands(); } // Load updated runs for this hand if (eventData.run_id) { loadHandRuns(eventData.hand_name); } // Inject result into chat if (injectResultsToChat && eventData.hand_status === 'completed') { const resultContent = eventData.hand_result ? typeof eventData.hand_result === 'string' ? eventData.hand_result : JSON.stringify(eventData.hand_result, null, 2) : 'Hand completed successfully'; addMessage({ id: `hand-${eventData.run_id || Date.now()}`, role: 'hand', content: `**${eventData.hand_name}** 执行完成\n\n${resultContent}`, timestamp: new Date(), handName: eventData.hand_name, handStatus: eventData.hand_status, handResult: eventData.hand_result, runId: eventData.run_id, }); } // Handle error status if (eventData.hand_status === 'failed' && eventData.hand_error) { addMessage({ id: `hand-error-${eventData.run_id || Date.now()}`, role: 'hand', content: `**${eventData.hand_name}** 执行失败\n\n错误: ${eventData.hand_error}`, timestamp: new Date(), handName: eventData.hand_name, handStatus: eventData.hand_status, error: eventData.hand_error, runId: eventData.run_id, }); } // Handle approval needed if (eventData.hand_status === 'needs_approval') { loadApprovals('pending'); } // Call custom handler onHandEvent?.(eventData); }; // === Workflow Event Handler === const handleWorkflowEvent = (data: unknown) => { if (!isWorkflowEvent(data)) return; const eventData = data as WorkflowEventData; console.log('[useAutomationEvents] Workflow event:', eventData); // Refresh workflows if status changed if (refreshOnStatusChange) { loadWorkflows(); } // Load updated runs for this workflow if (eventData.run_id) { loadWorkflowRuns(eventData.workflow_id); } // Inject result into chat if (injectResultsToChat && eventData.workflow_status === 'completed') { const resultContent = eventData.result ? typeof eventData.result === 'string' ? eventData.result : JSON.stringify(eventData.result, null, 2) : 'Workflow completed successfully'; addMessage({ id: `workflow-${eventData.run_id || Date.now()}`, role: 'workflow', content: `**工作流: ${eventData.workflow_id}** 执行完成\n\n${resultContent}`, timestamp: new Date(), workflowId: eventData.workflow_id, workflowStatus: eventData.workflow_status, workflowResult: eventData.result, runId: eventData.run_id, }); } // Call custom handler onWorkflowEvent?.(eventData); }; // === Approval Event Handler === const handleApprovalEvent = (data: unknown) => { if (!isApprovalEvent(data)) return; const eventData = data as ApprovalEventData; console.log('[useAutomationEvents] Approval event:', eventData); // Refresh approvals list loadApprovals(); // Call custom handler onApprovalEvent?.(eventData); }; // Subscribe to events const unsubHand = client.on('hand', handleHandEvent); const unsubWorkflow = client.on('workflow', handleWorkflowEvent); const unsubApproval = client.on('approval', handleApprovalEvent); unsubscribersRef.current = [unsubHand, unsubWorkflow, unsubApproval]; // Cleanup on unmount or client change return () => { unsubscribersRef.current.forEach(unsub => unsub()); unsubscribersRef.current = []; }; }, [ client, injectResultsToChat, refreshOnStatusChange, loadHands, loadHandRuns, loadApprovals, loadWorkflows, loadWorkflowRuns, addMessage, onHandEvent, onWorkflowEvent, onApprovalEvent, ]); } // === Utility Hooks === /** * Hook for subscribing to a specific hand's events only */ export function useHandEvents( client: GatewayClient | null, handName: string, onEvent?: (data: HandEventData) => void ): void { useEffect(() => { if (!client || !handName) return; const handler = (data: unknown) => { if (isHandEvent(data) && (data as HandEventData).hand_name === handName) { onEvent?.(data as HandEventData); } }; const unsub = client.on('hand', handler); return unsub; }, [client, handName, onEvent]); } /** * Hook for subscribing to a specific workflow's events only */ export function useWorkflowEvents( client: GatewayClient | null, workflowId: string, onEvent?: (data: WorkflowEventData) => void ): void { useEffect(() => { if (!client || !workflowId) return; const handler = (data: unknown) => { if (isWorkflowEvent(data) && (data as WorkflowEventData).workflow_id === workflowId) { onEvent?.(data as WorkflowEventData); } }; const unsub = client.on('workflow', handler); return unsub; }, [client, workflowId, onEvent]); } export default useAutomationEvents; |