1use std::sync::Arc;
14
15use agent_client_protocol::schema::v1::{
16 ContentBlock, ContentChunk, EmbeddedResourceResource, PlanEntryStatus, ToolCallStatus, ToolKind,
17};
18use anyhow::{Result, bail};
19use serde::{Deserialize, Serialize};
20
21pub const SESSION_RESTART_TEXT: &str = "[session restarted]";
22pub const SESSION_RESTART_ITEM_PREFIX: &str = "system:session-restarted:";
23pub const WORK_INTERRUPTED_ITEM_PREFIX: &str = "system:work-interrupted:";
24pub const TURN_INTERRUPTED_TEXT: &str = "Interrupted";
26pub const TURN_INTERRUPTED_ITEM_PREFIX: &str = "system:turn-interrupted:";
27pub const HARNESS_TURN_TEXT: &str = "Agent continued on its own";
29pub const HARNESS_TURN_ITEM_PREFIX: &str = "harness-turn:";
30pub const ELICITATION_REPLY_ITEM_PREFIX: &str = "elicitation-reply:";
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
35#[serde(rename_all = "snake_case")]
36pub enum ToolSummarySourceKind {
37 RawInput,
38 RawOutput,
39 Title,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
44pub struct ToolCallPresentation {
45 pub summary: String,
46 pub source: String,
47 pub source_kind: ToolSummarySourceKind,
48 pub tool_kind: ToolKind,
49 #[serde(default)]
52 pub summary_version: u8,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
59#[serde(tag = "kind", rename_all = "snake_case")]
60pub enum TranscriptBody {
61 User {
62 content: Vec<serde_json::Value>,
63 },
64 Agent {
65 chunks: Vec<serde_json::Value>,
68 streaming: bool,
69 },
70 Thought {
71 chunks: Vec<serde_json::Value>,
74 streaming: bool,
75 },
76 Tool {
77 call: serde_json::Value,
80 #[serde(default, skip_serializing_if = "Vec::is_empty")]
85 terminal_outputs: Vec<TerminalOutputRecord>,
86 #[serde(default, skip_serializing_if = "Vec::is_empty")]
91 terminal_refs: Vec<String>,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
95 presentation: Option<Box<ToolCallPresentation>>,
96 },
97 TerminalOutput {
102 record: TerminalOutputRecord,
103 },
104 Plan {
105 plan: serde_json::Value,
108 },
109 PlanProposal {
115 proposal_id: String,
117 plan: String,
119 },
120 System {
121 text: String,
122 },
123}
124
125pub fn push_content_chunk(chunks: &mut Vec<serde_json::Value>, chunk: serde_json::Value) {
140 if chunks
141 .last()
142 .is_some_and(|last| text_chunks_mergeable(last, &chunk))
143 {
144 let addition = chunk
145 .get("content")
146 .and_then(|content| content.get("text"))
147 .and_then(serde_json::Value::as_str)
148 .unwrap_or_default()
149 .to_owned();
150 if let Some(serde_json::Value::Object(last)) = chunks.last_mut()
151 && let Some(serde_json::Value::Object(content)) = last.get_mut("content")
152 && let Some(serde_json::Value::String(text)) = content.get_mut("text")
153 {
154 text.push_str(&addition);
155 return;
156 }
157 }
158 chunks.push(chunk);
159}
160
161pub fn coalesce_content_chunks(chunks: &mut Vec<serde_json::Value>) {
167 if chunks.len() < 2 {
168 return;
169 }
170 let mut merged = Vec::with_capacity(chunks.len());
171 for chunk in std::mem::take(chunks) {
172 push_content_chunk(&mut merged, chunk);
173 }
174 merged.shrink_to_fit();
175 *chunks = merged;
176}
177
178fn text_chunks_mergeable(last: &serde_json::Value, next: &serde_json::Value) -> bool {
182 let (serde_json::Value::Object(last), serde_json::Value::Object(next)) = (last, next) else {
183 return false;
184 };
185 let (
186 Some(serde_json::Value::Object(last_content)),
187 Some(serde_json::Value::Object(next_content)),
188 ) = (last.get("content"), next.get("content"))
189 else {
190 return false;
191 };
192 let is_text = |content: &serde_json::Map<String, serde_json::Value>| {
193 content.get("type").and_then(serde_json::Value::as_str) == Some("text")
194 && content
195 .get("text")
196 .is_some_and(serde_json::Value::is_string)
197 };
198 if !is_text(last_content) || !is_text(next_content) {
199 return false;
200 }
201 if last.len() != next.len()
203 || !last
204 .iter()
205 .all(|(key, value)| key == "content" || next.get(key) == Some(value))
206 {
207 return false;
208 }
209 last_content.len() == next_content.len()
211 && last_content
212 .iter()
213 .all(|(key, value)| key == "text" || next_content.get(key) == Some(value))
214}
215
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220pub struct TerminalOutputRecord {
221 pub terminal_id: String,
222 pub output: String,
223 #[serde(default, skip_serializing_if = "is_false")]
224 pub truncated: bool,
225 #[serde(default, skip_serializing_if = "Option::is_none")]
226 pub exit_code: Option<u32>,
227 #[serde(default, skip_serializing_if = "Option::is_none")]
228 pub signal: Option<String>,
229}
230
231impl TerminalOutputRecord {
232 pub fn exited_cleanly(&self) -> bool {
237 self.exit_code == Some(0) && self.signal.is_none()
238 }
239
240 pub fn matches_tool_raw_result(&self, call: &serde_json::Value) -> bool {
245 if !matches!(
246 call.get("status").and_then(serde_json::Value::as_str),
247 Some("completed" | "failed")
248 ) {
249 return false;
250 }
251 let Some(raw) = call.get("rawOutput") else {
252 return false;
253 };
254 let Some(exit_code) = raw
255 .get("exit_code")
256 .and_then(serde_json::Value::as_u64)
257 .and_then(|code| u32::try_from(code).ok())
258 else {
259 return false;
260 };
261 if self.exit_code != Some(exit_code) || self.signal.is_some() {
262 return false;
263 }
264 match raw.get("output") {
265 Some(serde_json::Value::Array(bytes)) => {
266 bytes.len() == self.output.len()
267 && bytes
268 .iter()
269 .zip(self.output.as_bytes())
270 .all(|(value, byte)| value.as_u64() == Some(u64::from(*byte)))
271 }
272 Some(serde_json::Value::String(output)) => output == &self.output,
273 _ => false,
274 }
275 }
276}
277
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(deny_unknown_fields)]
280pub struct TranscriptItem {
281 pub stable_id: String,
282 pub position: u64,
284 pub latest_content_event_ordinal: Option<u64>,
287 pub created_at_ms: i64,
288 pub last_changed_at_ms: i64,
289 pub body: TranscriptBody,
290}
291
292impl TranscriptItem {
293 pub fn is_work_interruption(&self) -> bool {
294 self.stable_id.starts_with(WORK_INTERRUPTED_ITEM_PREFIX)
295 }
296
297 pub fn is_session_restart(&self) -> bool {
298 self.stable_id.starts_with(SESSION_RESTART_ITEM_PREFIX)
299 }
300
301 pub fn seq(&self) -> u64 {
309 self.latest_content_event_ordinal.unwrap_or(self.position)
310 }
311
312 pub fn is_user_prompt(&self) -> bool {
314 matches!(self.body, TranscriptBody::User { .. })
315 && !self.stable_id.starts_with(ELICITATION_REPLY_ITEM_PREFIX)
316 }
317
318 pub fn is_turn_start(&self) -> bool {
322 self.is_user_prompt() || self.stable_id.starts_with(HARNESS_TURN_ITEM_PREFIX)
323 }
324
325 pub fn is_nonempty_agent_message(&self) -> bool {
326 let TranscriptBody::Agent { chunks, .. } = &self.body else {
327 return false;
328 };
329 chunks.iter().any(|chunk| {
330 let Some(content) = chunk.get("content") else {
331 return false;
332 };
333 match content.get("type").and_then(serde_json::Value::as_str) {
334 Some("text") => content
335 .get("text")
336 .and_then(serde_json::Value::as_str)
337 .is_some_and(|text| !text.trim().is_empty()),
338 Some(_) => true,
339 None => false,
340 }
341 })
342 }
343
344 pub fn validate(&self, through: u64) -> Result<()> {
345 if self.stable_id.trim().is_empty() {
346 bail!("materialized transcript item has an empty stable id");
347 }
348 if self.position == 0 || self.position > through {
349 bail!(
350 "materialized transcript item {:?} has invalid position {} at frontier {through}",
351 self.stable_id,
352 self.position
353 );
354 }
355 match (&self.body, self.latest_content_event_ordinal) {
356 (TranscriptBody::Agent { .. }, Some(ordinal))
357 if ordinal >= self.position && ordinal <= through => {}
358 (TranscriptBody::Agent { .. }, Some(ordinal)) => bail!(
359 "materialized agent message {:?} has invalid latest content ordinal {ordinal} at position {} and frontier {through}",
360 self.stable_id,
361 self.position
362 ),
363 (TranscriptBody::Agent { .. }, None) => bail!(
364 "materialized agent message {:?} has no latest content ordinal",
365 self.stable_id
366 ),
367 (_, Some(ordinal)) => bail!(
368 "non-agent transcript item {:?} has latest content ordinal {ordinal}",
369 self.stable_id
370 ),
371 (_, None) => {}
372 }
373 if self.last_changed_at_ms < self.created_at_ms {
374 bail!(
375 "materialized transcript item {:?} changed before it was created",
376 self.stable_id
377 );
378 }
379 Ok(())
380 }
381}
382
383#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
384pub enum ChatRole {
385 User,
386 Agent,
387 Thought,
389 Tool,
391 Plan,
393 PlanProposal,
395 System,
396}
397
398#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
399pub struct ChatEntry {
400 #[serde(default)]
401 pub start_seq: u64,
402 pub seq: u64,
403 pub role: ChatRole,
404 pub text: String,
405 pub recorded_at_ms: Option<i64>,
406 pub revision: u64,
407 pub message_id: Option<String>,
408 pub tool_call_id: Option<String>,
409 pub tool_status: Option<ToolStatus>,
410 #[serde(default, skip_serializing_if = "Option::is_none")]
413 pub tool_summary: Option<String>,
414 #[serde(default, skip_serializing_if = "Option::is_none")]
417 pub tool_presentation: Option<ToolCallPresentation>,
418 pub tool_content: Vec<String>,
419 pub tool_diffstats: Vec<String>,
420 pub tool_locations: Vec<String>,
421 pub plan: Vec<PlanLine>,
422 #[serde(default, skip_serializing_if = "is_false")]
423 pub leading_omitted: bool,
424 #[serde(default, skip_serializing_if = "is_false")]
428 pub raw_only: bool,
429 #[serde(default, skip_serializing_if = "is_false")]
433 pub ended_after_interrupt: bool,
434 #[serde(skip)]
438 pub source: TranscriptSource,
439}
440
441#[derive(Debug, Clone, Default)]
448pub struct TranscriptSource(pub Option<Arc<TranscriptItem>>);
449
450impl TranscriptSource {
451 pub fn is(&self, item: &Arc<TranscriptItem>) -> bool {
452 self.0
453 .as_ref()
454 .is_some_and(|source| Arc::ptr_eq(source, item))
455 }
456}
457
458impl PartialEq for TranscriptSource {
459 fn eq(&self, _other: &Self) -> bool {
460 true
461 }
462}
463
464impl Eq for TranscriptSource {}
465
466impl ChatEntry {
467 pub fn is_session_restart(&self) -> bool {
472 self.source
473 .0
474 .as_ref()
475 .is_some_and(|item| item.is_session_restart())
476 || (self.role == ChatRole::System && self.text == SESSION_RESTART_TEXT)
477 }
478
479 pub fn plan(seq: u64, plan: Vec<PlanLine>) -> Self {
480 Self {
481 start_seq: seq,
482 seq,
483 role: ChatRole::Plan,
484 text: String::new(),
485 recorded_at_ms: None,
486 revision: 0,
487 message_id: None,
488 tool_call_id: None,
489 tool_status: None,
490 tool_summary: None,
491 tool_presentation: None,
492 tool_content: Vec::new(),
493 tool_diffstats: Vec::new(),
494 tool_locations: Vec::new(),
495 plan,
496 leading_omitted: false,
497 raw_only: false,
498 ended_after_interrupt: false,
499 source: TranscriptSource::default(),
500 }
501 }
502
503 pub fn touch(&mut self, seq: u64) {
504 self.seq = seq;
505 self.revision = self.revision.wrapping_add(1);
506 }
507
508 #[doc(hidden)]
514 pub fn bounded_for_dashboard(mut self) -> Self {
515 self.bound_dashboard_content();
516 self
517 }
518
519 fn bound_dashboard_content(&mut self) {
520 const TEXT_BYTES: usize = 64 * 1024;
521 const DETAIL_BYTES: usize = 2 * 1024;
522 const DETAIL_COUNT: usize = 8;
523
524 self.leading_omitted |= truncate_string_start(&mut self.text, TEXT_BYTES);
525 for values in [
526 &mut self.tool_content,
527 &mut self.tool_diffstats,
528 &mut self.tool_locations,
529 ] {
530 values.truncate(DETAIL_COUNT);
531 for value in values {
532 truncate_string_start(value, DETAIL_BYTES);
533 }
534 }
535 if let Some(summary) = &mut self.tool_summary {
536 truncate_string_start(summary, DETAIL_BYTES);
537 }
538 if let Some(presentation) = &mut self.tool_presentation {
539 truncate_string_start(&mut presentation.summary, DETAIL_BYTES);
540 truncate_string_start(&mut presentation.source, TEXT_BYTES);
541 }
542 self.plan.truncate(DETAIL_COUNT);
543 for line in &mut self.plan {
544 truncate_string_start(&mut line.text, DETAIL_BYTES);
545 }
546 }
547
548 pub fn with_recorded_at(mut self, recorded_at_ms: Option<i64>) -> Self {
549 self.recorded_at_ms = recorded_at_ms;
550 self
551 }
552}
553
554impl ChatEntry {
557 pub fn plain(seq: u64, role: ChatRole, text: impl Into<String>) -> Self {
558 Self {
559 start_seq: seq,
560 seq,
561 role,
562 text: sanitize_terminal_text(&text.into()),
563 recorded_at_ms: None,
564 revision: 0,
565 message_id: None,
566 tool_call_id: None,
567 tool_status: None,
568 tool_summary: None,
569 tool_presentation: None,
570 tool_content: Vec::new(),
571 tool_diffstats: Vec::new(),
572 tool_locations: Vec::new(),
573 plan: Vec::new(),
574 leading_omitted: false,
575 raw_only: false,
576 ended_after_interrupt: false,
577 source: TranscriptSource::default(),
578 }
579 }
580
581 pub fn tool(
582 seq: u64,
583 title: impl Into<String>,
584 tool_call_id: Option<String>,
585 tool_status: ToolStatus,
586 ) -> Self {
587 Self {
588 start_seq: seq,
589 seq,
590 role: ChatRole::Tool,
591 text: sanitize_terminal_text(&title.into()),
592 recorded_at_ms: None,
593 revision: 0,
594 message_id: None,
595 tool_call_id,
596 tool_status: Some(tool_status),
597 tool_summary: None,
598 tool_presentation: None,
599 tool_content: Vec::new(),
600 tool_diffstats: Vec::new(),
601 tool_locations: Vec::new(),
602 plan: Vec::new(),
603 leading_omitted: false,
604 raw_only: false,
605 ended_after_interrupt: false,
606 source: TranscriptSource::default(),
607 }
608 }
609}
610
611pub(crate) fn is_false(value: &bool) -> bool {
612 !*value
613}
614
615pub fn plan_status(status: &PlanEntryStatus) -> PlanStatus {
616 match status {
617 PlanEntryStatus::InProgress => PlanStatus::Running,
618 PlanEntryStatus::Completed => PlanStatus::Completed,
619 _ => PlanStatus::Pending,
620 }
621}
622
623pub fn sanitize_terminal_text(text: &str) -> String {
625 let mut sanitized = String::with_capacity(text.len());
626 let mut chars = text.chars().peekable();
627 while let Some(ch) = chars.next() {
628 if ch == '\x1b' {
629 while consume_escape_body(&mut chars) {}
633 } else if ch == '\r' {
634 if chars.peek() != Some(&'\n') {
635 sanitized.push('\n');
636 }
637 } else if matches!(ch, '\n' | '\t') || !ch.is_control() {
638 sanitized.push(ch);
639 }
640 }
641 sanitized
642}
643
644fn consume_escape_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
651 match chars.next() {
652 Some('[') => {
654 let _ = chars.find(|ch| ('@'..='~').contains(ch));
655 false
656 }
657 Some(']' | 'P' | 'X' | '^' | '_') => consume_string_body(chars),
659 Some('(' | ')' | '*' | '+' | '-' | '.' | '/' | '#' | '%' | ' ') => {
661 chars.next();
662 false
663 }
664 _ => false,
667 }
668}
669
670fn consume_string_body(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> bool {
674 while let Some(&ch) = chars.peek() {
675 match ch {
676 '\n' | '\r' | '\x18' | '\x1a' => return false,
677 '\x07' => {
678 chars.next();
679 return false;
680 }
681 '\x1b' => {
682 chars.next();
683 return true;
684 }
685 _ => {
686 chars.next();
687 }
688 }
689 }
690 false
691}
692
693pub fn materialized_content_text(content: &[serde_json::Value]) -> String {
694 let text = content
695 .iter()
696 .map(materialized_value_text)
697 .filter(|text| !text.is_empty())
698 .collect::<Vec<_>>()
699 .join("\n");
700 crate::relay::strip_hidden_prompt_context(&text).to_owned()
701}
702
703#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
709#[serde(rename_all = "snake_case")]
710pub enum TranscriptRole {
711 User,
712 Agent,
713 Thought,
714 Tool,
715 Terminal,
716 Plan,
717 PlanProposal,
718 System,
719}
720
721impl TranscriptRole {
722 pub fn as_str(self) -> &'static str {
723 match self {
724 Self::User => "user",
725 Self::Agent => "agent",
726 Self::Thought => "thought",
727 Self::Tool => "tool",
728 Self::Terminal => "terminal",
729 Self::Plan => "plan",
730 Self::PlanProposal => "plan_proposal",
731 Self::System => "system",
732 }
733 }
734 pub fn storage_kind(self) -> &'static str {
735 match self {
736 Self::Terminal => "terminal_output",
737 other => other.as_str(),
738 }
739 }
740}
741
742pub fn transcript_item_role(body: &TranscriptBody) -> &'static str {
743 let role = match body {
744 TranscriptBody::User { .. } => TranscriptRole::User,
745 TranscriptBody::Agent { .. } => TranscriptRole::Agent,
746 TranscriptBody::Thought { .. } => TranscriptRole::Thought,
747 TranscriptBody::Tool { .. } => TranscriptRole::Tool,
748 TranscriptBody::TerminalOutput { .. } => TranscriptRole::Terminal,
749 TranscriptBody::Plan { .. } => TranscriptRole::Plan,
750 TranscriptBody::PlanProposal { .. } => TranscriptRole::PlanProposal,
751 TranscriptBody::System { .. } => TranscriptRole::System,
752 };
753 role.as_str()
754}
755
756pub fn materialized_chunks_text(chunks: &[serde_json::Value]) -> String {
757 chunks
758 .iter()
759 .filter_map(|value| match ContentChunk::deserialize(value) {
760 Ok(chunk) => Some(chunk),
761 Err(error) => {
762 tracing::warn!(%error, "could not decode a stored content chunk");
763 None
764 }
765 })
766 .filter_map(|chunk| content_block_text(&chunk.content))
767 .map(|text| sanitize_terminal_text(&text))
768 .collect::<Vec<_>>()
769 .join("")
770}
771
772fn materialized_value_text(value: &serde_json::Value) -> String {
773 if let Ok(block) = ContentBlock::deserialize(value)
774 && let Some(text) = content_block_text(&block)
775 {
776 return sanitize_terminal_text(&text);
777 }
778 if let Some(text) = value.as_str() {
779 return sanitize_terminal_text(text);
780 }
781 sanitize_terminal_text(&serde_json::to_string(value).unwrap_or_else(|_| "[content]".into()))
782}
783
784pub fn tool_status(status: &ToolCallStatus) -> ToolStatus {
785 match status {
786 ToolCallStatus::InProgress => ToolStatus::Running,
787 ToolCallStatus::Completed => ToolStatus::Completed,
788 ToolCallStatus::Failed => ToolStatus::Failed,
789 _ => ToolStatus::Pending,
790 }
791}
792
793pub fn content_block_text(content: &ContentBlock) -> Option<String> {
794 match content {
795 ContentBlock::Text(text) => Some(text.text.clone()),
796 ContentBlock::Image(_) => Some("[image]".into()),
797 ContentBlock::Audio(_) => Some("[audio]".into()),
798 ContentBlock::ResourceLink(link) => Some(format!("[{}]({})", link.name, link.uri)),
799 ContentBlock::Resource(resource) => Some(match &resource.resource {
800 EmbeddedResourceResource::TextResourceContents(resource) => resource.text.clone(),
801 EmbeddedResourceResource::BlobResourceContents(resource) => {
802 format!("[embedded resource: {}]", resource.uri)
803 }
804 _ => "[embedded resource]".into(),
805 }),
806 _ => None,
807 }
808}
809
810pub fn truncate_string_start(value: &mut String, maximum_bytes: usize) -> bool {
811 if value.len() <= maximum_bytes {
812 return false;
813 }
814 let mut start = value.len() - maximum_bytes;
815 while !value.is_char_boundary(start) {
816 start += 1;
817 }
818 value.drain(..start);
819 true
820}
821
822#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
824pub enum ToolStatus {
825 Pending,
826 Running,
827 Completed,
828 Failed,
829}
830
831#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
832pub enum PlanStatus {
833 Pending,
834 Running,
835 Completed,
836}
837
838#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
839pub struct PlanLine {
840 pub text: String,
841 pub status: PlanStatus,
842}
843
844#[cfg(test)]
845mod tests {
846 use super::*;
847 use serde_json::json;
848
849 fn text_chunk(text: &str, message_id: Option<&str>) -> serde_json::Value {
850 match message_id {
851 Some(id) => json!({"content": {"type": "text", "text": text}, "messageId": id}),
852 None => json!({"content": {"type": "text", "text": text}}),
853 }
854 }
855
856 #[test]
858 fn push_content_chunk_merges_adjacent_text_for_the_same_message_id() {
859 let mut chunks = vec![text_chunk("x", Some("m1"))];
860 for _ in 1..15_001 {
861 push_content_chunk(&mut chunks, text_chunk("x", Some("m1")));
862 }
863 assert_eq!(chunks, vec![text_chunk(&"x".repeat(15_001), Some("m1"))]);
864 }
865
866 #[test]
867 fn push_content_chunk_keeps_chunks_from_different_message_ids_apart() {
868 let image = json!({"content": {"type": "image", "data": "abc", "mimeType": "image/png"}});
869 let mut chunks = vec![text_chunk("first", Some("m1"))];
870 push_content_chunk(&mut chunks, text_chunk(" more", Some("m1")));
871 push_content_chunk(&mut chunks, text_chunk("second", Some("m2")));
872 push_content_chunk(&mut chunks, text_chunk("third", None));
873 push_content_chunk(&mut chunks, text_chunk(" more", None));
874 push_content_chunk(&mut chunks, image.clone());
875 push_content_chunk(&mut chunks, image.clone());
876 push_content_chunk(
877 &mut chunks,
878 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
879 );
880 push_content_chunk(
881 &mut chunks,
882 json!({"content": {"type": "text", "text": "b"}, "meta": {"source": "two"}}),
883 );
884 push_content_chunk(
885 &mut chunks,
886 json!({"content": {"type": "text", "text": "c"}, "meta": {"source": "two"}}),
887 );
888 push_content_chunk(
889 &mut chunks,
890 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
891 );
892 push_content_chunk(
893 &mut chunks,
894 json!({"content": {"type": "text", "text": "plain"}}),
895 );
896 assert_eq!(
897 chunks,
898 vec![
899 text_chunk("first more", Some("m1")),
900 text_chunk("second", Some("m2")),
901 text_chunk("third more", None),
902 image.clone(),
903 image,
904 json!({"content": {"type": "text", "text": "a"}, "meta": {"source": "one"}}),
905 json!({"content": {"type": "text", "text": "bc"}, "meta": {"source": "two"}}),
906 json!({"content": {"type": "text", "text": "annotated", "annotations": {"audience": ["user"]}}}),
907 json!({"content": {"type": "text", "text": "plain"}}),
908 ]
909 );
910 }
911
912 #[test]
914 fn coalesce_content_chunks_collapses_runs_and_keeps_segment_boundaries() {
915 let image = json!({"content": {"type": "image", "data": "x", "mimeType": "image/png"}});
916 let mut chunks = (0..15_001)
917 .map(|_| text_chunk("x", Some("m1")))
918 .collect::<Vec<_>>();
919 chunks.extend([
920 text_chunk("next", Some("m2")),
921 text_chunk(" turn", Some("m2")),
922 image.clone(),
923 ]);
924 coalesce_content_chunks(&mut chunks);
925 assert_eq!(
926 chunks,
927 vec![
928 text_chunk(&"x".repeat(15_001), Some("m1")),
929 text_chunk("next turn", Some("m2")),
930 image
931 ]
932 );
933 }
934}