/* Brain of Reese — chat shell. * * Renders suggestions, shows KB health, and runs chat turns against * POST /api/chat (SSE, PLAN §4): deltas render live into the Brain bubble, * the done event appends source chips (and "Maybe try" chips when the * turn was deflected — honesty gate, phase 04), errors surface as a red * banner. The full feedback state machine lands with the loading-feedback * story; this keeps the "never stale" contract: the button is busy for the * whole turn and is always re-enabled at the end. * All DOM ids match frontend/index.html. */ const messagesEl = document.querySelector("#messages"); const emptyState = document.querySelector("#empty-state"); const suggestionsEl = document.querySelector("#suggestions"); const composer = document.querySelector("#composer"); const input = document.querySelector("#message-input"); const sendBtn = document.querySelector("#send-btn"); const sendLabel = document.querySelector("#send-label"); const sendStatus = document.querySelector("#send-status"); const banner = document.querySelector("#kb-banner"); const bannerText = document.querySelector("#kb-banner-text"); const versionEl = document.querySelector("#app-version"); /* ---------- tiny, safe markdown renderer (no external libs, no CDN) ---------- */ export function escapeHtml(s) { return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'", }[c])); } export function renderMarkdown(md) { // 1. Protect fenced code blocks. const codeBlocks = []; let text = md.replace(/```(\w*)\n([\s\S]*?)```/g, (_m, _lang, code) => { codeBlocks.push(`
${escapeHtml(code.replace(/\n$/, ""))}
`); return `\u0000CODE${codeBlocks.length - 1}\u0000`; }); // 2. Escape everything else, then apply inline + block transforms. text = escapeHtml(text) .replace(/`([^`\n]+)`/g, "$1") .replace(/\*\*([^*]+)\*\*/g, "$1") .replace(/(^|[\s(])\*([^*\n]+)\*/g, "$1$2") .replace(/^### (.*)$/gm, "

$1

") .replace(/^## (.*)$/gm, "

$1

") .replace(/^# (.*)$/gm, "

$1

") .replace(/^\s*[-*] (.*)$/gm, "
  • $1
  • ") .replace(/(
  • [\s\S]*?<\/li>)(?!\s*
  • )/g, "") .replace(/^\d+\. (.*)$/gm, "
  • $1
  • "); // 3. Paragraphs (double newline separated). text = text .split(/\n{2,}/) .map((block) => { const b = block.trim(); if (!b) return ""; if (/^<(h\d|ul|ol|pre|li)/.test(b)) return b; return `

    ${b.replace(/\n/g, "
    ")}

    `; }) .join(""); // 4. Restore code blocks. return text.replace(/\u0000CODE(\d+)\u0000/g, (_m, i) => codeBlocks[Number(i)]); } /* ---------- messages ---------- */ function addMessage(who, html) { if (emptyState) emptyState.hidden = true; const wrap = document.createElement("div"); wrap.className = `msg ${who}`; wrap.innerHTML = `
    ${html}
    `; messagesEl.appendChild(wrap); wrap.scrollIntoView({ behavior: "smooth", block: "end" }); return wrap; } function addTyping() { if (emptyState) emptyState.hidden = true; const wrap = document.createElement("div"); wrap.className = "msg brain"; wrap.id = "typing-indicator"; wrap.innerHTML = `
    `; messagesEl.appendChild(wrap); wrap.scrollIntoView({ behavior: "smooth", block: "end" }); } function removeTyping() { document.querySelector("#typing-indicator")?.remove(); } /* ---------- suggestions ---------- */ async function loadSuggestions() { try { const r = await fetch("/api/suggestions"); if (!r.ok) return; const { suggestions } = await r.json(); suggestionsEl.innerHTML = ""; for (const s of suggestions) { const btn = document.createElement("button"); btn.type = "button"; btn.className = "suggestion-chip"; btn.textContent = s; btn.setAttribute("role", "listitem"); btn.addEventListener("click", () => { input.value = s; input.focus(); }); suggestionsEl.appendChild(btn); } } catch { /* suggestions are progressive enhancement */ } } /* ---------- health / version ---------- */ async function loadHealth() { try { const r = await fetch("/api/health"); const body = await r.json(); versionEl.textContent = `v${body.version}`; if (body.db === "down") { bannerText.textContent = "Knowledge base is offline — start Postgres with `podman compose up -d db`."; banner.hidden = false; } } catch { /* API unreachable: page still renders, composer will explain on send */ } } /* ---------- composer ---------- */ function setBusy(busy) { sendBtn.disabled = busy; sendBtn.querySelector(".spinner").hidden = !busy; sendLabel.textContent = busy ? "Thinking…" : "Send"; sendStatus.textContent = busy ? "Brain of Reese is working" : ""; } function autoGrow() { input.style.height = "auto"; input.style.height = `${Math.min(input.scrollHeight, 192)}px`; } /* ---------- chat turn (SSE streaming, PLAN §4) ---------- */ /* Parse an SSE response body into JSON events. */ async function readSSE(response, onEvent) { const reader = response.body.getReader(); const decoder = new TextDecoder(); let buf = ""; for (;;) { 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 frame = buf.slice(0, sep).trim(); buf = buf.slice(sep + 2); if (!frame.startsWith("data:")) continue; const payload = frame.slice(5).trim(); if (!payload || payload === "[DONE]") continue; onEvent(JSON.parse(payload)); } } } /* Source chips (mono, source/path) under a Brain bubble. */ function appendSources(wrap, sources) { if (!sources || !sources.length) return; const body = wrap.querySelector(".msg-body"); const meta = document.createElement("div"); meta.className = "msg-meta"; meta.setAttribute("role", "list"); meta.setAttribute("aria-label", "Sources"); for (const s of sources) { const label = `${s.source}/${s.path}`; const chip = document.createElement("a"); chip.className = "source-chip"; chip.setAttribute("role", "listitem"); chip.href = "/sources.html"; chip.textContent = label; chip.title = label; meta.appendChild(chip); } body.appendChild(meta); // Accessible full path whenever the pill visually truncates. for (const chip of meta.children) { if (chip.scrollWidth > chip.clientWidth) chip.setAttribute("aria-label", chip.title); } } /* "Maybe try:" chips under a deflected bubble (honesty gate, phase 04). Same .suggestion-chip component as onboarding; clicking wires what exists today — fill the input + focus. One-tap submit lands with the phase 05 chip component. The group is accessible (role=list + aria-label) and wraps cleanly at every width. */ function appendMaybeTry(wrap, suggestions) { if (!suggestions || !suggestions.length) return; const body = wrap.querySelector(".msg-body"); const group = document.createElement("div"); group.className = "maybe-try"; group.setAttribute("role", "list"); group.setAttribute("aria-label", "Maybe try"); const label = document.createElement("span"); label.className = "visually-hidden"; label.textContent = "Maybe try:"; group.appendChild(label); for (const s of suggestions) { const btn = document.createElement("button"); btn.type = "button"; btn.className = "suggestion-chip"; btn.setAttribute("role", "listitem"); btn.textContent = s; btn.addEventListener("click", () => { input.value = s; autoGrow(); input.focus(); }); group.appendChild(btn); } body.appendChild(group); } function showErrorBanner(detail) { banner.hidden = false; banner.classList.add("is-error"); banner.setAttribute("role", "alert"); bannerText.textContent = `${detail} Try your question again — I'm ready.`; } function clearErrorBanner() { if (banner.classList.contains("is-error")) { banner.classList.remove("is-error"); banner.setAttribute("role", "status"); bannerText.textContent = ""; banner.hidden = true; } } async function handleSend(e) { e.preventDefault(); const text = input.value.trim(); if (!text || sendBtn.disabled) return; addMessage("user", renderMarkdown(text)); input.value = ""; autoGrow(); clearErrorBanner(); setBusy(true); addTyping(); let wrap = null; let acc = ""; let res = null; try { res = await fetch("/api/chat", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ message: text }), }); if (!res.ok || !res.body) { let detail = `Brain's API answered with HTTP ${res.status}.`; try { const body = await res.json(); if (body.detail) detail = body.detail; } catch { /* non-JSON error body */ } throw new Error(detail); } await readSSE(res, (ev) => { if (ev.type === "delta") { acc += ev.text || ""; if (!wrap) { removeTyping(); wrap = addMessage("brain", ""); } wrap.querySelector(".bubble").innerHTML = renderMarkdown(acc); wrap.scrollIntoView({ behavior: "smooth", block: "end" }); } else if (ev.type === "done") { if (!wrap) { removeTyping(); wrap = addMessage("brain", "…"); } if (ev.deflected) { wrap.classList.add("is-deflected"); appendMaybeTry(wrap, ev.suggestions); } appendSources(wrap, ev.sources); } else if (ev.type === "error") { throw new Error(ev.detail || "Something went wrong on my side."); } }); if (!wrap) { removeTyping(); addMessage("brain", "Hmm — that came back empty. Ask me again?"); } } catch (err) { removeTyping(); showErrorBanner(err.message || "Something went wrong on my side."); } finally { try { res?.body?.cancel(); } catch { /* stream already closed */ } setBusy(false); input.focus(); } } input.addEventListener("input", autoGrow); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); composer.requestSubmit(); } }); composer.addEventListener("submit", handleSend); loadSuggestions(); loadHealth();