synthetic_data / public /index.html
Pepguy's picture
Update public/index.html
720be8f verified
<!DOCTYPE html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>AI Developer Hub</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/3.0.6/purify.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>
<script>
tailwind.config = {
darkMode: 'class',
theme: { extend: { colors: { gray: { 850: '#1f2937', 900: '#111827', 950: '#030712' } } } }
}
</script>
<style>
::-webkit-scrollbar { width: 6px; height: 6px; }
::-webkit-scrollbar-track { background: transparent; }
::-webkit-scrollbar-thumb { background: #374151; border-radius: 4px; }
::-webkit-scrollbar-thumb:hover { background: #4b5563; }
.markdown-body { font-size: 0.95rem; line-height: 1.6; }
.markdown-body p { margin-bottom: 1rem; }
.markdown-body p:last-child { margin-bottom: 0; }
.markdown-body code:not(pre code) { background: #374151; padding: 0.2rem 0.4rem; border-radius: 0.25rem; font-size: 0.85em; }
.markdown-body pre { background: #1e1e1e; padding: 2.5rem 1rem 1rem 1rem; border-radius: 0.5rem; position: relative; overflow-x: auto; margin-bottom: 1rem; }
.markdown-body pre code { font-size: 0.85rem; }
.copy-btn { position: absolute; top: 0.5rem; right: 0.5rem; background: #4b5563; color: #e5e7eb; border: none; padding: 0.25rem 0.75rem; border-radius: 0.375rem; cursor: pointer; font-size: 0.75rem; transition: background 0.2s; }
.copy-btn:hover { background: #6b7280; }
.expand-btn { position: absolute; top: 0.5rem; right: 4.5rem; background: #4b5563; color: #e5e7eb; border: none; padding: 0.25rem 0.75rem; border-radius: 0.375rem; cursor: pointer; font-size: 0.75rem; transition: background 0.2s; }
.expand-btn:hover { background: #6b7280; }
.markdown-body pre.snippet-collapsed { max-height: 8rem; overflow: hidden !important; }
.markdown-body pre.snippet-collapsed::after {
content: "";
position: absolute;
bottom: 0; left: 0; right: 0;
height: 3rem;
background: linear-gradient(transparent, #1e1e1e);
pointer-events: none;
}
.reasoning-block { border-left: 3px solid #6366f1; padding-left: 1rem; margin-bottom: 1rem; color: #9ca3af; font-size: 0.9em; background: rgba(99, 102, 241, 0.05); padding: 0.75rem; border-radius: 0 0.5rem 0.5rem 0; }
</style>
</head>
<body class="bg-gray-950 text-gray-200 h-[100dvh] flex font-sans overflow-hidden antialiased">
<div id="mobile-overlay" class="fixed inset-0 bg-black/60 z-20 hidden lg:hidden transition-opacity" onclick="toggleSidebar()"></div>
<aside id="sidebar" class="absolute lg:relative z-30 inset-y-0 left-0 w-72 lg:w-64 bg-gray-900 border-r border-gray-800 transform -translate-x-full lg:translate-x-0 transition-transform duration-300 ease-in-out flex flex-col shadow-2xl lg:shadow-none">
<div class="p-4 border-b border-gray-800 flex justify-between items-center bg-gray-900">
<h1 class="font-bold text-lg text-white tracking-wide">Dev AI Hub</h1>
<div class="flex items-center gap-2">
<button onclick="createNewChat()" class="p-2 text-blue-400 hover:text-blue-300 bg-gray-800 rounded-md transition" title="New Chat">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4"></path></svg>
</button>
<button onclick="toggleSidebar()" class="p-2 text-gray-400 hover:text-white lg:hidden">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</button>
</div>
</div>
<div id="chat-list" class="flex-1 overflow-y-auto p-3 space-y-2"></div>
</aside>
<main class="flex-1 flex flex-col h-full w-full bg-gray-950 min-w-0 relative">
<header class="h-14 min-h-[3.5rem] border-b border-gray-800 flex items-center px-4 lg:px-6 justify-between bg-gray-900/80 backdrop-blur-sm z-10 shrink-0">
<div class="flex items-center gap-3 overflow-hidden group w-full max-w-[45%]">
<button onclick="toggleSidebar()" class="lg:hidden p-1 -ml-1 text-gray-400 hover:text-white shrink-0">
<svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"></path></svg>
</button>
<div id="title-display" class="flex items-center gap-2 overflow-hidden w-full">
<h2 id="current-chat-title" class="font-semibold text-gray-100 truncate text-sm lg:text-base">Select or create a chat</h2>
<button onclick="enableTitleEdit()" id="edit-title-btn" class="hidden text-gray-500 hover:text-blue-400 p-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0" title="Rename Chat">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"></path></svg>
</button>
</div>
<div id="title-edit" class="hidden items-center gap-2 w-full">
<input type="text" id="title-input" class="bg-gray-800 text-sm lg:text-base text-gray-100 border border-blue-500 rounded px-2 py-1 outline-none w-full" />
<button onclick="saveTitle()" class="text-blue-400 hover:text-blue-300 p-1 shrink-0 bg-gray-800 rounded">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
</button>
<button onclick="cancelTitleEdit()" class="text-gray-400 hover:text-red-400 p-1 shrink-0 bg-gray-800 rounded">
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>
</button>
</div>
</div>
<div class="flex items-center gap-3 lg:gap-4 shrink-0 pl-2">
<div class="hidden sm:flex flex-col items-end text-[10px] text-blue-300 bg-blue-900/30 border border-blue-800/50 px-2 py-1 rounded-md font-mono leading-tight">
<span class="font-semibold text-[11px]">Total: <span id="token-total">0</span></span>
<span class="text-blue-400/70">In: <span id="token-in">0</span> | Out: <span id="token-out">0</span></span>
</div>
<select id="model-select" class="bg-gray-800 text-xs lg:text-sm rounded-md border border-gray-700 px-2 py-1.5 outline-none focus:border-blue-500 transition-colors cursor-pointer text-gray-200">
<option value="claude">Claude Sonnet 3.5</option>
<option value="haiku">Claude Haiku</option>
<option value="maverick">Llama 3 Maverick</option>
</select>
<button onclick="deleteCurrentChat()" class="text-gray-500 hover:text-red-400 transition-colors p-1" title="Delete Chat">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path></svg>
</button>
</div>
</header>
<div id="chat-window" class="flex-1 overflow-y-auto p-4 lg:p-6 space-y-6 scroll-smooth"></div>
<button id="scroll-bottom-btn" onclick="scrollToBottom()" class="hidden absolute bottom-28 right-8 p-2 bg-gray-800/80 hover:bg-gray-700 text-gray-300 hover:text-white rounded-full shadow-lg border border-gray-700 backdrop-blur-sm transition-all z-20">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"></path></svg>
</button>
<div class="p-3 lg:p-4 bg-gray-900 border-t border-gray-800 shrink-0 relative z-30">
<div class="max-w-4xl mx-auto">
<div id="image-preview-container" class="flex flex-wrap gap-2 mb-2 hidden px-1"></div>
<div class="flex items-end gap-2 bg-gray-850 rounded-xl border border-gray-700 p-2 focus-within:border-blue-500 focus-within:ring-1 focus-within:ring-blue-500 transition-all shadow-sm">
<label class="cursor-pointer p-2 text-gray-400 hover:text-blue-400 transition shrink-0 rounded-lg hover:bg-gray-800">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"></path></svg>
<input type="file" id="image-input" accept="image/*" multiple class="hidden" onchange="handleImageSelect(event)">
</label>
<textarea id="message-input" rows="1" class="flex-1 bg-transparent resize-none outline-none text-[15px] p-2 max-h-32 min-h-[40px] text-gray-100 placeholder-gray-500" placeholder="Message the AI..."></textarea>
<button onclick="sendMessage()" id="send-btn" class="p-2 text-blue-400 hover:text-blue-300 transition shrink-0 rounded-lg hover:bg-gray-800">
<svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"></path></svg>
</button>
<button onclick="stopGeneration()" id="stop-btn" class="hidden p-2 text-red-500 hover:text-red-400 transition shrink-0 rounded-lg hover:bg-gray-800" title="Stop Generation">
<svg class="w-5 h-5" fill="currentColor" viewBox="0 0 24 24"><rect x="6" y="6" width="12" height="12" rx="2"></rect></svg>
</button>
</div>
<div class="text-center mt-2 text-[10px] text-gray-600">Shift + Enter for new line</div>
</div>
</div>
</main>
<script>
marked.setOptions({
highlight: function(code, lang) {
const language = hljs.getLanguage(lang) ? lang : 'plaintext';
return hljs.highlight(code, { language }).value;
}
});
// ─── State ────────────────────────────────────────────────────────────────
let currentChatId = null;
let attachedImages =[];
let pollingInterval = null;
let currentTokens = { total: 0, in: 0, out: 0 };
// ─── UI Helpers ───────────────────────────────────────────────────────────
function toggleInputState(isGenerating) {
document.getElementById('send-btn').classList.toggle('hidden', isGenerating);
document.getElementById('stop-btn').classList.toggle('hidden', !isGenerating);
}
async function stopGeneration() {
if (!currentChatId) return;
toggleInputState(false);
try {
await fetch(`/api/chats/${currentChatId}/stop`, { method: 'POST' });
} catch (err) {
console.error("Failed to send stop signal", err);
}
}
const chatWindow = document.getElementById('chat-window');
const scrollBtn = document.getElementById('scroll-bottom-btn');
chatWindow.addEventListener('scroll', () => {
const dist = chatWindow.scrollHeight - chatWindow.scrollTop - chatWindow.clientHeight;
scrollBtn.classList.toggle('hidden', dist <= 100);
});
function scrollToBottom() {
chatWindow.scrollTo({ top: chatWindow.scrollHeight, behavior: 'smooth' });
}
function updateTokenDisplay(total, input, output) {
currentTokens = { total, in: input, out: output };
document.getElementById('token-total').innerText = (total || 0).toLocaleString();
document.getElementById('token-in').innerText = (input || 0).toLocaleString();
document.getElementById('token-out').innerText = (output || 0).toLocaleString();
}
// ─── Copy buttons & snippet collapse ──────────────────────────────────────
function attachCopyButtons(scope) {
(scope || document).querySelectorAll('.markdown-body pre').forEach(pre => {
if (pre.querySelector('.copy-btn')) return;
const expandBtn = document.createElement('button');
expandBtn.className = 'expand-btn';
expandBtn.innerText = 'Expand';
expandBtn.style.display = 'none';
const btn = document.createElement('button');
btn.className = 'copy-btn';
btn.innerText = 'Copy';
btn.onclick = () => {
const codeBlock = pre.querySelector('code');
let text = '';
if (codeBlock) {
text = codeBlock.textContent;
} else {
const clone = pre.cloneNode(true);
clone.querySelectorAll('.copy-btn, .expand-btn').forEach(b => b.remove());
text = clone.textContent;
}
navigator.clipboard.writeText(text.trim());
btn.innerText = 'Copied!';
setTimeout(() => btn.innerText = 'Copy', 2000);
};
pre.appendChild(expandBtn);
pre.appendChild(btn);
if (pre.scrollHeight > 160) {
pre.classList.add('snippet-collapsed');
expandBtn.style.display = 'block';
expandBtn.onclick = () => {
if (pre.classList.contains('snippet-collapsed')) {
pre.classList.remove('snippet-collapsed');
expandBtn.innerText = 'Collapse';
} else {
pre.classList.add('snippet-collapsed');
expandBtn.innerText = 'Expand';
}
};
}
});
}
// ─── Title editing ────────────────────────────────────────────────────────
function enableTitleEdit() {
if (!currentChatId) return;
document.getElementById('title-display').classList.add('hidden');
const edit = document.getElementById('title-edit');
edit.classList.remove('hidden');
edit.classList.add('flex');
const input = document.getElementById('title-input');
input.value = document.getElementById('current-chat-title').innerText;
input.focus();
input.select();
}
function cancelTitleEdit() {
document.getElementById('title-edit').classList.add('hidden');
document.getElementById('title-edit').classList.remove('flex');
document.getElementById('title-display').classList.remove('hidden');
}
async function saveTitle() {
if (!currentChatId) return cancelTitleEdit();
const newTitle = document.getElementById('title-input').value.trim();
if (!newTitle) return cancelTitleEdit();
document.getElementById('current-chat-title').innerText = newTitle;
cancelTitleEdit();
await fetch(`/api/chats/${currentChatId}/title`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title: newTitle })
});
loadSidebar();
}
document.getElementById('title-input').addEventListener('keydown', e => {
if (e.key === 'Enter') saveTitle();
if (e.key === 'Escape') cancelTitleEdit();
});
function toggleSidebar() {
document.getElementById('sidebar').classList.toggle('-translate-x-full');
document.getElementById('mobile-overlay').classList.toggle('hidden');
}
const textarea = document.getElementById('message-input');
textarea.addEventListener('input', function() {
this.style.height = 'auto';
this.style.height = Math.min(this.scrollHeight, 128) + 'px';
});
// ─── Sidebar / Chat list ──────────────────────────────────────────────────
async function loadSidebar() {
const res = await fetch('/api/chats');
const chats = await res.json();
document.getElementById('chat-list').innerHTML = chats.map(c => `
<div onclick="selectChat('${c.id}')" class="p-3 rounded-xl cursor-pointer transition border border-transparent ${c.id === currentChatId ? 'bg-gray-800 border-gray-700' : 'hover:bg-gray-800/50'}">
<div class="text-sm font-medium truncate text-gray-200">${c.title}</div>
<div class="text-[10px] text-gray-500 mt-1 flex justify-between">
<span>Total: ${c.totalTokens.toLocaleString()}</span>
<span class="opacity-70">↑${(c.outputTokens || 0).toLocaleString()}</span>
</div>
</div>
`).join('');
}
async function createNewChat() {
const res = await fetch('/api/chats', { method: 'POST' });
const chat = await res.json();
selectChat(chat.id);
loadSidebar();
if (window.innerWidth < 1024) toggleSidebar();
}
async function deleteCurrentChat() {
if (!currentChatId) return;
if (!confirm("Permanently delete this chat?")) return;
await fetch(`/api/chats/${currentChatId}`, { method: 'DELETE' });
currentChatId = null;
document.getElementById('chat-window').innerHTML = '';
document.getElementById('current-chat-title').innerText = 'Select or create a chat';
document.getElementById('edit-title-btn').classList.add('hidden');
updateTokenDisplay(0, 0, 0);
toggleInputState(false);
loadSidebar();
}
// ─── Select / render chat ─────────────────────────────────────────────────
async function selectChat(id) {
currentChatId = id;
stopPolling();
const res = await fetch(`/api/chats/${id}`);
const chat = await res.json();
// Strict: Discard everything but the last 3 messages from memory
chat.messages = chat.messages.slice(-3);
document.getElementById('current-chat-title').innerText = chat.title;
document.getElementById('edit-title-btn').classList.remove('hidden');
updateTokenDisplay(chat.totalTokens, chat.inputTokens, chat.outputTokens);
cancelTitleEdit();
renderMessages(chat.messages);
loadSidebar();
if (window.innerWidth < 1024 && !document.getElementById('sidebar').classList.contains('-translate-x-full')) {
toggleSidebar();
}
toggleInputState(chat.isGenerating);
if (chat.isGenerating) pollGeneratingChat(id);
}
function renderMessages(messages) {
const isAtBottom = chatWindow.scrollHeight - chatWindow.clientHeight <= chatWindow.scrollTop + 20;
// Strict: Only render the last 3 messages
const limitedMessages = messages.slice(-6); // messages.slice(-3);
chatWindow.innerHTML = limitedMessages.map(m => {
let html = '';
if (m.reasoning) {
html += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(m.reasoning)}</div>`;
}
if (m.content) {
html += DOMPurify.sanitize(marked.parse(m.content));
}
return `
<div class="flex ${m.role === 'user' ? 'justify-end' : 'justify-start'} w-full">
<div class="max-w-[95%] lg:max-w-[85%] rounded-2xl p-4 shadow-sm ${m.role === 'user' ? 'bg-blue-600 text-white rounded-br-sm' : 'bg-gray-850 border border-gray-800 text-gray-200 markdown-body rounded-bl-sm'}">
${m.role === 'user' ? `<div class="whitespace-pre-wrap">${m.content}</div>` : html}
</div>
</div>`;
}).join('');
attachCopyButtons();
if (isAtBottom) scrollToBottom();
}
// ─── Polling (for resumed/in-progress sessions) ───────────────────────────
function stopPolling() {
if (pollingInterval !== null) {
clearInterval(pollingInterval);
pollingInterval = null;
}
}
function pollGeneratingChat(id) {
stopPolling();
pollingInterval = setInterval(async () => {
const res = await fetch(`/api/chats/${id}`);
const chat = await res.json();
// Memory management: Discard all but last 3
chat.messages = chat.messages.slice(-3);
renderMessages(chat.messages);
updateTokenDisplay(chat.totalTokens, chat.inputTokens, chat.outputTokens);
const titleEl = document.getElementById('current-chat-title');
const titleEditHidden = !document.getElementById('title-display').classList.contains('hidden');
if (titleEditHidden && chat.title !== titleEl.innerText) {
titleEl.innerText = chat.title;
loadSidebar();
}
if (!chat.isGenerating) {
stopPolling();
if (currentChatId === id) toggleInputState(false);
}
}, 1500);
}
// ─── Image attach ─────────────────────────────────────────────────────────
function handleImageSelect(event) {
const container = document.getElementById('image-preview-container');
container.classList.remove('hidden');
Array.from(event.target.files).forEach(file => {
const reader = new FileReader();
reader.onload = e => {
attachedImages.push(e.target.result);
container.innerHTML += `
<div class="relative group">
<img src="${e.target.result}" class="h-14 w-14 object-cover rounded-lg border border-gray-600 shadow-sm">
</div>`;
};
reader.readAsDataURL(file);
});
}
// ─── Send message & stream ────────────────────────────────────────────────
async function sendMessage() {
const input = document.getElementById('message-input');
const text = input.value.trim();
if (!text || !currentChatId) return;
// Prune UI memory before adding new ones: ensure we only have room for 1 existing + 2 new
const container = document.getElementById('chat-window');
while (container.children.length > 1) {
container.removeChild(container.firstChild);
}
const payload = {
model: document.getElementById('model-select').value,
prompt: text,
images: attachedImages
};
// Optimistic user bubble + spinner
container.innerHTML += `
<div class="flex justify-end w-full">
<div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-br-sm p-4 bg-blue-600 text-white shadow-sm whitespace-pre-wrap">${text}</div>
</div>
<div class="flex justify-start w-full" id="temp-ai-wrapper">
<div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-bl-sm p-4 bg-gray-850 border border-gray-800 text-gray-200 markdown-body shadow-sm" id="temp-ai-msg">
<span class="flex items-center gap-2 text-gray-400">
<svg class="animate-spin h-4 w-4" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path></svg>
Thinking...
</span>
</div>
</div>`;
scrollToBottom();
// Reset input
input.value = '';
input.style.height = 'auto';
attachedImages =[];
document.getElementById('image-preview-container').innerHTML = '';
document.getElementById('image-preview-container').classList.add('hidden');
toggleInputState(true);
try {
const response = await fetch(`/api/chats/${currentChatId}/stream`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
});
if (!response.ok) throw new Error("API stream rejected. Chat might be busy.");
const reader = response.body.getReader();
const decoder = new TextDecoder('utf-8');
let aiContent = '';
let aiReasoning = '';
let buffer = '';
const MARKER_LEN = 9;
function flushBuffer(final = false) {
let progress = true;
while (progress) {
progress = false;
const thinkIdx = buffer.indexOf('__THINK__');
const usageIdx = buffer.indexOf('__USAGE__');
if (usageIdx !== -1) {
if (usageIdx > 0) aiContent += buffer.slice(0, usageIdx);
const jsonStr = buffer.slice(usageIdx + MARKER_LEN);
try {
const usageData = JSON.parse(jsonStr);
updateTokenDisplay(
currentTokens.total + usageData.totalTokens,
currentTokens.in + usageData.inputTokens,
currentTokens.out + usageData.outputTokens
);
buffer = '';
progress = true;
} catch (_) {
buffer = buffer.slice(usageIdx);
}
} else if (thinkIdx !== -1) {
if (thinkIdx > 0) {
aiContent += buffer.slice(0, thinkIdx);
buffer = buffer.slice(thinkIdx);
}
const afterMarker = buffer.slice(MARKER_LEN);
const nextThink = afterMarker.indexOf('__THINK__');
const nextUsage = afterMarker.indexOf('__USAGE__');
const candidates = [nextThink, nextUsage].filter(x => x !== -1);
const nextMarker = candidates.length ? Math.min(...candidates) : -1;
if (nextMarker !== -1) {
aiReasoning += afterMarker.slice(0, nextMarker);
buffer = afterMarker.slice(nextMarker);
progress = true;
} else {
const safeLen = afterMarker.length - MARKER_LEN;
if (safeLen > 0) {
aiReasoning += afterMarker.slice(0, safeLen);
buffer = '__THINK__' + afterMarker.slice(safeLen);
}
}
} else {
if (final) {
aiContent += buffer;
buffer = '';
progress = true;
} else {
const safeLen = buffer.length - MARKER_LEN;
if (safeLen > 0) {
aiContent += buffer.slice(0, safeLen);
buffer = buffer.slice(safeLen);
progress = true;
}
}
}
}
}
while (true) {
const { value, done } = await reader.read();
if (done) {
flushBuffer(true);
break;
}
buffer += decoder.decode(value, { stream: true });
flushBuffer(false);
let tempHtml = '';
if (aiReasoning) tempHtml += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(aiReasoning)}</div>`;
if (aiContent) tempHtml += DOMPurify.sanitize(marked.parse(aiContent));
const tempMsg = document.getElementById('temp-ai-msg');
if (tempMsg) {
tempMsg.innerHTML = tempHtml || "<span class='animate-pulse text-gray-400'>Thinking...</span>";
}
if (container.scrollHeight - container.scrollTop - container.clientHeight < 100) {
scrollToBottom();
}
}
const tempWrapper = document.getElementById('temp-ai-wrapper');
if (tempWrapper) {
let finalHtml = '';
if (aiReasoning) finalHtml += `<div class="reasoning-block"><i>Thinking Process</i><br/>${marked.parse(aiReasoning)}</div>`;
if (aiContent) finalHtml += DOMPurify.sanitize(marked.parse(aiContent));
tempWrapper.outerHTML = `
<div class="flex justify-start w-full">
<div class="max-w-[95%] lg:max-w-[85%] rounded-2xl rounded-bl-sm p-4 bg-gray-850 border border-gray-800 text-gray-200 markdown-body shadow-sm">
${finalHtml || "<span class='text-gray-500'>No response generated.</span>"}
</div>
</div>`;
attachCopyButtons();
}
// Final sync with API state (strictly last 3)
const finalRes = await fetch(`/api/chats/${currentChatId}`);
const finalChat = await finalRes.json();
renderMessages(finalChat.messages);
loadSidebar();
} catch (error) {
console.error(error);
const tempMsg = document.getElementById('temp-ai-msg');
if (tempMsg) {
tempMsg.innerHTML = "<span class='text-red-400'>Connection lost or chat busy. Reload to sync.</span>";
}
} finally {
if (pollingInterval === null) toggleInputState(false);
}
}
// ─── Keyboard shortcut ────────────────────────────────────────────────────
document.getElementById('message-input').addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
if (!document.getElementById('send-btn').classList.contains('hidden')) {
sendMessage();
}
}
});
// ─── Boot ─────────────────────────────────────────────────────────────────
loadSidebar();
</script>
</body>
</html>