Add context management: notepad, sliding window, cache reuse, windowed GUI

Per-session notepad: agent-curated labelled entries via the notepad tool
(set/remove/clear), injected as a pinned <NOTEPAD> section above DIALOG,
char-budgeted with a consolidate ceiling, exposed in a read-only GUI panel.

Sliding DIALOG window (src/window.rs): retains recent messages by count in
two tiers (MAIN_AREA=40 + BUFFER=10), append-only while the buffer fills so
the prompt prefix stays byte-stable for KV reuse, then stepped hysteresis
eviction snapping to user-turn boundaries (never splits a tool exchange).
window_start persisted per session; full history never deleted.

Engine prefix-cache reuse: leave DIALOG open (a moving </DIALOG> closer broke
the engine prompt_ckpt_prefix every user turn, forcing full re-prefill);
surface usage.cached_tokens as a GUI badge; fix the PerfMeter prefill gauge to
gauge over non-cached tokens; add a static sliding-window marker after the
opener so the model knows older turns are omitted.

Stats clarity: distinguish the current inference context (last_prompt_tokens,
new "Contesto attuale" card) from the cumulative lifetime token total
(relabeled "Token cumulativi ... su tutti i turni"); /api/stats carries both.

Windowed browser transcript: GET /api/sessions/{id}/messages returns only the
retained window (SQL-filtered by window_start, never loads the full history)
plus the total count, wrapped as {messages, window_start, total}; the GUI shows
a banner noting older turns are preserved server-side. Full-chat export deferred.

Settings: the session scope re-reads the persisted instance fresh from the store
(like the general scope already did), fixing a stale-cache display that looked
like the session System Prompt was not being kept.

Docs (README) refreshed; 158 tests + 3 ignored green, clippy and fmt clean.
This commit is contained in:
adm committed 2026-11-26 03:12:23 +01:00
1 parent 7c945890f4
commit 0ce84581a4
20 files changed
+1412 -118

No files matched your search

