Foundation (phase 01, verified): - FastAPI app: /api/health, /api/suggestions, /api/chat (placeholder), static frontend served locally (no CDN) - Postgres 17 + pgvector via db/Containerfile + compose.yaml (podman compose up -d db), Alembic initial migration (documents, chunks with vector(768), query_log) - LLM client targeting https://aipi.reeseapps.com/v1 (turbo/embed); scripts/llm_probe.py verified models + 768-dim embeddings live - Conditional debugpy: imported only when DEBUGPY=1 (attach on demand, :5678); logging config for clean single-line logs - Frontend shell: mobile-first chat + Sources pages, tokens, a11y baselines - Tests: 24 unit+integration (99% coverage on app/), ruff + pyright clean, Playwright smoke E2E (3 tests) against a deterministic mock LLM - Planning: .agent/PLAN.md (architecture + LOCKED decisions), AGENTS.md, 6 user stories, 7 phase files (one story / one phase / one Playwright suite each)
190 lines
6.0 KiB
JavaScript
190 lines
6.0 KiB
JavaScript
/* Brain of Reese — chat shell.
|
|
*
|
|
* Scaffolding-stage behavior: renders suggestions, shows KB health, and
|
|
* echoes a friendly placeholder answer. The real RAG streaming chat is
|
|
* implemented in the chat-rag phase (see .agent/user_stories/).
|
|
* 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(`<pre><code>${escapeHtml(code.replace(/\n$/, ""))}</code></pre>`);
|
|
return `\u0000CODE${codeBlocks.length - 1}\u0000`;
|
|
});
|
|
|
|
// 2. Escape everything else, then apply inline + block transforms.
|
|
text = escapeHtml(text)
|
|
.replace(/`([^`\n]+)`/g, "<code>$1</code>")
|
|
.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
|
|
.replace(/(^|[\s(])\*([^*\n]+)\*/g, "$1<em>$2</em>")
|
|
.replace(/^### (.*)$/gm, "<h4>$1</h4>")
|
|
.replace(/^## (.*)$/gm, "<h3>$1</h3>")
|
|
.replace(/^# (.*)$/gm, "<h3>$1</h3>")
|
|
.replace(/^\s*[-*] (.*)$/gm, "<li>$1</li>")
|
|
.replace(/(<li>[\s\S]*?<\/li>)(?!\s*<li>)/g, "<ul>$1</ul>")
|
|
.replace(/^\d+\. (.*)$/gm, "<li>$1</li>");
|
|
|
|
// 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 `<p>${b.replace(/\n/g, "<br>")}</p>`;
|
|
})
|
|
.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 = `
|
|
<span class="avatar" aria-hidden="true">${who === "brain" ? "🧠" : "🧑"}</span>
|
|
<div class="msg-body">
|
|
<div class="bubble">${html}</div>
|
|
</div>`;
|
|
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 = `
|
|
<span class="avatar" aria-hidden="true">🧠</span>
|
|
<div class="msg-body">
|
|
<div class="bubble typing" role="status" aria-label="Brain of Reese is thinking">
|
|
<span></span><span></span><span></span>
|
|
</div>
|
|
</div>`;
|
|
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`;
|
|
}
|
|
|
|
async function handleSend(e) {
|
|
e.preventDefault();
|
|
const text = input.value.trim();
|
|
if (!text || sendBtn.disabled) return;
|
|
|
|
addMessage("user", renderMarkdown(text));
|
|
input.value = "";
|
|
autoGrow();
|
|
setBusy(true);
|
|
addTyping();
|
|
|
|
try {
|
|
// TODO(chat-rag phase): replace with POST /api/chat (SSE streaming).
|
|
await new Promise((res) => setTimeout(res, 500));
|
|
const reply =
|
|
"I'm still getting my neurons wired up — the real me ships in the " +
|
|
"next phase! Keep the questions coming, you're on a roll. 🚀";
|
|
removeTyping();
|
|
addMessage("brain", renderMarkdown(reply));
|
|
} catch {
|
|
removeTyping();
|
|
addMessage("brain", "Something went wrong on my side — please try again in a moment.");
|
|
} finally {
|
|
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();
|