From 16607e5bb2dcaca36c18d2143862be193f4e925b Mon Sep 17 00:00:00 2001 From: NginxL <8777777+NginxL@users.noreply.github.com> Date: Sun, 6 Dec 2026 21:34:17 +0800 Subject: [PATCH] fix(chat): hold closing tags after empty XML parameters Co-Authored-By: Little Code Sauce Signed-off-by: NginxL <8777777+NginxL@users.noreply.github.com> --- src/chat.rs | 40 +++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/src/chat.rs b/src/chat.rs index fb03768a..447c4137 100644 --- a/src/chat.rs +++ b/src/chat.rs @@ -746,10 +746,14 @@ fn xml_partial(r: &str, tools: &[Json]) -> Option<(String, String)> { continue; } if props.get(k).get("type").as_str() == Some("string") { - // The value so far, less a tail that could still be the `\n` that ends it. + // Hold back a tail that could still be the closing tag, with or without its preceding newline. let v = x.strip_prefix('\n').unwrap_or(x); - let end = "\n"; - let hold = (1..=end.len().min(v.len())).rev().find(|&n| v.ends_with(&end[..n])).unwrap_or(0); + let mut hold = 0; + for end in ["\n", ""] { + if let Some(n) = (1..=end.len().min(v.len())).rev().find(|&n| v.ends_with(&end[..n])) { + hold = hold.max(n); + } + } let q = key(&v[..v.len() - hold]); s += &format!("{sep}{}: {}", key(k), &q[..q.len() - 1]); } @@ -890,6 +894,36 @@ mod think_tests { assert_eq!(Template::Xml.partial_calls(text, &tools), done); assert!(Template::Xml.partial_calls("\n\n\nx", &tools).is_empty()); } + /// Issue 247: an empty string parameter has no value newline before its closing tag. + #[test] + fn partial_empty_string_parameter_does_not_leak_closing_tag() { + let tools: Vec = serde_json::from_str(r#"[{"type":"function","function":{"name":"edit","parameters":{"properties": + {"file_path":{"type":"string"},"new_string":{"type":"string"},"old_string":{"type":"string"}}}}}]"#).unwrap(); + let close = ""; + let text = format!( + "\n\n\nreport.js\n{close}\n\n{close}\n\nlegacy\n{close}\n\n" + ); + let (_, done) = Template::Xml.parse_calls(&text, &tools).unwrap(); + let args: Json = serde_json::from_str(&done[0].1).unwrap(); + assert_eq!(args.get("new_string").as_str(), Some("")); + assert_eq!(args.get("old_string").as_str(), Some("legacy")); + + for (p, _) in text.char_indices() { + let partial = Template::Xml.partial_calls(&text[..p], &tools); + if partial.is_empty() { + continue; + } + assert_eq!(partial.len(), 1); + assert_eq!(partial[0].0, "edit"); + assert!( + done[0].1.starts_with(&partial[0].1), + "at byte {p}: {:?} is not a prefix of {:?}", + partial[0].1, + done[0].1 + ); + } + } + #[test] fn image_source_must_be_a_url() { let req = |url: &str| crate::serve::chat_request(format!(r#"{{"messages":[{{"role":"user","content":[{{"type":"image_url","image_url":{{"url":"{url}"}}}}]}}]}}"#).as_bytes());