Spaces:
Running
Running
| import { get } from "svelte/store"; | |
| import { websocketService } from "../services/websocket"; | |
| import { chatStore } from "../stores/chat-store"; | |
| import { authStore } from "../services/auth"; | |
| import { type ChatMessage } from "../models/chat-data"; | |
| export class ChatController { | |
| sendMessage(content: string): void { | |
| const trimmedContent = content.trim(); | |
| if (!trimmedContent) return; | |
| const state = get(chatStore); | |
| if (!state.connected || state.processing) return; | |
| const userMessage: ChatMessage = { | |
| id: `user_${Date.now()}`, | |
| role: "user", | |
| content: trimmedContent, | |
| timestamp: Date.now(), | |
| }; | |
| chatStore.addMessage(userMessage); | |
| chatStore.setError(null); | |
| websocketService.send({ | |
| type: "chat", | |
| payload: { content: trimmedContent }, | |
| timestamp: Date.now(), | |
| }); | |
| chatStore.setProcessing(true); | |
| } | |
| stopConversation(): void { | |
| const state = get(chatStore); | |
| if (!state.connected) return; | |
| websocketService.send({ | |
| type: "abort", | |
| payload: {}, | |
| timestamp: Date.now(), | |
| }); | |
| chatStore.setProcessing(false); | |
| } | |
| clearConversation(): void { | |
| const state = get(chatStore); | |
| if (!state.connected) return; | |
| websocketService.send({ | |
| type: "clear_conversation", | |
| payload: {}, | |
| timestamp: Date.now(), | |
| }); | |
| chatStore.clearMessages(); | |
| } | |
| handleConnectionChange(connected: boolean): void { | |
| chatStore.setConnected(connected); | |
| if (connected) { | |
| this.authenticate(); | |
| this.syncEditor(); | |
| } | |
| } | |
| handleProcessingChange(processing: boolean): void { | |
| chatStore.setProcessing(processing); | |
| } | |
| handleError(error: string | null): void { | |
| chatStore.setError(error); | |
| chatStore.setProcessing(false); | |
| } | |
| private authenticate(): void { | |
| const token = authStore.getToken(); | |
| if (token) { | |
| websocketService.send({ | |
| type: "auth", | |
| payload: { token }, | |
| timestamp: Date.now(), | |
| }); | |
| } else { | |
| const authState = get(authStore); | |
| if (!authState.isAuthenticated && !authState.loading) { | |
| chatStore.setError( | |
| "Authentication required. Please sign in with Hugging Face.", | |
| ); | |
| chatStore.setConnected(false); | |
| websocketService.disconnect(); | |
| } | |
| } | |
| } | |
| private syncEditor(): void { | |
| import("../services/content-manager").then(({ contentManager }) => { | |
| const currentContent = contentManager.getCurrentContent(); | |
| if (currentContent) { | |
| setTimeout(() => { | |
| if (websocketService.isConnected()) { | |
| websocketService.send({ | |
| type: "editor_sync", | |
| payload: { content: currentContent }, | |
| timestamp: Date.now(), | |
| }); | |
| } | |
| }, 500); | |
| } | |
| }); | |
| } | |
| } | |
| export const chatController = new ChatController(); | |