import type { OperoChatMessage } from "../types"; import type { OperoChatAPI } from "./OperoChatAPI"; export interface Conversation { id: string; title: string; updated_at: string; created_at: string; last_message_at?: string; } export interface ConversationMessages { messages: OperoChatMessage[]; conversation: { id: string; title: string; created_at: string; }; has_more: boolean; } export interface ConversationsResponse { conversations: Conversation[]; total: number; has_more: boolean; } export class OperoChatHistoryService { private apiEndpoint: string; private apiKey: string; private api: OperoChatAPI; private cache: Map = new Map(); // Local caching constructor(apiEndpoint: string, apiKey: string, api: OperoChatAPI) { this.apiEndpoint = apiEndpoint; this.apiKey = apiKey; this.api = api; } /** * Get user's conversations with pagination. * Returns 5 conversations by default, expandable with scroll. * Conversations are sorted by the timestamp of their last message. */ async getConversations( limit: number = 5, offset: number = 0, ): Promise { // Check cache first const cacheKey = `conversations_${limit}_${offset}`; if (this.cache.has(cacheKey)) { return this.cache.get(cacheKey); } try { // Fetch from API const response = await fetch( `${this.apiEndpoint}/conversations?limit=${limit}&offset=${offset}`, { method: "GET", headers: { "Content-Type": "application/json", "X-API-Key": this.apiKey, ...(this.api.getUserIdentifier && { "X-User-Id": this.api.getUserIdentifier, }), }, }, ); if (!response.ok) { throw new Error( `Failed to fetch conversations: ${response.statusText}`, ); } const data = await response.json(); // Cache the result this.cache.set(cacheKey, data); return data; } catch (error) { console.error("Error fetching conversations:", error); throw error; } } /** * Get messages in a conversation with pagination. * Returns 10 messages by default, expandable with scroll. */ async getMessages( conversationId: string, limit: number = 10, offset: number = 0, ): Promise { // Check cache first const cacheKey = `messages_${conversationId}_${limit}_${offset}`; if (this.cache.has(cacheKey)) { return this.cache.get(cacheKey); } try { // Fetch from API const response = await fetch( `${this.apiEndpoint}/conversations/${conversationId}/messages?limit=${limit}&offset=${offset}`, { method: "GET", headers: { "Content-Type": "application/json", "X-API-Key": this.apiKey, ...(this.api.getUserIdentifier && { "X-User-Id": this.api.getUserIdentifier, }), }, }, ); if (!response.ok) { throw new Error(`Failed to fetch messages: ${response.statusText}`); } const data = await response.json(); // Transform messages to include sources from metadata and preserve reactions const transformedData = { ...data, messages: data.messages?.map((message: any) => ({ id: message.id, role: message.role, content: message.content, timestamp: new Date(message.created_at), citations: message.metadata?.citations || [], message_id: message.id, // Backend message ID for reactions reaction: message.reaction || undefined, // Preserve reaction data })) || [], }; // Cache the result this.cache.set(cacheKey, transformedData); return transformedData; } catch (error) { console.error("Error fetching conversation messages:", error); throw error; } } /** * Clear cache when needed (e.g., after new messages are sent) */ clearCache(): void { this.cache.clear(); } /** * Clear cache for a specific conversation (e.g., after new messages in that conversation) */ clearConversationCache(conversationId: string): void { const keysToDelete: string[] = []; for (const key of this.cache.keys()) { if ( key.includes(`messages_${conversationId}`) || key.includes("conversations_") ) { keysToDelete.push(key); } } keysToDelete.forEach((key) => this.cache.delete(key)); } }