Tag model-context turns with [SPEAKER: name - datetime] provenance; add global user-name setting (default User, read live), agent name = session title

This commit is contained in:
adm committed 2026-11-25 20:17:55 +01:00
1 parent 0754262b37
commit 95c41c2c21
8 files changed
+157 -5

No files matched your search

+136 -5
View File
@@ -242,6 +242,44 @@ fn text_message(role: Role, text: String) -> ChatMessage {
}
}
/// The `[SPEAKER: name - datetime]` line prefixed to a turn's content in the
/// model prompt (provenance), followed by a newline.
fn speaker_prefix(name: &str, secs: i64) -> String {
format!(
"{}\n",
t(
"speaker.tag",
&[("name", name), ("when", &format_utc(secs))]
)
)
}
/// Format unix seconds as a compact, unambiguous UTC datetime (no chrono dep).
fn format_utc(secs: i64) -> String {
let days = secs.div_euclid(86400);
let tod = secs.rem_euclid(86400);
let (y, m, d) = civil_from_days(days);
format!(
"{y:04}-{m:02}-{d:02} {:02}:{:02} UTC",
tod / 3600,
(tod % 3600) / 60
)
}
/// Days since 1970-01-01 -> (year, month, day). Howard Hinnant's algorithm.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719468;
let era = if z >= 0 { z } else { z - 146096 } / 146097;
let doe = z - era * 146097;
let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
(if m <= 2 { y + 1 } else { y }, m as u32, d as u32)
}
/// 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(
@@ -250,6 +288,7 @@ fn build_request(
body: &SessionChat,
extra: &str,
images: &[serde_json::Value],
user_name: &str,
) -> ChatRequest {
let mut messages = Vec::new();
// Structural identity reminder: always present, not an editable setting. It
@@ -258,12 +297,22 @@ fn build_request(
if let Some(folder) = &sess.folder {
identity.push_str(&t("identity.folder", &[("folder", folder)]));
}
identity.push_str(&t("speaker.note", &[]));
messages.push(text_message(Role::System, identity));
if let Some(sp) = &sess.settings.system_prompt {
messages.push(text_message(Role::System, sp.clone()));
}
for m in history {
let mut msg = text_message(role_of(&m.role), m.content.clone());
// Per-turn provenance for the model: [SPEAKER: name - datetime]. The
// human uses the global user name; the assistant uses the session name.
// Tool/system turns stay untagged. This annotates the prompt only —
// stored content stays clean (the GUI shows its own timestamp).
let content = match m.role.as_str() {
"user" => format!("{}{}", speaker_prefix(user_name, m.created_at), m.content),
"assistant" => format!("{}{}", speaker_prefix(&sess.title, m.created_at), m.content),
_ => m.content.clone(),
};
let mut msg = text_message(role_of(&m.role), content);
msg.tool_calls = m
.tool_calls_json
.as_deref()
@@ -273,7 +322,12 @@ fn build_request(
// The user turn: typed text + attachment context (inline files / path
// reminders / image markers). Images become multipart image_url parts that
// the Vision bridge materializes; without images it stays a plain string.
let user_text = format!("{}{}", body.content, extra);
let user_text = format!(
"{}{}{}",
speaker_prefix(user_name, now_unix() as i64),
body.content,
extra
);
if images.is_empty() {
messages.push(text_message(Role::User, user_text));
} else {
@@ -431,7 +485,18 @@ pub(crate) async fn session_chat(
}
let extra = uploads::context_text(&metas);
let images = uploads::image_parts(&metas);
let mut req = build_request(&sess, &history, &body, &extra, &images);
// The human speaker name is global and read live (the same person across
// every chat), not the session's copy-on-create snapshot. Empty -> "User".
let defaults = match with_store(&st, |s| s.get_defaults()).await {
Ok(d) => d,
Err(e) => return e.into_response(),
};
let user_name = defaults
.and_then(|d| d.user_name)
.map(|n| n.trim().to_string())
.filter(|n| !n.is_empty())
.unwrap_or_else(|| "User".to_string());
let mut req = build_request(&sess, &history, &body, &extra, &images, &user_name);
// Persist the user turn (text + attachment context) before generating.
let user_content = format!("{}{}", body.content, extra);
@@ -687,12 +752,78 @@ mod tests {
temperature: None,
top_p: None,
};
let req = build_request(&sess, &[], &body, "", &[]);
let req = build_request(&sess, &[], &body, "", &[], "Federico");
// Identity reminder first (name + folder), then the session SP, then user.
assert!(matches!(req.messages[0].role, Role::System));
let t0 = req.messages[0].text().unwrap();
assert!(t0.contains("Pippo") && t0.contains("/tmp/pippo"));
assert_eq!(req.messages[1].text().unwrap(), "sii breve");
assert!(matches!(req.messages.last().unwrap().role, Role::User));
let last = req.messages.last().unwrap();
assert!(matches!(last.role, Role::User));
// The new user turn carries the human speaker tag.
assert!(last.text().unwrap().starts_with("[SPEAKER: Federico - "));
assert!(last.text().unwrap().ends_with("ciao"));
}
#[test]
fn build_request_tags_history_with_speaker_and_time() {
let sess = Session {
id: "s".into(),
title: "Nebula".into(),
model: "m".into(),
settings: SessionSettings::default(),
name_locked: true,
folder: None,
created_at: 0,
updated_at: 0,
};
let history = vec![
StoredMessage {
id: 1,
role: "user".into(),
content: "domanda".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_000_000_000,
},
StoredMessage {
id: 2,
role: "assistant".into(),
content: "risposta".into(),
reasoning_content: None,
tool_calls_json: None,
tool_call_id: None,
prompt_tokens: 0,
completion_tokens: 0,
created_at: 1_000_000_001,
},
];
let body = SessionChat {
content: "ok".into(),
stream: false,
agent: false,
attachments: Vec::new(),
max_tokens: None,
temperature: None,
top_p: None,
};
let req = build_request(&sess, &history, &body, "", &[], "User");
// messages: [identity, user(history), assistant(history), user(new)]
let u = req.messages[1].text().unwrap();
assert!(u.starts_with("[SPEAKER: User - 2001-09-09 01:46 UTC]"));
assert!(u.ends_with("domanda"));
let a = req.messages[2].text().unwrap();
assert!(a.starts_with("[SPEAKER: Nebula - "));
assert!(a.ends_with("risposta"));
}
#[test]
fn format_utc_known_dates() {
assert_eq!(format_utc(0), "1970-01-01 00:00 UTC");
assert_eq!(format_utc(1_000_000_000), "2001-09-09 01:46 UTC");
assert_eq!(format_utc(951_782_400), "2000-02-29 00:00 UTC"); // leap day
}
}