+20 -1
View File
@@ -121,6 +121,16 @@ body.resizing { cursor: col-resize; user-select: none; }
}
.empty { color: var(--muted); text-align: center; margin: auto; max-width: 28ch; }
/* Sliding-window banner: the browser shows the same recent window the model
sees; older turns are preserved server-side. Sticky so it stays visible. */
.window-note {
position: sticky; top: 0; z-index: 1;
max-width: 860px; width: 100%; margin: 0 auto;
padding: 6px 12px; font-size: 0.75rem; color: var(--muted);
background: var(--panel-2); border: 1px solid var(--border);
border-radius: 8px; text-align: center;
}
/* ---- Message bubbles ---- */
.msg { max-width: 860px; width: 100%; margin: 0 auto; display: flex; flex-direction: column; }
.msg .role { font-size: 0.75rem; color: var(--muted); margin-bottom: 4px; }
@@ -260,7 +270,7 @@ details.thinking .reasoning {
.msg-attachments { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 6px; }
/* ---- Stats modal ---- */
#stats-modal, #dialog, #settings-modal {
#stats-modal, #dialog, #settings-modal, #notepad-modal {
position: fixed; inset: 0; z-index: 40;
background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center;
padding: 20px;
@@ -380,6 +390,15 @@ details.thinking .reasoning {
.field-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 0 12px; }
.sess-btn:disabled { opacity: 0.35; cursor: default; }
/* ---- Notepad (read-only pinned entries, agent-managed) ---- */
.notepad-card { width: min(560px, 100%); max-width: 560px; max-height: 85dvh; display: flex; flex-direction: column; padding: 0; overflow: hidden; }
.notepad-card .stats-head h2 { flex: 1; }
.notepad-hint { margin: 0; padding: 10px 18px 0; }
.notepad-content { padding: 14px 18px 18px; overflow-y: auto; display: flex; flex-direction: column; gap: 8px; }
.notepad-entry { display: flex; gap: 10px; align-items: baseline; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; background: var(--panel-2); }
.notepad-key { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-weight: 600; color: var(--accent); flex: 0 0 auto; max-width: 42%; overflow-wrap: anywhere; }
.notepad-text { flex: 1 1 auto; min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
/* ---- Wide screens: persistent sidebar ---- */
@media (min-width: 900px) {
#drawer { position: static; transform: none; width: var(--sidebar-w); flex-shrink: 0; }
+80 -14
View File
@@ -99,6 +99,7 @@ function usageText(u) {
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;
}
@@ -169,32 +170,40 @@ function renderSessions() {
}
}
function renderTranscript(messages) {
const t = $("#transcript");
t.textContent = "";
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) {
t.appendChild(el("div", "empty", "Inizia una conversazione: scrivi un messaggio qui sotto."));
tr.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));
tr.appendChild(messageNode("user", m.content, null, null, m.created_at));
} else if (m.role === "tool") {
t.appendChild(toolResultNode(m.content));
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 || {};
t.appendChild(toolCallNode(f.name, f.arguments));
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;
t.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html));
tr.appendChild(messageNode("assistant", m.content, m.reasoning_content, usage, m.created_at, m.content_html));
}
}
}
@@ -221,8 +230,8 @@ async function selectSession(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);
const data = await getJSON(`/api/sessions/${id}/messages`);
renderTranscript(data.messages, data);
}
async function newSession() {
@@ -512,6 +521,11 @@ function renderStats(s) {
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) })
@@ -637,6 +651,37 @@ function closeStats() {
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; }
// ---- Settings (per-session instance or global defaults) -------------------
let settingsScope = "session";
let settingsBase = {};
@@ -693,10 +738,23 @@ async function openSettings(scope) {
$("#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");
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);
$("#settings-modal").hidden = false;
}
@@ -835,6 +893,14 @@ function wire() {
$("#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-settings").addEventListener("click", () => openSettings("session"));
$("#set-scope-session").addEventListener("click", () => openSettings("session"));
$("#set-scope-general").addEventListener("click", () => openSettings("general"));
+13 -3
View File
@@ -24,6 +24,8 @@
"attach.remove": "Remove attachment",
"attach.error": "Upload failed: {msg}",
"usage.ttft": "1st token {n} s",
"usage.cached": "{n} cached",
"window.note": "Sliding window: showing {shown} recent messages; {omitted} older ones are kept in history.",
"stats.title": "Statistics",
"stats.close": "Close",
"stats.updated": "Updated {time}",
@@ -32,11 +34,13 @@
"stats.engine.idle": "Idle",
"stats.engine.busy": "In use",
"stats.context": "{n} token context",
"stats.context_now": "Current context",
"stats.context_now.sub": "prompt sent on the last turn",
"stats.decode": "Decode speed",
"stats.decode.sub": "run average",
"stats.prefill": "prefill {n} tok/s",
"stats.tokens": "Total tokens",
"stats.tokens.sub": "{p} prompt · {c} completion",
"stats.tokens": "Cumulative tokens",
"stats.tokens.sub": "{p} prompt · {c} completion · across all turns",
"stats.sessions": "Sessions",
"stats.messages.sub": "{n} messages",
"stats.tools": "Tool calls",
@@ -53,5 +57,11 @@
"stats.perSession.empty": "No sessions yet.",
"stats.session.updated": "updated {when}",
"stats.tps": "{n} tok/s",
"stats.na": "—"
"stats.na": "—",
"notepad.title": "Notepad",
"notepad.hint": "The session's persistent notes, managed by the agent. Read-only.",
"notepad.empty": "No notes yet. The agent can pin important things here.",
"notepad.refresh": "Refresh",
"notepad.close": "Close",
"notepad.error": "Error: {msg}"
}
+13 -3
View File
@@ -24,6 +24,8 @@
"attach.remove": "Rimuovi allegato",
"attach.error": "Caricamento fallito: {msg}",
"usage.ttft": "1° token {n} s",
"usage.cached": "{n} cache",
"window.note": "Finestra scorrevole: vedi {shown} messaggi recenti; {omitted} più vecchi sono conservati nella cronologia.",
"stats.title": "Statistiche",
"stats.close": "Chiudi",
"stats.updated": "Aggiornato {time}",
@@ -32,11 +34,13 @@
"stats.engine.idle": "Inattivo",
"stats.engine.busy": "In uso",
"stats.context": "{n} token di contesto",
"stats.context_now": "Contesto attuale",
"stats.context_now.sub": "prompt inviato nell'ultimo turno",
"stats.decode": "Velocità decode",
"stats.decode.sub": "media dall'avvio",
"stats.prefill": "prefill {n} tok/s",
"stats.tokens": "Token totali",
"stats.tokens.sub": "{p} prompt · {c} completati",
"stats.tokens": "Token cumulativi",
"stats.tokens.sub": "{p} prompt · {c} completati · su tutti i turni",
"stats.sessions": "Sessioni",
"stats.messages.sub": "{n} messaggi",
"stats.tools": "Chiamate tool",
@@ -53,5 +57,11 @@
"stats.perSession.empty": "Nessuna sessione.",
"stats.session.updated": "aggiornato {when}",
"stats.tps": "{n} tok/s",
"stats.na": "—"
"stats.na": "—",
"notepad.title": "Notepad",
"notepad.hint": "Appunti persistenti della sessione, gestiti dall'agente. Sola lettura.",
"notepad.empty": "Nessun appunto. L'agente può fissare qui le cose importanti.",
"notepad.refresh": "Aggiorna",
"notepad.close": "Chiudi",
"notepad.error": "Errore: {msg}"
}
+14
View File
@@ -32,6 +32,7 @@
<span id="session-title">Conversazione</span>
<span id="model-name" class="muted"></span>
</div>
<button id="show-notepad" class="btn icon" aria-label="Notepad">&#128221;</button>
<button id="show-settings" class="btn icon" aria-label="Impostazioni">&#9881;&#65039;</button>
</header>
@@ -59,6 +60,19 @@
</div>
</div>
<!-- Notepad (read-only): the session's pinned entries, managed by the agent -->
<div id="notepad-modal" hidden>
<div class="modal-card notepad-card">
<div class="stats-head">
<h2 data-i18n="notepad.title">Notepad</h2>
<button id="refresh-notepad" class="btn icon" aria-label="Aggiorna">&#8635;</button>
<button id="close-notepad" class="btn icon" aria-label="Chiudi">&#10005;</button>
</div>
<p class="muted small notepad-hint" data-i18n="notepad.hint">Appunti persistenti della sessione, gestiti dall'agente. Sola lettura.</p>
<div id="notepad-content" class="notepad-content"></div>
</div>
</div>
<!-- Generic dialog (rename input / delete confirm); replaces native prompt/confirm -->
<div id="dialog" hidden>
<div class="modal-card">