File size: 4,204 Bytes
c564bcb
 
 
 
 
 
 
 
 
 
703af34
c564bcb
703af34
8aa84ea
 
703af34
c564bcb
 
 
 
 
 
 
8aa84ea
c564bcb
 
 
 
 
 
8aa84ea
 
c564bcb
 
 
 
 
 
 
 
 
 
8aa84ea
 
 
c564bcb
 
8aa84ea
 
 
 
c564bcb
 
 
8aa84ea
 
 
 
 
 
 
 
 
 
 
c564bcb
8aa84ea
 
c564bcb
 
8aa84ea
 
c564bcb
 
 
 
8aa84ea
c564bcb
 
703af34
8aa84ea
 
c564bcb
8aa84ea
c564bcb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8aa84ea
703af34
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
// --- 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 = `<p>${userMessageText}</p>`;
    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.");
        }
    }
}