// --- Helper function for quick prompts --- function quickPrompt(prompt) { const userInput = document.getElementById('user-input'); if (userInput) { userInput.value = prompt; sendMessage(); } else { window.logToScreen('ERROR: User input field not found for quickPrompt.'); } } // --- Main function to send messages to the AI --- async function sendMessage() { const userInput = document.getElementById('user-input'); const chatMessages = document.getElementById('chat-messages'); if (!userInput || !chatMessages) { window.logToScreen('ERROR: Cannot find chat UI elements.'); return; } const userMessageText = userInput.value.trim(); if (userMessageText === '') return; // 1. Add user's message to the chat window const userBubble = document.createElement('div'); userBubble.className = 'chat-bubble user-bubble p-4 w-3/4 ml-auto mb-4 fade-in'; userBubble.innerHTML = `
${userMessageText}
`; chatMessages.appendChild(userBubble); chatMessages.scrollTop = chatMessages.scrollHeight; userInput.value = ''; // 2. Prepare the AI's response bubble (will be filled in as the stream arrives) const aiBubble = document.createElement('div'); aiBubble.className = 'chat-bubble ai-bubble p-4 w-3/4 fade-in'; const aiParagraph = document.createElement('p'); aiBubble.appendChild(aiParagraph); chatMessages.appendChild(aiBubble); chatMessages.scrollTop = chatMessages.scrollHeight; // 3. Start the fetch process and log everything window.logToScreen('sendMessage triggered. Preparing to fetch...'); try { // IMPORTANT: Replace this with your actual Cloudflare Worker URL const workerUrl = 'https://stream-ai-backend.your-username.workers.dev'; window.logToScreen(`Fetching from: ${workerUrl}`); const response = await fetch(workerUrl, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ prompt: userMessageText }), }); window.logToScreen(`Fetch response received. Status: ${response.status} ${response.statusText}`); if (!response.ok) { const errorText = await response.text(); window.logToScreen(`Error response body: ${errorText}`); throw new Error(`Network response was not ok: ${response.statusText}`); } // 4. Handle the streaming response const reader = response.body.getReader(); const decoder = new TextDecoder(); window.logToScreen('Stream starting...'); while (true) { const { done, value } = await reader.read(); if (done) { window.logToScreen('Stream finished.'); break; } const chunk = decoder.decode(value, { stream: true }); aiParagraph.textContent += chunk; // Append chunk to the AI's paragraph chatMessages.scrollTop = chatMessages.scrollHeight; // Keep scrolling } } catch (error) { // Log the error and display a message in the UI window.logToScreen(`FETCH FAILED: ${error.message}`); aiParagraph.textContent = "Sorry, an error occurred. Check the debug console for details."; aiParagraph.style.color = 'red'; } } // --- Initialization function for the chat module --- export function initChat() { const sendBtn = document.getElementById('send-btn'); const userInput = document.getElementById('user-input'); if (sendBtn && userInput) { sendBtn.addEventListener('click', sendMessage); userInput.addEventListener('keypress', (e) => { if (e.key === 'Enter') { sendMessage(); } }); // Make quickPrompt globally accessible for the inline HTML onclick attributes window.quickPrompt = quickPrompt; } else { // Use the logger in case the elements don't exist if (window.logToScreen) { window.logToScreen("ERROR: Could not find 'send-btn' or 'user-input' to initialize chat."); } } }