// strata-ctl web GUI — vanilla ES module, no build step, no dependencies. // Talks to the session-aware API (/api/sessions...); the server owns context. // User text is inserted via textContent; assistant Markdown/LaTeX arrives as // server-sanitized HTML (content_html) injected via innerHTML. Mobile-first: // the session list is an off-canvas drawer on phones. const $ = (sel) => document.querySelector(sel); const state = { sessions: [], current: null, busy: false, attachments: [], queue: [] }; // ---- i18n: new user-facing strings go through t(key, params) -------------- // Catalogs are served at /assets/locales/.json; language follows the // browser. Static HTML uses data-i18n attributes; dynamic strings use t(). const I18N = { lang: "it", map: {} }; function t(key, params = {}) { let s = I18N.map[key] ?? key; for (const [k, v] of Object.entries(params)) s = s.replaceAll(`{${k}}`, v); return s; } async function loadI18n() { const nav = (navigator.language || "it").slice(0, 2).toLowerCase(); const lang = ["it", "en"].includes(nav) ? nav : "it"; for (const l of [lang, "it"]) { try { const r = await fetch(`/assets/locales/${l}.json`); if (r.ok) { I18N.map = await r.json(); I18N.lang = l; return; } } catch { /* try next */ } } } function applyI18n() { document.querySelectorAll("[data-i18n]").forEach((n) => { n.textContent = t(n.getAttribute("data-i18n")); }); document.querySelectorAll("[data-i18n-ph]").forEach((n) => { n.placeholder = t(n.getAttribute("data-i18n-ph")); }); } // ---- 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()); // Several endpoints (PUT/PATCH/DELETE) reply 200/204 with an EMPTY body; // parse only when there is content, else r.json() throws "Unexpected end of // JSON input". Treat any bodyless success as null. const text = await r.text(); return text ? JSON.parse(text) : null; } // ---- 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; } // Mark agent-shared download links (relative /api/sessions/…/download) so they // download in place via the same-origin `download` attribute and read as a chip. // The server already forces Content-Disposition: attachment and a safe type. function enhanceDownloadLinks(node) { for (const a of node.querySelectorAll("a[href]")) { const href = a.getAttribute("href") || ""; if (href.startsWith("/api/sessions/") && href.includes("/download")) { a.classList.add("download-link"); a.setAttribute("download", ""); } } } function messageNode(role, content, reasoning, usage, ts, html) { const wrap = el("div", `msg ${role}`); const roleNode = el("div", "role", role === "user" ? "Tu" : "Assistente"); if (ts) roleNode.appendChild(el("span", "when", " · " + stampLabel(ts))); wrap.appendChild(roleNode); 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); } const contentNode = el("div", "content"); if (html != null) { // Server-sanitized Markdown/LaTeX (assistant only): safe to inject. contentNode.classList.add("rendered"); contentNode.innerHTML = html; enhanceDownloadLinks(contentNode); } else { contentNode.textContent = content || ""; } bubble.appendChild(contentNode); if (usage) bubble.appendChild(el("div", "usage", usage)); wrap.appendChild(bubble); return wrap; } function scrollDown() { const t = $("#transcript"); t.scrollTop = t.scrollHeight; } function usageText(u) { if (!u) return null; let s = `${u.prompt_tokens} + ${u.completion_tokens} token`; // Per-turn perf when the engine reported timings (live turns; history keeps // only token counts): decode tok/s + first-token lag (engine prefill ms). if (u.decode_ms > 0 && u.completion_tokens > 0) { s += " · " + t("stats.tps", { n: fmt1(u.completion_tokens / (u.decode_ms / 1000)) }); } if (u.cached_tokens > 0) s += " · " + t("usage.cached", { n: fmtInt(u.cached_tokens) }); if (u.prompt_ms > 0) s += " · " + t("usage.ttft", { n: fmtInt(u.prompt_ms / 1000) }); return s; } // Compact locale-aware date+time for a message bubble (epoch seconds). // The [SPEAKER] tag is model-context metadata; hide any echoed copy in the live // preview (the backend also strips it from stored / final / history content). function stripSpeaker(s) { return s.replace(/^(\s*\[SPEAKER:[^\]]*-\s*\d{4}-\d{2}-\d{2} \d{2}:\d{2}\]\s*)+/, ""); } function stampLabel(secs) { const d = new Date(secs * 1000); const date = d.toLocaleDateString(I18N.lang, { day: "2-digit", month: "2-digit" }); const time = d.toLocaleTimeString(I18N.lang, { hour: "2-digit", minute: "2-digit" }); return `${date} ${time}`; } // A tool-call block (command + an output area filled when the result arrives). function toolCallNode(name, argsJson) { let cmd = argsJson; try { const a = JSON.parse(argsJson); if (a && a.command !== undefined) cmd = a.command; } catch { /* keep raw */ } const wrap = el("div", "msg tool"); wrap.appendChild(el("div", "role", `\u{1F527} ${name || "tool"}`)); const bubble = el("div", "bubble"); bubble.appendChild(el("code", "tool-cmd", cmd)); const out = el("pre", "tool-out", ""); bubble.appendChild(out); wrap.appendChild(bubble); wrap._out = out; return wrap; } function toolResultNode(output) { const wrap = el("div", "msg tool"); wrap.appendChild(el("div", "role", "\u{1F527} output")); const bubble = el("div", "bubble"); bubble.appendChild(el("pre", "tool-out", output)); wrap.appendChild(bubble); return wrap; } // ---- 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); li.appendChild(el("span", "session-title", s.title)); const actions = el("span", "session-actions"); const ren = el("button", "sess-btn", "\u{270F}\u{FE0F}"); ren.title = s.name_locked ? "Nome bloccato dopo la prima interazione" : "Rinomina"; ren.disabled = s.name_locked; ren.setAttribute("aria-label", "Rinomina chat"); ren.addEventListener("click", (e) => { e.stopPropagation(); renameSessionById(s.id, s.title); }); const del = el("button", "sess-btn danger", "\u{1F5D1}\u{FE0F}"); del.title = "Elimina"; del.setAttribute("aria-label", "Elimina chat"); del.addEventListener("click", (e) => { e.stopPropagation(); deleteSessionById(s.id); }); actions.appendChild(ren); actions.appendChild(del); li.appendChild(actions); li.addEventListener("click", () => { selectSession(s.id); closeDrawer(); }); list.appendChild(li); } } function renderTranscript(messages, win) { const tr = $("#transcript"); tr.textContent = ""; // The browser shows the SAME sliding window the model sees. When older turns // have slid out, say so: they are preserved server-side (full export later). if (win && win.total > messages.length) { tr.appendChild(el("div", "window-note", t("window.note", { shown: fmtInt(messages.length), omitted: fmtInt(win.total - messages.length), }))); } if (!messages.length) { tr.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto.")); return; } for (const m of messages) { if (m.role === "user") { tr.appendChild(messageNode("user", m.content, null, null, m.created_at)); } else if (m.role === "tool") { tr.appendChild(toolResultNode(m.content)); } else if (m.role === "assistant") { if (m.tool_calls_json) { let calls = []; try { calls = JSON.parse(m.tool_calls_json); } catch { /* ignore */ } for (const tc of calls) { const f = tc.function || {}; tr.appendChild(toolCallNode(f.name, f.arguments)); } } if (m.content) { const usage = m.completion_tokens ? usageText({ prompt_tokens: m.prompt_tokens, completion_tokens: m.completion_tokens }) : null; tr.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html)); } } } 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; state.attachments = []; renderAttachments(); // Queued turns belong to the session they were typed in: drop them on switch // so they can never be delivered to a different session. state.queue = []; renderQueue(); const sess = state.sessions.find((s) => s.id === id); $("#session-title").textContent = sess ? sess.title : "Conversazione"; $("#model-name").textContent = sess ? sess.model : ""; renderSessions(); const data = await getJSON(`/api/sessions/${id}/messages`); renderTranscript(data.messages, data); } async function newSession() { const s = await sendJSON("/api/sessions", "POST", {}); state.sessions.unshift(s); renderSessions(); await selectSession(s.id); closeDrawer(); $("#input").focus(); } async function renameSessionById(id, currentTitle) { const input = await showDialog({ title: "Rinomina chat", input: currentTitle, okText: "Salva" }); if (input === null) return; const title = input.trim(); if (!title) return; await sendJSON(`/api/sessions/${id}`, "PATCH", { title }); state.sessions = await getJSON("/api/sessions"); renderSessions(); if (id === state.current) $("#session-title").textContent = title; } async function deleteSessionById(id) { const ok = await showDialog({ title: "Elimina chat", message: "Eliminare questa chat? L'operazione non è reversibile.", okText: "Elimina", }); if (!ok) return; await sendJSON(`/api/sessions/${id}`, "DELETE"); const wasCurrent = id === state.current; state.sessions = await getJSON("/api/sessions"); if (wasCurrent) { state.current = null; if (!state.sessions.length) { const s = await sendJSON("/api/sessions", "POST", {}); state.sessions = [s]; } await selectSession(state.sessions[0].id); } else { renderSessions(); } } // ---- Attachments (upload -> shared store; routed server-side by kind) ----- function attachChip(a, removable) { const chip = el("span", "attach-chip"); const icon = a.kind === "image" ? "\u{1F5BC}\u{FE0F}" : a.kind === "binary" ? "\u{1F4E6}" : "\u{1F4C4}"; chip.appendChild(el("span", "attach-kind", icon)); chip.appendChild(el("span", "attach-name", a.original_name)); if (removable) { const x = el("button", null, "\u{00D7}"); x.setAttribute("aria-label", t("attach.remove")); x.addEventListener("click", () => { state.attachments = state.attachments.filter((m) => m.id !== a.id); renderAttachments(); }); chip.appendChild(x); } return chip; } function renderAttachments() { const box = $("#attachments"); box.textContent = ""; box.hidden = state.attachments.length === 0; for (const a of state.attachments) box.appendChild(attachChip(a, true)); } // Pending turns typed while the framework is busy (FIFO, no steer). Shown as // removable chips above the composer; each runs as a normal turn when free. function renderQueue() { const box = $("#queue"); box.textContent = ""; box.hidden = state.queue.length === 0; for (const item of state.queue) { const chip = el("div", "queue-chip"); chip.appendChild(el("span", "queue-label", t("queue.label"))); chip.appendChild(el("span", "queue-text", item.content || t("queue.attachment_only"))); if (item.attachments.length) chip.appendChild(el("span", "queue-attach", `\u{1F4CE} ${item.attachments.length}`)); const x = el("button", null, "\u{00D7}"); x.setAttribute("aria-label", t("queue.remove")); x.addEventListener("click", () => { state.queue = state.queue.filter((q) => q !== item); renderQueue(); }); chip.appendChild(x); box.appendChild(chip); } } function readFileAsDataURL(file) { return new Promise((resolve, reject) => { const fr = new FileReader(); fr.onload = () => resolve(fr.result); fr.onerror = () => reject(fr.error || new Error("read failed")); fr.readAsDataURL(file); }); } async function uploadFiles(files) { for (const file of files) { try { const data = await readFileAsDataURL(file); const meta = await sendJSON("/api/uploads", "POST", { name: file.name, data }); state.attachments.push(meta); renderAttachments(); } catch (e) { const tr = $("#transcript"); tr.appendChild(messageNode("assistant", t("attach.error", { msg: e.message }))); scrollDown(); } } } async function sendMessage() { const input = $("#input"); const content = input.value.trim(); const attachments = state.attachments.slice(); if ((!content && !attachments.length) || !state.current) return; input.value = ""; autoGrow(input); state.attachments = []; renderAttachments(); if (state.busy) { // Framework busy: queue the turn (no steer). It runs as a normal new turn // when the current one finishes, so the model never sees a mid-loop inject. state.queue.push({ content, attachments }); renderQueue(); return; } await dispatchTurn(content, attachments); } // Run one turn end-to-end (the former sendMessage body). On completion it drains // the next queued turn, if any, so type-ahead messages are delivered in order. async function dispatchTurn(content, attachments) { setBusy(true); const t = $("#transcript"); const empty = t.querySelector(".empty"); if (empty) empty.remove(); const userNode = messageNode("user", content, null, null, Date.now() / 1000); if (attachments.length) { const row = el("div", "msg-attachments"); for (const a of attachments) row.appendChild(attachChip(a, false)); userNode.querySelector(".bubble").appendChild(row); } t.appendChild(userNode); scrollDown(); const ids = attachments.map((a) => a.id); try { await agentTurn(content, t, ids); state.sessions = await getJSON("/api/sessions"); renderSessions(); } catch (e) { t.appendChild(messageNode("assistant", `Errore: ${e.message}`, null, null, Date.now() / 1000)); } finally { setBusy(false); $("#input").focus(); scrollDown(); drainQueue(); } } // Deliver the next queued turn (FIFO). dispatchTurn sets busy synchronously, so // this never double-fires; each queued turn drains the next when it ends. function drainQueue() { if (state.busy || !state.queue.length || !state.current) return; const next = state.queue.shift(); renderQueue(); dispatchTurn(next.content, next.attachments); } // The only turn path: tools are always on (no user toggle). Stream tool_call / // tool_result / final events (observability, no gate). async function agentTurn(content, t, attachments) { const r = await fetch(`/api/sessions/${state.current}/chat`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content, agent: true, attachments }), }); if (!r.ok) throw new Error(await r.text()); const reader = r.body.getReader(); const dec = new TextDecoder(); let buf = ""; const toolNodes = {}; let live = null; // the assistant bubble currently being streamed function ensureLive() { if (live) return live; const wrap = el("div", "msg assistant"); const roleNode = el("div", "role", "Assistente"); roleNode.appendChild(el("span", "when", " · " + stampLabel(Date.now() / 1000))); wrap.appendChild(roleNode); 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); live = { bubble, det, reasoningNode, contentNode, reasoning: "", text: "" }; return live; } function closeLive() { if (live) { live.det.open = false; live = null; } } 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; let ev; try { ev = JSON.parse(data); } catch { continue; } if (ev.type === "delta") { const L = ensureLive(); if (ev.reasoning) { L.reasoning += ev.reasoning; L.reasoningNode.textContent = L.reasoning; L.det.hidden = false; L.det.open = true; } if (ev.content) { if (!L.text) L.det.open = false; L.text += ev.content; L.contentNode.textContent = stripSpeaker(L.text); } } else if (ev.type === "tool_call") { closeLive(); const n = toolCallNode(ev.name, ev.arguments); toolNodes[ev.id] = n; t.appendChild(n); } else if (ev.type === "tool_result") { const n = toolNodes[ev.id]; if (n) n._out.textContent = ev.output; } else if (ev.type === "final") { const L = ensureLive(); const m = ev.response.choices[0].message; if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = stripSpeaker(m.content); } if (!L.reasoning && m.reasoning_content) { L.reasoning = m.reasoning_content; L.reasoningNode.textContent = L.reasoning; L.det.hidden = false; } // Swap the streamed plain text for server-rendered Markdown/LaTeX. if (ev.content_html != null) { L.contentNode.classList.add("rendered"); L.contentNode.innerHTML = ev.content_html; enhanceDownloadLinks(L.contentNode); } L.det.open = false; if (ev.response.usage) L.bubble.appendChild(el("div", "usage", usageText(ev.response.usage))); live = null; } else if (ev.type === "error") { closeLive(); t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`, null, null, Date.now() / 1000)); } scrollDown(); } } } } // ---- Stats dashboard ------------------------------------------------------ // Our angle vs the reference's ephemeral request monitor: a dashboard over the // PERSISTENT history (overview cards, daily token chart, per-session share) plus // a live engine/perf gauge. Polls every 2s while open; re-renders only on change. let statsTimer = null; let statsStamp = ""; let _nf = null, _nfLang = null; function nf() { if (_nfLang !== I18N.lang) { _nf = new Intl.NumberFormat(I18N.lang); _nfLang = I18N.lang; } return _nf; } function fmtInt(n) { return nf().format(Math.round(Number(n) || 0)); } function fmt1(n) { return (Number(n) || 0).toFixed(1); } function fmtCompact(n) { n = Number(n) || 0; if (n >= 1e6) return (n / 1e6).toFixed(n >= 1e7 ? 0 : 1) + "M"; if (n >= 1e3) return (n / 1e3).toFixed(n >= 1e4 ? 0 : 1) + "k"; return String(n); } function dayLabel(secs) { return new Date(secs * 1000).toLocaleDateString(I18N.lang, { day: "2-digit", month: "short", timeZone: "UTC" }); } function whenLabel(secs) { if (!secs) return t("stats.na"); return new Date(secs * 1000).toLocaleString(I18N.lang, { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }); } // One overview card; `value` is a string or a Node (the engine status dot). function statCard(label, value, sub, cls) { const card = el("div", "stat-card" + (cls ? " " + cls : "")); card.appendChild(el("div", "label", label)); const v = el("div", "value"); if (value instanceof Node) v.appendChild(value); else v.textContent = value; card.appendChild(v); if (sub) card.appendChild(el("div", "sub", sub)); return card; } function engineCard(engine) { const card = el("div", "stat-card engine"); card.appendChild(el("div", "label", t("stats.engine"))); const v = el("div", "value"); v.appendChild(el("span", "dot " + (engine.busy ? "busy" : "idle"))); v.appendChild(el("span", null, engine.busy ? t("stats.engine.busy") : t("stats.engine.idle"))); card.appendChild(v); card.appendChild(el("div", "model", engine.model || t("stats.na"))); card.appendChild(el("div", "sub", t("stats.context", { n: fmtInt(engine.max_context) }))); return card; } function renderStats(s) { const root = $("#stats-content"); root.textContent = ""; const perf = s.perf || {}; const cards = el("div", "stat-cards"); cards.appendChild(engineCard(s.engine || {})); // Current inference context (last turn's prompt) — distinct from the // cumulative token total below, which re-counts the window every turn. cards.appendChild(statCard(t("stats.context_now"), s.last_prompt_tokens ? fmtInt(s.last_prompt_tokens) : t("stats.na"), t("stats.context_now.sub"))); const decode = perf.decode_tps != null ? t("stats.tps", { n: fmt1(perf.decode_tps) }) : t("stats.na"); const decodeSub = perf.prefill_tps != null ? t("stats.decode.sub") + " · " + t("stats.prefill", { n: fmt1(perf.prefill_tps) }) : t("stats.decode.sub"); cards.appendChild(statCard(t("stats.decode"), decode, decodeSub)); cards.appendChild(statCard(t("stats.tokens"), fmtInt(s.total_tokens), t("stats.tokens.sub", { p: fmtInt(s.prompt_tokens), c: fmtInt(s.completion_tokens) }))); cards.appendChild(statCard(t("stats.sessions"), fmtInt(s.sessions), t("stats.messages.sub", { n: fmtInt(s.messages) }))); cards.appendChild(statCard(t("stats.tools"), fmtInt(s.tool_calls), t("stats.tools.sub"))); cards.appendChild(statCard(t("stats.requests"), fmtInt(perf.requests), t("stats.requests.sub"))); root.appendChild(cards); root.appendChild(dailySection(s.daily || [])); root.appendChild(sessionSection(s.by_session || [])); } // Daily token chart: a continuous, zero-filled UTC-day window (last 30 bars), // each bar stacked prompt (bottom) + completion (top), scaled to the peak day. function dailySection(daily) { const sec = el("div", "stat-section"); sec.appendChild(el("h3", null, t("stats.daily"))); sec.appendChild(el("div", "sub", t("stats.daily.sub"))); if (!daily.length) { sec.appendChild(el("div", "stat-empty", t("stats.daily.empty"))); return sec; } const byDay = new Map(daily.map((d) => [d.day, d])); const last = daily[daily.length - 1].day; const span = Math.round((last - daily[0].day) / 86400) + 1; const count = Math.min(span, 30); const start = last - (count - 1) * 86400; const days = []; let max = 1; for (let i = 0; i < count; i++) { const day = start + i * 86400; const d = byDay.get(day) || { day, prompt_tokens: 0, completion_tokens: 0 }; const total = (d.prompt_tokens || 0) + (d.completion_tokens || 0); if (total > max) max = total; days.push({ day, prompt_tokens: d.prompt_tokens || 0, completion_tokens: d.completion_tokens || 0, total }); } const bars = el("div", "chart-bars"); for (const d of days) { const bar = el("div", "bar"); bar.title = dayLabel(d.day) + " · " + t("stats.tokens.sub", { p: fmtInt(d.prompt_tokens), c: fmtInt(d.completion_tokens) }); const c = el("i", "completion"); c.style.height = (d.completion_tokens / max * 100) + "%"; const p = el("i", "prompt"); p.style.height = (d.prompt_tokens / max * 100) + "%"; bar.appendChild(c); bar.appendChild(p); bars.appendChild(bar); } sec.appendChild(bars); const x = el("div", "chart-x"); x.appendChild(el("span", null, dayLabel(days[0].day))); if (days.length > 2) x.appendChild(el("span", null, dayLabel(days[Math.floor(days.length / 2)].day))); x.appendChild(el("span", null, dayLabel(days[days.length - 1].day))); sec.appendChild(x); const legend = el("div", "chart-legend"); for (const [cls, key] of [["prompt", "stats.legend.prompt"], ["completion", "stats.legend.completion"]]) { const item = el("span"); item.appendChild(el("i", "swatch " + cls)); item.appendChild(document.createTextNode(t(key))); legend.appendChild(item); } sec.appendChild(legend); return sec; } // Per-session share bars (relative to the busiest session), busiest first. function sessionSection(rows) { const sec = el("div", "stat-section"); sec.appendChild(el("h3", null, t("stats.perSession"))); sec.appendChild(el("div", "sub", t("stats.perSession.sub"))); if (!rows.length) { sec.appendChild(el("div", "stat-empty", t("stats.perSession.empty"))); return sec; } const total = (r) => (r.prompt_tokens || 0) + (r.completion_tokens || 0); const max = Math.max(1, ...rows.map(total)); const list = el("div", "sess-stats"); for (const r of rows) { const row = el("div", "sess-stat" + (r.id === state.current ? " current" : "")); const top = el("div", "sess-stat-top"); top.appendChild(el("span", "name", r.title || r.id)); top.appendChild(el("span", "tok", fmtCompact(total(r)))); row.appendChild(top); const bar = el("div", "sess-bar"); const p = el("i", "prompt"); p.style.width = ((r.prompt_tokens || 0) / max * 100) + "%"; const c = el("i", "completion"); c.style.width = ((r.completion_tokens || 0) / max * 100) + "%"; bar.appendChild(p); bar.appendChild(c); row.appendChild(bar); row.appendChild(el("div", "sess-stat-sub", t("stats.messages.sub", { n: fmtInt(r.messages) }) + " · " + t("stats.session.updated", { when: whenLabel(r.updated_at) }))); list.appendChild(row); } sec.appendChild(list); return sec; } async function refreshStats() { try { const s = await getJSON("/api/stats"); $("#stats-live").textContent = t("stats.updated", { time: new Date().toLocaleTimeString(I18N.lang) }); const stamp = JSON.stringify(s); if (stamp === statsStamp) return; statsStamp = stamp; renderStats(s); } catch (e) { $("#stats-live").textContent = t("stats.disconnected"); } } async function showStats() { $("#stats-modal").hidden = false; statsStamp = ""; $("#stats-content").textContent = ""; await refreshStats(); clearInterval(statsTimer); statsTimer = setInterval(refreshStats, 2000); } function closeStats() { $("#stats-modal").hidden = true; clearInterval(statsTimer); statsTimer = null; } // ---- Notepad (read-only observability; the agent writes via the tool) ------ async function showNotepad() { if (!currentSession()) return; $("#notepad-modal").hidden = false; await refreshNotepad(); } async function refreshNotepad() { const sess = currentSession(); if (!sess) return; const root = $("#notepad-content"); root.textContent = ""; try { const entries = await getJSON(`/api/sessions/${sess.id}/notepad`); if (!entries.length) { root.appendChild(el("div", "empty", t("notepad.empty"))); return; } for (const e of entries) { const row = el("div", "notepad-entry"); row.appendChild(el("span", "notepad-key", e.key)); row.appendChild(el("span", "notepad-text", e.text)); root.appendChild(row); } } catch (err) { root.appendChild(el("div", "empty", t("notepad.error", { msg: err.message }))); } } function closeNotepad() { $("#notepad-modal").hidden = true; } // ---- Todo (read-only observability; the agent writes via the tool) --------- async function showTodo() { if (!currentSession()) return; $("#todo-modal").hidden = false; await refreshTodo(); } async function refreshTodo() { const sess = currentSession(); if (!sess) return; const root = $("#todo-content"); root.textContent = ""; try { const items = await getJSON(`/api/sessions/${sess.id}/todos`); if (!items.length) { root.appendChild(el("div", "empty", t("todo.empty"))); return; } for (const i of items) { const row = el("div", "notepad-entry" + (i.status === "done" ? " todo-done" : "")); row.appendChild(el("span", "notepad-key", String(i.seq))); row.appendChild(el("span", "todo-status todo-" + i.status, t("todo.status." + i.status))); row.appendChild(el("span", "notepad-text", i.content)); root.appendChild(row); } } catch (err) { root.appendChild(el("div", "empty", t("todo.error", { msg: err.message }))); } } function closeTodo() { $("#todo-modal").hidden = true; } // ---- Settings (per-session instance or global defaults) ------------------- let settingsScope = "session"; let settingsBase = {}; // Font size: a device-local display preference (localStorage, like sidebarW), // NOT a model/session parameter. Scales the UI via the root --font-size variable // (rem-based sizes follow); the 16px composer input stays fixed for iOS focus. const FONT_MIN = 12, FONT_MAX = 24, FONT_DEFAULT = 16; function loadFontSize() { let n = FONT_DEFAULT; try { n = Number(localStorage.getItem("fontSize")) || FONT_DEFAULT; } catch { /* private mode */ } return Math.max(FONT_MIN, Math.min(FONT_MAX, n)); } function applyFontSize(px) { const n = Math.max(FONT_MIN, Math.min(FONT_MAX, Number(px) || FONT_DEFAULT)); document.documentElement.style.setProperty("--font-size", n + "px"); try { localStorage.setItem("fontSize", String(n)); } catch { /* private mode */ } } function currentSession() { return state.sessions.find((s) => s.id === state.current); } function fillSettingsForm(data, scope) { const isSession = scope === "session"; $("#set-name-field").hidden = !isSession; $("#set-name-hint").hidden = !isSession; $("#set-username-field").hidden = isSession; $("#set-username").value = data.user_name || ""; if (isSession) { const sess = currentSession(); $("#set-name").value = sess ? sess.title : ""; const locked = sess ? sess.name_locked : false; $("#set-name").disabled = locked; $("#set-name-hint").textContent = locked ? t("settings.name.locked") : t("settings.name.unlocked"); $("#set-hint").textContent = t("settings.hint.session"); } else { $("#set-hint").textContent = t("settings.hint.general"); } $("#set-notes").value = data.notes || ""; $("#set-sp").value = data.system_prompt || ""; $("#set-temp").value = data.temperature ?? ""; $("#set-topp").value = data.top_p ?? ""; $("#set-topk").value = data.top_k ?? ""; $("#set-minp").value = data.min_p ?? ""; $("#set-maxtokens").value = data.max_tokens ?? ""; // Display preference is device-local and scope-independent. $("#set-fontsize").value = String(loadFontSize()); // MCP: catalog editor in Generali, per-session tool allowlist in Sessione. $("#set-mcp-catalog").hidden = scope !== "general"; $("#set-mcp-tools").hidden = scope !== "session"; // Semantic memory: per-session ONE-WAY opt-in (hidden in Generali). Once on, // the checkbox is disabled — it can never be turned off (irreversible latch). $("#set-memory-field").hidden = !isSession; if (isSession) { const on = !!data.memory_enabled; $("#set-memory").checked = on; $("#set-memory").disabled = on; $("#set-memory-hint").textContent = on ? t("settings.memory.hint.on") : t("settings.memory.hint.off"); } } function readSettingsForm() { const num = (v) => (v === "" ? null : Number(v)); const txt = (v) => (v.trim() === "" ? null : v); return { user_name: txt($("#set-username").value), notes: txt($("#set-notes").value), system_prompt: txt($("#set-sp").value), temperature: num($("#set-temp").value), top_p: num($("#set-topp").value), top_k: num($("#set-topk").value), min_p: num($("#set-minp").value), max_tokens: num($("#set-maxtokens").value), }; } async function openSettings(scope) { settingsScope = scope; $("#set-scope-session").classList.toggle("active", scope === "session"); $("#set-scope-general").classList.toggle("active", scope === "general"); $("#settings-title").textContent = scope === "session" ? t("settings.title.session") : t("settings.title.general"); if (scope === "session") { // Read the persisted instance fresh from the store, exactly like the general // scope does. The cached session list can be stale (e.g. a tab opened before // the last edit, or a general save that doesn't refresh sessions), which would // show an empty/outdated System Prompt and look like the note wasn't kept. const sess = currentSession(); if (sess) { try { const fresh = await getJSON(`/api/sessions/${sess.id}`); const i = state.sessions.findIndex((s) => s.id === sess.id); if (i >= 0) state.sessions[i] = fresh; } catch { /* fall back to the cached instance */ } } settingsBase = { ...(currentSession()?.settings || {}) }; } else { settingsBase = await getJSON("/api/settings/defaults"); } fillSettingsForm(settingsBase, scope); // Load the global connector catalog for both scopes (Generali edits it; // Sessione picks tools from it). Best-effort: a failure leaves it empty. await loadMcpCatalog(); if (scope === "general") renderMcpCatalog(); else renderMcpTools(); $("#settings-modal").hidden = false; } async function saveSettings() { // Font size is a device-local display preference: apply + persist it here, // never in the backend payload (it is not a model/session parameter). applyFontSize(Number($("#set-fontsize").value)); // Preserve unexposed fields (seed, penalties) from the loaded instance. const settings = { ...settingsBase, ...readSettingsForm() }; // One-way memory latch in the UI too: checking enables, never un-enables. if (settingsScope === "session") { settings.memory_enabled = $("#set-memory").checked || !!settingsBase.memory_enabled; } try { if (settingsScope === "session") { const sess = currentSession(); if (!sess) return; const body = { settings }; const newName = $("#set-name").value.trim(); if (!sess.name_locked && newName && newName !== sess.title) body.title = newName; await sendJSON(`/api/sessions/${sess.id}`, "PATCH", body); state.sessions = await getJSON("/api/sessions"); renderSessions(); const updated = currentSession(); if (updated) $("#session-title").textContent = updated.title; } else { await sendJSON("/api/settings/defaults", "PUT", settings); } $("#settings-modal").hidden = true; } catch (e) { $("#set-hint").textContent = t("settings.error", { msg: e.message }); } } // ---- MCP connectors (settings) ------------------------------------------- // Two levels: the global catalog (Generali) holds connection params only; the // per-session allowlist (Sessione) curates which tools the model may use. The // picker fetches tools/list live and writes the selection into settingsBase, // persisted by the main Salva (readSettingsForm leaves mcp_enabled untouched). let mcpCatalog = []; let mcpPickerConnector = null; async function loadMcpCatalog() { try { mcpCatalog = await getJSON("/api/mcp/connectors"); } catch { mcpCatalog = []; } } function renderMcpCatalog() { const list = $("#mcp-connector-list"); list.textContent = ""; if (!mcpCatalog.length) { list.appendChild(el("p", "muted small", t("settings.mcp.empty"))); return; } for (const c of mcpCatalog) { const row = el("div", "mcp-row"); const info = el("div", "mcp-row-info"); info.appendChild(el("span", "mcp-name", c.name)); info.appendChild(el("span", "mcp-url", c.url)); info.appendChild(el("span", "mcp-token", "••••••••")); row.appendChild(info); const actions = el("div", "mcp-row-actions"); const edit = el("button", "btn ghost", t("settings.mcp.edit")); edit.addEventListener("click", () => { $("#mcp-new-name").value = c.name; $("#mcp-new-url").value = c.url; $("#mcp-new-token").value = c.token; }); const del = el("button", "btn ghost danger", t("settings.mcp.delete")); del.addEventListener("click", async () => { const ok = await showDialog({ title: t("settings.mcp.delete"), message: t("settings.mcp.delete.confirm", { name: c.name }), }); if (!ok) return; try { await sendJSON(`/api/mcp/connectors/${encodeURIComponent(c.name)}`, "DELETE"); await loadMcpCatalog(); renderMcpCatalog(); } catch (e) { $("#mcp-catalog-hint").textContent = t("settings.mcp.error", { msg: e.message }); } }); actions.appendChild(edit); actions.appendChild(del); row.appendChild(actions); list.appendChild(row); } } async function addMcpConnector() { const name = $("#mcp-new-name").value.trim(); const url = $("#mcp-new-url").value.trim(); const token = $("#mcp-new-token").value.trim(); const hint = $("#mcp-catalog-hint"); if (!name || !url || !token) { hint.textContent = t("settings.mcp.fields.required"); return; } try { await sendJSON(`/api/mcp/connectors/${encodeURIComponent(name)}`, "PUT", { url, token }); $("#mcp-new-name").value = ""; $("#mcp-new-url").value = ""; $("#mcp-new-token").value = ""; hint.textContent = t("settings.mcp.saved"); await loadMcpCatalog(); renderMcpCatalog(); } catch (e) { hint.textContent = t("settings.mcp.error", { msg: e.message }); } } function renderMcpTools() { const list = $("#mcp-tools-list"); list.textContent = ""; if (!mcpCatalog.length) { list.appendChild(el("p", "muted small", t("settings.mcp.noconnectors"))); return; } const enabled = settingsBase.mcp_enabled || {}; for (const c of mcpCatalog) { const row = el("div", "mcp-row"); const info = el("div", "mcp-row-info"); info.appendChild(el("span", "mcp-name", c.name)); const n = (enabled[c.name] || []).length; info.appendChild(el("span", "mcp-count", t("settings.mcp.enabled.count", { n }))); row.appendChild(info); const pick = el("button", "btn ghost", t("settings.mcp.choose")); pick.addEventListener("click", () => openMcpPicker(c)); row.appendChild(pick); list.appendChild(row); } } async function openMcpPicker(connector) { mcpPickerConnector = connector.name; $("#mcp-picker-title").textContent = t("settings.mcp.picker.title", { name: connector.name }); const list = $("#mcp-picker-list"); const hint = $("#mcp-picker-hint"); list.textContent = ""; hint.textContent = t("settings.mcp.loading"); $("#mcp-picker-modal").hidden = false; let tools; try { tools = await sendJSON(`/api/mcp/connectors/${encodeURIComponent(connector.name)}/tools`, "POST"); } catch (e) { hint.textContent = t("settings.mcp.error", { msg: e.message }); return; } hint.textContent = t("settings.mcp.picker.hint", { n: tools.length }); const enabled = new Set((settingsBase.mcp_enabled || {})[connector.name] || []); list.textContent = ""; for (const tool of tools) { const label = el("label", "mcp-tool"); const cb = el("input"); cb.type = "checkbox"; cb.value = tool.name; cb.checked = enabled.has(tool.name); label.appendChild(cb); const txt = el("span", "mcp-tool-text"); const head = el("span", "mcp-tool-name", tool.name); if (tool.write) head.appendChild(el("span", "mcp-write-badge", t("settings.mcp.write"))); txt.appendChild(head); if (tool.description) txt.appendChild(el("span", "mcp-tool-desc", tool.description)); label.appendChild(txt); list.appendChild(label); } } function confirmMcpPicker() { if (!mcpPickerConnector) return; const checked = [...$("#mcp-picker-list").querySelectorAll("input[type=checkbox]:checked")] .map((c) => c.value); settingsBase.mcp_enabled = settingsBase.mcp_enabled || {}; if (checked.length) settingsBase.mcp_enabled[mcpPickerConnector] = checked; else delete settingsBase.mcp_enabled[mcpPickerConnector]; $("#mcp-picker-modal").hidden = true; renderMcpTools(); } // A custom modal dialog (replaces native prompt/confirm: styled, mobile-friendly, // and inspectable by automation). Resolves with the input string (or null on // cancel) when `input` is given, otherwise true/false. function showDialog({ title, message = "", input = null, okText = "OK" }) { return new Promise((resolve) => { $("#dialog-title").textContent = title; const msg = $("#dialog-msg"); msg.textContent = message; msg.hidden = !message; const inp = $("#dialog-input"); inp.hidden = input === null; if (input !== null) inp.value = input; $("#dialog-ok").textContent = okText; const dlg = $("#dialog"); dlg.hidden = false; if (input !== null) { inp.focus(); inp.select(); } const finish = (val) => { dlg.hidden = true; $("#dialog-ok").removeEventListener("click", onOk); $("#dialog-cancel").removeEventListener("click", onCancel); inp.removeEventListener("keydown", onKey); resolve(val); }; const onOk = () => finish(input !== null ? inp.value : true); const onCancel = () => finish(input !== null ? null : false); const onKey = (e) => { if (e.key === "Enter") { e.preventDefault(); onOk(); } else if (e.key === "Escape") { e.preventDefault(); onCancel(); } }; $("#dialog-ok").addEventListener("click", onOk); $("#dialog-cancel").addEventListener("click", onCancel); inp.addEventListener("keydown", onKey); }); } // ---- 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"; } // Reflect the in-flight turn on the send button: red + hourglass + an explicit // "busy" label, so it is unmistakable that the framework is generating and a new // message cannot be sent yet (the disabled grey alone was easy to miss). Driven // by the local turn flag: it covers the common case where THIS GUI sent the turn. function setBusy(on) { state.busy = on; const send = $("#send"); send.disabled = on; send.classList.toggle("busy", on); send.textContent = on ? "\u23F3" : "\u27A4"; const label = t(on ? "send.busy" : "send.idle"); send.setAttribute("aria-label", label); send.title = label; } // ---- Resizable sidebar/chat separator (desktop only) ---------------------- function initSplitter() { const splitter = $("#splitter"); const root = document.documentElement; const width = () => parseInt(getComputedStyle(root).getPropertyValue("--sidebar-w")) || 280; const apply = (w) => { const max = Math.min(480, Math.floor(window.innerWidth * 0.5)); w = Math.max(200, Math.min(max, w)); root.style.setProperty("--sidebar-w", w + "px"); splitter.setAttribute("aria-valuenow", String(w)); return w; }; const save = () => { try { localStorage.setItem("sidebarW", String(width())); } catch { /* private mode */ } }; let dragging = false, startX = 0, startW = 0; splitter.addEventListener("pointerdown", (e) => { dragging = true; startX = e.clientX; startW = width(); splitter.setPointerCapture(e.pointerId); document.body.classList.add("resizing"); e.preventDefault(); }); splitter.addEventListener("pointermove", (e) => { if (dragging) apply(startW + (e.clientX - startX)); }); const end = () => { if (!dragging) return; dragging = false; document.body.classList.remove("resizing"); save(); }; splitter.addEventListener("pointerup", end); splitter.addEventListener("pointercancel", end); splitter.addEventListener("keydown", (e) => { if (e.key === "ArrowLeft") apply(width() - 16); else if (e.key === "ArrowRight") apply(width() + 16); else return; e.preventDefault(); save(); }); try { const w = localStorage.getItem("sidebarW"); if (w) apply(parseInt(w)); } catch { /* private mode */ } } function wire() { initSplitter(); $("#menu").addEventListener("click", openDrawer); $("#scrim").addEventListener("click", closeDrawer); $("#new-session").addEventListener("click", newSession); $("#send").addEventListener("click", sendMessage); $("#send").setAttribute("aria-label", t("send.idle")); $("#attach").title = t("attach.title"); $("#attach").setAttribute("aria-label", t("attach.title")); $("#attach").addEventListener("click", () => $("#file-input").click()); $("#file-input").addEventListener("change", (e) => { const files = Array.from(e.target.files || []); e.target.value = ""; if (files.length) uploadFiles(files); }); $("#show-stats").addEventListener("click", showStats); $("#close-stats").setAttribute("aria-label", t("stats.close")); $("#close-stats").addEventListener("click", closeStats); $("#stats-modal").addEventListener("click", (e) => { if (e.target.id === "stats-modal") closeStats(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#stats-modal").hidden) closeStats(); }); $("#show-notepad").setAttribute("aria-label", t("notepad.title")); $("#show-notepad").addEventListener("click", showNotepad); $("#refresh-notepad").setAttribute("aria-label", t("notepad.refresh")); $("#refresh-notepad").addEventListener("click", refreshNotepad); $("#close-notepad").setAttribute("aria-label", t("notepad.close")); $("#close-notepad").addEventListener("click", closeNotepad); $("#notepad-modal").addEventListener("click", (e) => { if (e.target.id === "notepad-modal") closeNotepad(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#notepad-modal").hidden) closeNotepad(); }); $("#show-todo").setAttribute("aria-label", t("todo.title")); $("#show-todo").addEventListener("click", showTodo); $("#refresh-todo").setAttribute("aria-label", t("todo.refresh")); $("#refresh-todo").addEventListener("click", refreshTodo); $("#close-todo").setAttribute("aria-label", t("todo.close")); $("#close-todo").addEventListener("click", closeTodo); $("#todo-modal").addEventListener("click", (e) => { if (e.target.id === "todo-modal") closeTodo(); }); document.addEventListener("keydown", (e) => { if (e.key === "Escape" && !$("#todo-modal").hidden) closeTodo(); }); $("#show-settings").addEventListener("click", () => openSettings("session")); $("#set-scope-session").addEventListener("click", () => openSettings("session")); $("#set-scope-general").addEventListener("click", () => openSettings("general")); $("#set-save").addEventListener("click", saveSettings); $("#set-cancel").addEventListener("click", () => { $("#settings-modal").hidden = true; }); $("#mcp-add-btn").addEventListener("click", addMcpConnector); $("#mcp-picker-ok").addEventListener("click", confirmMcpPicker); $("#mcp-picker-cancel").addEventListener("click", () => { $("#mcp-picker-modal").hidden = true; }); $("#mcp-picker-modal").addEventListener("click", (e) => { if (e.target.id === "mcp-picker-modal") $("#mcp-picker-modal").hidden = true; }); const input = $("#input"); input.addEventListener("input", () => autoGrow(input)); input.addEventListener("keydown", (e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); } }); } (async () => { await loadI18n(); applyI18n(); applyFontSize(loadFontSize()); wire(); await loadSessions(); })().catch((e) => { $("#transcript").textContent = ""; $("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`)); });