-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathsystem.ts
More file actions
400 lines (352 loc) · 13.4 KB
/
Copy pathsystem.ts
File metadata and controls
400 lines (352 loc) · 13.4 KB
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
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { StatusUpdate, Theme, Toast, InfoResponse, RoutingInfo } from '@/types'
import api from '@/services/api'
export const useSystemStore = defineStore('system', () => {
// State
const status = ref<StatusUpdate | null>(null)
const eventSource = ref<EventSource | null>(null)
const connected = ref(false)
const currentTheme = ref<string>('corporate')
const toasts = ref<Toast[]>([])
const info = ref<InfoResponse | null>(null)
const routing = ref<RoutingInfo | null>(null)
// Available themes
const themes: Theme[] = [
{ name: 'light', displayName: 'Light', dark: false },
{ name: 'dark', displayName: 'Dark', dark: true },
{ name: 'corporate', displayName: 'Corporate', dark: false },
{ name: 'business', displayName: 'Business', dark: true },
{ name: 'emerald', displayName: 'Emerald', dark: false },
{ name: 'forest', displayName: 'Forest', dark: true },
{ name: 'aqua', displayName: 'Aqua', dark: false },
{ name: 'lofi', displayName: 'Lo-Fi', dark: false },
{ name: 'pastel', displayName: 'Pastel', dark: false },
{ name: 'fantasy', displayName: 'Fantasy', dark: false },
{ name: 'wireframe', displayName: 'Wireframe', dark: false },
{ name: 'luxury', displayName: 'Luxury', dark: true },
{ name: 'dracula', displayName: 'Dracula', dark: true },
{ name: 'synthwave', displayName: 'Synthwave', dark: true },
{ name: 'cyberpunk', displayName: 'Cyberpunk', dark: true },
]
// Computed
const isRunning = computed(() => {
// Priority: Top-level running field, then nested status.running, default false
if (status.value?.running !== undefined) {
return status.value.running
}
// Fallback to nested status.running if top-level is undefined
if (status.value?.status?.running !== undefined) {
return status.value.status.running
}
return false
})
const listenAddr = computed(() => status.value?.listen_addr ?? '')
const upstreamStats = computed(() => status.value?.upstream_stats ?? {
connected_servers: 0,
total_servers: 0,
total_tools: 0,
})
const currentThemeConfig = computed(() =>
themes.find(t => t.name === currentTheme.value) || themes[0]
)
// Version information
const version = computed(() => info.value?.version ?? '')
const updateAvailable = computed(() => info.value?.update?.available ?? false)
const latestVersion = computed(() => info.value?.update?.latest_version ?? '')
// Routing mode
const routingMode = computed(() => routing.value?.routing_mode ?? status.value?.routing_mode ?? 'retrieve_tools')
// Actions
function connectEventSource() {
if (eventSource.value) {
eventSource.value.close()
}
console.log('Attempting to connect EventSource...')
console.log('API key status:', {
hasApiKey: api.hasAPIKey(),
apiKeyPreview: api.getAPIKeyPreview()
})
const es = api.createEventSource()
eventSource.value = es
es.onopen = () => {
connected.value = true
console.log('EventSource connected successfully')
}
es.onmessage = (event) => {
try {
const data = JSON.parse(event.data) as StatusUpdate
status.value = data
// Debug logging to help diagnose status issues
console.log('SSE Status Update:', {
topLevelRunning: data.running,
nestedStatusRunning: data.status?.running,
listen_addr: data.listen_addr,
timestamp: data.timestamp,
finalRunningValue: data.running !== undefined ? data.running : (data.status?.running ?? false)
})
// You could emit events here for other stores to listen to
// For example, update server statuses
} catch (error) {
console.error('Failed to parse SSE message:', error)
}
}
// Listen specifically for status events
es.addEventListener('status', (event) => {
try {
const data = JSON.parse(event.data) as StatusUpdate
status.value = data
// Debug logging to help diagnose status issues
console.log('SSE Status Event Update:', {
topLevelRunning: data.running,
nestedStatusRunning: data.status?.running,
listen_addr: data.listen_addr,
timestamp: data.timestamp,
finalRunningValue: data.running !== undefined ? data.running : (data.status?.running ?? false)
})
} catch (error) {
console.error('Failed to parse SSE status event:', error)
}
})
// Listen for servers.changed events to trigger immediate UI updates
es.addEventListener('servers.changed', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE servers.changed event received:', data)
// Import and call serversStore.fetchServers() to refresh server list
// Note: This creates a circular dependency, so we'll emit a custom event instead
window.dispatchEvent(new CustomEvent('mcpproxy:servers-changed', { detail: data }))
} catch (error) {
console.error('Failed to parse SSE servers.changed event:', error)
}
})
// Listen for config.reloaded events
es.addEventListener('config.reloaded', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE config.reloaded event received:', data)
// Trigger server list refresh on config reload
window.dispatchEvent(new CustomEvent('mcpproxy:config-reloaded', { detail: data }))
} catch (error) {
console.error('Failed to parse SSE config.reloaded event:', error)
}
})
// Listen for config.saved events to notify Configuration page
es.addEventListener('config.saved', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE config.saved event received:', data)
// Dispatch event for Configuration page to refresh
window.dispatchEvent(new CustomEvent('mcpproxy:config-saved', { detail: data }))
} catch (error) {
console.error('Failed to parse SSE config.saved event:', error)
}
})
// Listen for activity events (tool calls, policy decisions, etc.)
es.addEventListener('activity.tool_call.started', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.tool_call.started event received:', data)
// Extract payload - SSE wraps activity data in {payload: ..., timestamp: ...}
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity-started', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.tool_call.started event:', error)
}
})
es.addEventListener('activity.tool_call.completed', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.tool_call.completed event received:', data)
// Extract payload - SSE wraps activity data in {payload: ..., timestamp: ...}
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity-completed', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.tool_call.completed event:', error)
}
})
es.addEventListener('activity.policy_decision', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.policy_decision event received:', data)
// Extract payload - SSE wraps activity data in {payload: ..., timestamp: ...}
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity-policy', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.policy_decision event:', error)
}
})
es.addEventListener('activity', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity event received:', data)
// Extract payload - SSE wraps activity data in {payload: ..., timestamp: ...}
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity event:', error)
}
})
// Listen for internal tool call events (Spec 024)
es.addEventListener('activity.internal_tool_call.completed', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.internal_tool_call.completed event received:', data)
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity-completed', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.internal_tool_call.completed event:', error)
}
})
// Listen for system lifecycle events (Spec 024)
// Note: Backend sends "activity.system.start" (with dots, not underscores)
es.addEventListener('activity.system.start', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.system_start event received:', data)
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.system_start event:', error)
}
})
// Note: Backend sends "activity.system.stop" (with dots, not underscores)
es.addEventListener('activity.system.stop', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.system_stop event received:', data)
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.system_stop event:', error)
}
})
// Listen for config change events (Spec 024)
es.addEventListener('activity.config_change', (event) => {
try {
const data = JSON.parse(event.data)
console.log('SSE activity.config_change event received:', data)
const payload = data.payload || data
window.dispatchEvent(new CustomEvent('mcpproxy:activity', { detail: payload }))
} catch (error) {
console.error('Failed to parse SSE activity.config_change event:', error)
}
})
es.onerror = (event) => {
connected.value = false
console.error('EventSource error occurred:', event)
// Check if this might be an authentication error
if (es.readyState === EventSource.CLOSED) {
console.error('EventSource connection closed - possible authentication failure')
// If we have an API key but still failed, try reinitializing
if (api.hasAPIKey()) {
console.log('Attempting to reinitialize API key and retry connection...')
api.reinitializeAPIKey()
}
}
// Retry connection after a delay
setTimeout(() => {
console.log('Retrying EventSource connection in 5 seconds...')
connectEventSource()
}, 5000)
}
}
function disconnectEventSource() {
if (eventSource.value) {
eventSource.value.close()
eventSource.value = null
}
connected.value = false
}
function setTheme(themeName: string) {
const theme = themes.find(t => t.name === themeName)
if (theme) {
currentTheme.value = themeName
document.documentElement.setAttribute('data-theme', themeName)
localStorage.setItem('mcpproxy-theme', themeName)
}
}
function loadTheme() {
const savedTheme = localStorage.getItem('mcpproxy-theme')
if (savedTheme && themes.find(t => t.name === savedTheme)) {
setTheme(savedTheme)
} else {
setTheme('corporate')
}
}
function addToast(toast: Omit<Toast, 'id'>): string {
const id = Math.random().toString(36).substr(2, 9)
const newToast: Toast = {
...toast,
id,
duration: toast.duration ?? 5000,
}
toasts.value.push(newToast)
// Auto-remove toast after duration
if (newToast.duration && newToast.duration > 0) {
setTimeout(() => {
removeToast(id)
}, newToast.duration)
}
return id
}
function removeToast(id: string) {
const index = toasts.value.findIndex(t => t.id === id)
if (index > -1) {
toasts.value.splice(index, 1)
}
}
function clearToasts() {
toasts.value = []
}
async function fetchInfo() {
try {
const response = await api.getInfo()
if (response.success && response.data) {
info.value = response.data
}
} catch (error) {
console.error('Failed to fetch info:', error)
}
}
async function fetchRouting() {
try {
const response = await api.getRouting()
if (response.success && response.data) {
routing.value = response.data
}
} catch (error) {
console.error('Failed to fetch routing:', error)
}
}
// Initialize theme on store creation
loadTheme()
return {
// State
status,
connected,
currentTheme,
toasts,
themes,
info,
routing,
// Computed
isRunning,
listenAddr,
upstreamStats,
currentThemeConfig,
version,
updateAvailable,
latestVersion,
routingMode,
// Actions
connectEventSource,
disconnectEventSource,
setTheme,
loadTheme,
addToast,
removeToast,
clearToasts,
fetchInfo,
fetchRouting,
}
})