Spaces:
Running
Running
| import { websocketService, type WebSocketMessage } from "./websocket"; | |
| import { messageHandler } from "./message-handler"; | |
| import { chatController } from "../controllers/chat-controller"; | |
| import { authStore } from "./auth"; | |
| export class AgentService { | |
| private isInitialized = false; | |
| private unsubscribeHandlers: Array<() => void> = []; | |
| connect(): void { | |
| if (this.isInitialized) return; | |
| this.unsubscribeHandlers.push( | |
| websocketService.onConnection((connected) => { | |
| chatController.handleConnectionChange(connected); | |
| }), | |
| websocketService.onMessage(this.handleMessage.bind(this)), | |
| ); | |
| websocketService.connect(); | |
| this.isInitialized = true; | |
| } | |
| disconnect(): void { | |
| websocketService.disconnect(); | |
| this.unsubscribeHandlers.forEach((unsubscribe) => unsubscribe()); | |
| this.unsubscribeHandlers = []; | |
| this.isInitialized = false; | |
| } | |
| sendMessage(content: string): void { | |
| chatController.sendMessage(content); | |
| } | |
| stopConversation(): void { | |
| chatController.stopConversation(); | |
| } | |
| clearConversation(): void { | |
| chatController.clearConversation(); | |
| } | |
| sendRawMessage(message: unknown): void { | |
| if (websocketService.isConnected()) { | |
| websocketService.send(message as WebSocketMessage); | |
| } | |
| } | |
| reauthenticate(): void { | |
| if (websocketService.isConnected()) { | |
| const token = authStore.getToken(); | |
| if (token) { | |
| websocketService.send({ | |
| type: "auth", | |
| payload: { token }, | |
| timestamp: Date.now(), | |
| } as WebSocketMessage); | |
| } | |
| } else { | |
| this.connect(); | |
| } | |
| } | |
| private handleMessage(message: WebSocketMessage): void { | |
| messageHandler.handleMessage(message); | |
| } | |
| } | |
| export const agentService = new AgentService(); | |