/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-floating-promises, @typescript-eslint/no-misused-promises */ // Extension content script import type { ConversationMessage, ExtensionMessage as SharedExtensionMessage } from '@buzztrail/shared-types'; import { sendOpenSidePanel, requestStorageManager, saveSiteConfig, sendUserMessage, saveConversation, BuzzTrailParser, type BuzzTrailConfig } from '@buzztrail/shared-utils'; // Deprecated: floating container UI (file retained for archival only) // Use shared ExtensionMessage for typing outbound messages (subset at runtime) type ContentScriptMessage = SharedExtensionMessage; interface BackgroundResponse { success: boolean; data?: unknown; error?: string; } // Persistent connection for real-time updates interface PersistentConnection { port: chrome.runtime.Port; isConnected: boolean; reconnectAttempts: number; maxReconnectAttempts: number; } // Conversation state management interface ConversationState { messages: ConversationMessage[]; isTyping: boolean; lastActivity: string; sessionId: string; } // Site configuration state interface SiteConfigurationState { buzztrailConfig: BuzzTrailConfig | null; isLoaded: boolean; lastChecked: string; } // Mutation observer state interface MutationObserverState { observer: MutationObserver | null; isObserving: boolean; debounceTimer: number | null; lastMutationTime: number; } // AI Companion UI using Floating Container class AICompanionUI { // Floating container UI deprecated; Side Panel is canonical private isInitialized = false; private cleanupFunctions: (() => void)[] = []; private persistentConnection: PersistentConnection | null = null; private messageTimeout = 10000; // 10 seconds timeout private conversationState: ConversationState; private sessionId: string; private siteConfig: SiteConfigurationState; private mutationState: MutationObserverState; private storageManager: unknown = null; // Will be set via message from background private currentDomain = ''; constructor() { console.log('AICompanionUI constructor called'); // Initialize conversation state this.sessionId = this.generateSessionId(); this.conversationState = { messages: [], isTyping: false, lastActivity: new Date().toISOString(), sessionId: this.sessionId }; // Initialize site configuration state this.siteConfig = { buzztrailConfig: null, isLoaded: false, lastChecked: new Date().toISOString() }; // Initialize mutation observer state this.mutationState = { observer: null, isObserving: false, debounceTimer: null, lastMutationTime: 0 }; // No floating UI in side panel mode } /** * Generate a unique session ID */ private generateSessionId(): string { return `session_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`; } /** * Setup storage manager via background script */ private async setupStorageManager(): Promise { try { // Request storage manager from background script const data = await requestStorageManager(); if (data) { this.storageManager = data; console.log('Storage manager setup completed'); } else { console.warn('Failed to setup storage manager, continuing without persistence'); } } catch (error) { // WXT best practice: Handle build/test environment gracefully if (error instanceof Error && (error.message.includes('Extension context not available') || error.message.includes('Chrome runtime not available') || error.message.includes('Not in browser environment'))) { console.log('Extension context not available, continuing without storage manager (build/test environment)'); this.storageManager = null; return; } console.error('Error setting up storage manager:', error); // Don't throw error, just continue without storage manager this.storageManager = null; } } /** * Setup floating container with storage integration */ private setupFloatingContainerStorage(): void { /* deprecated */ } /** * Initialize the AI companion UI */ public async initialize(): Promise { if (this.isInitialized) return; // Get current domain this.currentDomain = window.location?.hostname || 'unknown'; // Setup storage manager via background script await this.setupStorageManager(); // No floating container/storage; only open side panel // No floating UI events this.establishPersistentConnection(); this.loadConversationState(); this.detectAndParseBuzzTrailConfig(); // this.setupMutationObserver(); // Disabled - no automatic collision detection this.isInitialized = true; console.log('AI Companion side-panel launcher initialized'); // Side Panel requires a user gesture; do not auto-open } // Document PiP helpers removed in favor of Side Panel private createMinimalLauncher(): void { // Deprecated: floating container UI const contentElement = document.createElement('div'); const container = document.createElement('div'); container.style.cssText = 'padding:12px;background:#fff;border-top:1px solid #e9ecef'; const btn = document.createElement('button'); btn.textContent = 'Open Side Panel'; btn.style.cssText = 'padding:10px 12px;border-radius:8px;border:1px solid #ddd;background:#667eea;color:#fff;font-weight:600;cursor:pointer'; btn.addEventListener('click', async () => { try { const ok = await sendOpenSidePanel(); if (!ok) console.warn('Failed to open side panel'); } catch (e) { console.error('Open side panel error', e); } }); container.appendChild(btn); contentElement.appendChild(container); } /** * Setup MutationObserver to monitor DOM changes */ private setupMutationObserver(): void { // Disabled for now - no automatic collision detection console.log('Content script: MutationObserver disabled - no automatic collision detection'); // try { // // Create mutation observer with comprehensive options // this.mutationState.observer = new MutationObserver((mutations) => { // this.handleDOMMutations(mutations); // }); // // Start observing with comprehensive options // this.mutationState.observer.observe(document.body, { // childList: true, // subtree: true, // attributes: false, // We don't need attribute changes for UI positioning // characterData: false // We don't need text content changes // }); // this.mutationState.isObserving = true; // console.log('Content script: MutationObserver started'); // } catch (error) { // console.error('Content script: Failed to setup MutationObserver', error); // } } /** * Handle DOM mutations with debouncing and filtering */ private handleDOMMutations(mutations: MutationRecord[]): void { const now = Date.now(); // Prevent excessive processing with time-based throttling if (now - this.mutationState.lastMutationTime < 100) { return; } this.mutationState.lastMutationTime = now; // Filter mutations to only process relevant changes const relevantMutations = mutations.filter(mutation => { // Only process childList mutations (new nodes added/removed) if (mutation.type !== 'childList') { return false; } // Check if the mutation affects elements near our UI const addedNodes = Array.from(mutation.addedNodes); const removedNodes = Array.from(mutation.removedNodes); // Check if any added/removed nodes might affect our positioning const hasRelevantChanges = addedNodes.some(node => this.isNodeRelevant(node) ) || removedNodes.some(node => this.isNodeRelevant(node) ); return hasRelevantChanges; }); if (relevantMutations.length === 0) { return; } // Debounce expensive operations if (this.mutationState.debounceTimer) { clearTimeout(this.mutationState.debounceTimer); } this.mutationState.debounceTimer = window.setTimeout(() => { this.handleRelevantMutations(relevantMutations); }, 1000); // 1 second debounce delay to reduce excessive repositioning } /** * Check if a node is relevant to our UI positioning */ private isNodeRelevant(node: Node): boolean { if (node.nodeType !== Node.ELEMENT_NODE) { return false; } const element = node as Element; const hostElement = document.createElement('div'); // Skip our own elements completely if (hostElement.contains(element) || element.contains(hostElement)) { return false; } // Check if element is positioned and might overlap with our UI const rect = element.getBoundingClientRect(); const ourRect = hostElement.getBoundingClientRect(); // Check for potential overlap const hasOverlap = !( rect.right < ourRect.left || rect.left > ourRect.right || rect.bottom < ourRect.top || rect.top > ourRect.bottom ); // Check if element has positioning that might affect our UI const style = window.getComputedStyle(element); const {position} = style; const zIndex = parseInt(style.zIndex) || 0; const isPositioned = position === 'fixed' || position === 'absolute'; const hasHighZIndex = zIndex > 1000; return hasOverlap || (isPositioned && hasHighZIndex); } /** * Handle relevant mutations */ private handleRelevantMutations(mutations: MutationRecord[]): void { console.log('Content script: Processing relevant DOM mutations', mutations.length); // Check for collisions and reposition if necessary this.checkForCollisions(); // Ensure our UI remains visible and functional this.ensureUIVisibility(); } /** * Check for collisions with new DOM elements */ private checkForCollisions(): void { // Deprecated floating container path disabled const hostElement = document.createElement('div'); const ourRect = hostElement.getBoundingClientRect(); const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; // Check if our UI is still in a good position const isInViewport = ( ourRect.left >= 0 && ourRect.right <= viewportWidth && ourRect.top >= 0 && ourRect.bottom <= viewportHeight ); if (!isInViewport) { this.repositionUI(); return; } // Check for overlapping elements const overlappingElements = this.findOverlappingElements(); if (overlappingElements.length > 0) { console.log('Content script: Found overlapping elements, repositioning UI'); this.repositionUI(); } } /** * Find elements that overlap with our UI */ private findOverlappingElements(): Element[] { const hostElement = document.createElement('div'); const ourRect = hostElement.getBoundingClientRect(); const overlappingElements: Element[] = []; // Get all fixed/absolute positioned elements const positionedElements = document.querySelectorAll('[style*="position: fixed"], [style*="position: absolute"]'); positionedElements.forEach(element => { // Skip our own elements if (hostElement.contains(element)) { return; } const rect = element.getBoundingClientRect(); // Check for overlap const hasOverlap = !( rect.right < ourRect.left || rect.left > ourRect.right || rect.bottom < ourRect.top || rect.top > ourRect.bottom ); if (hasOverlap) { overlappingElements.push(element); } }); return overlappingElements; } /** * Reposition the UI to avoid collisions */ private repositionUI(): void { const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; const uiWidth = 350; // Width of our UI const uiHeight = 500; // Max height of our UI // Try different positions in order of preference const positions = [ { x: 20, y: 20 }, // Original position { x: 20, y: 20 }, // Top left { x: viewportWidth - uiWidth - 20, y: viewportHeight - uiHeight - 20 }, // Bottom right { x: 20, y: viewportHeight - uiHeight - 20 }, // Bottom left { x: viewportWidth - uiWidth - 20, y: 20 }, // Top right { x: (viewportWidth - uiWidth) / 2, y: (viewportHeight - uiHeight) / 2 } // Center ]; for (const position of positions) { if (this.isPositionAvailable(position, uiWidth, uiHeight)) { // deprecated console.log('Content script: UI repositioned to', position); return; } } // If no position works, use the original position // deprecated console.log('Content script: UI repositioned to original position'); } /** * Check if a position is available (no overlapping elements) */ private isPositionAvailable(position: { x: number; y: number }, width: number, height: number): boolean { // Create a temporary element to test the position const testElement = document.createElement('div'); testElement.style.cssText = ` position: fixed; width: ${width}px; height: ${height}px; left: ${position.x}px; top: ${position.y}px; pointer-events: none; z-index: -1; `; document.body.appendChild(testElement); const testRect = testElement.getBoundingClientRect(); document.body.removeChild(testElement); // Check if the position is within viewport const viewportWidth = window.innerWidth; const viewportHeight = window.innerHeight; const isInViewport = ( testRect.left >= 0 && testRect.right <= viewportWidth && testRect.top >= 0 && testRect.bottom <= viewportHeight ); if (!isInViewport) { return false; } // Check for overlapping elements at this position const overlappingElements = this.findOverlappingElementsAtPosition(testRect); return overlappingElements.length === 0; } /** * Find overlapping elements at a specific position */ private findOverlappingElementsAtPosition(testRect: DOMRect): Element[] { const overlappingElements: Element[] = []; // Get all fixed/absolute positioned elements const positionedElements = document.querySelectorAll('[style*="position: fixed"], [style*="position: absolute"]'); positionedElements.forEach(element => { // Skip our own elements const hostElement = document.createElement('div'); if (hostElement.contains(element)) { return; } const rect = element.getBoundingClientRect(); // Check for overlap const hasOverlap = !( rect.right < testRect.left || rect.left > testRect.right || rect.bottom < testRect.top || rect.top > testRect.bottom ); if (hasOverlap) { overlappingElements.push(element); } }); return overlappingElements; } /** * Ensure UI remains visible and functional */ private ensureUIVisibility(): void { const hostElement = document.createElement('div'); // Check if our UI is still in the DOM if (!document.body.contains(hostElement)) { console.log('Content script: UI was removed from DOM, re-injecting'); document.body.appendChild(hostElement); } // Check if our UI is visible const rect = hostElement.getBoundingClientRect(); if (rect.width === 0 || rect.height === 0) { console.log('Content script: UI has zero dimensions, ensuring visibility'); hostElement.style.display = 'block'; } } /** * Detect and parse buzztrail.txt configuration */ private async detectAndParseBuzzTrailConfig(): Promise { try { console.log('Content script: Detecting buzztrail.txt configuration'); const currentUrl = window.location.href; const buzztrailConfig = await BuzzTrailParser.parseBuzzTrailFile(currentUrl); this.siteConfig.buzztrailConfig = buzztrailConfig; this.siteConfig.isLoaded = true; this.siteConfig.lastChecked = new Date().toISOString(); console.log('Content script: Loaded buzztrail configuration', buzztrailConfig); // Apply configuration to AI companion behavior this.applyBuzzTrailConfiguration(buzztrailConfig); // Save configuration to background storage await this.saveSiteConfiguration(buzztrailConfig); } catch (error) { console.error('Content script: Failed to detect/parse buzztrail.txt', error); // Create default configuration const defaultConfig = BuzzTrailParser.parseContent('', window.location.href); this.siteConfig.buzztrailConfig = defaultConfig; this.siteConfig.isLoaded = true; this.siteConfig.lastChecked = new Date().toISOString(); console.log('Content script: Using default configuration', defaultConfig); } } /** * Apply buzztrail configuration to AI companion behavior */ private applyBuzzTrailConfiguration(config: BuzzTrailConfig): void { // Update UI based on configuration this.updateUIFromConfiguration(config); // Update conversation context with site information this.updateConversationContext(config); // Apply payment tier styling if applicable this.applyPaymentTierStyling(config.payment); } /** * Update UI elements based on configuration */ private updateUIFromConfiguration(_config: BuzzTrailConfig): void { // No in-page floating UI in Side Panel mode } /** * Update conversation context with site information */ private updateConversationContext(_config: BuzzTrailConfig): void { // Side panel mode: don't mutate messages in content script to avoid errors } /** * Apply payment tier styling */ private applyPaymentTierStyling(_payment: BuzzTrailConfig['payment']): void { // No in-page floating UI in Side Panel mode } /** * Save site configuration to background storage */ private async saveSiteConfiguration(config: BuzzTrailConfig): Promise { try { const domain = window.location.hostname; await saveSiteConfig(domain, { ...config, lastUpdated: new Date().toISOString() }); } catch (error) { console.error('Failed to save site configuration:', error); } } /** * Load conversation state from storage */ private async loadConversationState(): Promise { try { // Not currently supported by shared types; skip or implement if needed const response = { success: false } as BackgroundResponse; if (response.success && response.data) { const storedState = response.data as ConversationState; this.conversationState = { ...storedState, sessionId: this.sessionId, lastActivity: new Date().toISOString() }; // No in-page conversation display in side panel mode } } catch (error) { console.error('Failed to load conversation state:', error); } } /** * Save conversation state to storage */ private async saveConversationState(): Promise { try { // Not currently defined in shared types; omit in Side Panel mode } catch (error) { console.error('Failed to save conversation state:', error); } } /** * Restore conversation display from state */ private restoreConversationDisplay(): void { // No in-page conversation in side panel mode } /** * Update conversation state */ private updateConversationState(message: Partial): void { const fullMessage: ConversationMessage = { metadata: { id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`, createdAt: new Date().toISOString(), lastModified: new Date().toISOString(), schemaVersion: '1.0.0', isEdited: false }, role: message.role || 'user', content: message.content || { type: 'text', text: '' }, context: message.context || { pageUrl: window.location.href, pageTitle: document.title, domain: window.location.hostname }, status: 'sent', analytics: {}, childMessageIds: [], tags: [], ...message }; this.conversationState.messages.push(fullMessage); this.conversationState.lastActivity = new Date().toISOString(); // Save state to storage this.saveConversationState(); } /** * Set typing indicator */ private setTypingIndicator(isTyping: boolean): void { this.conversationState.isTyping = isTyping; const contentElement = document.createElement('div'); const conversationArea = contentElement.querySelector('#buzztrail-ai-conversation'); if (!conversationArea) return; let typingIndicator = conversationArea.querySelector('#buzztrail-ai-typing'); if (isTyping && !typingIndicator) { typingIndicator = document.createElement('div'); typingIndicator.id = 'buzztrail-ai-typing'; typingIndicator.style.cssText = ` padding: 12px; background: white; border: 1px solid #e9ecef; border-radius: 8px; margin-right: 20px; font-style: italic; color: #6c757d; `; typingIndicator.textContent = 'AI is typing...'; conversationArea.appendChild(typingIndicator); } else if (!isTyping && typingIndicator) { typingIndicator.remove(); } } /** * Establish persistent connection for real-time updates */ private establishPersistentConnection(): void { try { const port = chrome.runtime.connect({ name: 'content-script' }); this.persistentConnection = { port, isConnected: true, reconnectAttempts: 0, maxReconnectAttempts: 5 }; // Handle port messages port.onMessage.addListener((message: BackgroundResponse) => { this.handlePersistentMessage(message); }); // Handle port disconnection port.onDisconnect.addListener(() => { // No logging for connection events - too noisy if (this.persistentConnection) { this.persistentConnection.isConnected = false; } this.attemptReconnection(); }); // No logging for connection establishment - too noisy } catch (error) { console.error('Content script: Failed to establish persistent connection', error); } } /** * Attempt to reconnect the persistent connection */ private attemptReconnection(): void { if (!this.persistentConnection || this.persistentConnection.reconnectAttempts >= this.persistentConnection.maxReconnectAttempts) { console.warn('Content script: Max reconnection attempts reached'); return; } this.persistentConnection.reconnectAttempts++; // No logging for reconnection attempts - too noisy setTimeout(() => { this.establishPersistentConnection(); }, 1000 * this.persistentConnection.reconnectAttempts); // Exponential backoff } /** * Handle messages from persistent connection */ private handlePersistentMessage(message: BackgroundResponse): void { console.log('Content script: Received persistent message', message); if (message.success && message.data) { // Handle real-time updates like conversation updates, video handoff events, etc. this.handleRealTimeUpdate(message.data); } } /** * Handle real-time updates from background service worker */ private handleRealTimeUpdate(data: unknown): void { // Handle different types of real-time updates if (typeof data === 'object' && data !== null) { const update = data as Record; if (update.type === 'conversation_update') { this.updateConversationDisplay(update.data as ConversationMessage); } else if (update.type === 'video_handoff') { this.handleVideoHandoff(update.data); } else if (update.type === 'configuration_update') { this.handleConfigurationUpdate(update.data); } else if (update.type === 'typing_indicator') { this.setTypingIndicator(update.data as boolean); } } } /** * Update conversation display with new message */ private updateConversationDisplay(message: ConversationMessage): void { this.addMessageToConversation(message); this.updateConversationState(message); } /** * Handle video handoff events */ private handleVideoHandoff(data: unknown): void { console.log('Content script: Handling video handoff', data); // TODO: Implement video handoff logic } /** * Handle configuration updates */ private handleConfigurationUpdate(data: unknown): void { console.log('Content script: Handling configuration update', data); // TODO: Implement configuration update logic } /** * Create the UI elements within the floating container */ private createUI(): void { const contentElement = document.createElement('div'); // Create conversation area const conversationArea = document.createElement('div'); conversationArea.id = 'buzztrail-ai-conversation'; conversationArea.style.cssText = ` height: 300px; overflow-y: auto; padding: 16px; background: #f8f9fa; `; // Create input area const inputArea = document.createElement('div'); inputArea.id = 'buzztrail-ai-input-area'; inputArea.style.cssText = ` padding: 16px; border-top: 1px solid #e9ecef; background: white; `; const inputContainer = document.createElement('div'); inputContainer.style.cssText = ` display: flex; gap: 8px; align-items: flex-end; `; const textarea = document.createElement('textarea'); textarea.id = 'buzztrail-ai-input'; textarea.placeholder = 'Ask me anything about this page...'; textarea.style.cssText = ` flex: 1; min-height: 60px; max-height: 120px; padding: 12px; border: 1px solid #e9ecef; border-radius: 8px; font-family: inherit; font-size: 14px; resize: vertical; outline: none; transition: border-color 0.2s; `; const sendButton = document.createElement('button'); sendButton.id = 'buzztrail-ai-send'; sendButton.textContent = 'Send'; sendButton.style.cssText = ` padding: 12px 16px; background: #667eea; color: white; border: none; border-radius: 8px; font-weight: 600; cursor: pointer; transition: background-color 0.2s; white-space: nowrap; `; inputContainer.appendChild(textarea); inputContainer.appendChild(sendButton); inputArea.appendChild(inputContainer); // Assemble the UI contentElement.appendChild(conversationArea); contentElement.appendChild(inputArea); } /** * Setup event listeners */ private setupEventListeners(): void { const contentElement = document.createElement('div'); const sendButton = contentElement.querySelector('#buzztrail-ai-send'); const textarea = contentElement.querySelector('#buzztrail-ai-input') as HTMLTextAreaElement; if (sendButton && textarea) { const sendHandler = (): void => { void this.handleSendMessage(); }; sendButton.addEventListener('click', sendHandler); this.cleanupFunctions.push(() => sendButton.removeEventListener('click', sendHandler)); // Handle Enter key const keydownHandler = (e: KeyboardEvent): void => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); void this.handleSendMessage(); } }; textarea.addEventListener('keydown', keydownHandler); this.cleanupFunctions.push(() => textarea.removeEventListener('keydown', keydownHandler)); // Handle input changes for auto-resize const inputHandler = (): void => { textarea.style.height = 'auto'; textarea.style.height = `${Math.min(textarea.scrollHeight, 120)}px`; }; textarea.addEventListener('input', inputHandler); this.cleanupFunctions.push(() => textarea.removeEventListener('input', inputHandler)); } } /** * Handle sending a message */ private async handleSendMessage(): Promise { const contentElement = document.createElement('div'); const textarea = contentElement.querySelector('#buzztrail-ai-input') as HTMLTextAreaElement; const message = textarea?.value.trim(); if (!message) return; // Clear input if (textarea) { textarea.value = ''; textarea.style.height = '60px'; // Reset height } // Add user message to conversation const userMessage: Partial = { role: 'user', content: { type: 'text', text: message }, context: { pageUrl: window.location.href, pageTitle: document.title, domain: window.location.hostname } }; this.addMessageToConversation(userMessage); this.updateConversationState(userMessage); // Show typing indicator this.setTypingIndicator(true); // Send message to background service worker with timeout try { const response = await sendUserMessage({ message, pageUrl: window.location.href, pageTitle: document.title, domain: window.location.hostname, siteConfig: this.siteConfig.buzztrailConfig as unknown as Record }); // Hide typing indicator this.setTypingIndicator(false); if (response.success && response.data) { // Add AI response to conversation const aiMessage: Partial = { role: 'assistant', content: { type: 'text', text: response.data as string }, context: { pageUrl: window.location.href, pageTitle: document.title, domain: window.location.hostname } }; this.addMessageToConversation(aiMessage); this.updateConversationState(aiMessage); // Save conversation to storage await this.saveConversation(userMessage, aiMessage); } } catch (error) { console.error('Failed to send message:', error); this.setTypingIndicator(false); this.addMessageToConversation({ role: 'error', content: { type: 'text', text: 'Sorry, I encountered an error. Please try again.' }, context: { pageUrl: window.location.href, pageTitle: document.title, domain: window.location.hostname } }); } } /** * Save conversation to storage */ private async saveConversation(userMessage: Partial, aiMessage: Partial): Promise { try { const domain = window.location.hostname; // Save user message await saveConversation(domain, userMessage); // Save AI message await saveConversation(domain, aiMessage); } catch (error) { console.error('Failed to save conversation:', error); } } /** * Add a message to the conversation display */ private addMessageToConversation(_message: Partial): void { // No in-page message rendering in side panel mode } /** * Send message to background service worker with timeout and error handling */ private async sendMessageToBackground(message: ContentScriptMessage): Promise { return new Promise((resolve, reject) => { // WXT best practice: Check if we're in a browser environment with proper extension context if (typeof globalThis === 'undefined' || typeof window === 'undefined') { reject(new Error('Not in browser environment')); return; } // WXT best practice: Check for proper extension context and avoid fake browser // Check for Node.js build environment if (typeof process !== 'undefined' && process.versions && process.versions.node) { reject(new Error('Extension context not available (Node.js build environment)')); return; } // Check for Chrome extension context if (!globalThis.chrome?.runtime?.id) { reject(new Error('Extension context not available (build/test environment)')); return; } // Additional check for sendMessage availability if (typeof globalThis.chrome.runtime.sendMessage !== 'function') { reject(new Error('chrome.runtime.sendMessage not available')); return; } // Set timeout for message response const timeoutId = setTimeout(() => { reject(new Error('Message timeout - background service worker unresponsive')); }, this.messageTimeout); try { globalThis.chrome.runtime.sendMessage(message, (response) => { clearTimeout(timeoutId); if (globalThis.chrome.runtime.lastError) { reject(new Error(globalThis.chrome.runtime.lastError.message)); } else { // Validate response structure if (response && typeof response === 'object') { resolve(response as BackgroundResponse); } else { reject(new Error('Invalid response format from background service worker')); } } }); } catch (error) { clearTimeout(timeoutId); // Handle any runtime errors gracefully if (error instanceof Error) { if (error.message.includes('No listeners available') || error.message.includes('Extension context invalidated') || error.message.includes('Could not establish connection')) { reject(new Error('Extension context not available (build/test environment)')); } else { reject(new Error(`Failed to send message to background: ${error.message}`)); } } else { reject(new Error('Failed to send message to background: Unknown error')); } } }); } /** * Show the UI */ public show(): void { // Intentionally empty - no floating UI in side panel mode } /** * Hide the UI */ public hide(): void { // Intentionally empty - no floating UI in side panel mode } /** * Cleanup all resources */ public cleanup(): void { // Remove event listeners this.cleanupFunctions.forEach(cleanup => cleanup()); this.cleanupFunctions = []; // Disconnect persistent connection if (this.persistentConnection && this.persistentConnection.isConnected) { this.persistentConnection.port.disconnect(); this.persistentConnection.isConnected = false; } // Disconnect mutation observer if (this.mutationState.observer && this.mutationState.isObserving) { this.mutationState.observer.disconnect(); this.mutationState.isObserving = false; } // Clear debounce timer if (this.mutationState.debounceTimer) { clearTimeout(this.mutationState.debounceTimer); this.mutationState.debounceTimer = null; } // Save final state this.saveConversationState(); // Cleanup floating container // deprecated this.isInitialized = false; } } // Global instance let aiCompanionUI: AICompanionUI | null = null; // Expose to window for background script access declare global { interface Window { aiCompanionUI: AICompanionUI | null; } } // Initialize content script const initContentScript = async (): Promise => { // WXT best practice: Only initialize in proper browser context // Check for Node.js build environment if (typeof process !== 'undefined' && process.versions && process.versions.node) { console.log('Content script: Detected Node.js build environment, skipping initialization'); return; } // Check for basic browser environment if (typeof globalThis === 'undefined' || typeof window === 'undefined') { console.log('Content script: Not in browser environment, skipping initialization'); return; } // Check for Chrome extension context if (!globalThis.chrome?.runtime?.id) { console.log('Content script: Chrome extension context not available, skipping initialization'); return; } console.log('Content script initialized'); try { // Create and initialize the AI companion UI console.log('Creating AICompanionUI...'); aiCompanionUI = new AICompanionUI(); // Expose to window for background script access window.aiCompanionUI = aiCompanionUI; console.log('Initializing AICompanionUI...'); await aiCompanionUI.initialize(); console.log('AICompanionUI initialized successfully'); // Show the UI after a short delay setTimeout(() => { console.log('Showing AICompanionUI...'); aiCompanionUI?.show(); console.log('AICompanionUI should now be visible'); }, 1000); } catch (error) { console.error('Error initializing content script:', error); } }; // Cleanup function const cleanupContentScript = (): void => { if (aiCompanionUI) { aiCompanionUI.cleanup(); aiCompanionUI = null; } // Clean up window reference window.aiCompanionUI = null; }; // WXT best practice: Only set up initialization in proper browser context // Check for Node.js build environment first if (typeof process !== 'undefined' && process.versions && process.versions.node) { console.log('Content script: Loaded in Node.js build environment, initialization skipped'); } else if (typeof globalThis !== 'undefined' && typeof window !== 'undefined' && globalThis.chrome?.runtime?.id) { // Initialize when DOM is ready if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => initContentScript()); } else { initContentScript(); } } else { console.log('Content script: Loaded in non-extension environment, initialization skipped'); } // Cleanup on page unload window.addEventListener('beforeunload', cleanupContentScript); export { initContentScript, cleanupContentScript }; // Default export for WXT export default { // WXT loader expects a main() entrypoint; map to our initializer main: initContentScript, cleanupContentScript, };