${intro}
I will only answer from the documents — no guessing.
${chips}
`;
}
/* ── Helpers ── */
function scrollToBottom() { messagesEl.scrollTop = messagesEl.scrollHeight; }
let isStreaming = false;
let chatAbort = null;
function setUISending(busy) {
isStreaming = busy;
// While streaming, the send button becomes a stop button
sendIcon.innerHTML = busy ? '■' : '►';
sendBtn.title = busy ? 'Stop generating' : 'Send';
sendBtn.classList.toggle('stopping', busy);
sendIcon.classList.remove('hidden');
sendSpinner.classList.add('hidden');
questionInput.disabled = busy;
}
function escapeHTML(str) {
return str
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"');
}
async function getToken() {
if (!sb) return null;
const { data } = await sb.auth.getSession();
return data.session ? data.session.access_token : null;
}
/* Authenticated fetch — attaches the Supabase access token */
async function authedFetch(url, options = {}) {
const token = await getToken();
const headers = { ...(options.headers || {}) };
if (token) headers['Authorization'] = `Bearer ${token}`;
const res = await fetch(url, { ...options, headers });
if (res.status === 401) {
await handleSignOut();
throw new Error('Session expired. Please log in again.');
}
return res;
}
/* ── Render messages ── */
if (window.marked) marked.setOptions({ breaks: true, gfm: true });
/* Assistant answers are markdown (lists, bold…); render them safely.
User messages stay plain text. */
function setBubbleContent(bubble, role, text) {
if (role === 'assistant' && window.marked && window.DOMPurify) {
bubble.classList.add('md');
bubble.innerHTML = DOMPurify.sanitize(marked.parse(text || ''));
} else {
bubble.textContent = text;
}
}
function renderSources(row, sources) {
if (!sources || sources.length === 0) return;
const sourcesEl = document.createElement('div');
sourcesEl.className = 'sources';
sources.forEach(s => {
const page = sourceDisplayPage(s);
const tag = document.createElement('button');
tag.type = 'button';
tag.className = 'source-tag';
tag.title = 'Preview this page of the PDF';
tag.innerHTML = `${escapeHTML(s.file)} p.${page} 🔍`;
tag.addEventListener('click', () => openPdfPreview(s.file, page, s.snippets || []));
sourcesEl.appendChild(tag);
});
row.appendChild(sourcesEl);
const allImages = sources.flatMap(s => s.image_urls || []);
const uniqueImages = [...new Set(allImages)];
if (uniqueImages.length > 0) {
const imgLabel = document.createElement('p');
imgLabel.className = 'ref-img-label';
imgLabel.textContent = 'Reference images from documents:';
row.appendChild(imgLabel);
const imgGrid = document.createElement('div');
imgGrid.className = 'ref-img-grid';
uniqueImages.forEach(url => {
const wrapper = document.createElement('div');
wrapper.className = 'ref-img-wrapper';
const img = document.createElement('img');
img.src = url;
img.className = 'ref-img';
img.alt = 'Document reference image';
img.loading = 'lazy';
img.addEventListener('click', () => window.open(url, '_blank'));
wrapper.appendChild(img);
imgGrid.appendChild(wrapper);
});
row.appendChild(imgGrid);
}
}
/* 👍/👎 buttons under an assistant answer; state is stored in Supabase */
function addFeedbackBar(row, messageId, current) {
if (!messageId || row.querySelector('.feedback-bar')) return;
const bar = document.createElement('div');
bar.className = 'feedback-bar';
const make = (value, icon, label) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'fb-btn' + (current === value ? ' active' : '');
btn.innerHTML = icon;
btn.title = label;
btn.addEventListener('click', async () => {
const newValue = btn.classList.contains('active') ? null : value;
try {
await authedFetch(`/messages/${messageId}/feedback`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ value: newValue }),
});
bar.querySelectorAll('.fb-btn').forEach(b => b.classList.remove('active'));
if (newValue) btn.classList.add('active');
} catch { /* ignore */ }
});
return btn;
};
bar.appendChild(make('up', '👍', 'Helpful'));
bar.appendChild(make('down', '👎', 'Not helpful'));
row.appendChild(bar);
}
function appendMessage(role, text, sources = [], info = null) {
const row = document.createElement('div');
row.className = `message ${role}`;
const bubble = document.createElement('div');
bubble.className = 'bubble';
setBubbleContent(bubble, role, text);
row.appendChild(bubble);
// Refusals cite nothing (also covers older messages saved with sources)
const refused = role === 'assistant' && (text || '').trim().startsWith("I don't have information");
if (!refused) renderSources(row, sources);
if (role === 'assistant' && info && info.id) {
addFeedbackBar(row, info.id, info.feedback || null);
}
messagesEl.appendChild(row);
scrollToBottom();
return row;
}
/* ── PDF reference preview ── */
const pdfModal = document.getElementById('pdfModal');
const pdfModalBackdrop = document.getElementById('pdfModalBackdrop');
const pdfTitle = document.getElementById('pdfTitle');
const pdfPrev = document.getElementById('pdfPrev');
const pdfNext = document.getElementById('pdfNext');
const pdfPageLabel = document.getElementById('pdfPageLabel');
const pdfOpenTab = document.getElementById('pdfOpenTab');
const pdfCloseBtn = document.getElementById('pdfClose');
const pdfBody = document.getElementById('pdfBody');
const pdfCanvas = document.getElementById('pdfCanvas');
const pdfHighlightLayer = document.getElementById('pdfHighlightLayer');
const pdfLoading = document.getElementById('pdfLoading');
if (window.pdfjsLib) {
pdfjsLib.GlobalWorkerOptions.workerSrc =
'https://cdn.jsdelivr.net/npm/pdfjs-dist@3.11.174/build/pdf.worker.min.js';
}
let pdfDoc = null;
let pdfCurrentUrl = '';
let pdfPageNum = 1;
let pdfSnippets = [];
let pdfRenderTask = null;
let pdfRenderSeq = 0;
/* Older stored messages have 0-based pages and no snippets; new ones are
1-based and carry the retrieved chunk text. */
function sourceDisplayPage(s) {
const n = Number(s.page);
if (!Number.isFinite(n)) return 1;
return Array.isArray(s.snippets) ? Math.max(1, n) : n + 1;
}
async function openPdfPreview(file, page, snippets) {
const url = `/docs/${encodeURIComponent(file)}`;
if (!window.pdfjsLib) {
// Fallback: the browser's own viewer still jumps to the page
window.open(`${url}#page=${page}`, '_blank');
return;
}
pdfTitle.textContent = file;
pdfSnippets = snippets || [];
pdfHighlightLayer.innerHTML = '';
pdfPageLabel.textContent = '…';
pdfModal.classList.remove('hidden');
pdfLoading.classList.remove('hidden');
try {
if (!pdfDoc || pdfCurrentUrl !== url) {
pdfDoc = await pdfjsLib.getDocument(url).promise;
pdfCurrentUrl = url;
}
pdfPageNum = Math.min(Math.max(1, page || 1), pdfDoc.numPages);
await renderPdfPage();
} catch (err) {
pdfPageLabel.textContent = 'failed to load';
pdfDoc = null;
pdfCurrentUrl = '';
} finally {
pdfLoading.classList.add('hidden');
}
}
async function renderPdfPage() {
if (!pdfDoc) return;
const seq = ++pdfRenderSeq;
pdfPageLabel.textContent = `${pdfPageNum} / ${pdfDoc.numPages}`;
pdfOpenTab.href = `${pdfCurrentUrl}#page=${pdfPageNum}`;
pdfPrev.disabled = pdfPageNum <= 1;
pdfNext.disabled = pdfPageNum >= pdfDoc.numPages;
const page = await pdfDoc.getPage(pdfPageNum);
if (seq !== pdfRenderSeq) return;
// Fit the page to the modal width (capped so text stays readable)
const base = page.getViewport({ scale: 1 });
const available = Math.max(pdfBody.clientWidth - 36, 280);
const scale = Math.min(Math.max(available / base.width, 0.5), 2.5);
const viewport = page.getViewport({ scale });
const dpr = window.devicePixelRatio || 1;
pdfCanvas.width = Math.floor(viewport.width * dpr);
pdfCanvas.height = Math.floor(viewport.height * dpr);
pdfCanvas.style.width = `${Math.floor(viewport.width)}px`;
pdfCanvas.style.height = `${Math.floor(viewport.height)}px`;
pdfHighlightLayer.innerHTML = '';
if (pdfRenderTask) { try { pdfRenderTask.cancel(); } catch { /* ignore */ } }
pdfRenderTask = page.render({
canvasContext: pdfCanvas.getContext('2d'),
viewport,
transform: dpr !== 1 ? [dpr, 0, 0, dpr, 0, 0] : null,
});
try {
await pdfRenderTask.promise;
} catch (err) {
return; // cancelled by a newer render
}
if (seq !== pdfRenderSeq) return;
await drawPdfHighlights(page, viewport);
}
/* Highlight the text items on the page that belong to the retrieved chunks. */
async function drawPdfHighlights(page, viewport) {
const norm = t => t.toLowerCase().replace(/\s+/g, ' ').trim();
const snips = (pdfSnippets || []).map(norm).filter(s => s.length > 0);
if (snips.length === 0) return;
const snippetWords = new Set(
snips.join(' ').split(' ').filter(w => w.length >= 4)
);
const textContent = await page.getTextContent();
let firstHighlight = null;
for (const item of textContent.items) {
const t = norm(item.str || '');
if (t.length < 4) continue;
// Exact containment first; fall back to word overlap because PDF.js and
// pypdf extract whitespace slightly differently.
let match = snips.some(s => s.includes(t));
if (!match) {
const words = t.split(' ').filter(w => w.length >= 4);
if (words.length >= 2) {
const hits = words.filter(w => snippetWords.has(w)).length;
match = hits / words.length >= 0.6;
}
}
if (!match) continue;
const tx = pdfjsLib.Util.transform(viewport.transform, item.transform);
const fontH = Math.hypot(tx[2], tx[3]);
const hl = document.createElement('div');
hl.className = 'pdf-highlight';
hl.style.left = `${tx[4]}px`;
hl.style.top = `${tx[5] - fontH}px`;
hl.style.width = `${(item.width || 0) * viewport.scale}px`;
hl.style.height = `${fontH * 1.2}px`;
pdfHighlightLayer.appendChild(hl);
if (!firstHighlight) firstHighlight = hl;
}
if (firstHighlight) {
firstHighlight.scrollIntoView({ block: 'center', behavior: 'smooth' });
}
}
function closePdfModal() {
pdfModal.classList.add('hidden');
}
pdfPrev.addEventListener('click', () => {
if (pdfDoc && pdfPageNum > 1) { pdfPageNum--; renderPdfPage(); }
});
pdfNext.addEventListener('click', () => {
if (pdfDoc && pdfPageNum < pdfDoc.numPages) { pdfPageNum++; renderPdfPage(); }
});
pdfCloseBtn.addEventListener('click', closePdfModal);
pdfModalBackdrop.addEventListener('click', closePdfModal);
document.addEventListener('keydown', (e) => {
if (pdfModal.classList.contains('hidden')) return;
if (e.key === 'Escape') closePdfModal();
if (e.key === 'ArrowLeft') pdfPrev.click();
if (e.key === 'ArrowRight') pdfNext.click();
});
let typingTicker = null;
function appendTypingIndicator() {
removeTypingIndicator();
const row = document.createElement('div');
row.className = 'message assistant';
row.id = 'typingIndicator';
const bubble = document.createElement('div');
bubble.className = 'bubble typing-bubble';
bubble.innerHTML = `
Searching policy documents…
`;
row.appendChild(bubble);
messagesEl.appendChild(row);
scrollToBottom();
// Show elapsed time and reassure the user during long waits — the free
// NVIDIA endpoint can queue requests when it's busy.
const start = Date.now();
typingTicker = setInterval(() => {
const timer = document.getElementById('typingTimer');
const status = document.getElementById('typingStatus');
if (!timer || !status) return;
const secs = Math.round((Date.now() - start) / 1000);
if (secs >= 3) timer.textContent = `${secs}s`;
if (secs >= 45) {
status.textContent = 'Still queued — the free AI service is crowded. Press ■ to cancel if needed.';
} else if (secs >= 15) {
status.textContent = 'The AI service is a bit busy — still working on it…';
}
}, 1000);
return row;
}
function setTypingStatus(text) {
const status = document.getElementById('typingStatus');
if (status) status.textContent = text;
}
function removeTypingIndicator() {
if (typingTicker) { clearInterval(typingTicker); typingTicker = null; }
const el = document.getElementById('typingIndicator');
if (el) el.remove();
}
function resetMessages() {
messagesEl.innerHTML = welcomeHTML();
}
/* ── Sessions ── */
async function loadSessions() {
try {
const res = await authedFetch('/sessions');
const data = await res.json();
renderSessions(data.sessions || []);
} catch { /* ignore */ }
}
function renderSessions(sessions) {
sessionList.innerHTML = '';
clearAllBtn.classList.toggle('hidden', sessions.length === 0);
if (sessions.length === 0) {
sessionList.innerHTML = '
No conversations yet
';
return;
}
sessions.forEach((s, i) => {
const li = document.createElement('li');
li.className = 'session-item' + (s.id === currentSessionId ? ' active' : '');
li.dataset.id = s.id;
li.style.animationDelay = Math.min(i * 25, 250) + 'ms'; // cascade in
const titleSpan = document.createElement('span');
titleSpan.className = 'session-title';
titleSpan.textContent = s.title || 'New chat';
titleSpan.addEventListener('click', () => openSession(s.id, s.title));
const ren = document.createElement('button');
ren.className = 'session-ren';
ren.innerHTML = '✎';
ren.title = 'Rename conversation';
ren.addEventListener('click', (e) => {
e.stopPropagation();
const editing = li.querySelector('.session-rename-input');
if (editing) editing.blur(); // acting as the save (tick) button
else startRename(li, s);
});
const del = document.createElement('button');
del.className = 'session-del';
del.innerHTML = '×';
del.title = 'Delete conversation';
del.addEventListener('click', (e) => { e.stopPropagation(); deleteSession(s.id); });
li.appendChild(titleSpan);
li.appendChild(ren);
li.appendChild(del);
sessionList.appendChild(li);
});
}
let openSessionSeq = 0;
async function openSession(sessionId, title) {
// Switch the UI immediately; the messages stream in when the API answers
const seq = ++openSessionSeq;
currentSessionId = sessionId;
chatTitle.textContent = title || 'Conversation';
exportBtn.classList.remove('hidden');
closeSidebar();
highlightActiveSession();
messagesEl.innerHTML = '
';
try {
const res = await authedFetch(`/sessions/${sessionId}/messages`);
const data = await res.json();
if (seq !== openSessionSeq) return; // user already switched again
const msgs = data.messages || [];
messagesEl.innerHTML = '';
if (msgs.length === 0) {
resetMessages();
} else {
msgs.forEach((m, i) => {
const row = appendMessage(m.role, m.content, m.sources || [], { id: m.id, feedback: m.feedback });
row.style.animationDelay = Math.min(i * 40, 360) + 'ms'; // history cascades in
});
}
scrollToBottom();
} catch {
if (seq === openSessionSeq) resetMessages();
}
}
function highlightActiveSession() {
[...sessionList.querySelectorAll('.session-item')].forEach(li => {
li.classList.toggle('active', li.dataset.id === currentSessionId);
});
}
function startNewChat() {
currentSessionId = null;
chatTitle.textContent = 'New chat';
exportBtn.classList.add('hidden');
closeSidebar();
resetMessages();
highlightActiveSession();
questionInput.focus();
}
/* ── Confirmation modal (Enter = confirm, Esc = cancel) ── */
const confirmModal = document.getElementById('confirmModal');
const confirmBackdrop = document.getElementById('confirmBackdrop');
const confirmText = document.getElementById('confirmText');
const confirmOk = document.getElementById('confirmOk');
const confirmCancel = document.getElementById('confirmCancel');
function confirmDialog(text, okLabel = 'Delete') {
return new Promise(resolve => {
confirmText.textContent = text;
confirmOk.textContent = okLabel;
confirmModal.classList.remove('hidden');
const done = (value) => {
confirmModal.classList.add('hidden');
document.removeEventListener('keydown', onKey, true);
confirmOk.removeEventListener('click', ok);
confirmCancel.removeEventListener('click', cancel);
confirmBackdrop.removeEventListener('click', cancel);
resolve(value);
};
const ok = () => done(true);
const cancel = () => done(false);
const onKey = (e) => {
if (e.key === 'Enter') { e.preventDefault(); e.stopPropagation(); ok(); }
else if (e.key === 'Escape') { e.preventDefault(); e.stopPropagation(); cancel(); }
};
confirmOk.addEventListener('click', ok);
confirmCancel.addEventListener('click', cancel);
confirmBackdrop.addEventListener('click', cancel);
document.addEventListener('keydown', onKey, true);
confirmOk.focus();
});
}
/* Small transient notice (bottom center) */
function showToast(text) {
let t = document.getElementById('toast');
if (!t) {
t = document.createElement('div');
t.id = 'toast';
t.className = 'toast';
document.body.appendChild(t);
}
t.textContent = text;
t.classList.add('show');
clearTimeout(showToast._timer);
showToast._timer = setTimeout(() => t.classList.remove('show'), 3500);
}
async function deleteSession(sessionId) {
if (!await confirmDialog('Delete this conversation? This cannot be undone.')) return;
// Optimistic: slide the item out of the sidebar, roll back if the API fails
const li = sessionList.querySelector(`.session-item[data-id="${sessionId}"]`);
if (li) {
li.classList.add('removing');
setTimeout(() => {
li.remove();
if (!sessionList.querySelector('.session-item')) {
sessionList.innerHTML = '
No conversations yet
';
clearAllBtn.classList.add('hidden');
}
}, 180);
}
if (sessionId === currentSessionId) startNewChat();
try {
const res = await authedFetch(`/sessions/${sessionId}`, { method: 'DELETE' });
if (!res.ok) throw new Error();
} catch {
await loadSessions(); // bring the conversation back
showToast('Could not delete the conversation — it has been restored.');
}
}
async function deleteAllSessions() {
if (!await confirmDialog('Delete ALL conversations? This cannot be undone.', 'Delete all')) return;
// Optimistic: empty the sidebar immediately, roll back if the API fails
sessionList.innerHTML = '
No conversations yet
';
clearAllBtn.classList.add('hidden');
startNewChat();
try {
const res = await authedFetch('/sessions', { method: 'DELETE' });
if (!res.ok) throw new Error();
} catch {
await loadSessions(); // bring the conversations back
showToast('Could not delete the conversations — they have been restored.');
}
}
clearAllBtn.addEventListener('click', deleteAllSessions);
/* Inline rename: swap the title for an input; Enter/blur/tick saves, Esc cancels */
function startRename(li, s) {
const titleSpan = li.querySelector('.session-title');
if (!titleSpan) return;
// The pencil becomes a tick (save) while editing
const ren = li.querySelector('.session-ren');
if (ren) {
ren.innerHTML = '✓';
ren.title = 'Save name';
ren.classList.add('confirming');
}
const input = document.createElement('input');
input.type = 'text';
input.className = 'session-rename-input';
input.value = s.title || 'New chat';
input.maxLength = 80;
li.replaceChild(input, titleSpan);
input.focus();
input.select();
let cancelled = false;
let finished = false;
const finish = async () => {
if (finished) return;
finished = true;
const title = input.value.trim();
if (!cancelled && title && title !== s.title) {
try {
await authedFetch(`/sessions/${s.id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title }),
});
if (s.id === currentSessionId) chatTitle.textContent = title;
} catch { /* keep old title */ }
}
await loadSessions();
};
input.addEventListener('keydown', (e) => {
e.stopPropagation();
if (e.key === 'Enter') input.blur();
else if (e.key === 'Escape') { cancelled = true; input.blur(); }
});
input.addEventListener('blur', finish);
input.addEventListener('click', (e) => e.stopPropagation());
}
/* ── Chat submit ── */
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
// While an answer is streaming, the send button acts as a stop button
if (isStreaming) {
if (chatAbort) chatAbort.abort();
return;
}
const question = questionInput.value.trim();
if (!question) return;
// Clear the welcome bubble on first real message
const welcome = messagesEl.querySelector('.welcome');
if (welcome) welcome.remove();
appendMessage('user', question);
questionInput.value = '';
questionInput.style.height = 'auto';
setUISending(true);
appendTypingIndicator();
const wasNew = !currentSessionId;
let row = null;
let bubble = null;
let meta = null;
let answerText = '';
let doneMsgId = null;
// Typewriter buffer: the API delivers tokens in bursts, so instead of
// rendering lumps we queue incoming text and reveal it at a steady rate
// (speeding up when the queue grows, so we never lag behind).
let pendingText = '';
let typeTimer = null;
const typeTick = () => {
if (!pendingText) return;
const step = Math.max(2, Math.ceil(pendingText.length / 25));
answerText += pendingText.slice(0, step);
pendingText = pendingText.slice(step);
setBubbleContent(bubble, 'assistant', answerText);
scrollToBottom();
};
const stopTypewriter = () => {
if (typeTimer) { clearInterval(typeTimer); typeTimer = null; }
if (pendingText && bubble) {
answerText += pendingText;
pendingText = '';
setBubbleContent(bubble, 'assistant', answerText);
}
};
const ensureRow = () => {
if (row) return;
removeTypingIndicator();
row = appendMessage('assistant', '');
bubble = row.querySelector('.bubble');
bubble.classList.add('streaming');
};
const finalize = async () => {
stopTypewriter();
removeTypingIndicator();
if (bubble) bubble.classList.remove('streaming');
// A refusal cites nothing — showing sources/images would be misleading
const refused = answerText.trim().startsWith("I don't have information");
if (meta) {
if (row && !refused) renderSources(row, meta.sources || []);
// Sidebar refresh is housekeeping — if it fails (e.g. server just went
// down) it must not surface as an error on an already-delivered answer.
if (wasNew) { try { await loadSessions(); } catch { /* refresh later */ } }
highlightActiveSession();
}
if (row && doneMsgId) addFeedbackBar(row, doneMsgId, null);
if (currentSessionId) exportBtn.classList.remove('hidden');
scrollToBottom();
};
try {
chatAbort = new AbortController();
const res = await authedFetch('/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ question, session_id: currentSessionId }),
signal: chatAbort.signal,
});
if (!res.ok) {
removeTypingIndicator();
const err = await res.json().catch(() => ({ detail: res.statusText }));
appendMessage('assistant', `Error: ${err.detail || `The server returned an error (HTTP ${res.status}). Please try again.`}`);
return;
}
// The answer arrives as a server-sent-event stream:
// meta (session + sources) → delta tokens → done
const handleEvent = (evt) => {
if (evt.type === 'meta') {
meta = evt;
currentSessionId = evt.session_id;
chatTitle.textContent = evt.title || 'Conversation';
const n = (evt.sources || []).length;
setTypingStatus(n > 0
? `Found ${n} relevant passage${n === 1 ? '' : 's'} — writing the answer…`
: 'Writing the answer…');
} else if (evt.type === 'delta') {
ensureRow();
pendingText += evt.text;
if (!typeTimer) typeTimer = setInterval(typeTick, 24);
} else if (evt.type === 'error') {
ensureRow();
stopTypewriter();
answerText += (answerText ? '\n\n' : '') + (evt.detail || 'Something went wrong.');
setBubbleContent(bubble, 'assistant', answerText);
} else if (evt.type === 'done') {
doneMsgId = evt.message_id || null;
}
};
const reader = res.body.getReader();
const decoder = new TextDecoder();
let buf = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buf += decoder.decode(value, { stream: true });
let sep;
while ((sep = buf.indexOf('\n\n')) !== -1) {
const raw = buf.slice(0, sep).trim();
buf = buf.slice(sep + 2);
if (!raw.startsWith('data:')) continue;
try { handleEvent(JSON.parse(raw.slice(5))); } catch { /* skip bad frame */ }
}
}
await finalize();
if (!row) appendMessage('assistant', 'No answer received. Please try again.');
} catch (err) {
// Always clean up (stop the typewriter, keep any partial answer on screen)
await finalize();
if (err.name !== 'AbortError') {
if (answerText) {
appendMessage('assistant', '⚠️ Connection to the server was lost — the answer above may be incomplete.');
} else if (err instanceof TypeError) {
appendMessage('assistant', '⚠️ Could not reach the server. Please check that it is running, then try again.');
} else {
appendMessage('assistant', `Error: ${err.message || 'Something went wrong.'}`);
}
}
} finally {
chatAbort = null;
setUISending(false);
questionInput.focus();
}
});
questionInput.addEventListener('input', () => {
questionInput.style.height = 'auto';
questionInput.style.height = Math.min(questionInput.scrollHeight, 140) + 'px';
// Only show a scrollbar once the textarea has grown to its max height
questionInput.style.overflowY = questionInput.scrollHeight > 140 ? 'auto' : 'hidden';
});
questionInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
chatForm.dispatchEvent(new Event('submit'));
}
});
newChatBtn.addEventListener('click', startNewChat);
logoutBtn.addEventListener('click', handleSignOut);
/* ── Mobile sidebar drawer ── */
function openSidebar() {
sidebar.classList.add('open');
sidebarBackdrop.classList.remove('hidden');
}
function closeSidebar() {
sidebar.classList.remove('open');
sidebarBackdrop.classList.add('hidden');
}
menuBtn.addEventListener('click', openSidebar);
sidebarBackdrop.addEventListener('click', closeSidebar);
/* ── Starter question chips (welcome screen) ── */
messagesEl.addEventListener('click', (e) => {
const chip = e.target.closest('.starter-chip');
if (!chip || isStreaming) return;
questionInput.value = chip.textContent;
chatForm.dispatchEvent(new Event('submit'));
});
/* ── Voice input (browser Web Speech API — free, works in Chrome/Edge) ── */
const SpeechRec = window.SpeechRecognition || window.webkitSpeechRecognition;
let recognition = null;
let recActive = false;
if (!SpeechRec) {
micBtn.classList.add('hidden');
} else {
micBtn.addEventListener('click', () => {
if (recActive) { recognition.stop(); return; }
recognition = new SpeechRec();
recognition.lang = 'en-US';
recognition.interimResults = true; // live transcription while speaking
recognition.maxAlternatives = 1;
// Anything already typed stays; the spoken words are appended after it
const prefix = questionInput.value ? questionInput.value.trim() + ' ' : '';
recognition.onresult = (e) => {
// Rebuild the transcript on every event so interim guesses get
// replaced (not appended) as the recogniser refines them
let text = '';
for (let i = 0; i < e.results.length; i++) {
text += e.results[i][0].transcript;
}
questionInput.value = prefix + text;
questionInput.dispatchEvent(new Event('input')); // autoresize
};
recognition.onend = () => {
recActive = false;
micBtn.classList.remove('recording');
questionInput.focus();
};
recActive = true;
micBtn.classList.add('recording');
recognition.start();
});
}
/* ── Export conversation as a text file ── */
exportBtn.addEventListener('click', async () => {
if (!currentSessionId) return;
try {
const res = await authedFetch(`/sessions/${currentSessionId}/messages`);
const data = await res.json();
const title = chatTitle.textContent || 'Conversation';
const lines = (data.messages || []).map(m => {
const who = m.role === 'user' ? 'You' : 'Docent AI';
const cites = (m.sources || [])
.map(s => ` [source: ${s.file}, p.${sourceDisplayPage(s)}]`)
.join('\n');
return `${who}:\n${m.content}${cites ? '\n' + cites : ''}\n`;
});
const text = `${title}\nExported ${new Date().toLocaleString()}\n${'='.repeat(50)}\n\n${lines.join('\n')}`;
const blob = new Blob([text], { type: 'text/plain' });
const a = document.createElement('a');
a.href = URL.createObjectURL(blob);
a.download = `${title.replace(/[^\w\- ]+/g, '').trim() || 'chat'}.txt`;
a.click();
URL.revokeObjectURL(a.href);
} catch { /* ignore */ }
});
/* ── Admin analytics: full dashboard page ── */
analyticsBtn.addEventListener('click', () => { window.location.href = '/admin'; });
/* ── File selection / upload ── */
fileInput.addEventListener('change', () => {
uploadBtn.disabled = fileInput.files.length === 0;
});
dropZone.addEventListener('click', () => fileInput.click());
dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('dragover');
const dt = e.dataTransfer;
if (dt.files.length > 0) {
fileInput.files = dt.files;
uploadBtn.disabled = false;
}
});
uploadBtn.addEventListener('click', async () => {
if (!fileInput.files.length) return;
uploadBtn.disabled = true;
uploadBtnText.textContent = 'Uploading…';
uploadSpinner.classList.remove('hidden');
uploadStatus.classList.add('hidden');
const form = new FormData();
for (const file of fileInput.files) form.append('files', file);
try {
const res = await authedFetch('/upload', { method: 'POST', body: form });
const data = await res.json();
const lines = (data.results || []).map(r =>
r.status === 'ingested' ? `\u2713 ${r.file} (${r.chunks} chunks)` : `\u2717 ${r.file}: ${r.status}`
);
uploadStatus.textContent = lines.join('\n');
uploadStatus.classList.remove('hidden');
fileInput.value = '';
await loadDocumentList();
} catch {
uploadStatus.textContent = 'Upload failed. Check the server.';
uploadStatus.classList.remove('hidden');
} finally {
uploadBtnText.textContent = 'Upload';
uploadSpinner.classList.add('hidden');
uploadBtn.disabled = false;
}
});
async function loadDocumentList() {
try {
const res = await authedFetch('/documents');
const data = await res.json();
const docs = data.documents || [];
docList.innerHTML = '';
if (docs.length === 0) {
docList.innerHTML = '
No documents yet
';
} else {
docs.forEach(name => {
const li = document.createElement('li');
li.className = 'doc-item';
const span = document.createElement('span');
span.className = 'doc-name';
span.textContent = name;
const del = document.createElement('button');
del.type = 'button';
del.className = 'doc-del';
del.innerHTML = '×';
del.title = 'Remove this document from the knowledge base';
del.addEventListener('click', () => deleteDocument(name, li));
li.appendChild(span);
li.appendChild(del);
docList.appendChild(li);
});
}
} catch { /* ignore */ }
}
async function deleteDocument(name, li) {
if (!await confirmDialog(`Remove "${name}" and all of its content from the knowledge base?`, 'Remove')) return;
li.style.opacity = '.4';
try {
const res = await authedFetch(`/documents/${encodeURIComponent(name)}`, { method: 'DELETE' });
if (!res.ok) throw new Error();
const data = await res.json();
uploadStatus.textContent = `Removed ${name} (${data.chunks_removed} chunks)`;
uploadStatus.classList.remove('hidden');
await loadDocumentList();
} catch {
li.style.opacity = '';
uploadStatus.textContent = `Could not remove ${name}.`;
uploadStatus.classList.remove('hidden');
}
}
/* ── Auth UI ──
Modes: 'login' | 'signup' | 'forgot' (request reset email)
| 'recovery' (arrived via the reset link — set a new password) */
function setAuthMode(mode) {
authMode = mode;
const showEmail = mode !== 'recovery';
const showPassword = mode === 'login' || mode === 'signup' || mode === 'recovery';
const showTabs = mode === 'login' || mode === 'signup';
authTabs.classList.toggle('hidden', !showTabs);
authEmail.classList.toggle('hidden', !showEmail);
authEmailLabel.classList.toggle('hidden', !showEmail);
passwordWrap.classList.toggle('hidden', !showPassword);
authPasswordLabel.classList.toggle('hidden', !showPassword);
authEmail.required = showEmail;
authPassword.required = showPassword;
forgotBtn.classList.toggle('hidden', mode !== 'login');
backToLogin.classList.toggle('hidden', mode !== 'forgot');
// Google sign-in applies to login/signup only, not reset flows
const showGoogle = mode === 'login' || mode === 'signup';
authDivider.classList.toggle('hidden', !showGoogle);
googleBtn.classList.toggle('hidden', !showGoogle);
authPasswordLabel.textContent = mode === 'recovery' ? 'New password' : 'Password';
tabLogin.classList.toggle('active', mode === 'login');
tabSignup.classList.toggle('active', mode === 'signup');
authSubmitText.textContent = {
login: 'Log in',
signup: 'Create account',
forgot: 'Send reset link',
recovery: 'Set new password',
}[mode];
hideAuthMessage();
}
function showAuthMessage(text, kind = 'error') {
authMessage.textContent = text;
authMessage.className = `auth-message ${kind}`;
}
function hideAuthMessage() { authMessage.className = 'auth-message hidden'; }
function setAuthBusy(busy) {
authSubmit.disabled = busy;
authSpinner.classList.toggle('hidden', !busy);
}
tabLogin.addEventListener('click', () => setAuthMode('login'));
tabSignup.addEventListener('click', () => setAuthMode('signup'));
/* ── Sign in with Google (Supabase OAuth) ──
One button covers both cases: existing users log in, new Google
accounts are created automatically. The page redirects to Google,
then back here where boot() picks up the fresh session. */
googleBtn.addEventListener('click', async () => {
if (!sb) {
showAuthMessage('Auth is not ready yet. Reload the page and try again.');
return;
}
googleBtn.disabled = true;
googleBtnText.textContent = 'Redirecting to Google…';
hideAuthMessage();
try {
const { error } = await sb.auth.signInWithOAuth({
provider: 'google',
options: { redirectTo: window.location.origin },
});
if (error) throw error;
// The browser is now navigating away — nothing more to do here.
} catch (err) {
showAuthMessage(err.message || 'Google sign-in failed. Please try again.');
googleBtn.disabled = false;
googleBtnText.textContent = 'Continue with Google';
}
});
authForm.addEventListener('submit', async (e) => {
e.preventDefault();
if (!sb) {
showAuthMessage('Auth is not ready yet. Reload the page; if it persists, the Supabase library failed to load.');
return;
}
const email = authEmail.value.trim();
const password = authPassword.value;
setAuthBusy(true);
hideAuthMessage();
try {
if (authMode === 'recovery') {
const { error } = await sb.auth.updateUser({ password });
if (error) { showAuthMessage(error.message); return; }
// Remove the recovery tokens from the URL before entering the app
history.replaceState(null, '', window.location.pathname);
setAuthMode('login');
await enterApp();
} else if (authMode === 'forgot') {
const { error } = await sb.auth.resetPasswordForEmail(email, {
redirectTo: window.location.origin,
});
if (error) { showAuthMessage(error.message); return; }
showAuthMessage('Reset link sent — check your inbox, then follow the link to set a new password.', 'success');
} else if (authMode === 'signup') {
const { data, error } = await sb.auth.signUp({ email, password });
if (error) { showAuthMessage(error.message); return; }
if (data.session) {
await enterApp();
} else {
// Email confirmation required — point the user at their inbox
setAuthMode('login');
authEmail.value = email;
showAuthMessage(`A verification email has been sent to ${email}. Confirm it from your inbox, it directly logs in or you can log in here.`, 'success');
}
} else {
const { error } = await sb.auth.signInWithPassword({ email, password });
if (error) {
// Unverified account — send a fresh verification email automatically
if (/confirm/i.test(error.message)) {
await sb.auth.resend({ type: 'signup', email }).catch(() => {});
showAuthMessage(`Your email isn't verified yet. We've sent a new verification email to ${email} — confirm it, then log in.`, 'success');
return;
}
showAuthMessage(error.message);
return;
}
await enterApp();
}
} catch (err) {
showAuthMessage(err.message || 'Authentication failed.');
} finally {
setAuthBusy(false);
}
});
forgotBtn.addEventListener('click', () => setAuthMode('forgot'));
backToLogin.addEventListener('click', () => setAuthMode('login'));
async function handleSignOut() {
if (sb) await sb.auth.signOut();
currentSessionId = null;
appShell.classList.add('hidden');
authOverlay.classList.remove('hidden');
resetMessages();
}
async function enterApp() {
const { data } = await sb.auth.getUser();
if (!data.user) return;
accountEmail.textContent = data.user.email || 'Signed in';
authOverlay.classList.add('hidden');
appShell.classList.remove('hidden');
// Only admins get the document-upload panel
isAdmin = false;
try {
const res = await authedFetch('/me');
const me = await res.json();
isAdmin = !!me.is_admin;
} catch { /* treat as regular user */ }
uploadPanel.classList.toggle('hidden', !isAdmin);
analyticsBtn.classList.toggle('hidden', !isAdmin);
startNewChat();
const tasks = [loadSessions()];
if (isAdmin) tasks.push(loadDocumentList());
await Promise.all(tasks);
}
/* ── Boot ── */
function showAuthScreen() {
appShell.classList.add('hidden');
authOverlay.classList.remove('hidden');
}
async function boot() {
// A stale service worker from another app previously hosted on this origin
// (localhost:8000) intercepts all requests and buffers streamed responses.
// Remove any and reload once so fetches go direct again.
if ('serviceWorker' in navigator) {
try {
const regs = await navigator.serviceWorker.getRegistrations();
if (regs.length > 0) {
await Promise.all(regs.map(r => r.unregister()));
window.location.reload();
return;
}
} catch { /* not critical */ }
}
try {
if (!window.supabase || !window.supabase.createClient) {
showAuthScreen();
showAuthMessage('Could not load the Supabase library (check your network / ad-blocker), then reload.', 'error');
return;
}
const res = await fetch('/config');
const cfg = await res.json();
if (!cfg.configured) {
showAuthScreen();
showAuthMessage('Server is missing Supabase configuration. Check the .env file.', 'error');
return;
}
// A password-reset link lands here with recovery tokens in the URL hash.
// Detect it BEFORE checking the session — the link logs the user in, and
// we must show the "set new password" form instead of the app.
const isRecoveryLink = window.location.hash.includes('type=recovery');
// A failed/denied Google sign-in comes back with the reason in the hash
const oauthError = new URLSearchParams(
window.location.hash.slice(1)
).get('error_description');
sb = window.supabase.createClient(cfg.supabaseUrl, cfg.supabaseAnonKey);
sb.auth.onAuthStateChange((event) => {
if (event === 'PASSWORD_RECOVERY') {
showAuthScreen();
setAuthMode('recovery');
showAuthMessage('Enter a new password for your account.', 'success');
}
});
const { data } = await sb.auth.getSession();
if (isRecoveryLink) {
showAuthScreen();
setAuthMode('recovery');
showAuthMessage('Enter a new password for your account.', 'success');
} else if (data.session) {
// After an OAuth redirect the tokens sit in the URL hash — remove them
if (window.location.hash.includes('access_token')) {
history.replaceState(null, '', window.location.pathname);
}
await enterApp();
} else if (oauthError) {
history.replaceState(null, '', window.location.pathname);
showAuthScreen();
showAuthMessage(`Google sign-in failed: ${oauthError}`);
} else {
showAuthScreen();
}
} catch (err) {
showAuthScreen();
showAuthMessage('Could not reach the server.', 'error');
} finally {
bootLoader.classList.add('hidden');
}
}
boot();