diff --git a/locales/en.json b/locales/en.json index 82fda26..3a2f96c 100644 --- a/locales/en.json +++ b/locales/en.json @@ -2,7 +2,7 @@ "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 - local date and time] tag identifying who generated them and when.", + "speaker.note": " User and agent turns are prefixed with a [SPEAKER: name - local date and time] tag identifying who generated them and when. It is framework-added metadata: never write or repeat it in your own replies.", "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 a856641..7ecac95 100644 --- a/locales/it.json +++ b/locales/it.json @@ -2,7 +2,7 @@ "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 locale] che identifica chi li ha generati e quando.", + "speaker.note": " I turni dell'utente e dell'agente sono preceduti da un tag [SPEAKER: nome - data e ora locale] che identifica chi li ha generati e quando. È un metadato aggiunto dal framework: non scriverlo né ripeterlo mai nelle tue risposte.", "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 df6b01d..d7a07e5 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -201,7 +201,12 @@ pub(crate) async fn get_messages( let msgs = with_store(&st, move |s| s.messages(&id)).await?; let views = msgs .into_iter() - .map(|m| { + .map(|mut m| { + // The [SPEAKER] tag is model-context metadata; if a reply echoed it, + // hide it from the GUI (and from the rendered HTML). + if m.role == "assistant" { + m.content = strip_speaker_tags(&m.content); + } let content_html = (m.role == "assistant" && !m.content.is_empty()) .then(|| render::markdown_to_safe_html(&m.content)); MessageView { @@ -278,6 +283,50 @@ fn speaker_prefix(name: &str, secs: i64, offset: i64) -> String { ) } +/// Remove leading `[SPEAKER: name - YYYY-MM-DD HH:MM]` tag(s) a model may have +/// echoed into its own reply. The tag is framework metadata for the prompt, not +/// reply text: stripping keeps stored/displayed content clean and breaks the +/// history feedback loop that would otherwise stack a second tag each turn. +fn strip_speaker_tags(content: &str) -> String { + let mut rest = content; + let mut stripped = false; + loop { + let t = rest.trim_start(); + if !t.starts_with("[SPEAKER:") { + break; + } + let Some(end) = t.find(']') else { break }; + let inner = &t[..end]; + let Some(dash) = inner.rfind(" - ") else { + break; + }; + if !looks_like_stamp(&inner[dash + 3..]) { + break; + } + rest = &t[end + 1..]; + stripped = true; + } + if stripped { + rest.trim_start().to_string() + } else { + content.to_string() + } +} + +/// Whether `s` is exactly `YYYY-MM-DD HH:MM` (the speaker tag's stamp shape). +fn looks_like_stamp(s: &str) -> bool { + let b = s.as_bytes(); + if b.len() != 16 { + return false; + } + b.iter().enumerate().all(|(i, c)| match i { + 4 | 7 => *c == b'-', + 10 => *c == b' ', + 13 => *c == b':', + _ => c.is_ascii_digit(), + }) +} + /// Format unix seconds as `YYYY-MM-DD HH:MM` in the server's local timezone /// (`offset` seconds east of UTC). Dependency-free civil-date arithmetic. fn format_stamp(secs: i64, offset: i64) -> String { @@ -363,18 +412,21 @@ fn build_request( // 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). + // Strip any tag the model echoed into stored content so we never stack + // a second [SPEAKER] on top of one (the duplication feedback loop). + let clean = strip_speaker_tags(&m.content); let content = match m.role.as_str() { "user" => format!( "{}{}", speaker_prefix(user_name, m.created_at, tz_offset), - m.content + clean ), "assistant" => format!( "{}{}", speaker_prefix(&sess.title, m.created_at, tz_offset), - m.content + clean ), - _ => m.content.clone(), + _ => clean, }; let mut msg = text_message(role_of(&m.role), content); msg.tool_calls = m @@ -634,8 +686,9 @@ pub(crate) async fn session_chat( index: 0, message: ChatMessage { role: Role::Assistant, - content: (!acc.content.is_empty()) - .then_some(serde_json::Value::String(acc.content)), + content: (!acc.content.is_empty()).then(|| { + serde_json::Value::String(strip_speaker_tags(&acc.content)) + }), tool_call_id: None, tool_calls: has_tools.then_some(tools), name: None, @@ -785,7 +838,7 @@ async fn persist_assistant(store: &Arc, sid: &str, a: &Accum, prompt_ .as_ref() .map(|u| (u.prompt_tokens, u.completion_tokens)) .unwrap_or((prompt_len, 0)); - let content = a.content.clone(); + let content = strip_speaker_tags(&a.content); let reasoning = if a.reasoning.is_empty() { None } else { @@ -906,6 +959,57 @@ mod tests { assert!(a.ends_with("risposta")); } + #[test] + fn strip_speaker_tags_removes_echoed_prefixes() { + let tag = "[SPEAKER: prato-rapido - 2026-11-25 21:09]"; + assert_eq!(strip_speaker_tags(&format!("{tag} {tag} Certo.")), "Certo."); + assert_eq!(strip_speaker_tags(&format!("{tag}\nCerto.")), "Certo."); + assert_eq!(strip_speaker_tags("Certo."), "Certo."); + assert_eq!(strip_speaker_tags("[nota] testo"), "[nota] testo"); + assert_eq!( + strip_speaker_tags("[SPEAKER: x - not-a-date] testo"), + "[SPEAKER: x - not-a-date] testo" + ); + } + + #[test] + fn build_request_does_not_stack_echoed_speaker_tag() { + 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: "assistant".into(), + content: "[SPEAKER: Nebula - 2026-11-25 21:09] 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"); + let a = req.messages[1].text().unwrap(); + assert_eq!(a.matches("[SPEAKER:").count(), 1, "exactly one tag: {a}"); + assert!(a.ends_with("risposta")); + } + #[test] fn format_stamp_known_dates_and_offset() { assert_eq!(format_stamp(0, 0), "1970-01-01 00:00"); diff --git a/web/assets/app.js b/web/assets/app.js index ad442d0..859afed 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -104,6 +104,12 @@ function usageText(u) { } // Compact locale-aware date+time for a message bubble (epoch seconds). +// The [SPEAKER] tag is model-context metadata; hide any echoed copy in the live +// preview (the backend also strips it from stored / final / history content). +function stripSpeaker(s) { + return s.replace(/^(\s*\[SPEAKER:[^\]]*-\s*\d{4}-\d{2}-\d{2} \d{2}:\d{2}\]\s*)+/, ""); +} + function stampLabel(secs) { const d = new Date(secs * 1000); const date = d.toLocaleDateString(I18N.lang, { day: "2-digit", month: "2-digit" }); @@ -413,7 +419,7 @@ async function agentTurn(content, t, attachments) { if (ev.content) { if (!L.text) L.det.open = false; L.text += ev.content; - L.contentNode.textContent = L.text; + L.contentNode.textContent = stripSpeaker(L.text); } } else if (ev.type === "tool_call") { closeLive(); @@ -426,7 +432,7 @@ async function agentTurn(content, t, attachments) { } else if (ev.type === "final") { const L = ensureLive(); const m = ev.response.choices[0].message; - if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = m.content; } + if (!L.text && m.content) { L.text = m.content; L.contentNode.textContent = stripSpeaker(m.content); } if (!L.reasoning && m.reasoning_content) { L.reasoning = m.reasoning_content; L.reasoningNode.textContent = L.reasoning;