Spaces:
Running
Running
File size: 15,285 Bytes
5c00819 c02fe07 5c00819 6bf47a1 5c00819 6bf47a1 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 5c00819 c02fe07 | 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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 | ο»Ώ/* ============================================================
Web3 Research Co-Pilot β app.js
Optimised streaming chat client with inline tool activity
============================================================ */
// ββ State ββββββββββββββββββββββββββββββββββββββββββββββββββββ
let chatHistory = [];
let useGemini = false;
// ββ Tool icon map βββββββββββββββββββββββββββββββββββββββββββββ
const TOOL_ICONS = {
coingecko: 'fa-coins',
defillama: 'fa-droplet',
cryptocompare: 'fa-chart-bar',
etherscan: 'fa-magnifying-glass',
chart: 'fa-chart-line',
price: 'fa-dollar-sign',
market: 'fa-chart-area',
gas: 'fa-gas-pump',
whale: 'fa-fish',
'default': 'fa-gear',
};
// ββ Marked.js setup βββββββββββββββββββββββββββββββββββββββββββ
try {
marked.use({ breaks: true, gfm: true });
} catch(e) { /* older marked version β ignore */ }
// ββ Init βββββββββββββββββββββββββββββββββββββββββββββββββββββ
document.addEventListener('DOMContentLoaded', () => {
initTheme();
initModel();
initTextarea();
checkStatus();
document.getElementById('queryInput').focus();
});
// ββ Textarea auto-grow βββββββββββββββββββββββββββββββββββββββ
function initTextarea() {
const ta = document.getElementById('queryInput');
ta.addEventListener('input', () => {
ta.style.height = 'auto';
ta.style.height = Math.min(ta.scrollHeight, 130) + 'px';
document.getElementById('charCount').textContent =
`${ta.value.length} / 1000`;
});
ta.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
sendQuery();
}
});
}
// ββ Model selection ββββββββββββββββββββββββββββββββββββββββββ
function setModel(model) {
useGemini = model === 'gemini';
localStorage.setItem('useGemini', useGemini);
document.getElementById('btnOllama').classList.toggle('active', !useGemini);
document.getElementById('btnGemini').classList.toggle('active', useGemini);
showToast(`Switched to ${useGemini ? 'Gemini (Cloud)' : 'Ollama (Local)'}`, 'info');
checkStatus();
}
function initModel() {
useGemini = localStorage.getItem('useGemini') === 'true';
document.getElementById('btnOllama').classList.toggle('active', !useGemini);
document.getElementById('btnGemini').classList.toggle('active', useGemini);
}
// ββ Status check βββββββββββββββββββββββββββββββββββββββββββββ
async function checkStatus() {
const badge = document.getElementById('statusBadge');
const text = document.getElementById('statusBadgeText');
try {
const res = await fetch('/status');
const data = await res.json();
if (data.enabled) {
badge.className = 'status-badge online';
text.textContent = 'Online';
} else {
badge.className = 'status-badge offline';
text.textContent = 'Limited';
}
} catch {
badge.className = 'status-badge offline';
text.textContent = 'Offline';
}
}
// ββ Send query βββββββββββββββββββββββββββββββββββββββββββββββ
async function sendQuery() {
const ta = document.getElementById('queryInput');
const sendBtn = document.getElementById('sendBtn');
const query = ta.value.trim();
if (!query) return;
addMessage('user', query);
ta.value = '';
ta.style.height = 'auto';
document.getElementById('charCount').textContent = '0 / 1000';
const thinkingId = showThinking();
sendBtn.disabled = true;
sendBtn.innerHTML = '<i class="fas fa-circle-notch fa-spin"></i>';
try {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 300000);
const res = await fetch('/query/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Accept': 'text/event-stream' },
body: JSON.stringify({ query, chat_history: chatHistory, use_gemini: useGemini }),
signal: controller.signal,
});
clearTimeout(timer);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
outer: while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // keep incomplete line
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
try {
const evt = JSON.parse(line.slice(6));
if (handleStreamEvent(evt, thinkingId) === 'done') break outer;
} catch { /* skip malformed JSON */ }
}
}
} catch (err) {
removeThinking(thinkingId);
if (err.name === 'AbortError') {
addMessage('assistant', 'Request timed out after 5 minutes. Try a shorter or simpler query.');
} else if (err.message.includes('Failed to fetch')) {
addMessage('assistant', 'Network error β please check your connection.');
} else {
addMessage('assistant', 'An unexpected error occurred. Please try again.');
}
} finally {
sendBtn.disabled = false;
sendBtn.innerHTML = '<i class="fas fa-paper-plane"></i>';
ta.focus();
}
}
// ββ Handle SSE events ββββββββββββββββββββββββββββββββββββββββ
function handleStreamEvent(data, thinkingId) {
switch (data.type) {
case 'status':
updateThinking(thinkingId, data.message, data.progress);
break;
case 'tools':
addToolStep(thinkingId, data.message);
break;
case 'result':
removeThinking(thinkingId);
if (data.data && data.data.success) {
addMessage('assistant', data.data.response, data.data.sources, data.data.visualizations);
} else {
const msg = (data.data && data.data.response) || 'Analysis temporarily unavailable.';
addMessage('assistant', msg);
}
return 'done';
case 'complete':
return 'done';
case 'error':
removeThinking(thinkingId);
addMessage('assistant', data.message || 'An error occurred.');
return 'done';
}
}
// ββ Thinking bubble ββββββββββββββββββββββββββββββββββββββββββ
function showThinking() {
const id = 'thinking-' + Date.now();
const msgs = document.getElementById('chatMessages');
clearWelcome();
const div = document.createElement('div');
div.className = 'message assistant';
div.id = id;
div.innerHTML = `
<div class="thinking-bubble">
<div class="thinking-header">
<div class="thinking-spinner"></div>
<span class="thinking-label" id="${id}-label">Analyzing queryβ¦</span>
</div>
<div class="tool-steps" id="${id}-steps"></div>
<div class="progress-strip"><div class="progress-fill" id="${id}-bar"></div></div>
</div>
<div class="message-time">${fmtTime()}</div>`;
msgs.appendChild(div);
msgs.scrollTop = msgs.scrollHeight;
return id;
}
function updateThinking(id, message, progress) {
const label = document.getElementById(`${id}-label`);
if (label) label.textContent = message;
const bar = document.getElementById(`${id}-bar`);
if (bar && progress != null) bar.style.width = `${progress}%`;
}
function addToolStep(id, message) {
const steps = document.getElementById(`${id}-steps`);
if (!steps) return;
// Parse "Available tools: ['CoinGecko', 'DeFiLlama', ...]" into individual rows
const listMatch = message.match(/\[(.+)\]/);
const toolNames = listMatch
? [...listMatch[1].matchAll(/'([^']+)'/g)].map(m => m[1])
: null;
if (toolNames && toolNames.length > 0) {
toolNames.forEach(name => {
const step = document.createElement('div');
step.className = 'tool-step';
step.innerHTML = `<i class="fas ${getToolIcon(name)}"></i><span>${escapeHtml(name)}</span>`;
steps.appendChild(step);
});
} else {
const step = document.createElement('div');
step.className = 'tool-step';
step.innerHTML = `<i class="fas ${getToolIcon(message)}"></i><span>${escapeHtml(message)}</span>`;
steps.appendChild(step);
}
document.getElementById('chatMessages').scrollTop = 9999;
}
function removeThinking(id) {
const el = document.getElementById(id);
if (el) el.remove();
}
// ββ Add message ββββββββββββββββββββββββββββββββββββββββββββββ
function addMessage(sender, content, sources = [], visualizations = []) {
clearWelcome();
const msgs = document.getElementById('chatMessages');
const div = document.createElement('div');
div.className = `message ${sender}`;
// Render content
let bodyHtml = '';
if (sender === 'assistant') {
try { bodyHtml = `<div class="md-content">${marked.parse(String(content))}</div>`; }
catch { bodyHtml = `<div class="md-content">${escapeHtml(String(content)).replace(/\n/g, '<br>')}</div>`; }
} else {
bodyHtml = `<div class="md-content">${escapeHtml(String(content))}</div>`;
}
// Sources
let srcHtml = '';
if (sources && sources.length > 0) {
const tags = sources.map(s => `<span class="source-tag">${escapeHtml(s)}</span>`).join('');
srcHtml = `<div class="sources-list"><span class="sources-label">Sources</span>${tags}</div>`;
}
// Visualizations
const vizHtml = (visualizations || []).map((v, i) =>
`<div class="viz-container" id="viz-${Date.now()}-${i}">${v}</div>`
).join('');
div.innerHTML = `
<div class="message-bubble">${bodyHtml}${srcHtml}</div>
${vizHtml}
<div class="message-time">${fmtTime()}</div>`;
msgs.appendChild(div);
msgs.scrollTop = msgs.scrollHeight;
// Apply syntax highlighting to code blocks
if (sender === 'assistant') {
requestAnimationFrame(() => {
if (typeof hljs !== 'undefined') {
div.querySelectorAll('pre code').forEach(b => hljs.highlightElement(b));
}
});
}
// Execute embedded Plotly scripts
if (visualizations && visualizations.length > 0) {
setTimeout(() => {
div.querySelectorAll('script').forEach(s => {
try { new Function(s.textContent).call(window); }
catch (e) { console.warn('Viz script error:', e); }
});
}, 120);
}
// Maintain rolling chat history (last 20 turns)
chatHistory.push({ role: sender, content });
if (chatHistory.length > 20) chatHistory = chatHistory.slice(-20);
}
// ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββ
function clearWelcome() {
const w = document.querySelector('.welcome-screen');
if (w) w.remove();
}
function setQuery(query) {
const ta = document.getElementById('queryInput');
ta.value = query;
ta.style.height = 'auto';
ta.style.height = Math.min(ta.scrollHeight, 130) + 'px';
document.getElementById('charCount').textContent = `${query.length} / 1000`;
setTimeout(sendQuery, 50);
}
function getToolIcon(message) {
const m = message.toLowerCase();
for (const [key, icon] of Object.entries(TOOL_ICONS)) {
if (key !== 'default' && m.includes(key)) return icon;
}
return TOOL_ICONS.default;
}
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function fmtTime() {
return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
// ββ Toast βββββββββββββββββββββββββββββββββββββββββββββββββββββ
let toastTimer = null;
function showToast(message, type = 'info') {
const toast = document.getElementById('statusIndicator');
const text = document.getElementById('statusText');
const icon = toast.querySelector('.toast-icon');
const icons = {
info: 'fa-circle-info',
processing: 'fa-circle-notch fa-spin',
success: 'fa-circle-check',
error: 'fa-circle-xmark',
warning: 'fa-triangle-exclamation',
};
text.textContent = message;
toast.className = `toast show ${type}`;
if (icon) icon.className = `fas ${icons[type] || icons.info} toast-icon`;
clearTimeout(toastTimer);
if (type !== 'processing') {
toastTimer = setTimeout(() => {
toast.classList.remove('show');
}, 3000);
}
}
// ββ Theme βββββββββββββββββββββββββββββββββββββββββββββββββββββ
function initTheme() {
const theme = localStorage.getItem('theme') || 'dark';
document.documentElement.setAttribute('data-theme', theme);
syncThemeIcon(theme);
}
function toggleTheme() {
const cur = document.documentElement.getAttribute('data-theme');
const next = cur === 'light' ? 'dark' : 'light';
document.documentElement.setAttribute('data-theme', next);
localStorage.setItem('theme', next);
syncThemeIcon(next);
}
function syncThemeIcon(theme) {
const icon = document.querySelector('#themeToggle i');
if (icon) icon.className = theme === 'light' ? 'fas fa-moon' : 'fas fa-sun';
}
// ββ Event listeners βββββββββββββββββββββββββββββββββββββββββββ
document.getElementById('sendBtn').addEventListener('click', sendQuery);
document.getElementById('themeToggle').addEventListener('click', toggleTheme);
|