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

+68 -7
View File
@@ -15,7 +15,7 @@ use strata_ctl::api::service::ChatService;
use strata_ctl::api::types::{ApiErrorEnvelope, ChatRequest};
use strata_ctl::api::{router_with_store, AuthConfig};
use strata_ctl::engine::Engine;
use strata_ctl::store::{SqliteStore, Store};
use strata_ctl::store::{NewMessage, SqliteStore, Store};
const MOCK: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/tests/mock_engine.py");
@@ -143,8 +143,10 @@ async fn session_holds_context_and_persists_usage() {
)
.await;
assert_eq!(st, StatusCode::OK);
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 2);
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 2);
assert_eq!(v["total"], 2);
assert_eq!(msgs[0]["role"], "user");
assert_eq!(msgs[0]["content"], "hi");
assert_eq!(msgs[1]["role"], "assistant");
@@ -167,8 +169,10 @@ async fn session_holds_context_and_persists_usage() {
None,
)
.await;
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 4);
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 4);
assert_eq!(v["total"], 4);
assert_eq!(msgs[2]["content"], "again");
// Stats aggregate across the session.
@@ -232,12 +236,69 @@ async fn session_stream_persists_and_ends_with_done() {
None,
)
.await;
let msgs: serde_json::Value = serde_json::from_str(&text).unwrap();
assert_eq!(msgs.as_array().unwrap().len(), 2);
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
let msgs = v["messages"].as_array().unwrap();
assert_eq!(msgs.len(), 2);
assert_eq!(msgs[1]["content"], "efghi");
assert_eq!(msgs[1]["completion_tokens"], 5);
}
#[tokio::test]
async fn messages_endpoint_returns_only_the_sliding_window() {
let (app, store) = build_app().await;
let id = create_session(&app).await;
// Seed a long history directly (60 messages, alternating user/assistant).
for i in 0..60 {
store
.append_message(
&id,
NewMessage {
role: if i % 2 == 0 { "user" } else { "assistant" },
content: "x",
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
},
)
.unwrap();
}
// One chat turn runs window::select over the 60-message history and persists
// the evicted start — the model's window. The GUI must see that same window.
let (st, _) = req(
&app,
Method::POST,
&format!("/api/sessions/{id}/chat"),
Some(serde_json::json!({"content": "hi"})),
)
.await;
assert_eq!(st, StatusCode::OK);
let (_, text) = req(
&app,
Method::GET,
&format!("/api/sessions/{id}/messages"),
None,
)
.await;
let v: serde_json::Value = serde_json::from_str(&text).unwrap();
let msgs = v["messages"].as_array().unwrap();
let total = v["total"].as_u64().unwrap();
assert_eq!(total, 62); // 60 seeded + the new user + assistant turns
// Bounded window (MAIN_AREA + BUFFER), never the whole history.
assert!(
msgs.len() <= 50,
"window must be bounded, got {}",
msgs.len()
);
assert!(msgs.len() < total as usize);
// The window snaps to a user-turn boundary (never mid-exchange).
assert_eq!(msgs[0]["role"], "user");
// The full history is still in the store — nothing was deleted.
assert_eq!(store.messages(&id).unwrap().len(), 62);
}
#[tokio::test]
async fn gui_is_served_and_delete_cascades() {
let (app, store) = build_app().await;
+4 -2
View File
@@ -143,10 +143,12 @@ fn real_prompt_closes_sections_with_blank_line() {
position: 1,
},
];
let msgs = context::compose(&sess, &[], "ciao", &[], "Federico", &sections);
let msgs = context::compose(&sess, &[], "ciao", &[], "Federico", &sections, &[]);
let val = serde_json::to_value(&msgs).unwrap();
let out = t.render(&val, None, Some("low")).unwrap();
assert!(out.contains("</SYSTEM_PROMPT>\n\n"), "{out}");
assert!(out.contains("</TOOL_USE>\n\n"), "{out}");
assert!(out.contains("</DIALOG>"), "{out}");
// DIALOG is an open tail: opener present, no moving closer (KV-cache prefix).
assert!(out.contains("<DIALOG>"), "{out}");
assert!(!out.contains("</DIALOG>"), "DIALOG must stay open: {out}");
}