Files
strata-ctl/web/assets/app.js
T
adm 8979201139 Add GUI agent mode: the model acts via a universal shell_exec tool
- agent:🐚 native shell_exec (bash -lc, cwd, timeout, 64 KiB output cap)
  behind a ShellRunner seam — base/host mode now; an isolated Docker-MCP runner
  plugs in later without touching the loop. OpenAI function declaration included.
- agent::run_loop: bounded model<->tool orchestration, generic over the model
  step so it is unit-testable without the engine. Persists the full trajectory
  (assistant tool-call turns + role:tool results + final answer) and emits
  tool_call / tool_result / final / error progress events.
- api::sessions: POST .../chat with agent:true drives the loop and streams the
  events as SSE; the GUI shows commands + output inline (observability, no gate).
- store: messages gains tool_call_id; an idempotent migration adds the column to
  pre-existing databases (CREATE TABLE IF NOT EXISTS does not alter them).
- web: robot agent toggle, tool-call/output blocks, history rendering of tool
  turns; inline favicon to silence the favicon 404.

Validated LIVE on engine 0.1.67: the model called shell_exec('uname -a'), the
host executed it, and the model reported the output; trajectory persisted; GUI
verified by browser (toggle, tool block, output, final answer). 106 tests +
2 ignored green, clippy/fmt clean. Isolated mode (user-provided Docker container)
is the next step.
2026-11-25 02:06:45 +01:00

406 lines
13 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 };
// ---- API helpers ----------------------------------------------------------
async function getJSON(url) {
const r = await fetch(url);
if (!r.ok) throw new Error(await r.text());
return r.json();
}
async function sendJSON(url, method, body) {
const r = await fetch(url, {
method,
headers: { "Content-Type": "application/json" },
body: body === undefined ? undefined : JSON.stringify(body),
});
if (!r.ok) throw new Error(await r.text());
return r.status === 204 ? null : r.json();
}
// Stream a chat turn, invoking onDelta for each SSE chunk.
async function streamChat(id, content, onDelta) {
const r = await fetch(`/api/sessions/${id}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, stream: true }),
});
if (!r.ok) throw new Error(await r.text());
const reader = r.body.getReader();
const dec = new TextDecoder();
let buf = "";
for (;;) {
const { done, value } = await reader.read();
if (done) break;
buf += dec.decode(value, { stream: true });
let idx;
while ((idx = buf.indexOf("\n\n")) >= 0) {
const block = buf.slice(0, idx);
buf = buf.slice(idx + 2);
for (const line of block.split("\n")) {
if (!line.startsWith("data:")) continue;
const data = line.slice(5).trim();
if (data === "[DONE]") return;
try { onDelta(JSON.parse(data)); } catch { /* ignore partial */ }
}
}
}
}
// ---- DOM builders ---------------------------------------------------------
function el(tag, cls, text) {
const n = document.createElement(tag);
if (cls) n.className = cls;
if (text !== undefined) n.textContent = text;
return n;
}
function messageNode(role, content, reasoning, usage) {
const wrap = el("div", `msg ${role}`);
wrap.appendChild(el("div", "role", role === "user" ? "Tu" : "Assistente"));
const bubble = el("div", "bubble");
if (reasoning) {
const det = el("details", "thinking");
det.appendChild(el("summary", null, "Pensiero"));
det.appendChild(el("div", "reasoning", reasoning));
bubble.appendChild(det);
}
bubble.appendChild(el("div", "content", content || ""));
if (usage) bubble.appendChild(el("div", "usage", usage));
wrap.appendChild(bubble);
return wrap;
}
function scrollDown() {
const t = $("#transcript");
t.scrollTop = t.scrollHeight;
}
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, s.title);
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;
const sess = state.sessions.find((s) => s.id === id);
$("#session-title").textContent = sess ? sess.title : "Conversazione";
$("#model-name").textContent = sess ? sess.model : "";
renderSessions();
const messages = await getJSON(`/api/sessions/${id}/messages`);
renderTranscript(messages);
}
async function newSession() {
const s = await sendJSON("/api/sessions", "POST", {});
state.sessions.unshift(s);
renderSessions();
await selectSession(s.id);
closeDrawer();
$("#input").focus();
}
async function deleteSession() {
if (!state.current) return;
if (!confirm("Eliminare questa conversazione?")) return;
await sendJSON(`/api/sessions/${state.current}`, "DELETE");
state.current = null;
await loadSessions();
}
async function sendMessage() {
const input = $("#input");
const content = input.value.trim();
if (!content || state.busy || !state.current) return;
state.busy = true;
$("#send").disabled = true;
input.value = "";
autoGrow(input);
const t = $("#transcript");
const empty = t.querySelector(".empty");
if (empty) empty.remove();
t.appendChild(messageNode("user", content));
scrollDown();
try {
if (state.agent) await agentTurn(content, t);
else await chatTurn(content, t);
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) {
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, (chunk) => {
const d = chunk.choices && chunk.choices[0] && chunk.choices[0].delta;
if (d && d.reasoning_content) {
reasoning += d.reasoning_content;
reasoningNode.textContent = reasoning;
det.hidden = false;
}
if (d && d.content) {
text += d.content;
contentNode.textContent = text;
}
if (chunk.usage) usage = chunk.usage;
scrollDown();
});
if (usage) bubble.appendChild(el("div", "usage", usageText(usage)));
}
// Agent mode: stream tool_call / tool_result / final events (observability, no gate).
async function agentTurn(content, t) {
const r = await fetch(`/api/sessions/${state.current}/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content, agent: true }),
});
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;
}
// ---- 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);
$("#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; });
const input = $("#input");
input.addEventListener("input", () => autoGrow(input));
input.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendMessage(); }
});
}
wire();
loadSessions().catch((e) => {
$("#transcript").textContent = "";
$("#transcript").appendChild(el("div", "empty", `Impossibile caricare: ${e.message}`));
});