File size: 5,013 Bytes
2df36ec
 
 
 
 
f1c5db8
 
2df36ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
// --- State ---
let sessionId = null;
let models = [];
let currentModel = null;

const REQUEST_LIMIT = 3;
const REQUEST_WINDOW_MS = 30 * 1000; // 1 minute
let requestTimestamps = [];

// --- DOM Elements ---
const modal = document.getElementById('modal');
const apiKeyInput = document.getElementById('apiKeyInput');
const loginBtn = document.getElementById('loginBtn');
const loginError = document.getElementById('loginError');
const app = document.getElementById('app');
const chatContainer = document.getElementById('chatContainer');
const toolToggle = document.getElementById('toolToggle');
const inputForm = document.getElementById('inputForm');
const userInput = document.getElementById('userInput');
const modelSelect = document.getElementById('modelSelect');
const logoutBtn = document.getElementById('logoutBtn');
const typingIndicator = document.getElementById('typingIndicator');

let toolUse = true;

// --- Helpers ---
function canSendRequest() {
    const now = Date.now();
    // Remove timestamps older than 1 minute
    requestTimestamps = requestTimestamps.filter(ts => now - ts < REQUEST_WINDOW_MS);
    return requestTimestamps.length < REQUEST_LIMIT;
  }
  
  function recordRequest() {
    requestTimestamps.push(Date.now());
  }

function scrollToBottom() {
  chatContainer.scrollTop = chatContainer.scrollHeight;
}

function addMessage(text, sender) {
  const msgDiv = document.createElement('div');
  msgDiv.className = 'message ' + sender;
  const bubble = document.createElement('div');
  bubble.className = 'bubble';
  bubble.textContent = text;
  msgDiv.appendChild(bubble);
  chatContainer.appendChild(msgDiv);
  scrollToBottom();
}

function setTyping(isTyping) {
  typingIndicator.classList.toggle('hidden', !isTyping);
  scrollToBottom();
}

function showError(msg) {
  loginError.textContent = msg || '';
}

toolToggle.addEventListener('change', function() {
    toolUse = toolToggle.checked;
  });

// --- Auth & Model Selection ---
loginBtn.onclick = async function () {
  const apiKey = apiKeyInput.value.trim();
  if (!apiKey) { showError('API key required.'); return; }
  loginBtn.disabled = true;
  showError('');
  try {
    const res = await fetch('/init', {
      method: 'POST',
      headers: {'Content-Type': 'application/json'},
      body: JSON.stringify({api_key: apiKey})
    });
    const data = await res.json();
    if (!data.success) { showError(data.error || 'Login failed.'); loginBtn.disabled = false; return; }
    sessionId = data.session_id;
    models = data.models || [];
    // Populate model dropdown
    modelSelect.innerHTML = '';
    models.forEach(m => {
      const opt = document.createElement('option');
      opt.value = m;
      opt.textContent = m;
      modelSelect.appendChild(opt);
    });
    currentModel = models[0];
    modelSelect.value = currentModel;
    // Show app, hide modal
    modal.classList.add('hidden');
    app.classList.remove('hidden');
    chatContainer.innerHTML = '';
    userInput.focus();
  } catch (e) {
    showError('Network error.');
    loginBtn.disabled = false;
  }
};

modelSelect.onchange = function () {
  currentModel = modelSelect.value;
};

// --- Chat Logic ---
inputForm.onsubmit = async function (e) {
    e.preventDefault();
    const text = userInput.value.trim();
    if (!text) return;

    if (!canSendRequest()) {
        addMessage('[Rate limit] Please wait: only 4 requests per minute allowed.', 'bot');
        return;
      }
      recordRequest();

    addMessage(text, 'user');
    userInput.value = '';
    setTyping(true);
    try {
      const res = await fetch('/chat', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({
          session_id: sessionId,
          query: text,
          tool_use: toolUse, // <-- Use the toggle value here
          model: currentModel
        })
      });
      const data = await res.json();
      setTyping(false);
      if (data.error) {
        addMessage('[Error] ' + data.error, 'bot');
        return;
      }
      addMessage(data.output, 'bot');
    } catch (e) {
      setTyping(false);
      addMessage('[Network error]', 'bot');
    }
  };

// --- Logout Logic ---
logoutBtn.onclick = async function () {
  await logoutAndReset();
};

async function logoutAndReset() {
  if (sessionId) {
    try {
      await fetch('/logout', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({session_id: sessionId})
      });
    } catch {}
    sessionId = null;
    models = [];
    currentModel = null;
  }
  app.classList.add('hidden');
  modal.classList.remove('hidden');
  apiKeyInput.value = '';
  chatContainer.innerHTML = '';
  showError('');
  loginBtn.disabled = false;
}

// --- Auto logout on exit ---
window.addEventListener('beforeunload', logoutAndReset);

// --- UX: Enter key in modal input triggers login ---
apiKeyInput.addEventListener('keyup', function(e) {
  if (e.key === 'Enter') loginBtn.click();
});