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

+166 -28
View File
@@ -29,8 +29,9 @@ use crate::i18n::t;
use crate::name;
use crate::render;
use crate::store::{
ContextSection, NewMessage, Session, SessionSettings, Stats, Store, StoredMessage,
ContextSection, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store, StoredMessage,
};
use crate::window;
use tokio_stream::wrappers::UnboundedReceiverStream;
/// Run a synchronous store operation off the async runtime.
@@ -197,12 +198,33 @@ pub(crate) struct MessageView {
content_html: Option<String>,
}
/// The GUI transcript payload: the sliding-window messages (the same recent view
/// the model sees) plus metadata so the UI can tell the user older turns are
/// omitted but preserved. The full history is never shipped to the browser — an
/// agent active for months could accumulate tens of millions of tokens.
#[derive(Serialize)]
pub(crate) struct MessagesView {
messages: Vec<MessageView>,
/// First retained message id (the persisted window start; 0 = from the start).
window_start: i64,
/// Total stored messages; exceeds `messages.len()` when older turns slid out.
total: u64,
}
pub(crate) async fn get_messages(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<MessageView>>, Error> {
let msgs = with_store(&st, move |s| s.messages(&id)).await?;
let views = msgs
) -> Result<Json<MessagesView>, Error> {
// The browser sees the SAME sliding window the model sees: only messages at
// or after the persisted window start, filtered in SQL (the full history is
// never loaded whole). Older turns stay in the store for a future export.
let (msgs, total, window_start) = with_store(&st, move |s| {
let ws = s.window_start(&id)?;
let (m, total) = s.message_window(&id, ws)?;
Ok((m, total, ws))
})
.await?;
let messages = msgs
.into_iter()
.map(|mut m| {
// The [SPEAKER] tag is model-context metadata; if a reply echoed it,
@@ -218,7 +240,20 @@ pub(crate) async fn get_messages(
}
})
.collect();
Ok(Json(views))
Ok(Json(MessagesView {
messages,
window_start,
total,
}))
}
/// `GET /api/sessions/{id}/notepad` — the session's pinned notepad entries
/// (read-only observability; the agent writes them via the notepad tool).
pub(crate) async fn get_notepad(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<NotepadEntry>>, Error> {
Ok(Json(with_store(&st, move |s| s.notepad(&id)).await?))
}
/// The stats dashboard payload: persistent history aggregates (from the store)
@@ -253,6 +288,15 @@ pub(crate) async fn stats(State(st): State<AppState>) -> Result<Json<StatsRespon
}))
}
/// Ambient context inputs resolved from the store + global defaults for one
/// turn: the human speaker name, the static sections and the session notepad.
/// Bundled so `build_request` stays within the argument-count lint.
struct Ambient<'a> {
user_name: &'a str,
sections: &'a [ContextSection],
notepad: &'a [NotepadEntry],
}
/// Rebuild a stateless [`ChatRequest`] from the stored history plus the new turn.
/// Prior `reasoning_content` is deliberately NOT replayed into the prompt.
fn build_request(
@@ -261,11 +305,18 @@ fn build_request(
body: &SessionChat,
extra: &str,
images: &[serde_json::Value],
user_name: &str,
sections: &[ContextSection],
ambient: Ambient<'_>,
) -> ChatRequest {
let user_content = format!("{}{}", body.content, extra);
let messages = context::compose(sess, history, &user_content, images, user_name, sections);
let messages = context::compose(
sess,
history,
&user_content,
images,
ambient.user_name,
ambient.sections,
ambient.notepad,
);
ChatRequest {
model: sess.model.clone(),
messages,
@@ -424,12 +475,51 @@ pub(crate) async fn session_chat(
Ok(v) => v,
Err(e) => return e.into_response(),
};
let notepad = match with_store(&st, {
let id = id.clone();
move |s| s.notepad(&id)
})
.await
{
Ok(v) => v,
Err(e) => return e.into_response(),
};
// Sliding DIALOG window: retain the most recent messages by COUNT (main area
// + buffer headroom), with stepped eviction so the prefix stays byte-stable
// for KV-cache reuse. Full history stays in SQLite; the agent pins what
// matters in the notepad. A total-size (char/token) cut is deferred.
let user_content = format!("{}{}", body.content, extra);
let window_start = match with_store(&st, {
let id = id.clone();
move |s| s.window_start(&id)
})
.await
{
Ok(v) => v,
Err(e) => return e.into_response(),
};
let sel = window::select(&history, window_start);
if sel.start_id != window_start {
let start_id = sel.start_id;
let idc = id.clone();
if let Err(e) = with_store(&st, move |s| s.set_window_start(&idc, start_id)).await {
return e.into_response();
}
}
let mut req = build_request(
&sess, &history, &body, &extra, &images, &user_name, &sections,
&sess,
&history[sel.start..],
&body,
&extra,
&images,
Ambient {
user_name: &user_name,
sections: &sections,
notepad: &notepad,
},
);
// Persist the user turn (text + attachment context) before generating.
let user_content = format!("{}{}", body.content, extra);
if let Err(e) = with_store(&st, {
let id = id.clone();
move |s| {
@@ -707,8 +797,19 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body, "", &[], "Federico", &[sp_section()]);
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG markers around turns.
let req = build_request(
&sess,
&[],
&body,
"",
&[],
Ambient {
user_name: "Federico",
sections: &[sp_section()],
notepad: &[],
},
);
// SYSTEM_PROMPT section wraps identity + session SP; DIALOG opens (no closer).
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
assert!(t0.starts_with("<SYSTEM_PROMPT>"));
@@ -716,15 +817,17 @@ mod tests {
assert!(t0.contains("sii breve"));
assert!(t0.ends_with("</SYSTEM_PROMPT>\n\n"));
assert_eq!(req.messages[1].text().unwrap(), "<DIALOG>\n");
let user = &req.messages[req.messages.len() - 2];
let user = &req.messages[req.messages.len() - 1];
assert!(matches!(user.role, Role::User));
// The new user turn carries the human speaker tag.
assert!(user.text().unwrap().starts_with("[SPEAKER: Federico - "));
assert!(user.text().unwrap().ends_with("ciao"));
assert_eq!(
req.messages.last().unwrap().text().unwrap(),
"\n</DIALOG>\n\n"
);
// DIALOG stays open: no moving </DIALOG> closer (it would break the
// engine's prefix checkpoint every user turn).
assert!(!req
.messages
.iter()
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
}
fn sp_section() -> ContextSection {
@@ -780,12 +883,23 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
// messages: [SYSTEM_PROMPT, <DIALOG>, user(hist), assistant(hist), user(new), </DIALOG>]
let u = req.messages[2].text().unwrap();
let req = build_request(
&sess,
&history,
&body,
"",
&[],
Ambient {
user_name: "User",
sections: &[sp_section()],
notepad: &[],
},
);
// messages: [SYSTEM_PROMPT, <DIALOG>, window-marker, user(hist), assistant(hist), user(new)]
let u = req.messages[3].text().unwrap();
assert!(u.starts_with("[SPEAKER: User - "));
assert!(u.ends_with("domanda"));
let a = req.messages[3].text().unwrap();
let a = req.messages[4].text().unwrap();
assert!(a.starts_with("[SPEAKER: Nebula - "));
assert!(a.ends_with("risposta"));
}
@@ -822,8 +936,19 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &history, &body, "", &[], "User", &[sp_section()]);
let a = req.messages[2].text().unwrap();
let req = build_request(
&sess,
&history,
&body,
"",
&[],
Ambient {
user_name: "User",
sections: &[sp_section()],
notepad: &[],
},
);
let a = req.messages[3].text().unwrap();
assert_eq!(a.matches("[SPEAKER:").count(), 1, "exactly one tag: {a}");
assert!(a.ends_with("risposta"));
}
@@ -857,7 +982,18 @@ mod tests {
position: 1,
},
];
let req = build_request(&sess, &[], &body, "", &[], "User", &sections);
let req = build_request(
&sess,
&[],
&body,
"",
&[],
Ambient {
user_name: "User",
sections: &sections,
notepad: &[],
},
);
assert!(req.messages[0]
.text()
.unwrap()
@@ -871,9 +1007,11 @@ mod tests {
"<TOOL_USE>\nmanuale\n</TOOL_USE>\n\n"
);
assert_eq!(req.messages[2].text().unwrap(), "<DIALOG>\n");
assert_eq!(
req.messages.last().unwrap().text().unwrap(),
"\n</DIALOG>\n\n"
);
// The new user turn is last; DIALOG is left open (no moving closer).
assert!(matches!(req.messages.last().unwrap().role, Role::User));
assert!(!req
.messages
.iter()
.any(|m| m.text().unwrap_or("").contains("</DIALOG>")));
}
}