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:
1 parent
7c945890f4
commit
0ce84581a4
20 files changed
+1412
-118
No files matched your search
+154
-28
@@ -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",
|
||||
§ions,
|
||||
¬epad,
|
||||
));
|
||||
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", §ions, &[]));
|
||||
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", §ions, &[]);
|
||||
let b = compose(&sess, &[], "altro turno", &[], "Federico", §ions, &[]);
|
||||
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());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user