Files
strata-ctl/web/assets/app.js
T
adm 7dd66ea138 Render assistant Markdown and LaTeX as sanitized HTML with native MathML
Server-side rendering keeps the browser free of any Markdown/MathJax toolchain (single-binary). New src/render.rs: pulldown-cmark (tables/strikethrough/math) + pulldown-latex -> MathML Core. Safety: raw HTML events are escaped to text (pulldown-cmark 0.13 has no ENABLE_HTML opt-out) and link/image URLs pass a scheme allowlist (javascript:/data:/vbscript: stripped, control chars removed). content_html is added to get_messages (assistant only) and to the agent Final SSE event; the GUI injects it via innerHTML for assistant bubbles (history + live) while user text stays textContent. CSS styles Markdown and native MathML; block math must not override display (UA block math layout) or it collapses to vertical stacks. 10 render unit tests incl. XSS; 136 tests green, clippy/fmt clean; verified live + visually.
2026-11-25 20:58:20 +01:00

852 lines
32 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.
// 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: [] };
// ---- i18n: new user-facing strings go through t(key, params) --------------
// Catalogs are served at /assets/locales/<lang>.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());
return r.status === 204 ? null : r.json();
}
// ---- 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, 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;
} 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.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).
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) {
const t = $("#transcript");
t.textContent = "";
if (!messages.length) {
t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
return;
}
for (const m of messages) {
if (m.role === "user") {
t.appendChild(messageNode("user", m.content, null, null, m.created_at));
} else if (m.role === "tool") {
t.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 || {};
t.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;
t.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();
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 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));
}
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.busy || !state.current) return;
state.busy = true;
$("#send").disabled = true;
input.value = "";
autoGrow(input);
state.attachments = [];
renderAttachments();
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 {
state.busy = false;
$("#send").disabled = false;
input.focus();
scrollDown();
}
}
// 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 = 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 = 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;
}
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 || {}));
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;
}
// ---- Settings (per-session instance or global defaults) -------------------
let settingsScope = "session";
let settingsBase = {};
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 ?? "";
}
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");
settingsBase =
scope === "session"
? { ...(currentSession()?.settings || {}) }
: await getJSON("/api/settings/defaults");
fillSettingsForm(settingsBase, scope);
$("#settings-modal").hidden = false;
}
async function saveSettings() {
// Preserve unexposed fields (seed, penalties) from the loaded instance.
const settings = { ...settingsBase, ...readSettingsForm() };
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 });
}
}
// 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";
}
// ---- 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);
$("#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-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; });
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();
wire();
await loadSessions();
})().catch((e) => {
$("#transcript").textContent = "";
$("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`));
});