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:
1 parent
7dd66ea138
commit
77bfa72689
4 files changed
+121
-11
No files matched your search
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"identity.name": "Your name is {name}.",
|
"identity.name": "Your name is {name}.",
|
||||||
"identity.folder": " Your personal folder is {folder}.",
|
"identity.folder": " Your personal folder is {folder}.",
|
||||||
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
"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_locked": "The session name is immutable after the first interaction.",
|
||||||
"error.name_empty": "The name must not be empty.",
|
"error.name_empty": "The name must not be empty.",
|
||||||
"error.session_not_found": "Session not found.",
|
"error.session_not_found": "Session not found.",
|
||||||
|
|||||||
+1
-1
@@ -2,7 +2,7 @@
|
|||||||
"identity.name": "Il tuo nome è {name}.",
|
"identity.name": "Il tuo nome è {name}.",
|
||||||
"identity.folder": " La tua cartella personale è {folder}.",
|
"identity.folder": " La tua cartella personale è {folder}.",
|
||||||
"speaker.tag": "[SPEAKER: {name} - {when}]",
|
"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_locked": "Il nome della sessione è immutabile dopo la prima interazione.",
|
||||||
"error.name_empty": "Il nome non può essere vuoto.",
|
"error.name_empty": "Il nome non può essere vuoto.",
|
||||||
"error.session_not_found": "Sessione non trovata.",
|
"error.session_not_found": "Sessione non trovata.",
|
||||||
|
|||||||
+111
-7
@@ -201,7 +201,12 @@ pub(crate) async fn get_messages(
|
|||||||
let msgs = with_store(&st, move |s| s.messages(&id)).await?;
|
let msgs = with_store(&st, move |s| s.messages(&id)).await?;
|
||||||
let views = msgs
|
let views = msgs
|
||||||
.into_iter()
|
.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())
|
let content_html = (m.role == "assistant" && !m.content.is_empty())
|
||||||
.then(|| render::markdown_to_safe_html(&m.content));
|
.then(|| render::markdown_to_safe_html(&m.content));
|
||||||
MessageView {
|
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
|
/// 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.
|
/// (`offset` seconds east of UTC). Dependency-free civil-date arithmetic.
|
||||||
fn format_stamp(secs: i64, offset: i64) -> String {
|
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.
|
// human uses the global user name; the assistant uses the session name.
|
||||||
// Tool/system turns stay untagged. This annotates the prompt only —
|
// Tool/system turns stay untagged. This annotates the prompt only —
|
||||||
// stored content stays clean (the GUI shows its own timestamp).
|
// 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() {
|
let content = match m.role.as_str() {
|
||||||
"user" => format!(
|
"user" => format!(
|
||||||
"{}{}",
|
"{}{}",
|
||||||
speaker_prefix(user_name, m.created_at, tz_offset),
|
speaker_prefix(user_name, m.created_at, tz_offset),
|
||||||
m.content
|
clean
|
||||||
),
|
),
|
||||||
"assistant" => format!(
|
"assistant" => format!(
|
||||||
"{}{}",
|
"{}{}",
|
||||||
speaker_prefix(&sess.title, m.created_at, tz_offset),
|
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);
|
let mut msg = text_message(role_of(&m.role), content);
|
||||||
msg.tool_calls = m
|
msg.tool_calls = m
|
||||||
@@ -634,8 +686,9 @@ pub(crate) async fn session_chat(
|
|||||||
index: 0,
|
index: 0,
|
||||||
message: ChatMessage {
|
message: ChatMessage {
|
||||||
role: Role::Assistant,
|
role: Role::Assistant,
|
||||||
content: (!acc.content.is_empty())
|
content: (!acc.content.is_empty()).then(|| {
|
||||||
.then_some(serde_json::Value::String(acc.content)),
|
serde_json::Value::String(strip_speaker_tags(&acc.content))
|
||||||
|
}),
|
||||||
tool_call_id: None,
|
tool_call_id: None,
|
||||||
tool_calls: has_tools.then_some(tools),
|
tool_calls: has_tools.then_some(tools),
|
||||||
name: None,
|
name: None,
|
||||||
@@ -785,7 +838,7 @@ async fn persist_assistant(store: &Arc<dyn Store>, sid: &str, a: &Accum, prompt_
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|u| (u.prompt_tokens, u.completion_tokens))
|
.map(|u| (u.prompt_tokens, u.completion_tokens))
|
||||||
.unwrap_or((prompt_len, 0));
|
.unwrap_or((prompt_len, 0));
|
||||||
let content = a.content.clone();
|
let content = strip_speaker_tags(&a.content);
|
||||||
let reasoning = if a.reasoning.is_empty() {
|
let reasoning = if a.reasoning.is_empty() {
|
||||||
None
|
None
|
||||||
} else {
|
} else {
|
||||||
@@ -906,6 +959,57 @@ mod tests {
|
|||||||
assert!(a.ends_with("risposta"));
|
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]
|
#[test]
|
||||||
fn format_stamp_known_dates_and_offset() {
|
fn format_stamp_known_dates_and_offset() {
|
||||||
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
|
assert_eq!(format_stamp(0, 0), "1970-01-01 00:00");
|
||||||
|
|||||||
+8
-2
@@ -104,6 +104,12 @@ function usageText(u) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Compact locale-aware date+time for a message bubble (epoch seconds).
|
// 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) {
|
function stampLabel(secs) {
|
||||||
const d = new Date(secs * 1000);
|
const d = new Date(secs * 1000);
|
||||||
const date = d.toLocaleDateString(I18N.lang, { day: "2-digit", month: "2-digit" });
|
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 (ev.content) {
|
||||||
if (!L.text) L.det.open = false;
|
if (!L.text) L.det.open = false;
|
||||||
L.text += ev.content;
|
L.text += ev.content;
|
||||||
L.contentNode.textContent = L.text;
|
L.contentNode.textContent = stripSpeaker(L.text);
|
||||||
}
|
}
|
||||||
} else if (ev.type === "tool_call") {
|
} else if (ev.type === "tool_call") {
|
||||||
closeLive();
|
closeLive();
|
||||||
@@ -426,7 +432,7 @@ async function agentTurn(content, t, attachments) {
|
|||||||
} else if (ev.type === "final") {
|
} else if (ev.type === "final") {
|
||||||
const L = ensureLive();
|
const L = ensureLive();
|
||||||
const m = ev.response.choices[0].message;
|
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) {
|
if (!L.reasoning && m.reasoning_content) {
|
||||||
L.reasoning = m.reasoning_content;
|
L.reasoning = m.reasoning_content;
|
||||||
L.reasoningNode.textContent = L.reasoning;
|
L.reasoningNode.textContent = L.reasoning;
|
||||||
|
|||||||
Reference in new issue
Block a user