Spaces:
Sleeping
Sleeping
File size: 14,094 Bytes
4343907 |
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 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 |
/**
* SAAP Agent Store - Pinia State Management
* Centralized state management for SAAP agents and system
*/
import { defineStore } from 'pinia'
import { ref, reactive, computed } from 'vue'
import { useApi, type SaapAgent, type ChatMessage, type SystemStatus } from '@/composables/useApi'
import { useWebSocket } from '@/composables/useWebSocket'
interface AgentOperation {
agentId: string
operation: 'starting' | 'stopping' | 'chatting'
timestamp: string
}
interface NotificationMessage {
id: string
type: 'success' | 'error' | 'info' | 'warning'
title: string
message: string
timestamp: string
duration?: number
}
export const useAgentStore = defineStore('agents', () => {
// API and WebSocket composables
const api = useApi()
const ws = useWebSocket()
// =====================================================
// STATE
// =====================================================
const agents = ref<SaapAgent[]>([])
const selectedAgent = ref<SaapAgent | null>(null)
const systemStatus = ref<SystemStatus | null>(null)
const chatHistory = ref<ChatMessage[]>([])
const activeOperations = ref<AgentOperation[]>([])
const notifications = ref<NotificationMessage[]>([])
// Loading states
const loading = reactive({
agents: false,
systemStatus: false,
operations: false
})
// Connection status
const connectionStatus = reactive({
api: false,
websocket: false,
lastCheck: null as string | null
})
// =====================================================
// COMPUTED
// =====================================================
const activeAgents = computed(() =>
agents.value.filter(agent => agent.status === 'active')
)
const inactiveAgents = computed(() =>
agents.value.filter(agent => agent.status === 'inactive')
)
const agentsByType = computed(() => {
const grouped: Record<string, SaapAgent[]> = {}
agents.value.forEach(agent => {
if (!grouped[agent.type]) {
grouped[agent.type] = []
}
grouped[agent.type].push(agent)
})
return grouped
})
const totalMessages = computed(() =>
agents.value.reduce((total, agent) =>
total + (agent.metrics?.messages_processed || 0), 0
)
)
const averageResponseTime = computed(() => {
const responseTimes = agents.value
.map(agent => agent.metrics?.average_response_time)
.filter((time): time is number => time !== undefined && time > 0)
if (responseTimes.length === 0) return 0
return responseTimes.reduce((sum, time) => sum + time, 0) / responseTimes.length
})
const isOperationActive = computed(() => (agentId: string, operation: string) => {
return activeOperations.value.some(
op => op.agentId === agentId && op.operation === operation
)
})
// =====================================================
// AGENT MANAGEMENT ACTIONS
// =====================================================
const fetchAgents = async (): Promise<boolean> => {
try {
loading.agents = true
const result = await api.getAgents()
if (result) {
agents.value = result
showNotification({
type: 'success',
title: 'Agents Loaded',
message: `Loaded ${result.length} agents successfully`,
})
return true
}
return false
} catch (error) {
showNotification({
type: 'error',
title: 'Load Failed',
message: 'Failed to load agents from server',
})
return false
} finally {
loading.agents = false
}
}
const selectAgent = async (agentId: string): Promise<boolean> => {
const agent = agents.value.find(a => a.id === agentId)
if (agent) {
selectedAgent.value = agent
return true
}
// Try to fetch from API if not found locally
const result = await api.getAgent(agentId)
if (result) {
selectedAgent.value = result
return true
}
return false
}
const updateAgentInStore = (updatedAgent: SaapAgent) => {
const index = agents.value.findIndex(a => a.id === updatedAgent.id)
if (index !== -1) {
agents.value[index] = updatedAgent
// Update selected agent if it's the same
if (selectedAgent.value?.id === updatedAgent.id) {
selectedAgent.value = updatedAgent
}
}
}
// =====================================================
// AGENT LIFECYCLE ACTIONS
// =====================================================
const startAgent = async (agentId: string): Promise<boolean> => {
try {
addOperation(agentId, 'starting')
const result = await api.startAgent(agentId)
if (result?.success) {
// Update agent status immediately
const agent = agents.value.find(a => a.id === agentId)
if (agent) {
agent.status = 'starting'
}
showNotification({
type: 'success',
title: 'Agent Starting',
message: `${result.agent?.name || agentId} is starting...`,
})
// Refresh agents after a short delay to get updated status
setTimeout(() => {
fetchAgents()
}, 2000)
return true
}
return false
} catch (error) {
showNotification({
type: 'error',
title: 'Start Failed',
message: `Failed to start agent ${agentId}`,
})
return false
} finally {
removeOperation(agentId, 'starting')
}
}
const stopAgent = async (agentId: string): Promise<boolean> => {
try {
addOperation(agentId, 'stopping')
const result = await api.stopAgent(agentId)
if (result?.success) {
// Update agent status immediately
const agent = agents.value.find(a => a.id === agentId)
if (agent) {
agent.status = 'inactive'
}
showNotification({
type: 'info',
title: 'Agent Stopped',
message: `Agent ${agentId} stopped successfully`,
})
return true
}
return false
} catch (error) {
showNotification({
type: 'error',
title: 'Stop Failed',
message: `Failed to stop agent ${agentId}`,
})
return false
} finally {
removeOperation(agentId, 'stopping')
}
}
// =====================================================
// AGENT COMMUNICATION ACTIONS
// =====================================================
const chatWithAgent = async (agentId: string, message: string): Promise<ChatMessage | null> => {
try {
addOperation(agentId, 'chatting')
const result = await api.chatWithAgent(agentId, message)
if (result) {
// Add to chat history
chatHistory.value.push(result)
// Update agent metrics
const agent = agents.value.find(a => a.id === agentId)
if (agent && agent.metrics) {
agent.metrics.messages_processed = (agent.metrics.messages_processed || 0) + 1
if (result.response_time) {
agent.metrics.average_response_time = result.response_time
}
}
showNotification({
type: 'success',
title: 'Message Sent',
message: `Received response from ${result.agent_name || agentId}`,
duration: 3000
})
return result
}
return null
} catch (error) {
showNotification({
type: 'error',
title: 'Chat Failed',
message: `Failed to chat with agent ${agentId}`,
})
return null
} finally {
removeOperation(agentId, 'chatting')
}
}
const getChatHistory = (agentId?: string): ChatMessage[] => {
if (agentId) {
return chatHistory.value.filter(msg => msg.agent_id === agentId)
}
return chatHistory.value
}
// =====================================================
// SYSTEM STATUS ACTIONS
// =====================================================
const fetchSystemStatus = async (): Promise<boolean> => {
try {
loading.systemStatus = true
const result = await api.getSystemStatus()
if (result) {
systemStatus.value = result
connectionStatus.api = true
connectionStatus.lastCheck = new Date().toISOString()
return true
}
connectionStatus.api = false
return false
} catch (error) {
connectionStatus.api = false
return false
} finally {
loading.systemStatus = false
}
}
const testConnections = async (): Promise<void> => {
// Test API connection
connectionStatus.api = await api.testConnection()
// Test WebSocket connection
if (!ws.connectionStatus.connected) {
connectionStatus.websocket = await ws.connect()
} else {
connectionStatus.websocket = true
}
connectionStatus.lastCheck = new Date().toISOString()
showNotification({
type: connectionStatus.api && connectionStatus.websocket ? 'success' : 'warning',
title: 'Connection Test',
message: `API: ${connectionStatus.api ? 'Connected' : 'Failed'}, WebSocket: ${connectionStatus.websocket ? 'Connected' : 'Failed'}`,
})
}
// =====================================================
// OPERATIONS TRACKING
// =====================================================
const addOperation = (agentId: string, operation: AgentOperation['operation']) => {
activeOperations.value.push({
agentId,
operation,
timestamp: new Date().toISOString()
})
}
const removeOperation = (agentId: string, operation: AgentOperation['operation']) => {
const index = activeOperations.value.findIndex(
op => op.agentId === agentId && op.operation === operation
)
if (index !== -1) {
activeOperations.value.splice(index, 1)
}
}
// =====================================================
// NOTIFICATIONS
// =====================================================
const showNotification = (notification: Omit<NotificationMessage, 'id' | 'timestamp'>) => {
const id = Date.now().toString() + Math.random().toString(36).substr(2, 9)
const fullNotification: NotificationMessage = {
...notification,
id,
timestamp: new Date().toISOString(),
duration: notification.duration || 5000
}
notifications.value.push(fullNotification)
// Auto-remove notification after duration
if (fullNotification.duration && fullNotification.duration > 0) {
setTimeout(() => {
removeNotification(id)
}, fullNotification.duration)
}
}
const removeNotification = (id: string) => {
const index = notifications.value.findIndex(n => n.id === id)
if (index !== -1) {
notifications.value.splice(index, 1)
}
}
const clearNotifications = () => {
notifications.value = []
}
// =====================================================
// WEBSOCKET INTEGRATION
// =====================================================
const initializeWebSocket = () => {
// Subscribe to agent updates
ws.subscribeToAgentUpdates((agentData: any) => {
console.log('π€ Agent update received:', agentData)
if (agentData.agent) {
updateAgentInStore(agentData.agent)
}
})
// Subscribe to message updates
ws.subscribeToMessageUpdates((messageData: any) => {
console.log('π¬ Message update received:', messageData)
if (messageData.agent_id) {
// Add to chat history if not already present
const exists = chatHistory.value.some(
msg => msg.timestamp === messageData.timestamp &&
msg.agent_id === messageData.agent_id
)
if (!exists) {
chatHistory.value.push(messageData)
}
}
})
// Subscribe to system updates
ws.subscribeToSystemUpdates((statusData: any) => {
console.log('π§ System update received:', statusData)
if (statusData.agents) {
systemStatus.value = statusData
}
})
// Connect WebSocket
ws.connect().then(connected => {
connectionStatus.websocket = connected
if (connected) {
ws.startHeartbeat()
}
})
}
// =====================================================
// INITIALIZATION
// =====================================================
const initialize = async (): Promise<void> => {
console.log('π Initializing SAAP Agent Store...')
// Initialize WebSocket
initializeWebSocket()
// Fetch initial data
await fetchSystemStatus()
await fetchAgents()
console.log('β
SAAP Agent Store initialized')
}
// =====================================================
// CLEANUP
// =====================================================
const cleanup = () => {
ws.disconnect()
ws.stopHeartbeat()
agents.value = []
selectedAgent.value = null
chatHistory.value = []
activeOperations.value = []
notifications.value = []
}
return {
// State
agents,
selectedAgent,
systemStatus,
chatHistory,
activeOperations,
notifications,
loading,
connectionStatus,
// Computed
activeAgents,
inactiveAgents,
agentsByType,
totalMessages,
averageResponseTime,
isOperationActive,
// Agent Management
fetchAgents,
selectAgent,
updateAgentInStore,
// Agent Lifecycle
startAgent,
stopAgent,
// Communication
chatWithAgent,
getChatHistory,
// System
fetchSystemStatus,
testConnections,
// Notifications
showNotification,
removeNotification,
clearNotifications,
// Lifecycle
initialize,
cleanup,
}
})
// Export types
export type { AgentOperation, NotificationMessage } |