Keep [SPEAKER] provenance model-only: strip echoed tags from replies and history

The descriptive speaker.note let the model imitate the tag into its visible reply; the echoed tag was then stored and re-tagged by build_request next turn, stacking duplicates. Fix: speaker.note now forbids writing/repeating the tag; strip_speaker_tags removes leading echoed [SPEAKER: name - YYYY-MM-DD HH:MM] runs at persist, at the agent Final content, in get_messages (display+HTML) and before re-tagging history, so the tag stays prompt-only and never stacks. Frontend strips it from the live preview too. Legacy tagged rows heal on reload without migration. +2 tests (138 green), clippy/fmt clean; live two-turn verify shows no tag in browser-facing content.
This commit is contained in:
adm committed 2026-11-25 21:18:01 +01:00
1 parent 7dd66ea138
commit 77bfa72689
4 files changed
+121 -11

No files matched your search

+111 -7
View File
@@ -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<dyn Store>, 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");