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

+1
View File
@@ -79,6 +79,7 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router {
.patch(sessions::patch_session),
)
.route("/api/sessions/{id}/messages", get(sessions::get_messages))
.route("/api/sessions/{id}/notepad", get(sessions::get_notepad))
.route("/api/sessions/{id}/chat", post(sessions::session_chat))
.route(
"/api/uploads",
+29 -4
View File
@@ -58,7 +58,10 @@ impl PerfMeter {
self.decode_ms += d;
}
if let Some(p) = u.prompt_ms.filter(|p| *p > 0.0) {
self.prompt_tokens += u.prompt_tokens as u64;
// prompt_ms covers only the tokens actually prefilled (RESUME excluded),
// so gauge throughput over the non-cached tokens, not the total prompt.
self.prompt_tokens +=
u.prompt_tokens.saturating_sub(u.cached_tokens.unwrap_or(0)) as u64;
self.prompt_ms += p;
}
}
@@ -308,7 +311,10 @@ impl ChatService {
.and_then(|o| o.done.as_ref())
.map(|d| (Some(d.prompt_ms), Some(d.decode_ms)))
.unwrap_or((None, None));
let usage = Usage::new(prompt_len, completion).with_timings(pms, dms);
let resumed = gen.as_ref().ok().map(|o| o.resumed).unwrap_or(0);
let usage = Usage::new(prompt_len, completion)
.with_timings(pms, dms)
.with_cached(resumed);
perf.lock()
.unwrap_or_else(|e| e.into_inner())
.record(&usage);
@@ -462,8 +468,9 @@ fn finish_reason(outcome: &Outcome, max_new: u32) -> FinishReason {
fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
match &outcome.done {
Some(d) => Usage::new(d.prompt_tokens.max(prompt_len), d.generated.max(completion))
.with_timings(Some(d.prompt_ms), Some(d.decode_ms)),
None => Usage::new(prompt_len, completion),
.with_timings(Some(d.prompt_ms), Some(d.decode_ms))
.with_cached(outcome.resumed),
None => Usage::new(prompt_len, completion).with_cached(outcome.resumed),
}
}
@@ -493,4 +500,22 @@ mod tests {
}
assert!(!p.exists(), "guard must remove the file on drop");
}
#[test]
fn usage_of_carries_cache_hits() {
let out = Outcome {
tokens: vec![1, 2, 3],
done: None,
resumed: 80,
};
let u = usage_of(&out, 100, 3);
assert_eq!(u.prompt_tokens, 100);
assert_eq!(u.cached_tokens, Some(80));
let cold = Outcome {
tokens: vec![],
done: None,
resumed: 0,
};
assert_eq!(usage_of(&cold, 50, 0).cached_tokens, None);
}
}
+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>")));
}
}
+12
View File
@@ -157,6 +157,10 @@ pub struct Usage {
/// Engine decode time (ms), when reported.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub decode_ms: Option<f64>,
/// Prompt tokens served from the engine's conversation cache (`RESUME`),
/// not re-prefilled. Non-standard extra; the GUI shows it to gauge reuse.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub cached_tokens: Option<u32>,
}
impl Usage {
@@ -167,6 +171,7 @@ impl Usage {
total_tokens: prompt_tokens + completion_tokens,
prompt_ms: None,
decode_ms: None,
cached_tokens: None,
}
}
@@ -176,6 +181,13 @@ impl Usage {
self.decode_ms = decode_ms.filter(|v| *v > 0.0);
self
}
/// Attach the engine's cache-hit count (`RESUME`): prompt tokens reused from
/// the conversation cache instead of re-prefilled. 0 -> absent.
pub fn with_cached(mut self, cached: u32) -> Self {
self.cached_tokens = (cached > 0).then_some(cached);
self
}
}
/// Why generation stopped (OpenAI spelling).