The reasoning phase (~6s before the answer) went into a collapsed <details>, so the bubble looked empty until generation finished — perceived as "no streaming" on the second turn. Auto-open the thinking panel while reasoning_content streams and fold it when the answer (content) begins, so the wait is visible progress. Server streaming was verified correct on BOTH turns (content spread over 1.4s and 3.1s, reasoning starting at 0.87s); this is a UX fix, not a protocol change.
677 lines
24 KiB
JavaScript
677 lines
24 KiB
JavaScript
// strata-ctl web GUI — vanilla ES module, no build step, no dependencies.
|
|
// Talks to the session-aware API (/api/sessions...); the server owns context.
|
|
// Model output is always inserted via textContent (never innerHTML) to avoid
|
|
// injection. Mobile-first: the session list is an off-canvas drawer on phones.
|
|
|
|
const $ = (sel) => document.querySelector(sel);
|
|
|
|
const state = { sessions: [], current: null, busy: false, agent: 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();
|
|
}
|
|
|
|
// Stream a chat turn, invoking onDelta for each SSE chunk.
|
|
async function streamChat(id, content, attachments, onDelta) {
|
|
const r = await fetch(`/api/sessions/${id}/chat`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body: JSON.stringify({ content, stream: true, attachments }),
|
|
});
|
|
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;
|
|
}
|
|
|
|
function usageText(u) {
|
|
return u ? `${u.prompt_tokens} + ${u.completion_tokens} token` : null;
|
|
}
|
|
|
|
// 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));
|
|
} 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));
|
|
}
|
|
}
|
|
}
|
|
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 deleteSession() {
|
|
if (state.current) await deleteSessionById(state.current);
|
|
}
|
|
|
|
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);
|
|
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 {
|
|
if (state.agent) await agentTurn(content, t, ids);
|
|
else await chatTurn(content, t, ids);
|
|
state.sessions = await getJSON("/api/sessions");
|
|
renderSessions();
|
|
} catch (e) {
|
|
t.appendChild(messageNode("assistant", `Errore: ${e.message}`));
|
|
} finally {
|
|
state.busy = false;
|
|
$("#send").disabled = false;
|
|
input.focus();
|
|
scrollDown();
|
|
}
|
|
}
|
|
|
|
// Plain chat: stream OpenAI chunks into a live assistant bubble.
|
|
async function chatTurn(content, t, attachments) {
|
|
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;
|
|
await streamChat(state.current, content, attachments, (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;
|
|
det.open = true; // show the thinking live, so the wait is visible progress
|
|
}
|
|
if (d && d.content) {
|
|
if (!text) det.open = false; // fold the thinking once the answer starts
|
|
text += d.content;
|
|
contentNode.textContent = text;
|
|
}
|
|
if (chunk.usage) usage = chunk.usage;
|
|
scrollDown();
|
|
});
|
|
if (usage) bubble.appendChild(el("div", "usage", usageText(usage)));
|
|
}
|
|
|
|
// Agent mode: 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 = {};
|
|
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 === "tool_call") {
|
|
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 m = ev.response.choices[0].message;
|
|
t.appendChild(messageNode("assistant", m.content || "", m.reasoning_content, usageText(ev.response.usage)));
|
|
} else if (ev.type === "error") {
|
|
t.appendChild(messageNode("assistant", `Errore agent: ${ev.message}`));
|
|
}
|
|
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;
|
|
}
|
|
|
|
// ---- 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;
|
|
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 {
|
|
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);
|
|
$("#delete-session").addEventListener("click", deleteSession);
|
|
$("#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);
|
|
});
|
|
$("#agent-toggle").addEventListener("click", () => {
|
|
state.agent = !state.agent;
|
|
const b = $("#agent-toggle");
|
|
b.classList.toggle("active", state.agent);
|
|
b.setAttribute("aria-pressed", String(state.agent));
|
|
});
|
|
$("#show-stats").addEventListener("click", showStats);
|
|
$("#close-stats").addEventListener("click", () => { $("#stats-modal").hidden = true; });
|
|
$("#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}`));
|
|
}); |