import { OperoChatAPI } from "./OperoChatAPI"; import { OperoChatHistoryService, type Conversation, } from "./OperoChatHistoryService"; import { OperoCallbackManager } from "./OperoCallbackManager"; import { OperoAnalyticsService } from "./OperoAnalyticsService"; import type { OperoChatMessage, OperoChatCallbacks, OperoApiFilters, OperoAnalyticsConfig, OperoChatError, OperoSource, } from "../types"; import { generateId, log } from "../utils/helpers"; import { DEFAULT_API_ENDPOINT } from "../utils/constants"; export interface OperoChatServiceConfig { apiKey: string; apiEndpoint?: string; userEmail?: string; userRole?: string; callbacks?: OperoChatCallbacks; filters?: OperoApiFilters; analytics?: OperoAnalyticsConfig; } export interface OperoChatServiceState { isVisible: boolean; messages: OperoChatMessage[]; isLoading: boolean; isConnected: boolean; errorMessage: string | null; progressMessage: string | null; conversationTitle: string; isViewerVisible: boolean; viewerSource: OperoSource | null; viewerPageNumber?: number; // History state conversations: Conversation[]; isLoadingHistory: boolean; hasMoreConversations: boolean; isHistoryDrawerVisible: boolean; } export class OperoChatService { private api: OperoChatAPI; private historyService: OperoChatHistoryService; private callbacks: OperoCallbackManager; private analytics: OperoAnalyticsService; private state: OperoChatServiceState; private stateListeners: ((state: OperoChatServiceState) => void)[] = []; private filters?: OperoApiFilters; private conversationId?: string; constructor(config: OperoChatServiceConfig) { this.api = new OperoChatAPI( config.apiEndpoint || DEFAULT_API_ENDPOINT, config.apiKey, config.userEmail, config.userRole, ); this.historyService = new OperoChatHistoryService( config.apiEndpoint || DEFAULT_API_ENDPOINT, config.apiKey, this.api, ); this.callbacks = new OperoCallbackManager(config.callbacks || {}); this.filters = config.filters; // Initialize analytics this.analytics = new OperoAnalyticsService( config.userEmail, config.userRole, config.analytics || {}, ); this.state = { isVisible: false, messages: [], isLoading: false, isConnected: false, errorMessage: null, progressMessage: null, conversationTitle: "Opero Assistant", isViewerVisible: false, viewerSource: null, viewerPageNumber: undefined, // History state conversations: [], isLoadingHistory: false, hasMoreConversations: true, isHistoryDrawerVisible: false, }; // Track SDK initialization this.analytics.trackSDKInitialized({ hasCustomStyles: false, // This will be set from the hook hasFilters: !!config.filters, apiEndpoint: config.apiEndpoint || DEFAULT_API_ENDPOINT, callbacksConfigured: Object.keys(config.callbacks || {}), }); // Auto-connect on initialization this.checkConnectivity(); } // State management private setState(updates: Partial) { this.state = { ...this.state, ...updates }; this.notifyStateListeners(); } private notifyStateListeners() { this.stateListeners.forEach((listener) => listener(this.state)); } subscribe(listener: (state: OperoChatServiceState) => void) { this.stateListeners.push(listener); // Return unsubscribe function return () => { const index = this.stateListeners.indexOf(listener); if (index > -1) { this.stateListeners.splice(index, 1); } }; } getState(): OperoChatServiceState { return { ...this.state }; } // Chat actions async checkConnectivity(): Promise { const startTime = Date.now(); try { this.setState({ errorMessage: null }); const connected = await this.api.checkConnectivity(); const duration = Date.now() - startTime; if (connected) { this.setState({ isConnected: true }); this.callbacks.onReady(); this.analytics.trackConnectivityCheck(true, duration); return true; } else { this.setState({ isConnected: false, errorMessage: "Failed to connect to Opero API", }); this.analytics.trackConnectivityCheck(false, duration); return false; } } catch (error) { const duration = Date.now() - startTime; this.setState({ isConnected: false, errorMessage: "Connection check failed", }); const networkError = { type: "network" as const, message: "Failed to connect to API", details: error instanceof Error ? error.message : String(error), }; this.callbacks.onError(networkError); this.analytics.trackConnectivityCheck(false, duration); // Track the error as well this.analytics.trackError(networkError, { userEmail: this.api.getUserEmail, conversationId: this.conversationId, messageCount: this.state.messages.length, apiEndpoint: this.api.getApiEndpoint, customStylesEnabled: false, filtersActive: !!this.filters, errorSequence: ["checkConnectivity"], retryAttempted: false, networkStatus: "offline", }); return false; } } openChat(): void { this.setState({ isVisible: true }); this.analytics.trackChatSessionStarted(); } closeChat(): void { this.setState({ isVisible: false }); // Track conversation metrics before ending session if (this.state.messages.length > 0) { this.analytics.trackConversationMetrics(this.state.messages); } this.analytics.trackChatSessionEnded(); } async sendMessage(messageText: string): Promise { if (!messageText.trim()) return; if (!this.state.isConnected) { this.setState({ errorMessage: "Please check your API connection first.", }); return; } this.setState({ errorMessage: null }); // Add user message const userMessage: OperoChatMessage = { id: generateId(), role: "user", content: messageText, timestamp: new Date(), }; this.setState({ messages: [...this.state.messages, userMessage], }); // Add assistant message placeholder const assistantMessage: OperoChatMessage = { id: generateId(), role: "assistant", content: "", timestamp: new Date(), isStreaming: true, hasFilters: !!this.filters, // Track if filters were applied }; this.setState({ messages: [...this.state.messages, assistantMessage], isLoading: true, }); this.callbacks.onMessageSent(messageText); this.callbacks.onStreamStart(); // Analytics tracking this.analytics.trackMessageSent(messageText.length, !!this.filters); this.analytics.trackStreamingStarted(); // Track API call timing const apiCallStart = Date.now(); try { // Convert all messages to API format for full conversation history const updatedMessages = [...this.state.messages, assistantMessage]; const apiMessages = updatedMessages .filter((msg) => msg.role !== "assistant" || !msg.isStreaming) // Exclude streaming assistant placeholder .map((msg) => ({ role: msg.role, content: msg.content, })); const { fullMessage, conversationId } = await this.api.sendMessage( apiMessages, // Send full conversation history this.conversationId, // Pass conversationId this.filters, // Pass filters through directly to API (chunk) => { // Update the assistant message with streaming content this.setState({ messages: this.state.messages.map((msg) => msg.id === assistantMessage.id ? { ...msg, content: msg.content + chunk, isStreaming: true } : msg, ), }); }, (error) => { this.setState({ errorMessage: error.message, }); this.callbacks.onError(error); }, (progress) => { // Transform progress message if onProgress callback is provided const transformedProgress = this.callbacks.onProgress(progress); this.setState({ progressMessage: transformedProgress }); }, (sources) => { if ( this.callbacks && typeof this.callbacks.onSources === "function" ) { sources = this.callbacks.onSources(sources); } // Attach sources to the current assistant message this.setState({ messages: this.state.messages.map((msg) => msg.id === assistantMessage.id ? { ...msg, sources: sources } : msg, ), }); this.analytics.trackSourcesViewed(sources.length); }, (messageId, role) => { // Capture message ID from stream and attach to appropriate message this.setState({ messages: this.state.messages.map((msg) => { if (role === "user" && msg.id === userMessage.id) { return { ...msg, message_id: messageId }; } if (role === "assistant" && msg.id === assistantMessage.id) { return { ...msg, message_id: messageId }; } return msg; }), }); log(`Captured message_id ${messageId} for ${role} message`, "debug"); }, ); if (conversationId && !this.conversationId) { this.conversationId = conversationId; } // Finalize the assistant message this.setState({ messages: this.state.messages.map((msg) => msg.id === assistantMessage.id ? { ...msg, content: fullMessage, isStreaming: false } : msg, ), progressMessage: null, isLoading: false, }); this.callbacks.onStreamEnd(fullMessage); // Analytics tracking for API call and streaming completion const apiCallDuration = Date.now() - apiCallStart; this.analytics.trackAPICall({ endpoint: "/chat/completions", method: "POST", duration: apiCallDuration, success: true, statusCode: 200, }); const streamingStartTime = assistantMessage.timestamp.getTime(); const streamingDuration = Date.now() - streamingStartTime; this.analytics.trackStreamingCompleted( streamingDuration, fullMessage.length, ); // Generate title after the first exchange if (this.state.messages.length === 2) { // user + assistant message this.generateConversationTitle(); } } catch (error) { // Analytics tracking for failed API call const apiCallDuration = Date.now() - apiCallStart; this.analytics.trackAPICall({ endpoint: "/chat/completions", method: "POST", duration: apiCallDuration, success: false, statusCode: 500, // Default error status errorType: "api", }); // Only set generic error message if no specific error was already set by onError callback if (!this.state.errorMessage) { this.setState({ errorMessage: "Failed to send message. Please try again.", isLoading: false, }); const chatError = { type: "api" as const, message: "Failed to send message", details: error instanceof Error ? error.message : String(error), }; this.callbacks.onError(chatError); // Analytics error tracking this.analytics.trackError(chatError, { userEmail: this.api.getUserEmail, conversationId: this.conversationId, messageCount: this.state.messages.length, apiEndpoint: this.api.getApiEndpoint, customStylesEnabled: false, // Will be set from hook filtersActive: !!this.filters, errorSequence: ["sendMessage"], retryAttempted: false, }); } else { // Error was already set by onError callback, just stop loading this.setState({ isLoading: false }); } // Remove the failed assistant message this.setState({ messages: this.state.messages.filter( (msg) => msg.id !== assistantMessage.id, ), }); } } private async generateConversationTitle(): Promise { if (!this.conversationId) { return; } try { const title = await this.api.generateTitle( this.state.messages, this.conversationId, ); this.setState({ conversationTitle: title }); } catch (error) { // Don't show error for title generation, just keep default title log(`Failed to generate title: ${error}`, "warn"); } } clearMessages(): void { this.setState({ messages: [], conversationTitle: "Opero Assistant", }); // Clear conversation ID and history cache this.conversationId = undefined; this.historyService.clearCache(); // Load conversations when clearing messages (starting fresh) this.loadConversations(); } dismissError(): void { this.setState({ errorMessage: null }); } setError(error: OperoChatError): void { this.setState({ errorMessage: error.message }); this.callbacks.onError(error); } updateFilters(filters?: OperoApiFilters): void { this.filters = filters; // Analytics tracking for filter usage if (filters) { const filterTypes = Object.keys(filters); const documentCount = filters.documentNames?.length || filters.document_names?.length || 0; this.analytics.trackFiltersApplied(filterTypes, documentCount); } } // Reaction methods async handleReaction( messageId: string, reactionType: "thumbs_up" | "thumbs_down", ): Promise { try { const messages = [...this.state.messages]; const messageIndex = messages.findIndex( (m) => m.message_id === messageId, ); if (messageIndex === -1) { throw new Error("Message not found"); } const message = messages[messageIndex]!; // Assert non-null since we checked index const currentReaction = message.reaction?.type; // Optimistic update if (currentReaction === reactionType) { // Remove reaction messages[messageIndex] = { ...message, reaction: undefined, }; this.setState({ messages }); await this.api.removeReaction(messageId); log( `Removed ${reactionType} reaction from message ${messageId}`, "info", ); } else { // Add or update reaction messages[messageIndex] = { ...message, reaction: { type: reactionType, created_at: new Date().toISOString(), }, }; this.setState({ messages }); await this.api.addReaction(messageId, reactionType); log(`Added ${reactionType} reaction to message ${messageId}`, "info"); } // Track analytics this.analytics.trackMessageReaction(reactionType, messageId); } catch (error) { // Rollback on error this.setState({ messages: [...this.state.messages] }); const errorMessage = error instanceof Error ? error.message : "Failed to save reaction"; this.setError({ type: "api", message: `${errorMessage}. Please try again.`, details: error, }); } } // Document Viewer methods openDocumentViewer(source: OperoSource, pageNumber?: number): void { this.setState({ isViewerVisible: true, viewerSource: source, viewerPageNumber: pageNumber, }); log( `Document viewer opened: ${source.title}${pageNumber ? ` (page ${pageNumber})` : ""}`, "debug", ); } closeDocumentViewer(): void { this.setState({ isViewerVisible: false, viewerSource: null, viewerPageNumber: undefined, }); log("Document viewer closed", "debug"); } // Getter methods for external access get isVisible(): boolean { return this.state.isVisible; } get messages(): OperoChatMessage[] { return this.state.messages; } get isLoading(): boolean { return this.state.isLoading; } get isConnected(): boolean { return this.state.isConnected; } get errorMessage(): string | null { return this.state.errorMessage; } get progressMessage(): string | null { return this.state.progressMessage; } get conversationTitle(): string { return this.state.conversationTitle; } get isViewerVisible(): boolean { return this.state.isViewerVisible; } get viewerSource(): OperoSource | null { return this.state.viewerSource; } get viewerPageNumber(): number | undefined { return this.state.viewerPageNumber; } // History methods async loadConversations(): Promise { try { this.setState({ isLoadingHistory: true }); const data = await this.historyService.getConversations(5, 0); this.setState({ conversations: data.conversations, hasMoreConversations: data.has_more, isLoadingHistory: false, }); } catch (error) { this.setState({ isLoadingHistory: false }); const historyError = { type: "api" as const, message: "Failed to load conversation history", details: error instanceof Error ? error.message : String(error), }; this.callbacks.onError(historyError); } } async loadMoreConversations(): Promise { try { this.setState({ isLoadingHistory: true }); const data = await this.historyService.getConversations( 5, this.state.conversations.length, ); this.setState({ conversations: [...this.state.conversations, ...data.conversations], hasMoreConversations: data.has_more, isLoadingHistory: false, }); } catch (error) { this.setState({ isLoadingHistory: false }); const historyError = { type: "api" as const, message: "Failed to load more conversations", details: error instanceof Error ? error.message : String(error), }; this.callbacks.onError(historyError); } } async loadConversation(conversationId: string): Promise { try { const data = await this.historyService.getMessages(conversationId); // Convert API messages to OperoChatMessage format const messages: OperoChatMessage[] = data.messages.map((msg) => { const sources = (msg as any).citations || []; // Apply user's onSources callback to historical sources let transformedSources = sources; try { if (sources.length > 0) { transformedSources = this.callbacks.onSources(sources); } } catch (error) { // Show error banner if callback fails this.setError({ type: "api", message: "Failed to load sources", details: error instanceof Error ? error.message : String(error), }); } return { id: msg.id, role: msg.role as "user" | "assistant", content: msg.content, timestamp: new Date((msg as any).created_at), sources: transformedSources, message_id: (msg as any).message_id, // Backend message ID for reactions reaction: (msg as any).reaction, // Preserve user's reaction }; }); this.setState({ messages, conversationTitle: data.conversation.title, // Store conversationId in a private property, not in state // this.conversationId = data.conversation.id; }); // Set the conversation ID for future messages this.conversationId = data.conversation.id; // Clear conversation cache to ensure fresh data on next load this.historyService.clearConversationCache(conversationId); } catch (error) { const historyError = { type: "api" as const, message: "Failed to load conversation", details: error instanceof Error ? error.message : String(error), }; this.callbacks.onError(historyError); } } // Getter methods for history state get conversations(): Conversation[] { return this.state.conversations; } get isLoadingHistory(): boolean { return this.state.isLoadingHistory; } get hasMoreConversations(): boolean { return this.state.hasMoreConversations; } // History drawer methods openHistoryDrawer(): void { this.setState({ isHistoryDrawerVisible: true }); log("History drawer opened", "debug"); } closeHistoryDrawer(): void { this.setState({ isHistoryDrawerVisible: false }); log("History drawer closed", "debug"); } }