import type { Agent, ChatMessage } from './types'; import { msgId } from './types'; export class AgentChatState { messages = $state([]); conversationId: string; streaming = $state(false); streamingFrom = $state(null); streamingText = $state(null); streamingThinking = $state(null); historyLoaded = $state(false); introRequested = $state(false); agentState = $state('unknown'); scheduleVersion = $state(0); skillVersion = $state(0); constructor(agentId: string) { this.conversationId = `user:${agentId}`; } /** Merge server history into local messages without losing un-persisted local ones. */ mergeHistory(serverMessages: ChatMessage[]): void { if (this.messages.length === 0) { this.messages = serverMessages; return; } const existingKeys = new Set( this.messages.map((m) => `${m.from}:${m.timestamp.getTime()}:${m.text.slice(0, 80)}`), ); const merged: ChatMessage[] = []; for (const sm of serverMessages) { const key = `${sm.from}:${sm.timestamp.getTime()}:${sm.text.slice(0, 80)}`; if (!existingKeys.has(key)) { merged.push(sm); } } if (merged.length === 0) return; const combined = [...merged, ...this.messages]; combined.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime()); this.messages = combined; } } export type ConnectionState = 'connecting' | 'connected' | 'disconnected'; class AppState { agents = $state([]); activeId = $state(sessionStorage.getItem('mozartActiveAgent')); chats = $state>({}); connectionState = $state('connecting'); get active(): Agent | undefined { return this.agents.find((a) => a.id === this.activeId); } ensureChat(id: string): AgentChatState { if (!this.chats[id]) { this.chats[id] = new AgentChatState(id); } return this.chats[id]; } getChat(id: string): AgentChatState | undefined { return this.chats[id]; } selectAgent(id: string) { this.ensureChat(id); this.activeId = id; sessionStorage.setItem('mozartActiveAgent', id); } removeChat(id: string) { delete this.chats[id]; if (this.activeId === id) { this.activeId = null; sessionStorage.removeItem('mozartActiveAgent'); } } } export const appState = new AppState();