Spaces:
Sleeping
Sleeping
File size: 10,604 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 |
/**
* SAAP Agent Store - Pinia State Management
* Centralized state management for SAAP agent operations
*/
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import saapApi, { saapWebSocket } from '@/services/saapApi'
export const useAgentStore = defineStore('agents', () => {
// ==========================================
// STATE
// ==========================================
const agents = ref([])
const isLoading = ref(false)
const isConnected = ref(false)
const error = ref(null)
const systemInfo = ref(null)
const lastUpdate = ref(null)
// Agent-specific loading states
const agentLoading = ref(new Map())
// Chat messages storage
const chatMessages = ref(new Map())
// ==========================================
// GETTERS (Computed)
// ==========================================
const activeAgents = computed(() =>
agents.value.filter(agent => agent.status === 'active')
)
const inactiveAgents = computed(() =>
agents.value.filter(agent => agent.status === 'inactive')
)
const startingAgents = computed(() =>
agents.value.filter(agent => agent.status === 'starting')
)
const errorAgents = computed(() =>
agents.value.filter(agent => agent.status === 'error')
)
const totalAgents = computed(() => agents.value.length)
const agentById = computed(() => (id) =>
agents.value.find(agent => agent.id === id)
)
const connectionStatus = computed(() => ({
isConnected: isConnected.value,
status: isConnected.value ? 'connected' : 'disconnected',
className: isConnected.value ? 'status-connected' : 'status-disconnected',
text: isConnected.value ? 'Connected' : 'Disconnected'
}))
// Agent statistics
const agentStats = computed(() => ({
total: totalAgents.value,
active: activeAgents.value.length,
inactive: inactiveAgents.value.length,
starting: startingAgents.value.length,
error: errorAgents.value.length
}))
// ==========================================
// ACTIONS
// ==========================================
/**
* Initialize store and WebSocket connection
*/
async function initialize() {
console.log('π Initializing SAAP Agent Store...')
try {
// Setup WebSocket listeners
setupWebSocketListeners()
// Connect to WebSocket
saapWebSocket.connect()
// Load initial data
await Promise.all([
loadAgents(),
loadSystemInfo()
])
console.log('β
SAAP Agent Store initialized successfully')
} catch (err) {
console.error('β Store initialization failed:', err)
setError('Failed to initialize SAAP Platform')
}
}
/**
* Setup WebSocket event listeners
*/
function setupWebSocketListeners() {
saapWebSocket.on('connected', () => {
console.log('β
WebSocket connected')
isConnected.value = true
clearError()
})
saapWebSocket.on('disconnected', () => {
console.log('π WebSocket disconnected')
isConnected.value = false
})
saapWebSocket.on('error', (error) => {
console.error('β WebSocket error:', error)
isConnected.value = false
setError('WebSocket connection failed')
})
saapWebSocket.on('message', (data) => {
handleWebSocketMessage(data)
})
}
/**
* Handle incoming WebSocket messages
*/
function handleWebSocketMessage(data) {
console.log('π¨ Processing WebSocket message:', data)
// Handle different message types
if (typeof data === 'string') {
// Handle echo messages or simple strings
console.log('Echo received:', data)
} else if (data && data.type) {
// Handle structured messages
switch (data.type) {
case 'agent_update':
updateAgentFromWebSocket(data.agent)
break
case 'agent_status':
updateAgentStatus(data.agent_id, data.status)
break
case 'chat_message':
addChatMessage(data.agent_id, data.message, data.response)
break
default:
console.log('Unknown message type:', data.type)
}
}
}
/**
* Load all agents from API
*/
async function loadAgents() {
setLoading(true)
try {
const response = await saapApi.getAgents()
agents.value = Array.isArray(response) ? response : []
lastUpdate.value = new Date().toISOString()
console.log(`π Loaded ${agents.value.length} agents`)
clearError()
} catch (err) {
console.error('β Failed to load agents:', err)
setError('Failed to load agents')
agents.value = []
} finally {
setLoading(false)
}
}
/**
* Load system information
*/
async function loadSystemInfo() {
try {
const info = await saapApi.getSystemInfo()
systemInfo.value = info
console.log('π System info loaded:', info)
} catch (err) {
console.error('β Failed to load system info:', err)
setError('Failed to load system information')
}
}
/**
* Start an agent
*/
async function startAgent(agentId) {
setAgentLoading(agentId, true)
try {
const response = await saapApi.startAgent(agentId)
console.log(`βΆοΈ Agent ${agentId} started:`, response)
// Update local state
updateAgentStatus(agentId, 'starting')
// Reload agents to get updated state
setTimeout(() => loadAgents(), 1000)
return response
} catch (err) {
console.error(`β Failed to start agent ${agentId}:`, err)
setError(`Failed to start agent: ${agentId}`)
throw err
} finally {
setAgentLoading(agentId, false)
}
}
/**
* Stop an agent
*/
async function stopAgent(agentId) {
setAgentLoading(agentId, true)
try {
const response = await saapApi.stopAgent(agentId)
console.log(`βΉοΈ Agent ${agentId} stopped:`, response)
// Update local state
updateAgentStatus(agentId, 'inactive')
return response
} catch (err) {
console.error(`β Failed to stop agent ${agentId}:`, err)
setError(`Failed to stop agent: ${agentId}`)
throw err
} finally {
setAgentLoading(agentId, false)
}
}
/**
* Send message to agent
*/
async function chatWithAgent(agentId, message) {
setAgentLoading(agentId, true)
try {
const response = await saapApi.chatWithAgent(agentId, message)
console.log(`π¬ Chat with ${agentId}:`, response)
// Store chat message
addChatMessage(agentId, message, response.response)
return response
} catch (err) {
console.error(`β Failed to chat with agent ${agentId}:`, err)
setError(`Failed to communicate with agent: ${agentId}`)
throw err
} finally {
setAgentLoading(agentId, false)
}
}
/**
* Create agent from template
*/
async function createAgentFromTemplate(templateName) {
setLoading(true)
try {
const response = await saapApi.createAgentFromTemplate(templateName)
console.log(`β¨ Agent created from template ${templateName}:`, response)
// Reload agents
await loadAgents()
return response
} catch (err) {
console.error(`β Failed to create agent from template ${templateName}:`, err)
setError(`Failed to create agent from template: ${templateName}`)
throw err
} finally {
setLoading(false)
}
}
// ==========================================
// HELPER FUNCTIONS
// ==========================================
/**
* Update agent status
*/
function updateAgentStatus(agentId, status) {
const agent = agents.value.find(a => a.id === agentId)
if (agent) {
agent.status = status
console.log(`π Agent ${agentId} status updated to: ${status}`)
}
}
/**
* Update agent from WebSocket message
*/
function updateAgentFromWebSocket(agentData) {
const index = agents.value.findIndex(a => a.id === agentData.id)
if (index !== -1) {
agents.value[index] = { ...agents.value[index], ...agentData }
console.log(`π Agent ${agentData.id} updated from WebSocket`)
}
}
/**
* Add chat message to history
*/
function addChatMessage(agentId, message, response) {
if (!chatMessages.value.has(agentId)) {
chatMessages.value.set(agentId, [])
}
const messages = chatMessages.value.get(agentId)
messages.push({
id: Date.now(),
user_message: message,
agent_response: response?.content || response,
timestamp: new Date().toISOString()
})
// Keep only last 100 messages per agent
if (messages.length > 100) {
messages.splice(0, messages.length - 100)
}
}
/**
* Set loading state
*/
function setLoading(loading) {
isLoading.value = loading
}
/**
* Set agent-specific loading state
*/
function setAgentLoading(agentId, loading) {
agentLoading.value.set(agentId, loading)
}
/**
* Check if agent is loading
*/
function isAgentLoading(agentId) {
return agentLoading.value.get(agentId) || false
}
/**
* Set error state
*/
function setError(errorMessage) {
error.value = errorMessage
console.error('Store Error:', errorMessage)
}
/**
* Clear error state
*/
function clearError() {
error.value = null
}
/**
* Get chat messages for agent
*/
function getChatMessages(agentId) {
return chatMessages.value.get(agentId) || []
}
/**
* Refresh all data
*/
async function refresh() {
await Promise.all([
loadAgents(),
loadSystemInfo()
])
}
/**
* Cleanup store (disconnect WebSocket)
*/
function cleanup() {
console.log('π§Ή Cleaning up SAAP Agent Store...')
saapWebSocket.disconnect()
isConnected.value = false
}
// ==========================================
// RETURN STORE INTERFACE
// ==========================================
return {
// State
agents,
isLoading,
isConnected,
error,
systemInfo,
lastUpdate,
// Getters
activeAgents,
inactiveAgents,
startingAgents,
errorAgents,
totalAgents,
agentById,
connectionStatus,
agentStats,
// Actions
initialize,
loadAgents,
loadSystemInfo,
startAgent,
stopAgent,
chatWithAgent,
createAgentFromTemplate,
refresh,
cleanup,
// Helper functions
isAgentLoading,
getChatMessages,
clearError
}
})
|