agent: Add XML escaping for TextThreadContext title attribute (#39734)

Xiaobo Liu and Bennet Bo Fenner created

Escape special characters (&, <, >, ", ') in the title attribute of
TextThreadContext's XML output to prevent malformed XML when titles
contain these characters.

Resolves TODO at context.rs:629

Release Notes:

- N/A

Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com>
Co-authored-by: Bennet Bo Fenner <bennetbo@gmx.de>

Change summary

crates/agent_ui/src/context.rs | 14 ++++++++++++--
1 file changed, 12 insertions(+), 2 deletions(-)

Detailed changes

crates/agent_ui/src/context.rs 🔗

@@ -620,8 +620,18 @@ impl TextThreadContextHandle {
 
 impl Display for TextThreadContext {
     fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
-        // TODO: escape title?
-        writeln!(f, "<text_thread title=\"{}\">", self.title)?;
+        write!(f, "<text_thread title=\"")?;
+        for c in self.title.chars() {
+            match c {
+                '&' => write!(f, "&amp;")?,
+                '<' => write!(f, "&lt;")?,
+                '>' => write!(f, "&gt;")?,
+                '"' => write!(f, "&quot;")?,
+                '\'' => write!(f, "&apos;")?,
+                _ => write!(f, "{}", c)?,
+            }
+        }
+        writeln!(f, "\">")?;
         write!(f, "{}", self.text.trim())?;
         write!(f, "\n</text_thread>")
     }