import * as React from 'react'; import { createRoot, type Root } from 'react-dom/client'; import { MessageSquare, Video, Play, Pause, Volume2, Minimize2, Square, Move, Maximize2 } from 'lucide-react'; import { TavusClientProxy } from '@buzztrail/shared-utils'; import { ChatPane, StubTransport, type ChatTransport } from './ChatPane'; import { ProxyTransport, FallbackTransport, NavigationTransport, LocalTestTransport } from './transports'; import { Conversation, CVIProvider, MicSelectBtn, CameraSelectBtn, ScreenShareButton } from '@buzztrail/shared-components'; import type { ChatbotUserPreferences, TavusRequestBody, TavusConversationResponse, TavusEndConversationResponse } from '@buzztrail/shared-types'; import { DEFAULT_PLACEHOLDER_DATA_URI, type WidgetConfig} from './widget-config'; import { WIDGET_STYLES } from './widget-styles'; export class BuzzTrailWidget { private cfg: Required = { personaId: 'p527c5d8b826', replicaId: 'rca8a38779a8', // Development mode flag - set to true to use mock responses enableMockMode: this.getMockMode(), conversationalContext: '', maxCallSeconds: 30, participantLeftTimeout: 0, mode: 'chat-first', theme: 'sendcloud', container: document.body as unknown as string | HTMLElement, fullScreenOnVideo: true, chatEnabled: true, chatSessionId: 'default', apiBase: '', headers: {}, videoPlaceholderSrc: '/chatbot/dist/tavus-video-placeholder.jpg', // Visibility controls showChat: true, showVideo: true, // Size and positioning defaults size: 'large', startSize: 'large', sizeOverride: undefined, sizeRules: {}, autoSize: false, position: { x: 0, y: 0 }, enableDrag: true, enableResize: true, // Overlay configuration defaults overlayBackdrop: 'blur', } as unknown as Required; private host: HTMLElement | null = null; private shadow: ShadowRoot | null = null; private root: Root | null = null; private tavusClient!: TavusClientProxy; private active?: { id: string; url: string; startTime: number }; private endTimer?: number; private showChat = false; private showVideoArea = true; // Audio/Video mode state private isAudioMode = false; private isCallActive = false; // Size and positioning state private currentSize: 'minimal' | 'medium' | 'large' = 'large'; private position = { x: 0, y: 0 }; // Will be set to optimal position in initializeSizeAndPosition private isDragging = false; private isResizing = false; private shouldSaveCustomSize = false; // Flag to track when to save custom size // Drag state private dragStartPos = { x: 0, y: 0 }; private dragStartOffset = { x: 0, y: 0 }; // Resize state private resizeStartSize = { width: 0, height: 0 }; private resizeStartPos = { x: 0, y: 0 }; private resizeDirection = ''; /** * Get the panel element with proper typing */ private getPanel(): HTMLElement | null { return this.shadow?.querySelector('.bt-panel') as HTMLElement | null; } /** * Get the current domain for the title */ private getCurrentDomain(): string { try { return window.location.hostname ?? 'unknown'; } catch { return 'unknown'; } } /** * Get the responsive title based on current size */ private getTitle(): string { const domain = this.getCurrentDomain(); // Show full title in large mode, just "BuzzTrail" in smaller modes if (this.currentSize === 'large') { return `BuzzTrail AI on ${domain}`; } return 'BuzzTrail'; } public init(cfg: Partial = {}): void { const next: Partial = { ...this.cfg }; Object.entries(cfg).forEach(([k, v]) => { if (v !== undefined) (next as Record)[k] = v; }); this.cfg = next as Required; this.showChat = this.cfg.showChat ?? (this.cfg.mode === 'chat-first'); this.showVideoArea = this.cfg.showVideo ?? true; // Always show video by default, can be toggled // Initialize TavusClientProxy (routes through proxy server) this.tavusClient = new TavusClientProxy({ apiKey: process.env.TAVUS_API_KEY || '', debug: true, }); // Initialize size and positioning this.initializeSizeAndPosition(); } private initializeSizeAndPosition(): void { // Load user preferences const prefs = this.loadUserPreferences(); // Determine initial size let initialSize = this.cfg.startSize; // Apply size override if specified if (this.cfg.sizeOverride) { initialSize = this.cfg.sizeOverride; } // Apply size rules if auto-size is enabled if (this.cfg.autoSize && Object.keys(this.cfg.sizeRules).length > 0) { const optimalSize = this.calculateOptimalSize(); if (optimalSize && ['minimal', 'medium', 'large'].includes(optimalSize)) { initialSize = optimalSize as 'minimal' | 'medium' | 'large'; } } // Use user preference if available if (prefs?.size) { initialSize = prefs.size; } this.currentSize = initialSize; // Restore position or set optimal default if (prefs?.position) { this.position = prefs.position; } else { // Set optimal default position based on size this.position = this.getOptimalDefaultPosition(initialSize); } // Restore interaction modes if (prefs?.enableDrag !== undefined) { this.cfg.enableDrag = prefs.enableDrag; } if (prefs?.enableResize !== undefined) { this.cfg.enableResize = prefs.enableResize; } // Restore content visibility if (prefs?.showChat !== undefined) { this.showChat = prefs.showChat; } if (prefs?.showVideo !== undefined) { this.showVideoArea = prefs.showVideo; } if (prefs?.isAudioMode !== undefined) { this.isAudioMode = prefs.isAudioMode; } // Restore call state if (prefs?.isCallActive !== undefined) { this.isCallActive = prefs.isCallActive; } console.log('[Widget] Initialized with state:', { size: this.currentSize, position: this.position, enableDrag: this.cfg.enableDrag, enableResize: this.cfg.enableResize, showChat: this.showChat, showVideo: this.showVideoArea, isAudioMode: this.isAudioMode, isCallActive: this.isCallActive }); } private loadUserPreferences(): ChatbotUserPreferences { try { const stored = localStorage.getItem('buzztrail_preferences'); if (stored) { const prefs = JSON.parse(stored); console.log('[Widget] Loading preferences:', prefs); return { // Basic size and position size: prefs.preferredSize, position: prefs.preferredPosition, customSizes: prefs.customSizes, // Interaction modes enableDrag: prefs.enableDrag, enableResize: prefs.enableResize, // Content visibility showChat: prefs.showChat, showVideo: prefs.showVideo, isAudioMode: prefs.isAudioMode, // Call state isCallActive: prefs.isCallActive }; } } catch (e) { console.warn('[Chatbot] Failed to load preferences:', e); } return {}; } private calculateOptimalSize(): string | null { const width = window.innerWidth; const height = window.innerHeight; const isLandscape = width > height; let breakpoint: string; if (width < 480) breakpoint = 'mobile'; else if (width < 768) breakpoint = isLandscape ? 'tablet-landscape' : 'tablet'; else breakpoint = 'desktop'; return this.cfg.sizeRules[breakpoint] ?? null; } private getOptimalDefaultPosition(size: 'minimal' | 'medium' | 'large'): { x: number; y: number } { const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; switch (size) { case 'minimal': // Minimal size: bottom-right corner return { x: viewportWidth - 140 - 16, y: viewportHeight - 60 - 16 }; case 'medium': { // Medium size: bottom-right, but centered for better video viewing const mediumWidth = 400; const mediumHeight = 313; // 16:9 video area + 88px header return { x: viewportWidth - mediumWidth - 16, y: viewportHeight - mediumHeight - 16 }; } case 'large': { // Large size: centered with slight offset for conversational video const largeWidth = viewportWidth * 0.96; const largeHeight = largeWidth * 0.5625 + 88; // 16:9 video area + 88px header return { x: (viewportWidth - largeWidth) / 2, y: Math.max(16, (viewportHeight - largeHeight) / 2) }; } default: return { x: 0, y: 0 }; } } public mount(): void { if (this.shadow) return; const container = typeof this.cfg.container === 'string' ? document.querySelector(this.cfg.container) ?? document.body : this.cfg.container; this.host = document.createElement('div'); this.host.setAttribute('data-bt', 'widget'); container.appendChild(this.host); this.shadow = this.host.attachShadow({ mode: 'open' }); // Apply theme variables to Shadow DOM root with a small delay to ensure theme is ready setTimeout(() => { this.applyThemeToShadowDOM(); }, 50); const rootEl = document.createElement('div'); rootEl.id = 'bt-widget-root'; this.shadow.appendChild(rootEl); this.root = createRoot(rootEl); this.render(); } /** * Apply theme variables to Shadow DOM root */ private applyThemeToShadowDOM(retryCount = 0): void { if (!this.shadow) { console.log('[Widget][Theme] No shadow DOM available for theme injection'); return; } // Limit retries to prevent infinite loops if (retryCount > 5) { console.warn('[Widget][Theme] Max retries reached, giving up on theme injection'); // Debug: Let's see what's actually on the document root const root = document.documentElement; const rootStyles = getComputedStyle(root); const btVars: string[] = []; for (const property of rootStyles) { if (property?.startsWith('--bt-')) { btVars.push(property); } } console.warn('[Widget][Theme] Debug: Found', btVars.length, 'theme variables on document root:', btVars.slice(0, 5)); return; } if (retryCount === 0) { console.log('[Widget][Theme] Starting theme variable injection to Shadow DOM...'); } // Get all CSS variables from document root using the same approach as theme loader const root = document.documentElement; const cssVars: string[] = []; // Parse cssText directly since Object.entries doesn't work for CSS custom properties const cssText = root.style.cssText; if (cssText) { const matches = cssText.match(/--bt-[^:]+/g); if (matches) { for (const varName of matches) { const value = root.style.getPropertyValue(varName); cssVars.push(`${varName}: ${value};`); } } } // If no variables found in cssText, try getComputedStyle as fallback if (cssVars.length === 0) { const rootStyles = getComputedStyle(root); for (const property of rootStyles) { if (property?.startsWith('--bt-')) { const value = rootStyles.getPropertyValue(property); cssVars.push(`${property}: ${value};`); } } } // If no variables found, retry after a short delay (theme might not be applied yet) if (cssVars.length === 0) { if (retryCount === 0) { console.log('[Widget][Theme] No theme variables found, retrying in 100ms...'); } setTimeout(() => this.applyThemeToShadowDOM(retryCount + 1), 100); return; } // Apply variables to Shadow DOM host if (cssVars.length > 0) { (this.shadow.host as HTMLElement).style.cssText = cssVars.join(' '); console.log('[Widget][Theme] Successfully injected', cssVars.length, 'theme variables to Shadow DOM'); // Log a few example variables for verification const sampleVars = cssVars.slice(0, 3); console.log('[Widget][Theme] Sample variables injected:', sampleVars); } else { console.warn('[Widget][Theme] No theme variables found to inject'); } } public open(): void { this.render(true); } public close(): void { this.render(false); } public minimize(): void { this.render(false); } /** * Enable drag functionality for floating mode */ private enableDrag(): void { if (this.currentSize !== 'medium') return; const panel = this.shadow?.querySelector('.bt-panel') as HTMLElement; if (!panel) return; // Use pointer events for better performance and cross-device support panel.addEventListener('pointerdown', this.handlePointerDown.bind(this)); } /** * Handle pointer down for drag start */ private handlePointerDown(e: PointerEvent): void { if (this.currentSize !== 'medium' || !this.cfg.enableDrag) return; // Only allow dragging from specific areas, NOT from buttons const target = e.target as HTMLElement; // Check if click is on a button or interactive element - if so, don't drag if (target.closest('button') || target.closest('.bt-icon') || target.closest('.bt-btn')) { console.log('[Widget][Drag] Click on button detected, not starting drag'); return; } // Only allow dragging from toolbar background or drag handle if (!target.closest('.bt-toolbar') && !target.closest('.bt-drag-handle')) { return; } // Additional check: if click is on toolbar but on a button, don't drag if (target.closest('.bt-toolbar') && (target.closest('button') || target.closest('.bt-icon') || target.closest('.bt-btn'))) { console.log('[Widget][Drag] Click on toolbar button detected, not starting drag'); return; } console.log('[Widget][Drag] Starting drag operation'); e.preventDefault(); this.startDrag(e.clientX, e.clientY); // Set pointer capture for smooth dragging const panel = this.shadow?.querySelector('.bt-panel') as HTMLElement; if (panel) { panel.setPointerCapture(e.pointerId); } // Add global pointer event listeners document.addEventListener('pointermove', this.handlePointerMove.bind(this)); document.addEventListener('pointerup', this.handlePointerUp.bind(this)); } /** * Handle pointer move for drag */ private handlePointerMove(e: PointerEvent): void { if (!this.isDragging) return; this.updateDragPosition(e.clientX, e.clientY); } /** * Handle pointer up for drag end */ private handlePointerUp(e: PointerEvent): void { if (!this.isDragging) return; // Release pointer capture const panel = this.shadow?.querySelector('.bt-panel') as HTMLElement; if (panel) { panel.releasePointerCapture(e.pointerId); } this.endDrag(); // Remove global listeners document.removeEventListener('pointermove', this.handlePointerMove.bind(this)); document.removeEventListener('pointerup', this.handlePointerUp.bind(this)); } /** * Start drag operation */ private startDrag(clientX: number, clientY: number): void { this.isDragging = true; this.dragStartPos = { x: clientX, y: clientY }; const panel = this.getPanel(); if (panel) { const rect = panel.getBoundingClientRect(); this.dragStartOffset = { x: clientX - rect.left, y: clientY - rect.top }; } // Add dragging class for visual feedback panel?.classList.add('bt-dragging'); } /** * Update position during drag with boundary constraints */ private updateDragPosition(clientX: number, clientY: number): void { // Calculate new position directly from mouse/touch position let newX = clientX - this.dragStartOffset.x; let newY = clientY - this.dragStartOffset.y; // Get viewport dimensions const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; // Get widget dimensions const panel = this.getPanel(); const rect = panel?.getBoundingClientRect(); const widgetWidth = rect?.width ?? 350; const widgetHeight = rect?.height ?? 250; // Constrain to viewport bounds newX = Math.max(0, Math.min(newX, viewportWidth - widgetWidth)); newY = Math.max(0, Math.min(newY, viewportHeight - widgetHeight)); this.position = { x: newX, y: newY }; this.render(); } /** * End drag operation */ private endDrag(): void { if (!this.isDragging) return; this.isDragging = false; this.saveUserPreferences(); // Remove dragging class const panel = this.getPanel(); panel?.classList.remove('bt-dragging'); } /** * Enable resize functionality for medium modes */ private enableResize(): void { if (this.currentSize !== 'medium') return; const panel = this.shadow?.querySelector('.bt-panel') as HTMLElement; if (!panel) return; this.addResizeHandles(panel); } /** * Add resize handles to the panel */ private addResizeHandles(panel: HTMLElement): void { // Clear existing resize handles first const existingHandles = panel.querySelectorAll('.bt-resize-handle'); existingHandles.forEach(handle => handle.remove()); const handles = ['nw', 'ne', 'sw', 'se']; // corner handles handles.forEach(direction => { const handle = document.createElement('div'); handle.className = `bt-resize-handle bt-resize-${direction}`; handle.setAttribute('data-direction', direction); // Mouse events handle.addEventListener('mousedown', (e) => this.handleResizeStart(e, direction)); // Touch events handle.addEventListener('touchstart', (e) => this.handleResizeStart(e, direction), { passive: false }); panel.appendChild(handle); }); } /** * Handle resize start */ private handleResizeStart(e: MouseEvent | TouchEvent, direction: string): void { if (!this.cfg.enableResize) return; e.preventDefault(); e.stopPropagation(); const clientX = 'touches' in e ? e.touches[0]?.clientX || 0 : e.clientX; const clientY = 'touches' in e ? e.touches[0]?.clientY || 0 : e.clientY; this.startResize(clientX, clientY, direction); if ('touches' in e) { document.addEventListener('touchmove', this.handleResizeMove.bind(this), { passive: false }); document.addEventListener('touchend', this.handleResizeEnd.bind(this)); } else { document.addEventListener('mousemove', this.handleResizeMove.bind(this)); document.addEventListener('mouseup', this.handleResizeEnd.bind(this)); } } /** * Start resize operation */ private startResize(clientX: number, clientY: number, direction: string): void { this.isResizing = true; this.resizeDirection = direction; this.resizeStartPos = { x: clientX, y: clientY }; const panel = this.getPanel(); if (panel) { const rect = panel.getBoundingClientRect(); this.resizeStartSize = { width: rect.width, height: rect.height }; } // Add resizing class for visual feedback panel?.classList.add('bt-resizing'); } /** * Handle resize move */ private handleResizeMove(e: MouseEvent | TouchEvent): void { if (!this.isResizing) return; const clientX = 'touches' in e ? e.touches[0]?.clientX || 0 : e.clientX; const clientY = 'touches' in e ? e.touches[0]?.clientY || 0 : e.clientY; if ('touches' in e) { e.preventDefault(); } this.updateResize(clientX, clientY); } /** * Update size during resize with constraints */ private updateResize(clientX: number, clientY: number): void { const deltaX = clientX - this.resizeStartPos.x; const deltaY = clientY - this.resizeStartPos.y; let newWidth = this.resizeStartSize.width; let newHeight = this.resizeStartSize.height; // Calculate new dimensions based on resize direction switch (this.resizeDirection) { case 'se': // bottom-right newWidth += deltaX; newHeight += deltaY; break; case 'sw': // bottom-left newWidth -= deltaX; newHeight += deltaY; break; case 'ne': // top-right newWidth += deltaX; newHeight -= deltaY; break; case 'nw': // top-left newWidth -= deltaX; newHeight -= deltaY; break; } // Apply constraints const constrained = this.applyResizeConstraints(newWidth, newHeight); // Check if constraints were applied (size was modified) const constraintsApplied = Math.abs(constrained.width - newWidth) > 1 || Math.abs(constrained.height - newHeight) > 1; // Update panel size const panel = this.shadow?.querySelector('.bt-panel') as HTMLElement; if (panel) { panel.style.width = `${constrained.width}px`; panel.style.height = `${constrained.height}px`; // Add visual feedback when constraints are applied if (constraintsApplied) { panel.classList.add('bt-constraint-applied'); // Remove the class after a short delay setTimeout(() => { panel.classList.remove('bt-constraint-applied'); }, 300); } } // Log constraint application for debugging if (constraintsApplied) { const headerHeight = 88; // Header height for ratio calculation const originalVideoRatio = (newWidth / (newHeight - headerHeight)).toFixed(2); const finalVideoRatio = (constrained.width / (constrained.height - headerHeight)).toFixed(2); console.log(`[Widget] Resize constraint applied: ${originalVideoRatio}:1 → ${finalVideoRatio}:1 (video area 16:9)`); } // Show current aspect ratio in title during resize (for debugging/feedback) if (this.isResizing) { const currentRatio = (constrained.width / constrained.height).toFixed(2); const panel = this.getPanel(); if (panel) { panel.setAttribute('data-aspect-ratio', `${currentRatio}:1`); } } } /** * Apply resize constraints to maintain exact 16:9 aspect ratio for video area * while accounting for header height to prevent letterboxing */ private applyResizeConstraints(width: number, height: number): { width: number; height: number } { // Minimum and maximum sizes (in pixels for consistency) const minWidth = 280; const maxWidth = Math.min(1200, window.innerWidth * 0.8); // Max 80% of screen width const minHeight = 200; const maxHeight = Math.min(800, window.innerHeight * 0.8); // Max 80% of screen height // Header height: 24px padding + 40px button + 24px padding = 88px const headerHeight = 88; // Clamp to min/max bounds let constrainedWidth = Math.max(minWidth, Math.min(maxWidth, width)); let constrainedHeight = Math.max(minHeight, Math.min(maxHeight, height)); // Calculate video area height (total height minus header) const videoAreaHeight = constrainedHeight - headerHeight; // Force exact 16:9 aspect ratio for the video area // Tavus recommends 720p (1280x720) and 1080p (1920x1080) - both 16:9 (1.78:1) const targetAspectRatio = 16/9; // Exactly 1.78:1 const videoAspectRatio = constrainedWidth / videoAreaHeight; // Always force exact 16:9 ratio for video area if (Math.abs(videoAspectRatio - targetAspectRatio) > 0.01) { // Calculate required total height for 16:9 video area const requiredVideoHeight = constrainedWidth / targetAspectRatio; const requiredTotalHeight = requiredVideoHeight + headerHeight; // Calculate required total width for 16:9 video area const requiredVideoWidth = videoAreaHeight * targetAspectRatio; const requiredTotalWidth = requiredVideoWidth; // Choose the adjustment that fits within bounds if (requiredTotalHeight <= maxHeight) { // Adjust height to match width constrainedHeight = requiredTotalHeight; } else if (requiredTotalWidth <= maxWidth) { // Adjust width to match height constrainedWidth = requiredTotalWidth; } else { // Both would exceed limits, use the one that fits better if (constrainedWidth / maxHeight <= targetAspectRatio) { constrainedHeight = maxHeight; const videoHeight = constrainedHeight - headerHeight; constrainedWidth = videoHeight * targetAspectRatio; } else { constrainedWidth = maxWidth; const videoHeight = constrainedWidth / targetAspectRatio; constrainedHeight = videoHeight + headerHeight; } } } return { width: constrainedWidth, height: constrainedHeight }; } /** * Handle resize end */ private handleResizeEnd(): void { this.endResize(); document.removeEventListener('mousemove', this.handleResizeMove.bind(this)); document.removeEventListener('mouseup', this.handleResizeEnd.bind(this)); document.removeEventListener('touchmove', this.handleResizeMove.bind(this)); document.removeEventListener('touchend', this.handleResizeEnd.bind(this)); } /** * End resize operation */ private endResize(): void { if (!this.isResizing) return; this.isResizing = false; // Set flag to save custom size when resize ends if (this.currentSize === 'medium') { this.shouldSaveCustomSize = true; const panel = this.getPanel(); if (panel) { const rect = panel.getBoundingClientRect(); console.log('[Widget] Resize ended, final size:', { width: rect.width, height: rect.height }); // Clear aspect ratio display panel.removeAttribute('data-aspect-ratio'); } } this.saveUserPreferences(); // Remove resizing class const panel = this.getPanel(); panel?.classList.remove('bt-resizing'); } public async startVideo(): Promise { if (this.active) return; // Start performance monitoring const startTime = performance.now(); console.log('[Chatbot][Performance] Starting conversation at:', new Date().toISOString()); // Validate configuration if (!this.cfg.personaId || !this.cfg.replicaId) { console.warn('[Chatbot][Tavus] Missing personaId or replicaId. Using current config:', { personaId: this.cfg.personaId, replicaId: this.cfg.replicaId, }); if (!this.cfg.personaId || !this.cfg.replicaId) { this.showError('Configuration Error', 'Missing Tavus persona or replica configuration. Please contact support.'); throw new Error('Missing Tavus personaId/replicaId. Provide via data attributes or BuzzTrail.init().'); } } // Show loading state this.showLoadingState(true); try { let conversationId: string; let conversationUrl: string; // Check if we should use mock mode if (this.cfg.enableMockMode) { console.log('[Chatbot][Tavus] Using mock mode for development testing'); const mockResult = await this.mockTavusConversation(); conversationId = mockResult.conversation_id; conversationUrl = mockResult.conversation_url; } else { // Real API call const body: TavusRequestBody = { persona_id: this.cfg.personaId, replica_id: this.cfg.replicaId, conversational_context: this.cfg.conversationalContext ?? undefined, properties: { max_call_duration: this.cfg.maxCallSeconds ?? 15, participant_left_timeout: this.cfg.participantLeftTimeout ?? 0, }, }; console.groupCollapsed('[Chatbot][Tavus] create_request'); console.log('body.properties:', body.properties); console.groupEnd(); // Ensure TavusClient is initialized if (!this.tavusClient.initialized) { this.tavusClient.initialize(); } // Convert the request to TavusClient format const conversationRequest = { replicaId: body.replica_id, personaId: body.persona_id, conversationalContext: body.conversational_context, properties: body.properties, }; // Use TavusClient to create conversation (this will be logged automatically) const conversation = await this.tavusClient.createConversation(conversationRequest); // Convert response back to expected format const data = { conversation_id: conversation.conversationId, conversation_url: conversation.roomUrl, access_token: conversation.accessToken, status: conversation.isActive ? 'active' : 'inactive', replica_id: conversation.replicaId, persona_id: conversation.personaId, created_at: conversation.startTime, }; conversationId = data.conversation_id; conversationUrl = data.conversation_url; if (!conversationId || !conversationUrl) { this.showError('Invalid Response', 'Received invalid response from conversation service. Please try again.'); throw new Error('Invalid response: missing conversation ID or URL'); } } this.active = { id: conversationId, url: conversationUrl, startTime: Date.now() }; console.log('[Widget] Video conversation started:', { conversationId, conversationUrl, startTime: this.active.startTime }); this.render(true); if (this.endTimer) window.clearTimeout(this.endTimer); const maxMs = (this.cfg.maxCallSeconds ?? 15) * 1000; this.endTimer = window.setTimeout(() => { void this.endVideo(); }, maxMs); // Start countdown timer for mock mode if (this.cfg.enableMockMode) { this.startMockCountdown(maxMs); } const endTime = performance.now(); const duration = endTime - startTime; console.log('[Chatbot][Performance] Conversation started in:', duration.toFixed(2), 'ms'); console.log('[Chatbot][Tavus] Conversation started successfully:', { conversationId, maxMs }); } catch (error) { console.error('[Chatbot][Tavus] Failed to start conversation:', error); // Log error details for debugging console.error('[Chatbot][Tavus] Error details:', { error: error instanceof Error ? error.message : String(error), type: 'start_conversation_error', timestamp: new Date().toISOString(), context: { enableMockMode: this.cfg.enableMockMode, maxCallSeconds: this.cfg.maxCallSeconds, personaId: this.cfg.personaId, replicaId: this.cfg.replicaId, performance: { startTime: startTime, endTime: performance.now(), duration: performance.now() - startTime } } }); // Reset call state on error to ensure button shows play button this.isCallActive = false; // Error message already shown by specific error handlers above } finally { // Hide loading state this.showLoadingState(false); } } public async endVideo(isTimeout = false): Promise { try { if (this.endTimer) { window.clearTimeout(this.endTimer); this.endTimer = undefined; } if (this.active?.id) { if (this.cfg.enableMockMode) { await this.mockEndConversation(); } else { // Ensure TavusClient is initialized if (!this.tavusClient.initialized) { this.tavusClient.initialize(); } // Use TavusClient to end conversation (this will be logged automatically) await this.tavusClient.endConversation(this.active.id); console.log('[Chatbot][Tavus] Conversation ended successfully'); } } } catch (error) { console.error('[Chatbot][Tavus] Error ending conversation:', error); // Log error details for debugging if (this.active?.id) { console.error('[Chatbot][Tavus] Error details:', { error: error instanceof Error ? error.message : String(error), type: 'json_parsing_error', conversationId: this.active.id }); } // Log error details for debugging const errorMessage = error instanceof Error ? error.message : String(error); if (this.active?.id) { console.error('[Chatbot][Tavus] Error details:', { error: errorMessage, type: 'end_conversation_error', conversationId: this.active.id, isTimeout: isTimeout, timestamp: new Date().toISOString(), context: { enableMockMode: this.cfg.enableMockMode, maxCallSeconds: this.cfg.maxCallSeconds, conversationStartTime: this.active.startTime, conversationDuration: Date.now() - this.active.startTime } }); } // Only show user-facing error for actual API failures, not for normal timeouts if (!this.cfg.enableMockMode && !isTimeout && !errorMessage.includes('Unexpected end of JSON input')) { this.showError('End Conversation Error', 'Failed to end conversation. Please try again.'); } else { console.log('[Chatbot][Tavus] Conversation ended normally (timeout or already ended)'); } } this.active = undefined; this.isCallActive = false; // Reset button state to show play button this.render(false); } /** * Mock end conversation for development testing */ private async mockEndConversation(): Promise { console.log('[Chatbot][Mock] Ending mock conversation'); console.log('[Chatbot][Mock] Conversation ID:', this.active?.id); // Simulate API delay await new Promise(resolve => setTimeout(resolve, 500)); // Simulate real Tavus API response structure const mockResponse: TavusEndConversationResponse = { conversation_id: this.active?.id ?? 'unknown', status: "ended", ended_at: new Date().toISOString(), duration_seconds: Math.floor((Date.now() - (this.active?.startTime ?? Date.now())) / 1000) }; console.log('[Chatbot][Mock] Mock end conversation response:', mockResponse); console.log('[Chatbot][Mock] Mock conversation ended successfully'); } /** * Show user-friendly error message */ private showError(title: string, message: string): void { console.error(`[Chatbot][Error] ${title}: ${message}`); // Create error notification const errorDiv = document.createElement('div'); errorDiv.className = 'bt-error-notification'; errorDiv.innerHTML = `
${title}
${message}
`; // Add to widget if available, otherwise to body const container = this.shadow?.querySelector('.bt-panel') ?? document.body; container.appendChild(errorDiv); // Auto-remove after 5 seconds setTimeout(() => { if (errorDiv.parentElement) { errorDiv.remove(); } }, 5000); } /** * Show/hide loading state */ private showLoadingState(show: boolean): void { const videoContainer = this.shadow?.querySelector('.bt-video-container'); if (!videoContainer) return; if (show) { // Add loading overlay const loadingDiv = document.createElement('div'); loadingDiv.className = 'bt-loading-overlay'; loadingDiv.innerHTML = `
Starting conversation...
`; videoContainer.appendChild(loadingDiv); } else { // Remove loading overlay const loadingDiv = videoContainer.querySelector('.bt-loading-overlay'); if (loadingDiv) { loadingDiv.remove(); } } } /** * Mock Tavus API response for development testing */ private async mockTavusConversation(): Promise { console.log('[Chatbot][Mock] Creating mock Tavus conversation'); console.log('[Chatbot][Mock] Configuration:', { personaId: this.cfg.personaId, replicaId: this.cfg.replicaId, enableMockMode: this.cfg.enableMockMode }); // Simulate API delay await new Promise(resolve => setTimeout(resolve, 1000)); // Optional: Simulate error scenarios for testing (uncomment to test) // if (Math.random() < 0.1) { // 10% chance of error // throw new Error('Mock API error: out of conversational credits'); // } // Generate mock conversation data matching actual Tavus API response const mockConversationId = `mock_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; // Use a mock URL that won't trigger real Daily.co requests const mockConversationUrl = `https://mock-tavus-daily.co/${mockConversationId}`; const now = new Date().toISOString(); const mockResponse: TavusConversationResponse = { conversation_id: mockConversationId, conversation_name: `A Meeting with Sendcloud Assistant`, status: "active", conversation_url: mockConversationUrl, replica_id: this.cfg.replicaId ?? "r92debe21318", persona_id: this.cfg.personaId ?? "p9c7988840cc", created_at: now }; console.log('[Chatbot][Mock] Mock conversation created:', mockResponse); return mockResponse; } /** * Mock Daily.co room creation to prevent real API calls */ private async mockDailyRoomCreation(conversationUrl: string): Promise { console.log('[Chatbot][Mock] Creating mock Daily.co room for:', conversationUrl); // Simulate Daily.co room creation delay await new Promise(resolve => setTimeout(resolve, 800)); // Mock successful room creation console.log('[Chatbot][Mock] Mock Daily.co room created successfully'); console.log('[Chatbot][Mock] Room URL:', conversationUrl); console.log('[Chatbot][Mock] Room is ready for conversation'); } /** * Start countdown timer for mock mode */ private startMockCountdown(maxMs: number): void { const startTime = Date.now(); const updateTimer = (): void => { const elapsed = Date.now() - startTime; const remaining = Math.max(0, maxMs - elapsed); const secondsLeft = Math.ceil(remaining / 1000); // Update the timer display in the mock conversation const timerElement = this.shadow?.querySelector('.bt-mock-timer'); if (timerElement) { timerElement.textContent = `⏱️ ${secondsLeft} seconds remaining`; } if (remaining > 0) { setTimeout(updateTimer, 1000); } else { // Timer expired - automatically end the conversation console.log('[Chatbot][Mock] Timer expired, automatically ending conversation'); this.endCall(); } }; // Start the countdown updateTimer(); } // Size control methods public setSize(size: 'minimal' | 'medium' | 'large'): void { console.log('[Widget][Button] setSize() called with size:', size, 'Current size:', this.currentSize); this.currentSize = size; console.log('[Widget][Button] Updated currentSize to:', this.currentSize); // Clear any custom size styles when switching away from medium mode if (this.currentSize !== 'medium') { const panel = this.getPanel(); if (panel) { panel.style.width = ''; panel.style.height = ''; } } // Ensure correct dimensions for medium size (16:9 video area + header) if (this.currentSize === 'medium') { const panel = this.getPanel(); if (panel) { // Check if we have a saved custom size const prefs = this.loadUserPreferences(); const customSize = prefs?.customSizes?.medium; if (customSize) { // Use saved custom size panel.style.width = `${customSize.width}px`; panel.style.height = `${customSize.height}px`; console.log('[Widget] Applied saved custom size:', customSize); } else { // Apply default 16:9 ratio dimensions const defaultWidth = 400; const defaultHeight = 313; // 16:9 video area + 88px header panel.style.width = `${defaultWidth}px`; panel.style.height = `${defaultHeight}px`; console.log('[Widget] Applied default medium size:', { width: defaultWidth, height: defaultHeight }); } } } // Save preferences after rendering to ensure we have the correct state this.render(); // Ensure widget stays within viewport after size change this.constrainToViewport(); this.saveUserPreferences(); console.log('[Widget][Button] Size changed to:', this.currentSize); } public setPosition(x: number, y: number): void { this.position = { x, y }; this.saveUserPreferences(); this.render(true); } /** * Ensure widget stays within viewport bounds */ private constrainToViewport(): void { const panel = this.getPanel(); if (!panel) return; const rect = panel.getBoundingClientRect(); const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; // Calculate new position to keep widget within viewport let newX = this.position.x; let newY = this.position.y; // Constrain X position if (newX + rect.width > viewportWidth) { newX = viewportWidth - rect.width; } if (newX < 0) { newX = 0; } // Constrain Y position if (newY + rect.height > viewportHeight) { newY = viewportHeight - rect.height; } if (newY < 0) { newY = 0; } // Update position if it changed if (newX !== this.position.x || newY !== this.position.y) { this.position = { x: newX, y: newY }; this.render(); } } public resetPosition(): void { this.position = { x: 0, y: 0 }; this.saveUserPreferences(); this.render(true); } public cycleSize(): void { const sizes: ('minimal' | 'medium' | 'large')[] = ['minimal', 'medium', 'large']; const currentIndex = sizes.indexOf(this.currentSize); const nextIndex = (currentIndex + 1) % sizes.length; const nextSize = sizes[nextIndex]; if (nextSize) { this.setSize(nextSize); } } private saveUserPreferences(): void { try { const panel = this.getPanel(); const customSizes = this.loadUserPreferences()?.customSizes ?? {}; // Save custom size for medium mode only when actually resizing if (panel && this.currentSize === 'medium' && this.shouldSaveCustomSize) { const rect = panel.getBoundingClientRect(); const customSize = { width: rect.width, height: rect.height }; customSizes[this.currentSize] = customSize; console.log('[Widget] Saving custom size for medium mode:', customSize); this.shouldSaveCustomSize = false; // Reset flag after saving } // Save comprehensive window state const prefs = { // Basic size and position preferredSize: this.currentSize, preferredPosition: this.position, customSizes: customSizes, // Interaction modes enableDrag: this.cfg.enableDrag, enableResize: this.cfg.enableResize, // Content visibility showChat: this.showChat, showVideo: this.showVideoArea, isAudioMode: this.isAudioMode, // Call state isCallActive: this.isCallActive }; localStorage.setItem('buzztrail_preferences', JSON.stringify(prefs)); console.log('[Widget] Saved preferences:', prefs); } catch (e) { console.warn('[Chatbot] Failed to save preferences:', e); } } /** * Handle navigation requests from the chatbot */ private handleNavigation = (url: string): void => { // For localhost/standalone contexts, use window.location if (typeof window !== 'undefined' && window.chrome?.runtime?.sendMessage && window.location.protocol === 'chrome-extension:') { // Chrome extension context (currently on hold) void window.chrome.runtime.sendMessage({ type: 'NAVIGATE_TO_URL', url }); } else { // Standalone context - use window.location window.location.href = url; } }; /** * Handle SPA navigation events */ private handleSPANavigation = (target: string, action: string, description: string): void => { console.log('[Chatbot][SPA] SPA navigation requested:', { target, action, description }); console.log('[Chatbot][SPA] window.chatbotNavigationHandlers:', window.chatbotNavigationHandlers); console.log('[Chatbot][SPA] typeof window.chatbotNavigationHandlers:', typeof window.chatbotNavigationHandlers); console.log('[Chatbot][SPA] Array.isArray(window.chatbotNavigationHandlers):', Array.isArray(window.chatbotNavigationHandlers)); // Call registered navigation handlers if (window.chatbotNavigationHandlers && window.chatbotNavigationHandlers.length > 0) { console.log('[Chatbot][SPA] Calling registered navigation handlers, count:', window.chatbotNavigationHandlers.length); window.chatbotNavigationHandlers.forEach((handler, index) => { console.log('[Chatbot][SPA] Calling handler', index, ':', handler); try { handler(target, action, description); console.log('[Chatbot][SPA] Handler', index, 'executed successfully'); } catch (error) { console.error('[Chatbot][SPA] Error in navigation handler', index, ':', error); } }); } else { console.log('[Chatbot][SPA] No navigation handlers registered'); console.log('[Chatbot][SPA] window.chatbotNavigationHandlers is:', window.chatbotNavigationHandlers); } }; /** * Register a navigation handler for SPA routing * This allows external pages to handle navigation events */ static registerNavigationHandler(handler: (target: string, action: string, description: string) => void): void { console.log('[Chatbot] registerNavigationHandler called'); console.log('[Chatbot] Handler function:', handler); console.log('[Chatbot] Current handlers:', window.chatbotNavigationHandlers); if (!window.chatbotNavigationHandlers) { console.log('[Chatbot] Creating new handlers array'); window.chatbotNavigationHandlers = []; } window.chatbotNavigationHandlers.push(handler); console.log('[Chatbot] Navigation handler registered, total handlers:', window.chatbotNavigationHandlers.length); console.log('[Chatbot] All handlers:', window.chatbotNavigationHandlers); } /** * Unregister a navigation handler */ static unregisterNavigationHandler(handler: (target: string, action: string, description: string) => void): void { console.log('[Chatbot] unregisterNavigationHandler called'); if (window.chatbotNavigationHandlers) { const index = window.chatbotNavigationHandlers.indexOf(handler); if (index > -1) { window.chatbotNavigationHandlers.splice(index, 1); console.log('[Chatbot] Navigation handler unregistered, remaining handlers:', window.chatbotNavigationHandlers.length); } else { console.log('[Chatbot] Handler not found for unregistration'); } } else { console.log('[Chatbot] No handlers array to unregister from'); } } public render(open = false): void { console.log('[Widget] Starting render...'); if (!this.root) return; const isActive = !!this.active; const showPanel = open || isActive || this.cfg.mode === 'video-first' || this.cfg.mode === 'chat-first'; const url = this.active?.url; console.log('[Widget] Starting render...'); // Transport selection let transport: ChatTransport; if (this.cfg.apiBase) { // Use proxy transport when API base is provided const baseTransport = new FallbackTransport( new ProxyTransport(this.cfg.apiBase, { headers: this.cfg.headers, sessionId: this.cfg.chatSessionId }), new StubTransport() ); transport = new NavigationTransport(baseTransport, this.handleNavigation); } else { // Use local test transport for self-contained testing transport = new LocalTestTransport(); } console.log('[Widget] Transport created:', transport.constructor.name); const placeholderUrl = this.cfg.videoPlaceholderSrc ?? DEFAULT_PLACEHOLDER_DATA_URI; // Determine layout based on what's visible const showChat = this.cfg.chatEnabled && this.showChat; const showVideo = this.showVideoArea && !this.isAudioMode; // Hide video in audio mode const showAudio = this.isAudioMode; // Show audio placeholder in audio mode const bothVisible = (showChat && showVideo) || (showChat && showAudio); // Ensure at least one area is visible const effectiveShowVideo = showVideo || (!showChat && !this.isAudioMode); const effectiveShowAudio = showAudio || (!showChat && this.isAudioMode); const effectiveShowChat = showChat || (!showVideo && !showAudio); this.root.render(
{/* Launcher - only show when panel is hidden */} {!showPanel && ( )} {/* Panel */} {showPanel && (
{/* Title in header */}
{this.currentSize !== 'minimal' && ( <> BuzzTrail AI on {this.getCurrentDomain()} BuzzTrail AI BuzzTrail BT )}
{/* Media Controls - Always visible in header, positioned left */} {(() => { console.log('[Widget] Checking media controls render, currentSize:', this.currentSize); return this.currentSize !== 'minimal' && (
); })()} {/* Size Controls - Exactly 2 buttons for each mode */}
{/* Minimal Mode: Medium + Large */} {this.currentSize === 'minimal' && ( <> )} {/* Medium Mode: Minimal + Large */} {this.currentSize === 'medium' && ( <> )} {/* Large Mode: Minimal + Medium */} {this.currentSize === 'large' && ( <> )}
{/* Interaction Controls - Only show for medium mode */} {this.currentSize === 'medium' && (
)} {/* Content Controls - Hidden in minimal mode */} {this.currentSize !== 'minimal' && (
)} {/* Call Controls - Hidden in minimal mode */} {this.currentSize !== 'minimal' && (
{/* Audio/Video Mode Toggle - Shows the mode it will switch TO */} {/* Play/Pause Call Button */} {!this.isCallActive ? ( ) : ( )} {/* Hidden status for screen readers */}
{this.isCallActive ? 'Conversation active' : 'Conversation ready to start'}
)} {/* Drag Handle - Only for medium mode when drag is enabled */} {this.currentSize === 'medium' && this.cfg.enableDrag && (
)}
{/* Body Content - Hidden in minimal mode */} {this.currentSize !== 'minimal' && (
{effectiveShowVideo && (
{isActive ? (
{this.cfg.enableMockMode ? ( // Mock conversation display - no iframe to avoid Daily.co errors
🤖
Sendcloud Assistant
● Live
Mock Tavus Conversation
Development Mode - No API Credits Required
⏱️ 15 seconds remaining
) : ( // Real conversation - use Tavus Conversation component with proper container
{ void this.endVideo(false); }} onTimeout={() => { void this.endVideo(true); }} />
)}
) : (
)}
)} {effectiveShowAudio && (
{isActive ? (
{this.cfg.enableMockMode ? ( // Mock conversation display for audio mode
Sendcloud Assistant
● Live Audio
Mock Tavus Audio Conversation
Development Mode - Audio Only
⏱️ 15 seconds remaining
) : ( // Real audio conversation - use Tavus Conversation component with proper container
{ void this.endVideo(false); }} onTimeout={() => { void this.endVideo(true); }} />
)}
) : (
Audio Mode
)}
)} {effectiveShowChat && (
)}
)}
)}
); // Enable drag functionality for floating mode this.enableDrag(); this.enableResize(); // Enable resize for medium modes // Apply custom size for medium modes after a small delay to ensure DOM is ready setTimeout(() => { this.applyCustomSize(); }, 50); } /** * Apply custom size for the current mode */ private applyCustomSize(): void { console.log('[Widget] applyCustomSize() called, currentSize:', this.currentSize); // Only apply custom sizes for medium mode that has been resized if (this.currentSize !== 'medium') { console.log('[Widget] Not medium size, skipping custom size application'); return; } const prefs = this.loadUserPreferences(); console.log('[Widget] Loaded preferences for custom size:', prefs); if (prefs.customSizes?.[this.currentSize]) { const customSize = prefs.customSizes[this.currentSize]; if (customSize) { console.log('[Widget] Applying custom size to panel:', customSize); const panel = this.getPanel(); if (panel) { panel.style.width = `${customSize.width}px`; panel.style.height = `${customSize.height}px`; // Verify the size was applied setTimeout(() => { const rect = panel.getBoundingClientRect(); console.log('[Widget] Verified applied size:', { width: rect.width, height: rect.height }); }, 10); } } } else { console.log('[Widget] Panel element not found for custom size application'); } } /** * Get mock mode setting with environment-focused logic * Priority: URL param > environment config > default */ private getMockMode(): boolean { // 1. Check URL parameter first (highest priority for testing) const urlParams = new URLSearchParams(window.location.search); const urlMockMode = urlParams.get('mock'); if (urlMockMode !== null) { const isMock = urlMockMode === 'true' || urlMockMode === '1'; console.log('[Chatbot][Mock] URL parameter mock mode:', isMock); return isMock; } // 2. Check environment-specific configuration const environment = this.getEnvironment(); const envConfig = this.getEnvironmentConfig(environment); if (envConfig.mockMode !== undefined) { console.log(`[Chatbot][Mock] Environment config mock mode: ${envConfig.mockMode} (${environment})`); return envConfig.mockMode; } // 3. Default based on environment const defaultMode = environment === 'production' ? false : true; console.log(`[Chatbot][Mock] Default mock mode: ${defaultMode} (${environment})`); return defaultMode; } /** * Get current environment */ private getEnvironment(): string { // Check for explicit environment in URL const urlParams = new URLSearchParams(window.location.search); const envParam = urlParams.get('env'); if (envParam) { return envParam; } // Check for environment in localStorage const storedEnv = localStorage.getItem('buzztrail_environment'); if (storedEnv) { return storedEnv; } // Check hostname for environment detection const hostname = window.location.hostname; if (hostname.includes('localhost') || hostname.includes('127.0.0.1')) { return 'development'; } if (hostname.includes('staging') || hostname.includes('test')) { return 'staging'; } if (hostname.includes('dev') || hostname.includes('sandbox')) { return 'development'; } if (hostname.includes('production') || hostname.includes('prod')) { return 'production'; } // Default to development for safety return 'development'; } /** * Get environment-specific configuration */ private getEnvironmentConfig(environment: string): { mockMode?: boolean; apiKey?: string; personaId?: string; replicaId?: string } { // Default API key for development/staging const defaultApiKey = '8ff39906dd5840a9bca8c6ce4e15135c'; const configs = { development: { mockMode: false, // Switch to real API now that we have credits apiKey: defaultApiKey, personaId: 'p9c7988840cc', replicaId: 'r92debe21318' }, staging: { mockMode: false, // Use real API in staging apiKey: defaultApiKey, personaId: 'p9c7988840cc', replicaId: 'r92debe21318' }, test: { mockMode: true, // Always use mock in test environment apiKey: 'test-api-key', personaId: 'p9c7988840cc', replicaId: 'r92debe21318' }, production: { mockMode: false, // Never use mock in production apiKey: defaultApiKey, // In production, this should be set via build process personaId: 'p9c7988840cc', replicaId: 'r92debe21318' } }; return configs[environment as keyof typeof configs] || configs.development; } /** * Get position style for the panel */ private getPositionStyle(): React.CSSProperties { if (this.currentSize === 'large') { return { position: 'fixed', top: '1vh', left: '1vw', cursor: 'default' }; } if (this.currentSize === 'medium') { return { position: 'fixed', top: `${this.position.y}px`, left: `${this.position.x}px`, cursor: 'move' }; } return {}; } private styles(): string { return WIDGET_STYLES; } /** * Toggle chat visibility */ public toggleChat(): void { console.log('[Widget][Button] toggleChat() called. Current showChat:', this.showChat); this.showChat = !this.showChat; console.log('[Widget][Button] New showChat value:', this.showChat); this.render(); } /** * Toggle video visibility */ public toggleVideo(): void { console.log('[Widget][Button] toggleVideo() called. Current showVideoArea:', this.showVideoArea); this.showVideoArea = !this.showVideoArea; console.log('[Widget][Button] New showVideoArea value:', this.showVideoArea); this.render(); } /** * Toggle between audio and video mode */ public toggleAudioVideoMode(): void { console.log('[Widget][Button] toggleAudioVideoMode() called. Current isAudioMode:', this.isAudioMode); this.isAudioMode = !this.isAudioMode; this.showVideoArea = !this.isAudioMode; // Hide video when in audio mode console.log('[Widget][Button] Audio mode toggled:', this.isAudioMode, 'Video area:', this.showVideoArea); this.render(); } /** * Start video call */ public startCall(): void { console.log('[Widget][Button] startCall() called'); this.isCallActive = true; void this.startVideo(); } /** * End video call */ public endCall(): void { console.log('[Widget][Button] endCall() called'); this.isCallActive = false; void this.endVideo(); } /** * Toggle drag mode for medium size */ public toggleDrag(): void { this.cfg.enableDrag = !this.cfg.enableDrag; this.saveUserPreferences(); this.render(true); } /** * Toggle resize mode for medium size */ public toggleResize(): void { this.cfg.enableResize = !this.cfg.enableResize; this.saveUserPreferences(); this.render(true); } /** * Toggle overlay backdrop between blur and gradient */ public toggleOverlayBackdrop(): void { this.cfg.overlayBackdrop = this.cfg.overlayBackdrop === 'blur' ? 'gradient' : 'blur'; this.render(true); } }