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

+97 -15
View File
@@ -9,6 +9,7 @@
//! [`run_loop`] is pure orchestration — generic over the "model step" — so it is
//! testable without the engine and independent of the concrete runner.
pub mod notepad;
pub mod shell;
use std::future::Future;
@@ -25,9 +26,13 @@ use shell::{ShellRequest, ShellRunner};
/// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever.
pub const MAX_ITERS: usize = 24;
/// The tools offered to the agent (currently the universal `shell_exec`).
/// The tools offered to the agent: the universal `shell_exec` (action) and the
/// `notepad` (per-session context management).
pub fn agent_tools() -> Json {
json!([shell::shell_exec_declaration()])
json!([
shell::shell_exec_declaration(),
notepad::notepad_declaration()
])
}
/// Progress events streamed to the GUI for observability (no confirmation gate).
@@ -69,24 +74,29 @@ fn emit(progress: &Option<UnboundedSender<AgentEvent>>, ev: AgentEvent) {
/// `default_cwd` (the session's personal folder) is used when the model omits cwd.
async fn execute_tool(
runner: &Arc<dyn ShellRunner>,
store: &Arc<dyn Store>,
session_id: &str,
tc: &ToolCall,
default_cwd: Option<&str>,
) -> String {
if tc.function.name != "shell_exec" {
return format!("error: unknown tool '{}'", tc.function.name);
}
let args: Json = match serde_json::from_str(&tc.function.arguments) {
Ok(v) => v,
Err(e) => return format!("error: invalid tool arguments JSON: {e}"),
};
let req = match ShellRequest::from_args(&args) {
Ok(r) => r,
Err(e) => return format!("error: {e}"),
};
let cwd = req.cwd.as_deref().or(default_cwd);
match runner.run(&req.command, cwd, req.timeout).await {
Ok(out) => out.to_result_text(),
Err(e) => format!("error: {e}"),
match tc.function.name.as_str() {
"shell_exec" => {
let req = match ShellRequest::from_args(&args) {
Ok(r) => r,
Err(e) => return format!("error: {e}"),
};
let cwd = req.cwd.as_deref().or(default_cwd);
match runner.run(&req.command, cwd, req.timeout).await {
Ok(out) => out.to_result_text(),
Err(e) => format!("error: {e}"),
}
}
"notepad" => notepad::execute(store, session_id, &args).await,
other => format!("error: unknown tool '{other}'"),
}
}
@@ -219,7 +229,8 @@ where
arguments: tc.function.arguments.clone(),
},
);
let output = execute_tool(&runner, tc, default_cwd.as_deref()).await;
let output =
execute_tool(&runner, &store, session_id, tc, default_cwd.as_deref()).await;
emit(
&progress,
AgentEvent::ToolResult {
@@ -443,6 +454,14 @@ mod tests {
#[tokio::test]
async fn unknown_tool_yields_error_result() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session(
"Agent",
"test-model",
&crate::store::SessionSettings::default(),
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
let tc = ToolCall {
id: "c".into(),
@@ -452,10 +471,73 @@ mod tests {
arguments: "{}".into(),
},
};
let out = execute_tool(&runner, &tc, None).await;
let out = execute_tool(&runner, &store, &sess.id, &tc, None).await;
assert!(out.contains("unknown tool"));
}
#[tokio::test]
async fn loop_runs_notepad_tool_and_persists_entry() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session(
"Agent",
"test-model",
&crate::store::SessionSettings::default(),
)
.unwrap();
let runner: Arc<dyn ShellRunner> = Arc::new(HostShell);
let n = Arc::new(AtomicUsize::new(0));
let model = move |_req: ChatRequest| {
let n = n.clone();
async move {
if n.fetch_add(1, Ordering::SeqCst) == 0 {
Ok(response(
ChatMessage {
role: Role::Assistant,
content: None,
tool_call_id: None,
tool_calls: Some(vec![ToolCall {
id: "np1".into(),
kind: "function".into(),
function: FunctionCall {
name: "notepad".into(),
arguments: json!({"action":"set","key":"goal","text":"dogfood the notepad"}).to_string(),
},
}]),
name: None,
reasoning_content: None,
},
FinishReason::ToolCalls,
))
} else {
Ok(final_response())
}
}
};
run_loop(
model,
LoopContext {
runner,
store: store.clone(),
default_cwd: None,
max_iters: 8,
progress: None,
},
&sess.id,
base_req(),
)
.await
.unwrap();
// The entry is persisted per-session, and the tool result is in the trajectory.
let np = store.notepad(&sess.id).unwrap();
assert_eq!(np.len(), 1);
assert_eq!(np[0].key, "goal");
assert_eq!(np[0].text, "dogfood the notepad");
let msgs = store.messages(&sess.id).unwrap();
let tool = msgs.iter().find(|m| m.role == "tool").unwrap();
assert!(tool.content.contains("saved"), "{}", tool.content);
}
#[tokio::test]
async fn default_cwd_is_used_when_model_omits_it() {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
+243
View File
@@ -0,0 +1,243 @@
//! The agent's notepad tool: a persistent, per-session set of labelled entries
//! the agent curates so important state survives the sliding context window.
//!
//! One action-based tool (`set`/`remove`/`clear`); entries are addressed by a
//! stable `key` (upsert is idempotent, no shifting numeric indices). Bounded by a
//! char budget with a soft warning and a hard ceiling that asks the agent to
//! consolidate — nothing is evicted automatically (importance, not recency).
use std::sync::Arc;
use anyhow::Result;
use serde_json::{json, Value as Json};
use crate::store::Store;
/// Per-entry char cap (unicode-aware). Over-long entries are refused, not
/// silently truncated: the agent must keep notes short.
const MAX_ENTRY_CHARS: usize = 1024;
/// Total notepad char cap (hard ceiling). Over it, a `set` is refused and the
/// agent is asked to consolidate stale entries itself.
const MAX_TOTAL_CHARS: usize = 8000;
/// Soft warning threshold: near the ceiling, nudge consolidation.
const SOFT_WARN_CHARS: usize = 6000;
/// Max key length.
const MAX_KEY_CHARS: usize = 64;
/// The OpenAI function declaration offered to the model for the agent.
pub fn notepad_declaration() -> Json {
json!({
"type": "function",
"function": {
"name": "notepad",
"description": "Manage your persistent per-session notepad, always visible above \
the dialog. Pin durable task state that must survive the sliding context window: \
goal, decisions + rationale, current state/next step, constraints, pitfalls, key \
paths/identifiers. Entries are labelled by a stable key: action=set upserts by key \
(idempotent), remove deletes one entry, clear empties all. Keep entries short. Do \
NOT store long logs/documents or single-task ephemera. The notepad is bounded: \
near the limit, consolidate stale entries yourself — nothing is evicted automatically.",
"parameters": {
"type": "object",
"properties": {
"action": {
"type": "string",
"enum": ["set", "remove", "clear"],
"description": "set creates/updates entry `key`; remove deletes `key`; clear empties the notepad."
},
"key": {
"type": "string",
"description": "Stable label addressing the entry (required for set/remove), e.g. goal, state, decision:auth, pitfall:x, ref:path."
},
"text": {
"type": "string",
"description": "Short entry content (required for set, max 1024 chars)."
}
},
"required": ["action"]
}
}
})
}
/// Execute a notepad tool call against the store, returning the text the model
/// reads as the tool result. Store work runs off the async runtime.
pub async fn execute(store: &Arc<dyn Store>, session_id: &str, args: &Json) -> String {
let action = args
.get("action")
.and_then(|v| v.as_str())
.unwrap_or("")
.to_string();
let key = args
.get("key")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let text = args
.get("text")
.and_then(|v| v.as_str())
.unwrap_or("")
.trim()
.to_string();
let store = store.clone();
let sid = session_id.to_string();
let res = tokio::task::spawn_blocking(move || -> Result<String> {
match action.as_str() {
"set" => {
if key.is_empty() {
return Ok("error: notepad set requires a non-empty 'key'".into());
}
if key.chars().count() > MAX_KEY_CHARS {
return Ok(format!("error: key too long (max {MAX_KEY_CHARS} chars)"));
}
if key.contains('\n') {
return Ok("error: key must be a single line".into());
}
if text.is_empty() {
return Ok("error: notepad set requires non-empty 'text'".into());
}
let nlen = text.chars().count();
if nlen > MAX_ENTRY_CHARS {
return Ok(format!(
"error: entry too long ({nlen} > {MAX_ENTRY_CHARS} chars); shorten it"
));
}
let entries = store.notepad(&sid)?;
let others: usize = entries
.iter()
.filter(|e| e.key != key)
.map(|e| e.text.chars().count())
.sum();
let total = others + nlen;
if total > MAX_TOTAL_CHARS {
return Ok(format!(
"error: notepad full ({total} > {MAX_TOTAL_CHARS} chars). Remove or \
consolidate stale entries (notepad remove/clear), then retry. Nothing \
is evicted automatically."
));
}
store.set_notepad_entry(&sid, &key, &text)?;
let count = store.notepad(&sid)?.len();
let mut msg = format!(
"Entry '{key}' saved. Notepad: {count} entries, {total}/{MAX_TOTAL_CHARS} chars."
);
if total >= SOFT_WARN_CHARS {
msg.push_str(" Warning: nearing the limit — consolidate stale entries.");
}
Ok(msg)
}
"remove" => {
if key.is_empty() {
return Ok("error: notepad remove requires a non-empty 'key'".into());
}
let existed = store.remove_notepad_entry(&sid, &key)?;
if existed {
Ok(format!("Entry '{key}' removed."))
} else {
Ok(format!("No entry '{key}' (nothing removed)."))
}
}
"clear" => {
store.clear_notepad(&sid)?;
Ok("Notepad cleared.".into())
}
other => Ok(format!(
"error: unknown notepad action '{other}' (use set|remove|clear)"
)),
}
})
.await;
match res {
Ok(Ok(msg)) => msg,
Ok(Err(e)) => format!("error: {e}"),
Err(e) => format!("error: notepad task failed: {e}"),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::store::{SessionSettings, SqliteStore};
fn setup() -> (Arc<dyn Store>, String) {
let store: Arc<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
let sess = store
.create_session("Chat", "m", &SessionSettings::default())
.unwrap();
(store, sess.id)
}
#[tokio::test]
async fn set_upsert_remove_clear() {
let (store, sid) = setup();
let out = execute(
&store,
&sid,
&json!({"action":"set","key":"goal","text":"ship it"}),
)
.await;
assert!(out.contains("saved"), "{out}");
// Upsert by key replaces, does not duplicate.
execute(
&store,
&sid,
&json!({"action":"set","key":"goal","text":"ship + dogfood"}),
)
.await;
let np = store.notepad(&sid).unwrap();
assert_eq!(np.len(), 1);
assert_eq!(np[0].text, "ship + dogfood");
// Remove.
let out = execute(&store, &sid, &json!({"action":"remove","key":"goal"})).await;
assert!(out.contains("removed"), "{out}");
assert!(store.notepad(&sid).unwrap().is_empty());
// Clear.
execute(&store, &sid, &json!({"action":"set","key":"a","text":"x"})).await;
let out = execute(&store, &sid, &json!({"action":"clear"})).await;
assert!(out.contains("cleared"), "{out}");
assert!(store.notepad(&sid).unwrap().is_empty());
}
#[tokio::test]
async fn validation_and_budget() {
let (store, sid) = setup();
assert!(execute(&store, &sid, &json!({"action":"set","text":"x"}))
.await
.contains("key"));
assert!(execute(&store, &sid, &json!({"action":"set","key":"k"}))
.await
.contains("text"));
assert!(execute(&store, &sid, &json!({"action":"bogus"}))
.await
.contains("unknown"));
// Over-long entry is refused (not truncated).
let long = "a".repeat(MAX_ENTRY_CHARS + 1);
assert!(
execute(&store, &sid, &json!({"action":"set","key":"k","text":long}))
.await
.contains("too long")
);
// Hard ceiling: 7 * 1024 = 7168 fits; an 8th (8192) exceeds 8000 -> refused.
let big = "b".repeat(MAX_ENTRY_CHARS);
for i in 0..7 {
execute(
&store,
&sid,
&json!({"action":"set","key":format!("k{i}"),"text":big}),
)
.await;
}
let out = execute(&store, &sid, &json!({"action":"set","key":"k7","text":big})).await;
assert!(out.contains("full"), "{out}");
assert_eq!(store.notepad(&sid).unwrap().len(), 7);
}
#[test]
fn declaration_shape() {
let d = notepad_declaration();
assert_eq!(d["type"], "function");
assert_eq!(d["function"]["name"], "notepad");
assert_eq!(d["function"]["parameters"]["required"][0], "action");
}
}
+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).
+154 -28
View File
@@ -1,14 +1,15 @@
//! The context compositor: assembles the model prompt from named sections.
//!
//! Static sections (`SYSTEM_PROMPT`, `TOOL_USE`, …) live in the store and are
//! emitted wrapped in `<NAME>…</NAME>`; the interactive `DIALOG` region wraps the
//! real role messages (history + new turn) so the engine keeps its turn structure.
//! emitted wrapped in `<NAME>…</NAME>`; the interactive `DIALOG` region is an open
//! tail (opener `<DIALOG>`, no moving closer) around the real role messages, so the
//! engine keeps its turn structure and the prompt prefix stays stable for KV reuse.
//! Per-turn `[SPEAKER]` provenance and the server-local stamp are applied here,
//! prompt-only (stored content stays clean). Adding a section = adding a store row.
use crate::api::types::{now_unix, ChatMessage, Role};
use crate::i18n::t;
use crate::store::{ContextSection, Session, StoredMessage};
use crate::store::{ContextSection, NotepadEntry, Session, StoredMessage};
/// Compose the full context message list: static sections, then the DIALOG region.
/// `user_content` is the new turn's typed text plus attachment context.
@@ -19,34 +20,23 @@ pub fn compose(
images: &[serde_json::Value],
user_name: &str,
sections: &[ContextSection],
notepad: &[NotepadEntry],
) -> Vec<ChatMessage> {
let mut messages = Vec::new();
// Server-local timezone offset, computed once for every turn in this request.
let tz_offset = server_utc_offset_secs();
// Structural identity reminder (name + personal folder) and the speaker
// convention are injected into the SYSTEM_PROMPT template via placeholders.
let mut identity = t("identity.name", &[("name", &sess.title)]);
if let Some(folder) = &sess.folder {
identity.push_str(&t("identity.folder", &[("folder", folder)]));
}
let speaker_note = t("speaker.note", &[]);
let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default();
// Static context sections live in the store (editable without recompiling);
// each is emitted as a system message wrapped in its own <NAME> tag.
for sec in sections {
let rendered = sec
.content
.replace("{identity}", &identity)
.replace("{speaker_note}", &speaker_note)
.replace("{session_prompt}", &session_prompt);
messages.push(text_message(
Role::System,
format!("<{}>\n{}\n</{}>\n\n", sec.name, rendered, sec.name),
));
}
// The interactive region is its own section: opener/closer markers around the
// real role messages, which keep the engine's turn structure intact.
// Pinned prefix: static sections + notepad, always present above the window.
let mut messages = pinned_messages(sess, sections, notepad);
// The interactive region opens with <DIALOG> and is left OPEN: a trailing
// </DIALOG> after the last user turn would move every turn and break the
// engine's prefix checkpoint (RESUME 0). Role messages keep turn structure.
messages.push(text_message(Role::System, "<DIALOG>\n".to_string()));
// Static sliding-window marker: tells the model this is a window (older turns
// omitted), so it doesn't mistake the first visible turn for the chat's first
// message. STATIC text (no counts) -> stable prefix, cache-safe.
messages.push(text_message(
Role::System,
format!("{}\n\n", t("dialog.window_note", &[])),
));
for m in history {
// Per-turn provenance for the model: [SPEAKER: name - datetime]. The
// human uses the global user name; the assistant uses the session name.
@@ -94,7 +84,46 @@ pub fn compose(
reasoning_content: None,
});
}
messages.push(text_message(Role::System, "\n</DIALOG>\n\n".to_string()));
messages
}
/// The pinned prefix: static sections (placeholders rendered) + the notepad
/// block. Always present above the sliding DIALOG window. Extracted from
/// `compose` so the pinned prefix is a single reusable unit.
pub fn pinned_messages(
sess: &Session,
sections: &[ContextSection],
notepad: &[NotepadEntry],
) -> Vec<ChatMessage> {
let mut messages = Vec::new();
let mut identity = t("identity.name", &[("name", &sess.title)]);
if let Some(folder) = &sess.folder {
identity.push_str(&t("identity.folder", &[("folder", folder)]));
}
let speaker_note = t("speaker.note", &[]);
let session_prompt = sess.settings.system_prompt.clone().unwrap_or_default();
for sec in sections {
let rendered = sec
.content
.replace("{identity}", &identity)
.replace("{speaker_note}", &speaker_note)
.replace("{session_prompt}", &session_prompt);
messages.push(text_message(
Role::System,
format!("<{}>\n{}\n</{}>\n\n", sec.name, rendered, sec.name),
));
}
if !notepad.is_empty() {
let body = notepad
.iter()
.map(|e| format!("{}: {}", e.key, e.text.replace('\n', " ")))
.collect::<Vec<_>>()
.join("\n");
messages.push(text_message(
Role::System,
format!("<NOTEPAD>\n{body}\n</NOTEPAD>\n\n"),
));
}
messages
}
@@ -259,4 +288,101 @@ mod tests {
assert_eq!(parse_utc_offset("+0000"), Some(0));
assert_eq!(parse_utc_offset("nope"), None);
}
#[test]
fn compose_places_notepad_above_dialog() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: crate::store::SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let sections = vec![ContextSection {
name: "TOOL_USE".into(),
content: "manuale".into(),
position: 1,
}];
let notepad = vec![
NotepadEntry {
key: "goal".into(),
text: "ship it".into(),
updated_at: 0,
},
NotepadEntry {
key: "state".into(),
text: "coding\nnow".into(),
updated_at: 0,
},
];
let texts = |msgs: Vec<ChatMessage>| -> Vec<String> {
msgs.iter()
.map(|m| {
m.content
.as_ref()
.and_then(|c| c.as_str())
.unwrap_or("")
.to_string()
})
.collect()
};
let t = texts(compose(
&sess,
&[],
"ciao",
&[],
"Federico",
&sections,
&notepad,
));
let tool = t.iter().position(|x| x.starts_with("<TOOL_USE>")).unwrap();
let np = t.iter().position(|x| x.starts_with("<NOTEPAD>")).unwrap();
let dlg = t.iter().position(|x| x == "<DIALOG>\n").unwrap();
assert!(
tool < np && np < dlg,
"notepad must sit between TOOL_USE and DIALOG"
);
assert!(t[np].contains("goal: ship it"));
assert!(t[np].contains("state: coding now")); // newline normalized to one line
assert!(t[np].ends_with("</NOTEPAD>\n\n"));
// Empty notepad emits no section.
let t2 = texts(compose(&sess, &[], "ciao", &[], "Federico", &sections, &[]));
assert!(!t2.iter().any(|x| x.starts_with("<NOTEPAD>")));
}
#[test]
fn dialog_window_marker_is_static() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: crate::store::SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let sections = vec![ContextSection {
name: "TOOL_USE".into(),
content: "manuale".into(),
position: 1,
}];
let a = compose(&sess, &[], "ciao", &[], "Federico", &sections, &[]);
let b = compose(&sess, &[], "altro turno", &[], "Federico", &sections, &[]);
let da = a
.iter()
.position(|m| m.text().unwrap_or("") == "<DIALOG>\n")
.unwrap();
let db = b
.iter()
.position(|m| m.text().unwrap_or("") == "<DIALOG>\n")
.unwrap();
// A static system marker sits right after the opener, identical across turns.
assert!(matches!(a[da + 1].role, Role::System));
assert!(a[da + 1].text().unwrap().ends_with("\n\n"));
assert_eq!(a[da + 1].text().unwrap(), b[db + 1].text().unwrap());
}
}
+2
View File
@@ -7,6 +7,7 @@
//! a swappable `Store` trait).
//! - [`render`]: safe Markdown + LaTeX → HTML for assistant messages.
//! - [`context`]: the context compositor (named sections + DIALOG) for the prompt.
//! - [`window`]: the sliding DIALOG window (token budget, stepped KV-cache eviction).
pub mod agent;
pub mod api;
@@ -18,3 +19,4 @@ pub mod inkling;
pub mod name;
pub mod render;
pub mod store;
pub mod window;
+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);
}
}
+173
View File
@@ -0,0 +1,173 @@
//! The sliding DIALOG window: retains the most recent messages by COUNT, with
//! stepped (hysteresis) eviction so the retained prefix stays byte-stable across
//! turns for engine KV-cache reuse.
//!
//! Two tiers, in messages: a MAIN area of the most recent turns always retained,
//! plus a BUFFER of headroom above it. Between evictions the window is append-only
//! (new turns join the tail) while the buffer fills, so the prompt prefix is
//! identical turn-to-turn and the engine reuses its cached KV. When occupancy
//! crosses MAIN + BUFFER the buffer is cleared: the start advances in chunks to
//! USER-message boundaries (never splitting a tool_call/tool_result exchange)
//! down to MAIN, and a new buffer starts filling. This amortizes one re-prefill
//! over several turns. The full history is never deleted — evicted turns stay
//! recallable from the store, and the agent pins what matters in the notepad.
//!
//! A total-SIZE (char/token) cut is deliberately deferred: it interacts with the
//! stepped anchor and is not as simple as adding a second cap.
use crate::store::StoredMessage;
/// Main dialogic area: the most recent messages always retained. This is the
/// low-water mark the window drops to after an eviction.
pub const MAIN_AREA: usize = 40;
/// Buffer headroom above the main area. While the retained count is at most
/// MAIN_AREA + BUFFER the window is append-only; crossing it clears the buffer
/// (evict down to MAIN_AREA) and starts a new one.
pub const BUFFER: usize = 10;
/// The window selection: where the retained history suffix begins.
pub struct Selection {
/// Index into `history` where the retained suffix starts.
pub start: usize,
/// Message id to persist as the session's window start (a user-turn id).
pub start_id: i64,
}
/// Select the retained history suffix by message count: keep the most recent
/// MAIN_AREA messages, allowing BUFFER headroom to accumulate append-only before
/// a stepped eviction. `window_start` is the persisted first-retained message id
/// (0 = from the beginning).
pub fn select(history: &[StoredMessage], window_start: i64) -> Selection {
if history.is_empty() {
return Selection {
start: 0,
start_id: window_start.max(0),
};
}
let cost = |s: usize| history[s..].len();
// Current start: first message at/after the persisted window start.
let mut start = history
.iter()
.position(|m| m.id >= window_start)
.unwrap_or(0);
// Append-only while the buffer has room: the prefix stays stable (KV hit).
if cost(start) <= MAIN_AREA + BUFFER {
return Selection {
start,
start_id: history[start].id,
};
}
// Buffer full: clear it down to the main area, advancing to successive
// user-turn boundaries. Never split an exchange; always keep at least the
// most recent user-initiated turn.
let last_user = history
.iter()
.rposition(|m| m.role == "user")
.unwrap_or(start);
while start < last_user && cost(start) > MAIN_AREA {
match history[start + 1..].iter().position(|m| m.role == "user") {
Some(off) => start += off + 1,
None => break,
}
}
Selection {
start,
start_id: history[start].id,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn msg(id: i64, role: &str) -> StoredMessage {
StoredMessage {
id,
role: role.into(),
content: "x".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: id,
}
}
/// `n` messages, ids 1..=n, alternating user (odd) / assistant (even).
fn exchanges(n: usize) -> Vec<StoredMessage> {
(1..=n as i64)
.map(|id| msg(id, if id % 2 == 1 { "user" } else { "assistant" }))
.collect()
}
#[test]
fn under_trigger_is_append_only() {
let h = exchanges(10);
let sel = select(&h, 0);
assert_eq!(sel.start, 0);
assert_eq!(sel.start_id, 1);
}
#[test]
fn buffer_fills_then_clears_to_main() {
// 51 messages > MAIN(40) + BUFFER(10) = 50 -> clear down to <= 40.
let h = exchanges(51);
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
assert!(h[sel.start..].len() <= MAIN_AREA);
assert!(sel.start > 0);
}
#[test]
fn eviction_snaps_to_user_boundary() {
let h = exchanges(60);
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
// 60 - start <= 40 -> start >= 20; id 21 is a user turn.
assert_eq!(sel.start, 20);
assert_eq!(sel.start_id, 21);
}
#[test]
fn never_starts_mid_tool_exchange() {
let mut h = exchanges(60);
// Turn id 20 into an assistant tool_call and id 21 into its tool result,
// so the cut must skip past them to the next user turn (id 23).
h[19].role = "assistant".into();
h[19].tool_calls_json = Some(r#"[{"id":"c1"}]"#.into());
h[20].role = "tool".into();
let sel = select(&h, 0);
assert_eq!(h[sel.start].role, "user");
assert_eq!(sel.start_id, 23);
}
#[test]
fn persisted_start_is_respected_append_only() {
let h = exchanges(10);
// window_start = 7 retains ids 7..10 (4 messages) <= 50 -> unchanged.
let sel = select(&h, 7);
assert_eq!(sel.start, 6);
assert_eq!(sel.start_id, 7);
}
#[test]
fn never_evicts_past_the_last_user_turn() {
// 55 messages, user only at the very start and the very end: the guard
// keeps the latest user turn even though dropping to MAIN would pass it.
let mut h = exchanges(55);
for m in h.iter_mut().take(54).skip(1) {
m.role = "assistant".into();
}
let sel = select(&h, 0);
assert_eq!(sel.start_id, 55);
assert_eq!(h[sel.start].role, "user");
}
#[test]
fn empty_history_is_safe() {
let sel = select(&[], 7);
assert_eq!(sel.start, 0);
assert_eq!(sel.start_id, 7);
}
}