Add mobile-first web GUI with a server-side session store (SQLite)

- 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).
This commit is contained in:
adm committed 2026-11-24 20:38:24 +01:00
1 parent 9e6d44fa1a
commit 1e13caa4ed
15 files changed
+1922 -23

No files matched your search

+174
View File
@@ -0,0 +1,174 @@
/* strata-ctl web GUI — mobile-first. Single column on phones; a persistent
session sidebar appears on wide screens. Touch-friendly targets, 16px inputs
(avoids iOS focus zoom), safe-area insets for notched phones. */
:root {
--bg: #0f1115;
--panel: #171a21;
--panel-2: #1f2430;
--border: #2a3040;
--text: #e6e9ef;
--muted: #9aa4b2;
--accent: #4f8cff;
--accent-press: #3a6fd6;
--user: #2b3a55;
--danger: #e5534b;
--radius: 14px;
--sidebar-w: 280px;
}
* { box-sizing: border-box; }
/* The `hidden` attribute must always win over author `display` rules (e.g. the
stats modal uses display:flex); otherwise toggling .hidden has no effect. */
[hidden] { display: none !important; }
html, body {
margin: 0;
height: 100%;
background: var(--bg);
color: var(--text);
font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
font-size: 16px;
line-height: 1.5;
}
#app { display: flex; height: 100dvh; overflow: hidden; }
/* ---- Buttons ---- */
.btn {
appearance: none;
border: 1px solid var(--border);
background: var(--panel-2);
color: var(--text);
border-radius: 10px;
padding: 10px 14px;
font-size: 0.95rem;
cursor: pointer;
min-height: 44px;
transition: background 0.12s ease, transform 0.05s ease;
}
.btn:active { transform: scale(0.97); }
.btn.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
.btn.primary:active { background: var(--accent-press); }
.btn.ghost { background: transparent; }
.btn.icon { padding: 8px 12px; font-size: 1.2rem; line-height: 1; }
.btn.danger { color: var(--danger); }
.btn:disabled { opacity: 0.5; cursor: default; }
/* ---- Drawer / sidebar ---- */
#drawer {
position: fixed;
inset: 0 auto 0 0;
width: min(82vw, var(--sidebar-w));
background: var(--panel);
border-right: 1px solid var(--border);
display: flex;
flex-direction: column;
transform: translateX(-100%);
transition: transform 0.2s ease;
z-index: 30;
padding-top: env(safe-area-inset-top);
}
#drawer.open { transform: translateX(0); }
#scrim {
position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 20;
}
.drawer-head {
display: flex; align-items: center; justify-content: space-between;
gap: 8px; padding: 12px;
border-bottom: 1px solid var(--border);
}
.brand { font-weight: 700; letter-spacing: 0.3px; }
#session-list { list-style: none; margin: 0; padding: 8px; overflow-y: auto; flex: 1; }
#session-list li {
padding: 12px; border-radius: 10px; cursor: pointer;
color: var(--muted); white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
min-height: 44px; display: flex; align-items: center;
}
#session-list li:hover { background: var(--panel-2); }
#session-list li.active { background: var(--panel-2); color: var(--text); }
.drawer-foot { padding: 12px; border-top: 1px solid var(--border); }
/* ---- Main column ---- */
#main { flex: 1; display: flex; flex-direction: column; min-width: 0; height: 100dvh; }
#topbar {
display: flex; align-items: center; gap: 10px;
padding: 10px 12px; padding-top: calc(10px + env(safe-area-inset-top));
border-bottom: 1px solid var(--border); background: var(--panel);
}
.title-wrap { flex: 1; min-width: 0; display: flex; flex-direction: column; }
#session-title { font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.muted { color: var(--muted); font-size: 0.8rem; }
#transcript {
flex: 1; overflow-y: auto; padding: 16px 12px;
display: flex; flex-direction: column; gap: 14px;
scroll-behavior: smooth;
}
.empty { color: var(--muted); text-align: center; margin: auto; max-width: 28ch; }
/* ---- Message bubbles ---- */
.msg { max-width: 860px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; }
.msg .role { font-size: 0.75rem; color: var(--muted); margin-bottom: 4px; }
.msg.user { align-items: flex-end; }
.msg.user .bubble {
background: var(--user); border-radius: var(--radius) var(--radius) 4px var(--radius);
padding: 10px 14px; max-width: 85%;
}
.msg.assistant .bubble {
background: var(--panel); border: 1px solid var(--border);
border-radius: var(--radius) var(--radius) var(--radius) 4px;
padding: 10px 14px; width: 100%;
}
.bubble .content { white-space: pre-wrap; word-wrap: break-word; }
.bubble .content:empty::after { content: "…"; color: var(--muted); }
details.thinking { margin-bottom: 8px; }
details.thinking summary {
cursor: pointer; color: var(--muted); font-size: 0.85rem; user-select: none;
}
details.thinking .reasoning {
white-space: pre-wrap; word-wrap: break-word; color: var(--muted);
font-size: 0.9rem; border-left: 2px solid var(--border);
padding-left: 10px; margin-top: 6px;
}
.usage { color: var(--muted); font-size: 0.72rem; margin-top: 6px; }
/* ---- Composer ---- */
#composer {
display: flex; gap: 8px; align-items: flex-end;
padding: 10px 12px; padding-bottom: calc(10px + env(safe-area-inset-bottom));
border-top: 1px solid var(--border); background: var(--panel);
}
#input {
flex: 1; resize: none; max-height: 40dvh;
background: var(--panel-2); color: var(--text);
border: 1px solid var(--border); border-radius: 12px;
padding: 12px 14px; font-size: 16px; font-family: inherit; line-height: 1.4;
}
#input:focus { outline: none; border-color: var(--accent); }
#send { min-width: 52px; font-size: 1.3rem; }
/* ---- Stats modal ---- */
#stats-modal {
position: fixed; inset: 0; z-index: 40;
background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center;
padding: 20px;
}
.modal-card {
background: var(--panel); border: 1px solid var(--border); border-radius: var(--radius);
padding: 20px; max-width: 420px; width: 100%;
}
.modal-card h2 { margin: 0 0 12px; font-size: 1.1rem; }
#stats-body { display: grid; grid-template-columns: 1fr auto; gap: 6px 16px; margin: 0 0 16px; }
#stats-body dt { color: var(--muted); }
#stats-body dd { margin: 0; font-variant-numeric: tabular-nums; }
/* ---- Wide screens: persistent sidebar ---- */
@media (min-width: 900px) {
#drawer { position: static; transform: none; width: var(--sidebar-w); flex-shrink: 0; }
#scrim { display: none !important; }
#menu { display: none; }
.msg.user .bubble { max-width: 70%; }
}
+258
View File
@@ -0,0 +1,258 @@
// 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}`));
});
+56
View File
@@ -0,0 +1,56 @@
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark light" />
<title>strata-ctl</title>
<link rel="stylesheet" href="/assets/app.css" />
</head>
<body>
<div id="app">
<!-- Session drawer (off-canvas on mobile, sidebar on wide screens) -->
<aside id="drawer" aria-label="Sessioni">
<div class="drawer-head">
<span class="brand">strata&#8209;ctl</span>
<button id="new-session" class="btn primary" title="Nuova conversazione">+ Nuova</button>
</div>
<ul id="session-list"></ul>
<div class="drawer-foot">
<button id="show-stats" class="btn ghost">Statistiche</button>
</div>
</aside>
<div id="scrim" hidden></div>
<!-- Main column -->
<main id="main">
<header id="topbar">
<button id="menu" class="btn icon" aria-label="Apri sessioni">&#9776;</button>
<div class="title-wrap">
<span id="session-title">Conversazione</span>
<span id="model-name" class="muted"></span>
</div>
<button id="delete-session" class="btn icon danger" aria-label="Elimina sessione">&#128465;</button>
</header>
<section id="transcript" aria-live="polite"></section>
<footer id="composer">
<textarea id="input" rows="1" placeholder="Scrivi un messaggio…" autocomplete="off"></textarea>
<button id="send" class="btn primary" aria-label="Invia">&#10148;</button>
</footer>
</main>
</div>
<!-- Stats modal -->
<div id="stats-modal" hidden>
<div class="modal-card">
<h2>Statistiche</h2>
<dl id="stats-body"></dl>
<button id="close-stats" class="btn">Chiudi</button>
</div>
</div>
<script type="module" src="/assets/app.js"></script>
</body>
</html>