import { EnxWebViewBridge, formatMultiSuggestionWireText } from './bridge'; import { EnxBotConfig, EnxChoice, EnxConnectionStatus, EnxMessage, EnxMessageSender, EnxMessageType, EnxSuggestionType, } from './types'; type Listener = () => void; export class EnxChatController { readonly bridge: EnxWebViewBridge; private listeners = new Set(); private _messages: EnxMessage[] = []; private _status = EnxConnectionStatus.Idle; private _isTyping = false; private _botInfo?: Record; private _conversationId?: string; private _errorMessage?: string; private typingTimer?: ReturnType; /** * Outbound user text variants we already showed locally; the WebView echoes one of them back. * Multi-select shows `a, b` but the wire payload is `["a","b"]` — register both so either echo is dropped. * Slots expire so stray entries cannot suppress a later real message indefinitely. */ private outgoingUserTextEchoDedup: { text: string; expiresAt: number }[] = []; private readonly userEchoDedupTtlMs = 15000; private readonly userEchoDedupMaxSlots = 24; onMessageReceived?: (message: EnxMessage) => void; onStatusChanged?: (status: EnxConnectionStatus) => void; onError?: (message: string, type: string) => void; onBotInfoReceived?: (info: Record) => void; /** Fired when the bot sends a video-room iframe URL (`audio_video_action: start`). */ onVideoCallRequest?: (url: string) => void; /** Fired when the bot sends `audio_video_action: stop` (end call / hang up). */ onVideoCallEnd?: () => void; constructor(public readonly config: EnxBotConfig) { this.bridge = new EnxWebViewBridge(config); this.bindBridge(); } get messages(): EnxMessage[] { return this._messages; } get status(): EnxConnectionStatus { return this._status; } get isConnected(): boolean { return this._status === EnxConnectionStatus.Connected; } get isTyping(): boolean { return this._isTyping; } get botInfo(): Record | undefined { return this._botInfo; } get conversationId(): string | undefined { return this._conversationId; } get errorMessage(): string | undefined { return this._errorMessage; } subscribe(listener: Listener): () => void { this.listeners.add(listener); return () => this.listeners.delete(listener); } async initialize(): Promise { if (this._status !== EnxConnectionStatus.Idle) return; this.setStatus(EnxConnectionStatus.Loading); } async sendText(text: string): Promise { const clean = text.trim(); if (!clean) return; this.push({ sender: EnxMessageSender.User, type: EnxMessageType.Text, timestamp: new Date(), text: clean }); this.enqueueOutgoingUserTextForDedup(clean); await this.bridge.sendText(clean); } async sendSuggestions(titles: string[], type: EnxSuggestionType): Promise { if (!titles.length) return; const joined = titles.join(', '); this.push({ sender: EnxMessageSender.User, type: EnxMessageType.Text, timestamp: new Date(), text: joined }); if (type === EnxSuggestionType.Multiple) { this.enqueueOutgoingUserTextForDedup(joined, formatMultiSuggestionWireText(titles)); } else { this.enqueueOutgoingUserTextForDedup(joined); } if (type === EnxSuggestionType.Single) await this.bridge.sendSingleSuggestion(titles[0]); else await this.bridge.sendMultiSuggestion(titles); } async sendChoice(choice: EnxChoice): Promise { await this.sendSuggestions([choice.title], EnxSuggestionType.Single); } async sendMultiChoice(choices: EnxChoice[]): Promise { await this.sendSuggestions(choices.map((c) => c.title), EnxSuggestionType.Multiple); } async sendFile(data: { base64: string; fileName: string; mimeType: string; localUri?: string; size?: number }): Promise { const type = data.mimeType.startsWith('video/') ? EnxMessageType.Video : data.mimeType.startsWith('image/') ? EnxMessageType.Image : EnxMessageType.File; this.push({ sender: EnxMessageSender.User, type, timestamp: new Date(), text: data.fileName, media: { fileName: data.fileName, mimeType: data.mimeType, localUri: data.localUri, size: data.size }, }); await this.bridge.sendFile(data.base64, data.fileName, data.mimeType); } async resetConversation(): Promise { await this.bridge.resetConversation(); this._messages = []; this.outgoingUserTextEchoDedup = []; this.emit(); } async reconnect(): Promise { this.setStatus(EnxConnectionStatus.Reconnecting); await this.bridge.reconnect(); } clearMessages(): void { this._messages = []; this.outgoingUserTextEchoDedup = []; this.emit(); } async dispose(): Promise { if (this.typingTimer) clearTimeout(this.typingTimer); await this.bridge.disconnect(); this.listeners.clear(); } private bindBridge(): void { this.bridge.callbacks.onReady = () => this.setStatus(EnxConnectionStatus.Connected); this.bridge.callbacks.onConnected = () => this.setStatus(EnxConnectionStatus.Connected); this.bridge.callbacks.onDisconnected = () => this.setStatus(EnxConnectionStatus.Disconnected); this.bridge.callbacks.onReconnecting = () => this.setStatus(EnxConnectionStatus.Reconnecting); this.bridge.callbacks.onReconnected = () => this.setStatus(EnxConnectionStatus.Connected); this.bridge.callbacks.onReconnectFailed = () => this.setStatus(EnxConnectionStatus.Error); this.bridge.callbacks.onBotInfo = (info) => { this._botInfo = info; this.onBotInfoReceived?.(info); this.emit(); }; this.bridge.callbacks.onConversationReady = (id) => { this._conversationId = id; this.emit(); }; this.bridge.callbacks.onVideoCallRequest = (url) => { this.onVideoCallRequest?.(url); }; this.bridge.callbacks.onVideoCallEnd = () => { this.onVideoCallEnd?.(); }; this.bridge.callbacks.onMessage = (raw) => { const msg = raw as EnxMessage; this._isTyping = false; if (this.shouldSkipBridgeUserTextEcho(msg)) return; this.push(msg); this.onMessageReceived?.(msg); }; this.bridge.callbacks.onTyping = (ms) => { this._isTyping = true; this.emit(); if (this.typingTimer) clearTimeout(this.typingTimer); this.typingTimer = setTimeout(() => { this._isTyping = false; this.emit(); }, ms); }; this.bridge.callbacks.onClear = () => { this._messages = []; this.outgoingUserTextEchoDedup = []; this.emit(); }; this.bridge.callbacks.onError = (message, type) => { this._errorMessage = message; this.onError?.(message, type); this.emit(); }; this.bridge.callbacks.onMessageSentToBot = () => { this._isTyping = true; this.emit(); if (this.typingTimer) clearTimeout(this.typingTimer); this.typingTimer = setTimeout(() => { this._isTyping = false; this.emit(); }, 8000); }; } private pruneUserEchoDedupSlots(now: number): void { this.outgoingUserTextEchoDedup = this.outgoingUserTextEchoDedup.filter((s) => s.expiresAt > now); while (this.outgoingUserTextEchoDedup.length > this.userEchoDedupMaxSlots) { this.outgoingUserTextEchoDedup.shift(); } } private enqueueOutgoingUserTextForDedup(...texts: string[]): void { const now = Date.now(); const expiresAt = now + this.userEchoDedupTtlMs; for (const raw of texts) { const t = raw.trim(); if (!t) continue; this.outgoingUserTextEchoDedup.push({ text: t, expiresAt }); } this.pruneUserEchoDedupSlots(now); } /** Drop WebView echo of a user line we already rendered from `sendText` / `sendSuggestions`. */ private shouldSkipBridgeUserTextEcho(incoming: EnxMessage): boolean { if (incoming.sender !== EnxMessageSender.User || incoming.type !== EnxMessageType.Text) return false; const body = incoming.text?.trim() ?? ''; if (!body) return false; const now = Date.now(); this.pruneUserEchoDedupSlots(now); const idx = this.outgoingUserTextEchoDedup.findIndex((s) => s.text === body); if (idx === -1) return false; this.outgoingUserTextEchoDedup.splice(idx, 1); return true; } private push(message: EnxMessage): void { this._messages = [...this._messages, message]; this.emit(); } private setStatus(status: EnxConnectionStatus): void { this._status = status; this.onStatusChanged?.(status); this.emit(); } private emit(): void { this.listeners.forEach((fn) => fn()); } }