// strata-ctl web GUI — vanilla ES module, no build step, no dependencies. // Talks to the session-aware API (/api/sessions...); the server owns context. // Model output is always inserted via textContent (never innerHTML) to avoid // injection. Mobile-first: the session list is an off-canvas drawer on phones. const $ = (sel) => document.querySelector(sel); const state = { sessions: [], current: null, busy: false }; // ---- API helpers ---------------------------------------------------------- async function getJSON(url) { const r = await fetch(url); if (!r.ok) throw new Error(await r.text()); return r.json(); } async function sendJSON(url, method, body) { const r = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: body === undefined ? undefined : JSON.stringify(body), }); if (!r.ok) throw new Error(await r.text()); return r.status === 204 ? null : r.json(); } // Stream a chat turn, invoking onDelta for each SSE chunk. async function streamChat(id, content, onDelta) { const r = await fetch(`/api/sessions/${id}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content, stream: true }), }); if (!r.ok) throw new Error(await r.text()); const reader = r.body.getReader(); const dec = new TextDecoder(); let buf = ""; for (;;) { const { done, value } = await reader.read(); if (done) break; buf += dec.decode(value, { stream: true }); let idx; while ((idx = buf.indexOf("\n\n")) >= 0) { const block = buf.slice(0, idx); buf = buf.slice(idx + 2); for (const line of block.split("\n")) { if (!line.startsWith("data:")) continue; const data = line.slice(5).trim(); if (data === "[DONE]") return; try { onDelta(JSON.parse(data)); } catch { /* ignore partial */ } } } } } // ---- DOM builders --------------------------------------------------------- function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; } function messageNode(role, content, reasoning, usage) { const wrap = el("div", `msg ${role}`); wrap.appendChild(el("div", "role", role === "user" ? "Tu" : "Assistente")); const bubble = el("div", "bubble"); if (reasoning) { const det = el("details", "thinking"); det.appendChild(el("summary", null, "Pensiero")); det.appendChild(el("div", "reasoning", reasoning)); bubble.appendChild(det); } bubble.appendChild(el("div", "content", content || "")); if (usage) bubble.appendChild(el("div", "usage", usage)); wrap.appendChild(bubble); return wrap; } function scrollDown() { const t = $("#transcript"); t.scrollTop = t.scrollHeight; } // ---- Rendering ------------------------------------------------------------ function renderSessions() { const list = $("#session-list"); list.textContent = ""; for (const s of state.sessions) { const li = el("li", s.id === state.current ? "active" : null, s.title); li.addEventListener("click", () => { selectSession(s.id); closeDrawer(); }); list.appendChild(li); } } function renderTranscript(messages) { const t = $("#transcript"); t.textContent = ""; const visible = messages.filter((m) => m.role === "user" || m.role === "assistant"); if (visible.length === 0) { t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto.")); return; } for (const m of visible) { const usage = m.role === "assistant" && m.completion_tokens ? `${m.prompt_tokens} + ${m.completion_tokens} token` : null; t.appendChild(messageNode(m.role, m.content, m.reasoning_content, usage)); } scrollDown(); } // ---- Actions -------------------------------------------------------------- async function loadSessions(selectId) { state.sessions = await getJSON("/api/sessions"); if (state.sessions.length === 0) { const s = await sendJSON("/api/sessions", "POST", {}); state.sessions = [s]; } const target = selectId || state.current || state.sessions[0].id; renderSessions(); await selectSession(target); } async function selectSession(id) { state.current = id; const sess = state.sessions.find((s) => s.id === id); $("#session-title").textContent = sess ? sess.title : "Conversazione"; $("#model-name").textContent = sess ? sess.model : ""; renderSessions(); const messages = await getJSON(`/api/sessions/${id}/messages`); renderTranscript(messages); } async function newSession() { const s = await sendJSON("/api/sessions", "POST", {}); state.sessions.unshift(s); renderSessions(); await selectSession(s.id); closeDrawer(); $("#input").focus(); } async function deleteSession() { if (!state.current) return; if (!confirm("Eliminare questa conversazione?")) return; await sendJSON(`/api/sessions/${state.current}`, "DELETE"); state.current = null; await loadSessions(); } async function sendMessage() { const input = $("#input"); const content = input.value.trim(); if (!content || state.busy || !state.current) return; state.busy = true; $("#send").disabled = true; input.value = ""; autoGrow(input); const t = $("#transcript"); const empty = t.querySelector(".empty"); if (empty) empty.remove(); t.appendChild(messageNode("user", content)); // Live assistant bubble. const wrap = el("div", "msg assistant"); wrap.appendChild(el("div", "role", "Assistente")); const bubble = el("div", "bubble"); const det = el("details", "thinking"); det.appendChild(el("summary", null, "Pensiero")); const reasoningNode = el("div", "reasoning", ""); det.appendChild(reasoningNode); det.hidden = true; const contentNode = el("div", "content", ""); bubble.appendChild(det); bubble.appendChild(contentNode); wrap.appendChild(bubble); t.appendChild(wrap); scrollDown(); let reasoning = "", text = "", usage = null; try { await streamChat(state.current, content, (chunk) => { const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta; if (d && d.reasoning_content) { reasoning += d.reasoning_content; reasoningNode.textContent = reasoning; det.hidden = false; } if (d && d.content) { text += d.content; contentNode.textContent = text; } if (chunk.usage) usage = chunk.usage; scrollDown(); }); if (usage) { bubble.appendChild(el("div", "usage", `${usage.prompt_tokens} + ${usage.completion_tokens} token`)); } // Refresh ordering/titles without losing the live transcript. state.sessions = await getJSON("/api/sessions"); renderSessions(); } catch (e) { contentNode.textContent = text || `Errore: ${e.message}`; } finally { state.busy = false; $("#send").disabled = false; input.focus(); scrollDown(); } } async function showStats() { const s = await getJSON("/api/stats"); const body = $("#stats-body"); body.textContent = ""; const rows = [ ["Sessioni", s.sessions], ["Messaggi", s.messages], ["Token prompt", s.prompt_tokens], ["Token completati", s.completion_tokens], ]; for (const [k, v] of rows) { body.appendChild(el("dt", null, k)); body.appendChild(el("dd", null, String(v))); } $("#stats-modal").hidden = false; } // ---- Drawer / input UX ---------------------------------------------------- function openDrawer() { $("#drawer").classList.add("open"); $("#scrim").hidden = false; } function closeDrawer() { $("#drawer").classList.remove("open"); $("#scrim").hidden = true; } function autoGrow(t) { t.style.height = "auto"; t.style.height = Math.min(t.scrollHeight, window.innerHeight * 0.4) + "px"; } function wire() { $("#menu").addEventListener("click", openDrawer); $("#scrim").addEventListener("click", closeDrawer); $("#new-session").addEventListener("click", newSession); $("#delete-session").addEventListener("click", deleteSession); $("#send").addEventListener("click", sendMessage); $("#show-stats").addEventListener("click", showStats); $("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; }); const input = $("#input"); input.addEventListener("input", () => autoGrow(input)); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); } }); } wire(); loadSessions().catch((e) => { $("#transcript").textContent = ""; $("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`)); });