diff --git a/locales/en.json b/locales/en.json index a4712a3..60c9756 100644 --- a/locales/en.json +++ b/locales/en.json @@ -1,6 +1,8 @@ { "identity.name": "Your name is {name}.", "identity.folder": " Your personal folder is {folder}.", + "speaker.tag": "[SPEAKER: {name} - {when}]", + "speaker.note": " User and agent turns are prefixed with a [SPEAKER: name - date and time UTC] tag identifying who generated them and when.", "error.name_locked": "The session name is immutable after the first interaction.", "error.name_empty": "The name must not be empty.", "error.session_not_found": "Session not found.", diff --git a/locales/it.json b/locales/it.json index 396b8fd..d0615b9 100644 --- a/locales/it.json +++ b/locales/it.json @@ -1,6 +1,8 @@ { "identity.name": "Il tuo nome è {name}.", "identity.folder": " La tua cartella personale è {folder}.", + "speaker.tag": "[SPEAKER: {name} - {when}]", + "speaker.note": " I turni dell'utente e dell'agente sono preceduti da un tag [SPEAKER: nome - data e ora UTC] che identifica chi li ha generati e quando.", "error.name_locked": "Il nome della sessione è immutabile dopo la prima interazione.", "error.name_empty": "Il nome non può essere vuoto.", "error.session_not_found": "Sessione non trovata.", diff --git a/src/api/sessions.rs b/src/api/sessions.rs index 11dd562..064b307 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -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 } } diff --git a/src/store.rs b/src/store.rs index fde91fa..13b8a00 100644 --- a/src/store.rs +++ b/src/store.rs @@ -29,6 +29,12 @@ pub struct SessionSettings { /// Free-form user notes describing the purpose of this chat. #[serde(default)] pub notes: Option, + /// The human speaker's name, shown to the model in per-turn [SPEAKER: …] + /// tags. Global-authoritative: read live from the global defaults at turn + /// time (the per-session copy is inert), so it applies to every chat. + /// Absent/empty -> "User". + #[serde(default)] + pub user_name: Option, #[serde(default)] pub temperature: Option, #[serde(default)] @@ -57,6 +63,7 @@ impl SessionSettings { SessionSettings { system_prompt: self.system_prompt.clone().or(base.system_prompt.clone()), notes: self.notes.clone().or(base.notes.clone()), + user_name: self.user_name.clone().or(base.user_name.clone()), temperature: self.temperature.or(base.temperature), top_p: self.top_p.or(base.top_p), top_k: self.top_k.or(base.top_k), diff --git a/web/assets/app.js b/web/assets/app.js index ae606fc..77bed4a 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -629,6 +629,8 @@ function fillSettingsForm(data, scope) { const isSession = scope === "session"; $("#set-name-field").hidden = !isSession; $("#set-name-hint").hidden = !isSession; + $("#set-username-field").hidden = isSession; + $("#set-username").value = data.user_name || ""; if (isSession) { const sess = currentSession(); $("#set-name").value = sess ? sess.title : ""; @@ -654,6 +656,7 @@ function readSettingsForm() { const num = (v) => (v === "" ? null : Number(v)); const txt = (v) => (v.trim() === "" ? null : v); return { + user_name: txt($("#set-username").value), notes: txt($("#set-notes").value), system_prompt: txt($("#set-sp").value), temperature: num($("#set-temp").value), diff --git a/web/assets/locales/en.json b/web/assets/locales/en.json index 9ee07cc..54d95d0 100644 --- a/web/assets/locales/en.json +++ b/web/assets/locales/en.json @@ -3,6 +3,8 @@ "settings.title.general": "General settings", "settings.scope.session": "Session", "settings.scope.general": "General", + "settings.username": "User name", + "settings.username.ph": "User", "settings.name": "Name", "settings.notes": "Notes (chat purpose)", "settings.sp": "System Prompt", diff --git a/web/assets/locales/it.json b/web/assets/locales/it.json index efa308a..a610068 100644 --- a/web/assets/locales/it.json +++ b/web/assets/locales/it.json @@ -3,6 +3,8 @@ "settings.title.general": "Impostazioni generali", "settings.scope.session": "Sessione", "settings.scope.general": "Generali", + "settings.username": "Nome utente", + "settings.username.ph": "User", "settings.name": "Nome", "settings.notes": "Note (scopo della chat)", "settings.sp": "System Prompt", diff --git a/web/index.html b/web/index.html index 5df7678..5835e88 100644 --- a/web/index.html +++ b/web/index.html @@ -81,6 +81,9 @@

+