File size: 5,952 Bytes
906d397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
// static/script.js (Updated to handle greeting triage)

document.addEventListener('DOMContentLoaded', () => {
    const sendBtn = document.getElementById('send-btn');
    const messageInput = document.getElementById('message-input');
    const chatWindow = document.getElementById('chat-window');
    let originalUserMessage = '';
    let currentEstimate = {};

    const appendMessage = (sender, message, isHtml = false) => {
        const senderClass = sender === 'You' ? 'user-message' : 'agent-message';
        const messageDiv = document.createElement('div');
        messageDiv.classList.add('message', senderClass);
        const contentDiv = document.createElement('div');
        const senderStrong = document.createElement('strong');
        senderStrong.textContent = `${sender}:`;
        contentDiv.appendChild(senderStrong);
        const messageP = document.createElement('p');
        if (isHtml) {
            messageP.innerHTML = message;
        } else {
            messageP.textContent = message;
        }
        contentDiv.appendChild(messageP);
        messageDiv.appendChild(contentDiv);
        chatWindow.appendChild(messageDiv);
        chatWindow.scrollTop = chatWindow.scrollHeight;
        return messageDiv;
    };

    const showApprovalDialog = (estimate) => {
        // ... (This function is unchanged)
        currentEstimate = estimate;
        const planHtml = `
            <p>Here is my plan to address your request:</p>
            <ul>${estimate.plan.map(step => `<li>${step}</li>`).join('')}</ul>
            <p>I estimate this will cost ~<strong>$${estimate.estimated_cost_usd}</strong> (for ${estimate.max_loops_initial + 1} attempts).</p>
            <div class="approval-form">
                <label for="budget-input">Set your maximum budget ($):</label>
                <input type="number" id="budget-input" step="0.05" min="0.05" value="${estimate.estimated_cost_usd}">
                <div class="approval-buttons">
                    <button id="proceed-btn">✅ Proceed with Budget</button>
                    <button id="cancel-btn">❌ Cancel</button>
                </div>
            </div>
        `;
        const dialog = appendMessage('Agent', planHtml, true);

        document.getElementById('proceed-btn').addEventListener('click', () => {
            const userBudget = document.getElementById('budget-input').value;
            dialog.remove();
            appendMessage('Agent', `Budget of $${userBudget} approved. Starting the main process...`);
            executeMainTask(userBudget);
});

        document.getElementById('cancel-btn').addEventListener('click', () => {
            dialog.remove();
            appendMessage('Agent', 'Task cancelled.');
            enableInput();
        });
    };
    
    const disableInput = () => { /* ... unchanged ... */ };
    const enableInput = () => { /* ... unchanged ... */ };
    
    const startEstimation = async () => {
        originalUserMessage = messageInput.value.trim();
        if (!originalUserMessage) return;

        appendMessage('You', originalUserMessage);
        messageInput.value = '';
        disableInput();
        
        const thinkingMessage = appendMessage('Agent', 'Thinking...');

        try {
            const response = await fetch('/estimate', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ message: originalUserMessage })
            });
            const result = await response.json();
            
            thinkingMessage.remove();

            if (result.error) {
                appendMessage('Agent', `Error during planning: ${result.error}`);
                enableInput();
            } else if (result.is_greeting) {
                // NEW: Handle the greeting case
                appendMessage('Agent', result.response);
                enableInput();
            } else {
                // It's a complex task, show the approval dialog
                showApprovalDialog(result);
            }
        } catch (error) {
            console.error('Error:', error);
            thinkingMessage.remove();
            appendMessage('Agent', 'Sorry, I encountered an error during estimation.');
            enableInput();
        }
    };
    
    const executeMainTask = async (userBudget) => { /* ... unchanged ... */ };
    
    // ... All other functions and event listeners are unchanged ...
    const disableInput = () => {
        messageInput.disabled = true;
        sendBtn.disabled = true;
    };

    const enableInput = () => {
        messageInput.disabled = false;
        sendBtn.disabled = false;
        messageInput.focus();
    };

    const executeMainTask = async (userBudget) => {
        disableInput();
        const thinkingMessage = appendMessage('Agent', 'Executing task within budget...');

        try {
            const response = await fetch('/chat', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    message: originalUserMessage,
                    user_budget: userBudget,
                    cost_per_loop: currentEstimate.cost_per_loop_usd
                })
            });
            const data = await response.json();
            thinkingMessage.remove();
            appendMessage('Agent', data.response, true);
        } catch (error) {
            console.error('Error:', error);
            thinkingMessage.remove();
            appendMessage('Agent', 'Sorry, I encountered an error during execution.');
        } finally {
            enableInput();
        }
    };

    sendBtn.addEventListener('click', startEstimation);
    messageInput.addEventListener('keydown', (event) => {
        if (event.key === 'Enter' && !event.shiftKey) {
            event.preventDefault();
            startEstimation();
        }
    });
});