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

+218 -2
View File
@@ -14,7 +14,7 @@ use std::sync::Mutex;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use rusqlite::{params, Connection};
use rusqlite::{params, Connection, OptionalExtension};
use serde::{Deserialize, Serialize};
/// A session's own settings instance. Global defaults are only a *template*:
@@ -128,6 +128,11 @@ pub struct Stats {
pub prompt_tokens: u64,
pub completion_tokens: u64,
pub total_tokens: u64,
/// Current inference context: prompt tokens of the most recent assistant
/// turn (the actual prompt last sent to the engine). Unlike `prompt_tokens`
/// — a cumulative sum that re-counts the whole window every turn — this is
/// the size of the context we are actually sending to inference now.
pub last_prompt_tokens: u64,
/// Tool calls requested across all assistant turns (agent activity).
pub tool_calls: u64,
/// Per-session breakdown, busiest (most tokens) first.
@@ -182,10 +187,22 @@ pub struct ContextSection {
pub position: i64,
}
/// One labelled entry of a session's persistent notepad: a stable `key` the
/// agent addresses (upsert/remove) and a short `text`. Per-session; injected as
/// the pinned <NOTEPAD> section above DIALOG, ordered by key for a deterministic
/// block. Nothing is evicted automatically — the agent curates it.
#[derive(Debug, Clone, Serialize)]
pub struct NotepadEntry {
pub key: String,
pub text: String,
pub updated_at: i64,
}
/// Bootstrap templates for the static context sections (seeded once into SQLite;
/// the DB rows are the source of truth afterwards).
const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}";
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
const TOOL_USE_SECTION_PRE_NOTEPAD: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti.";
const TOOL_USE_SECTION: &str = "Strumenti: shell_exec(command, cwd?, timeout?) esegue un comando shell nell'ambiente host e restituisce stdout/stderr ed exit code; la cartella predefinita è la tua cartella personale. Usalo per ispezionare o modificare file e per verificare i risultati invece di inventarli. Fai riferimento alle dichiarazioni dei tool fornite per gli argomenti esatti. notepad(action, key?, text?) gestisce il tuo blocco appunti persistente, sempre visibile sopra il dialogo: action=set crea o aggiorna la entry etichettata `key` con `text` (upsert idempotente); action=remove cancella la entry `key`; action=clear svuota tutto. Fissa qui ciò che deve sopravvivere allo scorrere della finestra di contesto: goal, decisioni e razionale, stato/next-step, vincoli, pitfall, path e identificatori chiave. Non usarlo per log o documenti lunghi né per dati effimeri del singolo task. È bounded: quando si avvicina al limite consolida le entry vecchie; non c'è eviction automatica, decidi tu cosa tenere. Tieni le entry brevi.";
/// The storage interface. Synchronous; call via `spawn_blocking` from async code.
pub trait Store: Send + Sync {
@@ -201,8 +218,15 @@ pub trait Store: Send + Sync {
fn update_settings(&self, id: &str, settings: &SessionSettings) -> Result<()>;
fn set_name_locked(&self, id: &str, locked: bool) -> Result<()>;
fn set_folder(&self, id: &str, folder: &str) -> Result<()>;
/// First retained history message id for the sliding DIALOG window (0 = all).
fn window_start(&self, id: &str) -> Result<i64>;
fn set_window_start(&self, id: &str, start: i64) -> Result<()>;
fn delete_session(&self, id: &str) -> Result<()>;
fn messages(&self, session_id: &str) -> Result<Vec<StoredMessage>>;
/// The GUI's sliding-window view: messages at/after `start_id` (the persisted
/// window start) plus the total stored message count. Filtered in SQL so a
/// months-long history is never loaded whole just to render the recent window.
fn message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)>;
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage>;
fn stats(&self) -> Result<Stats>;
/// The global default settings template (None until seeded).
@@ -211,6 +235,14 @@ pub trait Store: Send + Sync {
/// The static context sections, ordered (SYSTEM_PROMPT, TOOL_USE, ...).
fn context_sections(&self) -> Result<Vec<ContextSection>>;
fn set_context_section(&self, name: &str, content: &str, position: i64) -> Result<()>;
/// The session's notepad entries, ordered by key (deterministic block).
fn notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>>;
/// Create or update (upsert) the entry labelled `key`.
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()>;
/// Remove the entry `key`; returns whether it existed.
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool>;
/// Empty the session's notepad.
fn clear_notepad(&self, session_id: &str) -> Result<()>;
fn save_upload(&self, meta: &UploadMeta) -> Result<()>;
fn get_upload(&self, id: &str) -> Result<Option<UploadMeta>>;
}
@@ -242,6 +274,7 @@ CREATE TABLE IF NOT EXISTS sessions (
settings_json TEXT,
name_locked INTEGER NOT NULL DEFAULT 0,
folder TEXT,
window_start INTEGER NOT NULL DEFAULT 0,
created_at INTEGER NOT NULL,
updated_at INTEGER NOT NULL
);
@@ -276,6 +309,13 @@ CREATE TABLE IF NOT EXISTS context_sections (
content TEXT NOT NULL,
position INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS notepad_entries (
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
key TEXT NOT NULL,
text TEXT NOT NULL,
updated_at INTEGER NOT NULL,
PRIMARY KEY (session_id, key)
);
";
/// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for
@@ -351,6 +391,11 @@ fn migrate(conn: &Connection) -> Result<()> {
if !has_col("sessions", "folder")? {
conn.execute_batch("ALTER TABLE sessions ADD COLUMN folder TEXT;")?;
}
if !has_col("sessions", "window_start")? {
conn.execute_batch(
"ALTER TABLE sessions ADD COLUMN window_start INTEGER NOT NULL DEFAULT 0;",
)?;
}
Ok(())
}
@@ -365,6 +410,12 @@ fn seed_context_sections(conn: &Connection) -> Result<()> {
"INSERT OR IGNORE INTO context_sections (name, content, position) VALUES ('TOOL_USE', ?1, 1)",
params![TOOL_USE_SECTION],
)?;
// Refresh an untouched pre-notepad TOOL_USE row so the notepad manual reaches
// existing databases; a user-edited row (content differs) is left alone.
conn.execute(
"UPDATE context_sections SET content = ?1 WHERE name = 'TOOL_USE' AND content = ?2",
params![TOOL_USE_SECTION, TOOL_USE_SECTION_PRE_NOTEPAD],
)?;
Ok(())
}
@@ -472,6 +523,27 @@ impl Store for SqliteStore {
Ok(())
}
fn window_start(&self, id: &str) -> Result<i64> {
let conn = self.lock();
let v = conn
.query_row(
"SELECT window_start FROM sessions WHERE id = ?1",
params![id],
|r| r.get::<_, i64>(0),
)
.optional()?;
Ok(v.unwrap_or(0))
}
fn set_window_start(&self, id: &str, start: i64) -> Result<()> {
let conn = self.lock();
conn.execute(
"UPDATE sessions SET window_start = ?2 WHERE id = ?1",
params![id, start],
)?;
Ok(())
}
fn delete_session(&self, id: &str) -> Result<()> {
let conn = self.lock();
conn.execute("DELETE FROM sessions WHERE id = ?1", params![id])?;
@@ -498,6 +570,32 @@ impl Store for SqliteStore {
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn message_window(&self, session_id: &str, start_id: i64) -> Result<(Vec<StoredMessage>, u64)> {
let conn = self.lock();
let total: i64 = conn.query_row(
"SELECT COUNT(*) FROM messages WHERE session_id = ?1",
params![session_id],
|r| r.get(0),
)?;
let mut stmt = conn
.prepare("SELECT * FROM messages WHERE session_id = ?1 AND id >= ?2 ORDER BY id ASC")?;
let rows = stmt.query_map(params![session_id, start_id], |row| {
Ok(StoredMessage {
id: row.get("id")?,
role: row.get("role")?,
content: row.get("content")?,
reasoning_content: row.get("reasoning_content")?,
tool_calls_json: row.get("tool_calls_json")?,
tool_call_id: row.get("tool_call_id")?,
prompt_tokens: row.get::<_, i64>("prompt_tokens")? as u32,
completion_tokens: row.get::<_, i64>("completion_tokens")? as u32,
created_at: row.get("created_at")?,
})
})?;
let msgs = rows.collect::<rusqlite::Result<Vec<_>>>()?;
Ok((msgs, total as u64))
}
fn append_message(&self, session_id: &str, msg: NewMessage<'_>) -> Result<StoredMessage> {
let now = now_secs();
let conn = self.lock();
@@ -552,6 +650,21 @@ impl Store for SqliteStore {
|r| Ok((r.get(0)?, r.get(1)?, r.get(2)?, r.get(3)?)),
)?;
// Current context = the prompt of the latest assistant turn (the size
// actually sent to inference last). The cumulative SUM(prompt_tokens)
// above re-counts the whole retained window every turn, so it is NOT
// the context size; this single latest value is.
let last_prompt: i64 = conn
.query_row(
"SELECT prompt_tokens FROM messages
WHERE role = 'assistant' AND prompt_tokens > 0
ORDER BY id DESC LIMIT 1",
[],
|r| r.get(0),
)
.optional()?
.unwrap_or(0);
// Per-session breakdown (LEFT JOIN keeps empty sessions visible), busiest first.
let mut stmt = conn.prepare(
"SELECT s.id, s.title, COUNT(m.id),
@@ -599,6 +712,7 @@ impl Store for SqliteStore {
prompt_tokens: prompt as u64,
completion_tokens: completion as u64,
total_tokens: (prompt + completion) as u64,
last_prompt_tokens: last_prompt as u64,
tool_calls: tool_calls as u64,
by_session,
daily,
@@ -649,6 +763,49 @@ impl Store for SqliteStore {
Ok(())
}
fn notepad(&self, session_id: &str) -> Result<Vec<NotepadEntry>> {
let conn = self.lock();
let mut stmt = conn.prepare(
"SELECT key, text, updated_at FROM notepad_entries WHERE session_id = ?1 ORDER BY key ASC",
)?;
let rows = stmt.query_map(params![session_id], |r| {
Ok(NotepadEntry {
key: r.get(0)?,
text: r.get(1)?,
updated_at: r.get(2)?,
})
})?;
Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}
fn set_notepad_entry(&self, session_id: &str, key: &str, text: &str) -> Result<()> {
let conn = self.lock();
conn.execute(
"INSERT INTO notepad_entries (session_id, key, text, updated_at) VALUES (?1, ?2, ?3, ?4)
ON CONFLICT(session_id, key) DO UPDATE SET text = ?3, updated_at = ?4",
params![session_id, key, text, now_secs()],
)?;
Ok(())
}
fn remove_notepad_entry(&self, session_id: &str, key: &str) -> Result<bool> {
let conn = self.lock();
let n = conn.execute(
"DELETE FROM notepad_entries WHERE session_id = ?1 AND key = ?2",
params![session_id, key],
)?;
Ok(n > 0)
}
fn clear_notepad(&self, session_id: &str) -> Result<()> {
let conn = self.lock();
conn.execute(
"DELETE FROM notepad_entries WHERE session_id = ?1",
params![session_id],
)?;
Ok(())
}
fn save_upload(&self, meta: &UploadMeta) -> Result<()> {
let conn = self.lock();
conn.execute(
@@ -753,6 +910,7 @@ mod tests {
assert_eq!(stats.messages, 2);
assert_eq!(stats.prompt_tokens, 6);
assert_eq!(stats.completion_tokens, 5);
assert_eq!(stats.last_prompt_tokens, 3); // latest assistant turn, not the sum
s.delete_session(&sess.id).unwrap();
assert!(s.messages(&sess.id).unwrap().is_empty()); // cascade
@@ -802,6 +960,9 @@ mod tests {
assert_eq!(st.prompt_tokens, 24);
assert_eq!(st.completion_tokens, 5);
assert_eq!(st.total_tokens, 29);
// Current context tracks the latest assistant turn (Beta, pt=2), not
// the cumulative prompt sum (24) which re-counts every turn's window.
assert_eq!(st.last_prompt_tokens, 2);
assert_eq!(st.tool_calls, 2); // two calls inside Alpha's single turn
// Busiest first: Alpha (24 tokens) ahead of Beta (5).
assert_eq!(st.by_session.len(), 2);
@@ -907,6 +1068,7 @@ mod tests {
};
assert_eq!(has("settings_json"), 1);
assert_eq!(has("name_locked"), 1);
assert_eq!(has("window_start"), 1);
// The old system_prompt was backfilled into the settings instance.
let sj: String = conn
.query_row(
@@ -919,4 +1081,58 @@ mod tests {
// Idempotent: running again does not error.
migrate(&conn).unwrap();
}
#[test]
fn notepad_upsert_remove_clear_and_cascade() {
let s = store();
let sess = s
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
assert!(s.notepad(&sess.id).unwrap().is_empty());
s.set_notepad_entry(&sess.id, "goal", "ship the notepad")
.unwrap();
s.set_notepad_entry(&sess.id, "state", "coding").unwrap();
// Upsert by key replaces, does not duplicate.
s.set_notepad_entry(&sess.id, "goal", "ship + dogfood")
.unwrap();
let np = s.notepad(&sess.id).unwrap();
assert_eq!(np.len(), 2);
assert_eq!(np[0].key, "goal"); // ordered by key
assert_eq!(np[0].text, "ship + dogfood");
assert_eq!(np[1].key, "state");
assert!(s.remove_notepad_entry(&sess.id, "state").unwrap());
assert!(!s.remove_notepad_entry(&sess.id, "state").unwrap());
assert_eq!(s.notepad(&sess.id).unwrap().len(), 1);
s.clear_notepad(&sess.id).unwrap();
assert!(s.notepad(&sess.id).unwrap().is_empty());
// Per-session isolation + cascade on delete.
s.set_notepad_entry(&sess.id, "k", "v").unwrap();
let other = s
.create_session("Other", "m", &SessionSettings::default())
.unwrap();
assert!(s.notepad(&other.id).unwrap().is_empty());
s.delete_session(&sess.id).unwrap();
assert!(s.notepad(&sess.id).unwrap().is_empty());
}
#[test]
fn tool_use_section_includes_notepad_manual() {
let s = store();
let secs = s.context_sections().unwrap();
let tool_use = secs.iter().find(|x| x.name == "TOOL_USE").unwrap();
assert!(tool_use.content.contains("notepad("));
}
#[test]
fn window_start_default_and_roundtrip() {
let s = store();
let sess = s
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
assert_eq!(s.window_start(&sess.id).unwrap(), 0);
s.set_window_start(&sess.id, 42).unwrap();
assert_eq!(s.window_start(&sess.id).unwrap(), 42);
// Missing session -> 0, no panic.
assert_eq!(s.window_start("nope").unwrap(), 0);
}
}