- store: a swappable Store trait + bundled-SQLite implementation (WAL,
sessions/messages with per-turn token usage, cascade delete). The standard
/v1 API stays stateless; conversation context lives server-side so
multi-session, statistics and advanced settings can grow on top. DB path
configurable (db_path, default ~/.config/strata-ctl/sessions.db).
- api::sessions: session-aware GUI API — session CRUD, history, POST .../chat
(loads stored context, reuses the completion service, persists new turns with
usage; streaming accumulates the assistant turn and persists before [DONE]),
and /api/stats.
- api::web + web/: a mobile-first chat GUI (vanilla ES modules, no build step),
embedded via rust-embed and served at GET / (same-origin, offline, single
binary). Off-canvas session drawer on phones, persistent sidebar on wide
screens; live streaming with a collapsible thinking panel; model output is
inserted via textContent only.
- router_with_store mounts the GUI + session API only when a store is configured;
router()/router_with_auth() are unchanged (API-only).
- Fix: a global [hidden]{display:none!important} reset so an author display rule
(the stats modal's display:flex) cannot defeat the hidden attribute.
7 new tests (2 store unit + 4 session HTTP end-to-end + 1 config); 94 green +
2 ignored; clippy/fmt clean. Validated live on engine 0.1.67 (context retention,
streaming, stats) and via a browser check (modal, send/render, stats open/close).
Future: the Store backend is intended to move to ArangoDB (multi-model).
258 lines
8.4 KiB
JavaScript
258 lines
8.4 KiB
JavaScript
// 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}`));
|
|
}); |