1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3use serde_json::Value;
4use std::collections::HashMap;
5
6#[derive(Debug, Clone, Serialize, Deserialize)]
7#[serde(rename_all = "camelCase")]
8pub struct ConversationEntry {
9 #[serde(skip_serializing_if = "Option::is_none")]
10 pub parent_uuid: Option<String>,
11
12 #[serde(default)]
13 pub is_sidechain: bool,
14
15 #[serde(rename = "type")]
16 pub entry_type: String,
17
18 #[serde(default)]
19 pub uuid: String,
20
21 #[serde(default)]
22 pub timestamp: String,
23
24 #[serde(skip_serializing_if = "Option::is_none")]
25 pub session_id: Option<String>,
26
27 #[serde(skip_serializing_if = "Option::is_none")]
28 pub cwd: Option<String>,
29
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub git_branch: Option<String>,
32
33 #[serde(skip_serializing_if = "Option::is_none")]
34 pub version: Option<String>,
35
36 #[serde(skip_serializing_if = "Option::is_none")]
37 pub message: Option<Message>,
38
39 #[serde(skip_serializing_if = "Option::is_none")]
40 pub user_type: Option<String>,
41
42 #[serde(skip_serializing_if = "Option::is_none")]
43 pub request_id: Option<String>,
44
45 #[serde(skip_serializing_if = "Option::is_none")]
46 pub tool_use_result: Option<Value>,
47
48 #[serde(skip_serializing_if = "Option::is_none")]
49 pub snapshot: Option<Value>,
50
51 #[serde(skip_serializing_if = "Option::is_none")]
52 pub message_id: Option<String>,
53
54 #[serde(flatten)]
55 pub extra: HashMap<String, Value>,
56}
57
58#[derive(Debug, Clone, Serialize, Deserialize)]
59#[serde(rename_all = "camelCase")]
60pub struct Message {
61 pub role: MessageRole,
62
63 #[serde(skip_serializing_if = "Option::is_none")]
64 pub content: Option<MessageContent>,
65
66 #[serde(skip_serializing_if = "Option::is_none")]
67 pub model: Option<String>,
68
69 #[serde(skip_serializing_if = "Option::is_none")]
70 pub id: Option<String>,
71
72 #[serde(rename = "type", skip_serializing_if = "Option::is_none")]
73 pub message_type: Option<String>,
74
75 #[serde(skip_serializing_if = "Option::is_none", alias = "stop_reason")]
76 pub stop_reason: Option<String>,
77
78 #[serde(skip_serializing_if = "Option::is_none", alias = "stop_sequence")]
79 pub stop_sequence: Option<String>,
80
81 #[serde(skip_serializing_if = "Option::is_none")]
82 pub usage: Option<Usage>,
83}
84
85#[derive(Debug, Clone, Serialize, Deserialize)]
86#[serde(untagged)]
87pub enum MessageContent {
88 Text(String),
89 Parts(Vec<ContentPart>),
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93#[serde(tag = "type", rename_all = "snake_case")]
94pub enum ContentPart {
95 Text {
96 text: String,
97 },
98 Thinking {
99 thinking: String,
100 #[serde(default)]
101 signature: Option<String>,
102 },
103 ToolUse {
104 id: String,
105 name: String,
106 input: Value,
107 },
108 ToolResult {
109 tool_use_id: String,
110 content: ToolResultContent,
111 #[serde(default)]
112 is_error: bool,
113 },
114 #[serde(other)]
116 Unknown,
117}
118
119#[derive(Debug, Clone, Serialize, Deserialize)]
120#[serde(untagged)]
121pub enum ToolResultContent {
122 Text(String),
123 Parts(Vec<ToolResultPart>),
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct ToolResultPart {
128 #[serde(default)]
129 pub text: Option<String>,
130}
131
132impl ToolResultContent {
133 pub fn text(&self) -> String {
134 match self {
135 ToolResultContent::Text(s) => s.clone(),
136 ToolResultContent::Parts(parts) => parts
137 .iter()
138 .filter_map(|p| p.text.as_deref())
139 .collect::<Vec<_>>()
140 .join("\n"),
141 }
142 }
143}
144
145#[derive(Debug)]
147pub struct ToolUseRef<'a> {
148 pub id: &'a str,
149 pub name: &'a str,
150 pub input: &'a Value,
151}
152
153#[derive(Debug)]
155pub struct ToolResultRef<'a> {
156 pub tool_use_id: &'a str,
157 pub content: &'a ToolResultContent,
158 pub is_error: bool,
159}
160
161impl Message {
162 pub fn text(&self) -> String {
166 match &self.content {
167 Some(MessageContent::Text(t)) => t.clone(),
168 Some(MessageContent::Parts(parts)) => parts
169 .iter()
170 .filter_map(|p| match p {
171 ContentPart::Text { text } => Some(text.as_str()),
172 _ => None,
173 })
174 .collect::<Vec<_>>()
175 .join("\n"),
176 None => String::new(),
177 }
178 }
179
180 pub fn thinking(&self) -> Option<Vec<&str>> {
184 let parts = match &self.content {
185 Some(MessageContent::Parts(parts)) => parts,
186 _ => return None,
187 };
188 let thinking: Vec<&str> = parts
189 .iter()
190 .filter_map(|p| match p {
191 ContentPart::Thinking { thinking, .. } => Some(thinking.as_str()),
192 _ => None,
193 })
194 .collect();
195 if thinking.is_empty() {
196 None
197 } else {
198 Some(thinking)
199 }
200 }
201
202 pub fn tool_uses(&self) -> Vec<ToolUseRef<'_>> {
204 let parts = match &self.content {
205 Some(MessageContent::Parts(parts)) => parts,
206 _ => return Vec::new(),
207 };
208 parts
209 .iter()
210 .filter_map(|p| match p {
211 ContentPart::ToolUse { id, name, input } => Some(ToolUseRef { id, name, input }),
212 _ => None,
213 })
214 .collect()
215 }
216
217 pub fn tool_results(&self) -> Vec<ToolResultRef<'_>> {
219 let parts = match &self.content {
220 Some(MessageContent::Parts(parts)) => parts,
221 _ => return Vec::new(),
222 };
223 parts
224 .iter()
225 .filter_map(|p| match p {
226 ContentPart::ToolResult {
227 tool_use_id,
228 content,
229 is_error,
230 } => Some(ToolResultRef {
231 tool_use_id,
232 content,
233 is_error: *is_error,
234 }),
235 _ => None,
236 })
237 .collect()
238 }
239
240 pub fn is_role(&self, role: MessageRole) -> bool {
242 self.role == role
243 }
244
245 pub fn is_user(&self) -> bool {
247 self.role == MessageRole::User
248 }
249
250 pub fn is_assistant(&self) -> bool {
252 self.role == MessageRole::Assistant
253 }
254}
255
256impl ConversationEntry {
257 pub fn role(&self) -> Option<&MessageRole> {
259 self.message.as_ref().map(|m| &m.role)
260 }
261
262 pub fn text(&self) -> String {
266 self.message.as_ref().map(|m| m.text()).unwrap_or_default()
267 }
268
269 pub fn thinking(&self) -> Option<Vec<&str>> {
271 self.message.as_ref().and_then(|m| m.thinking())
272 }
273
274 pub fn tool_uses(&self) -> Vec<ToolUseRef<'_>> {
276 self.message
277 .as_ref()
278 .map(|m| m.tool_uses())
279 .unwrap_or_default()
280 }
281
282 pub fn stop_reason(&self) -> Option<&str> {
284 self.message.as_ref().and_then(|m| m.stop_reason.as_deref())
285 }
286
287 pub fn model(&self) -> Option<&str> {
289 self.message.as_ref().and_then(|m| m.model.as_deref())
290 }
291}
292
293impl ContentPart {
294 pub fn summary(&self) -> String {
296 match self {
297 ContentPart::Text { text } => {
298 if text.chars().count() > 100 {
299 let truncated: String = text.chars().take(97).collect();
300 format!("{}...", truncated)
301 } else {
302 text.clone()
303 }
304 }
305 ContentPart::Thinking { .. } => "[thinking]".to_string(),
306 ContentPart::ToolUse { name, .. } => format!("[tool_use: {}]", name),
307 ContentPart::ToolResult {
308 is_error, content, ..
309 } => {
310 let text = content.text();
311 let prefix = if *is_error { "error" } else { "result" };
312 if text.chars().count() > 80 {
313 let truncated: String = text.chars().take(77).collect();
314 format!("[{}: {}...]", prefix, truncated)
315 } else {
316 format!("[{}: {}]", prefix, text)
317 }
318 }
319 ContentPart::Unknown => "[unknown]".to_string(),
320 }
321 }
322}
323
324#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Copy)]
325#[serde(rename_all = "lowercase")]
326pub enum MessageRole {
327 User,
328 Assistant,
329 System,
330}
331
332impl std::str::FromStr for MessageRole {
333 type Err = String;
334
335 fn from_str(s: &str) -> Result<Self, Self::Err> {
336 match s.to_lowercase().as_str() {
337 "user" => Ok(MessageRole::User),
338 "assistant" => Ok(MessageRole::Assistant),
339 "system" => Ok(MessageRole::System),
340 _ => Err(format!("Invalid message role: {}", s)),
341 }
342 }
343}
344
345#[derive(Debug, Clone, Serialize, Deserialize)]
346#[serde(rename_all = "camelCase")]
347pub struct Usage {
348 #[serde(alias = "input_tokens")]
349 pub input_tokens: Option<u32>,
350 #[serde(alias = "output_tokens")]
351 pub output_tokens: Option<u32>,
352 #[serde(alias = "cache_creation_input_tokens")]
353 pub cache_creation_input_tokens: Option<u32>,
354 #[serde(alias = "cache_read_input_tokens")]
355 pub cache_read_input_tokens: Option<u32>,
356 #[serde(alias = "cache_creation")]
357 pub cache_creation: Option<CacheCreation>,
358 #[serde(alias = "service_tier")]
359 pub service_tier: Option<String>,
360}
361
362#[derive(Debug, Clone, Serialize, Deserialize)]
363#[serde(rename_all = "camelCase")]
364pub struct CacheCreation {
365 #[serde(alias = "ephemeral_5m_input_tokens")]
366 pub ephemeral_5m_input_tokens: Option<u32>,
367 #[serde(alias = "ephemeral_1h_input_tokens")]
368 pub ephemeral_1h_input_tokens: Option<u32>,
369}
370
371#[derive(Debug, Clone, Serialize, Deserialize)]
372pub struct HistoryEntry {
373 pub display: String,
374
375 #[serde(rename = "pastedContents", default)]
376 pub pasted_contents: HashMap<String, Value>,
377
378 pub timestamp: i64,
379
380 #[serde(skip_serializing_if = "Option::is_none")]
381 pub project: Option<String>,
382
383 #[serde(rename = "sessionId", skip_serializing_if = "Option::is_none")]
384 pub session_id: Option<String>,
385}
386
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct Conversation {
389 pub session_id: String,
390 pub project_path: Option<String>,
391 pub entries: Vec<ConversationEntry>,
392 pub started_at: Option<DateTime<Utc>>,
393 pub last_activity: Option<DateTime<Utc>>,
394}
395
396impl Conversation {
397 pub fn new(session_id: String) -> Self {
398 Self {
399 session_id,
400 project_path: None,
401 entries: Vec::new(),
402 started_at: None,
403 last_activity: None,
404 }
405 }
406
407 pub fn add_entry(&mut self, entry: ConversationEntry) {
408 if let Ok(timestamp) = entry.timestamp.parse::<DateTime<Utc>>() {
409 if self.started_at.is_none() || Some(timestamp) < self.started_at {
410 self.started_at = Some(timestamp);
411 }
412 if self.last_activity.is_none() || Some(timestamp) > self.last_activity {
413 self.last_activity = Some(timestamp);
414 }
415 }
416
417 if self.project_path.is_none() {
418 self.project_path = entry.cwd.clone();
419 }
420
421 self.entries.push(entry);
422 }
423
424 pub fn user_messages(&self) -> Vec<&ConversationEntry> {
425 self.entries
426 .iter()
427 .filter(|e| {
428 e.entry_type == "user"
429 && e.message
430 .as_ref()
431 .map(|m| m.role == MessageRole::User)
432 .unwrap_or(false)
433 })
434 .collect()
435 }
436
437 pub fn assistant_messages(&self) -> Vec<&ConversationEntry> {
438 self.entries
439 .iter()
440 .filter(|e| {
441 e.entry_type == "assistant"
442 && e.message
443 .as_ref()
444 .map(|m| m.role == MessageRole::Assistant)
445 .unwrap_or(false)
446 })
447 .collect()
448 }
449
450 pub fn tool_uses(&self) -> Vec<(&ConversationEntry, &ContentPart)> {
451 let mut results = Vec::new();
452
453 for entry in &self.entries {
454 if let Some(message) = &entry.message
455 && let Some(MessageContent::Parts(parts)) = &message.content
456 {
457 for part in parts {
458 if matches!(part, ContentPart::ToolUse { .. }) {
459 results.push((entry, part));
460 }
461 }
462 }
463 }
464
465 results
466 }
467
468 pub fn message_count(&self) -> usize {
469 self.entries.iter().filter(|e| e.message.is_some()).count()
470 }
471
472 pub fn duration(&self) -> Option<chrono::Duration> {
473 match (self.started_at, self.last_activity) {
474 (Some(start), Some(end)) => Some(end - start),
475 _ => None,
476 }
477 }
478
479 pub fn entries_since(&self, since_uuid: &str) -> Vec<ConversationEntry> {
483 match self.entries.iter().position(|e| e.uuid == since_uuid) {
484 Some(idx) => self.entries.iter().skip(idx + 1).cloned().collect(),
485 None => self.entries.clone(),
486 }
487 }
488
489 pub fn last_uuid(&self) -> Option<&str> {
491 self.entries.last().map(|e| e.uuid.as_str())
492 }
493
494 pub fn title(&self, max_len: usize) -> Option<String> {
496 self.first_user_text().map(|text| {
497 if text.chars().count() > max_len {
498 let truncated: String = text.chars().take(max_len).collect();
499 format!("{}...", truncated)
500 } else {
501 text
502 }
503 })
504 }
505
506 pub fn first_user_text(&self) -> Option<String> {
508 self.entries.iter().find_map(|e| {
509 e.message.as_ref().and_then(|msg| {
510 if msg.is_user() {
511 let text = msg.text();
512 if text.is_empty() { None } else { Some(text) }
513 } else {
514 None
515 }
516 })
517 })
518 }
519}
520
521#[derive(Debug, Clone, Serialize, Deserialize)]
522pub struct ConversationMetadata {
523 pub session_id: String,
524 pub project_path: String,
525 pub file_path: std::path::PathBuf,
526 pub message_count: usize,
527 pub started_at: Option<DateTime<Utc>>,
528 pub last_activity: Option<DateTime<Utc>>,
529}
530
531#[cfg(test)]
532mod tests {
533 use super::*;
534
535 fn create_test_conversation() -> Conversation {
536 let mut convo = Conversation::new("test-session".to_string());
537
538 let entries = vec![
539 r#"{"uuid":"uuid-1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"Hello"}}"#,
540 r#"{"uuid":"uuid-2","type":"assistant","timestamp":"2024-01-01T00:00:01Z","message":{"role":"assistant","content":"Hi"}}"#,
541 r#"{"uuid":"uuid-3","type":"user","timestamp":"2024-01-01T00:00:02Z","message":{"role":"user","content":"How are you?"}}"#,
542 r#"{"uuid":"uuid-4","type":"assistant","timestamp":"2024-01-01T00:00:03Z","message":{"role":"assistant","content":"I'm good!"}}"#,
543 ];
544
545 for entry_json in entries {
546 let entry: ConversationEntry = serde_json::from_str(entry_json).unwrap();
547 convo.add_entry(entry);
548 }
549
550 convo
551 }
552
553 #[test]
554 fn test_entries_since_middle() {
555 let convo = create_test_conversation();
556
557 let since = convo.entries_since("uuid-2");
559
560 assert_eq!(since.len(), 2);
561 assert_eq!(since[0].uuid, "uuid-3");
562 assert_eq!(since[1].uuid, "uuid-4");
563 }
564
565 #[test]
566 fn test_entries_since_first() {
567 let convo = create_test_conversation();
568
569 let since = convo.entries_since("uuid-1");
571
572 assert_eq!(since.len(), 3);
573 assert_eq!(since[0].uuid, "uuid-2");
574 }
575
576 #[test]
577 fn test_entries_since_last() {
578 let convo = create_test_conversation();
579
580 let since = convo.entries_since("uuid-4");
582
583 assert!(since.is_empty());
584 }
585
586 #[test]
587 fn test_entries_since_unknown() {
588 let convo = create_test_conversation();
589
590 let since = convo.entries_since("unknown-uuid");
592
593 assert_eq!(since.len(), 4);
594 }
595
596 #[test]
597 fn test_last_uuid() {
598 let convo = create_test_conversation();
599
600 assert_eq!(convo.last_uuid(), Some("uuid-4"));
601 }
602
603 #[test]
604 fn test_last_uuid_empty() {
605 let convo = Conversation::new("empty-session".to_string());
606
607 assert_eq!(convo.last_uuid(), None);
608 }
609
610 #[test]
613 fn test_user_messages() {
614 let convo = create_test_conversation();
615 let users = convo.user_messages();
616 assert_eq!(users.len(), 2);
617 assert!(users.iter().all(|e| e.entry_type == "user"));
618 }
619
620 #[test]
621 fn test_assistant_messages() {
622 let convo = create_test_conversation();
623 let assistants = convo.assistant_messages();
624 assert_eq!(assistants.len(), 2);
625 assert!(assistants.iter().all(|e| e.entry_type == "assistant"));
626 }
627
628 #[test]
629 fn test_message_count() {
630 let convo = create_test_conversation();
631 assert_eq!(convo.message_count(), 4);
632 }
633
634 #[test]
635 fn test_duration() {
636 let convo = create_test_conversation();
637 let dur = convo.duration().unwrap();
638 assert_eq!(dur.num_seconds(), 3); }
640
641 #[test]
642 fn test_duration_empty_conversation() {
643 let convo = Conversation::new("empty".to_string());
644 assert!(convo.duration().is_none());
645 }
646
647 #[test]
648 fn test_add_entry_tracks_timestamps() {
649 let mut convo = Conversation::new("test".to_string());
650 let entry: ConversationEntry = serde_json::from_str(
651 r#"{"uuid":"u1","type":"user","timestamp":"2024-06-15T10:00:00Z","message":{"role":"user","content":"hi"}}"#
652 ).unwrap();
653 convo.add_entry(entry);
654
655 assert!(convo.started_at.is_some());
656 assert!(convo.last_activity.is_some());
657 assert_eq!(convo.started_at, convo.last_activity);
658 }
659
660 #[test]
661 fn test_add_entry_sets_project_path() {
662 let mut convo = Conversation::new("test".to_string());
663 let entry: ConversationEntry = serde_json::from_str(
664 r#"{"uuid":"u1","type":"user","timestamp":"2024-06-15T10:00:00Z","cwd":"/home/user/project","message":{"role":"user","content":"hi"}}"#
665 ).unwrap();
666 convo.add_entry(entry);
667 assert_eq!(convo.project_path.as_deref(), Some("/home/user/project"));
668 }
669
670 #[test]
671 fn test_tool_uses() {
672 let mut convo = Conversation::new("test".to_string());
673 let entry: ConversationEntry = serde_json::from_str(
674 r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":[{"type":"tool_use","id":"t1","name":"Read","input":{"file_path":"/test"}}]}}"#
675 ).unwrap();
676 convo.add_entry(entry);
677
678 let uses = convo.tool_uses();
679 assert_eq!(uses.len(), 1);
680 match uses[0].1 {
681 ContentPart::ToolUse { name, .. } => assert_eq!(name, "Read"),
682 _ => panic!("Expected ToolUse"),
683 }
684 }
685
686 #[test]
687 fn test_tool_uses_empty() {
688 let convo = create_test_conversation();
689 let uses = convo.tool_uses();
691 assert!(uses.is_empty());
692 }
693
694 #[test]
697 fn test_content_part_summary_text_short() {
698 let part = ContentPart::Text {
699 text: "Hello world".to_string(),
700 };
701 assert_eq!(part.summary(), "Hello world");
702 }
703
704 #[test]
705 fn test_content_part_summary_text_long() {
706 let long = "A".repeat(200);
707 let part = ContentPart::Text { text: long };
708 let summary = part.summary();
709 assert!(summary.ends_with("..."));
710 assert!(summary.chars().count() <= 100);
711 }
712
713 #[test]
714 fn test_content_part_summary_thinking() {
715 let part = ContentPart::Thinking {
716 thinking: "deep thought".to_string(),
717 signature: None,
718 };
719 assert_eq!(part.summary(), "[thinking]");
720 }
721
722 #[test]
723 fn test_content_part_summary_tool_use() {
724 let part = ContentPart::ToolUse {
725 id: "t1".to_string(),
726 name: "Write".to_string(),
727 input: serde_json::json!({}),
728 };
729 assert_eq!(part.summary(), "[tool_use: Write]");
730 }
731
732 #[test]
733 fn test_content_part_summary_tool_result_short() {
734 let part = ContentPart::ToolResult {
735 tool_use_id: "t1".to_string(),
736 content: ToolResultContent::Text("OK".to_string()),
737 is_error: false,
738 };
739 assert_eq!(part.summary(), "[result: OK]");
740 }
741
742 #[test]
743 fn test_content_part_summary_tool_result_error() {
744 let part = ContentPart::ToolResult {
745 tool_use_id: "t1".to_string(),
746 content: ToolResultContent::Text("fail".to_string()),
747 is_error: true,
748 };
749 assert_eq!(part.summary(), "[error: fail]");
750 }
751
752 #[test]
753 fn test_content_part_summary_tool_result_long() {
754 let long = "X".repeat(200);
755 let part = ContentPart::ToolResult {
756 tool_use_id: "t1".to_string(),
757 content: ToolResultContent::Text(long),
758 is_error: false,
759 };
760 let summary = part.summary();
761 assert!(summary.starts_with("[result:"));
762 assert!(summary.ends_with("...]"));
763 }
764
765 #[test]
766 fn test_content_part_summary_unknown() {
767 let part = ContentPart::Unknown;
768 assert_eq!(part.summary(), "[unknown]");
769 }
770
771 #[test]
774 fn test_tool_result_content_text_string() {
775 let c = ToolResultContent::Text("hello".to_string());
776 assert_eq!(c.text(), "hello");
777 }
778
779 #[test]
780 fn test_tool_result_content_text_parts() {
781 let c = ToolResultContent::Parts(vec![
782 ToolResultPart {
783 text: Some("line1".to_string()),
784 },
785 ToolResultPart { text: None },
786 ToolResultPart {
787 text: Some("line2".to_string()),
788 },
789 ]);
790 assert_eq!(c.text(), "line1\nline2");
791 }
792
793 #[test]
796 fn test_message_role_from_str() {
797 assert_eq!("user".parse::<MessageRole>().unwrap(), MessageRole::User);
798 assert_eq!(
799 "assistant".parse::<MessageRole>().unwrap(),
800 MessageRole::Assistant
801 );
802 assert_eq!(
803 "system".parse::<MessageRole>().unwrap(),
804 MessageRole::System
805 );
806 }
807
808 #[test]
809 fn test_message_role_from_str_case_insensitive() {
810 assert_eq!("USER".parse::<MessageRole>().unwrap(), MessageRole::User);
811 assert_eq!(
812 "Assistant".parse::<MessageRole>().unwrap(),
813 MessageRole::Assistant
814 );
815 }
816
817 #[test]
818 fn test_message_role_from_str_invalid() {
819 assert!("invalid".parse::<MessageRole>().is_err());
820 }
821
822 #[test]
825 fn test_message_text_from_string() {
826 let msg = Message {
827 role: MessageRole::User,
828 content: Some(MessageContent::Text("Hello world".to_string())),
829 model: None,
830 id: None,
831 message_type: None,
832 stop_reason: None,
833 stop_sequence: None,
834 usage: None,
835 };
836 assert_eq!(msg.text(), "Hello world");
837 }
838
839 #[test]
840 fn test_message_text_from_parts() {
841 let msg = Message {
842 role: MessageRole::Assistant,
843 content: Some(MessageContent::Parts(vec![
844 ContentPart::Text {
845 text: "First".to_string(),
846 },
847 ContentPart::Thinking {
848 thinking: "hmm".to_string(),
849 signature: None,
850 },
851 ContentPart::Text {
852 text: "Second".to_string(),
853 },
854 ])),
855 model: None,
856 id: None,
857 message_type: None,
858 stop_reason: None,
859 stop_sequence: None,
860 usage: None,
861 };
862 assert_eq!(msg.text(), "First\nSecond");
863 }
864
865 #[test]
866 fn test_message_text_none() {
867 let msg = Message {
868 role: MessageRole::User,
869 content: None,
870 model: None,
871 id: None,
872 message_type: None,
873 stop_reason: None,
874 stop_sequence: None,
875 usage: None,
876 };
877 assert_eq!(msg.text(), "");
878 }
879
880 #[test]
881 fn test_message_thinking() {
882 let msg = Message {
883 role: MessageRole::Assistant,
884 content: Some(MessageContent::Parts(vec![
885 ContentPart::Thinking {
886 thinking: "deep thought".to_string(),
887 signature: None,
888 },
889 ContentPart::Text {
890 text: "answer".to_string(),
891 },
892 ContentPart::Thinking {
893 thinking: "more thought".to_string(),
894 signature: None,
895 },
896 ])),
897 model: None,
898 id: None,
899 message_type: None,
900 stop_reason: None,
901 stop_sequence: None,
902 usage: None,
903 };
904 let thinking = msg.thinking().unwrap();
905 assert_eq!(thinking, vec!["deep thought", "more thought"]);
906 }
907
908 #[test]
909 fn test_message_thinking_none() {
910 let msg = Message {
911 role: MessageRole::User,
912 content: Some(MessageContent::Text("hi".to_string())),
913 model: None,
914 id: None,
915 message_type: None,
916 stop_reason: None,
917 stop_sequence: None,
918 usage: None,
919 };
920 assert!(msg.thinking().is_none());
921 }
922
923 #[test]
924 fn test_message_tool_uses() {
925 let msg = Message {
926 role: MessageRole::Assistant,
927 content: Some(MessageContent::Parts(vec![
928 ContentPart::ToolUse {
929 id: "t1".to_string(),
930 name: "Read".to_string(),
931 input: serde_json::json!({"file": "test.rs"}),
932 },
933 ContentPart::Text {
934 text: "checking".to_string(),
935 },
936 ContentPart::ToolUse {
937 id: "t2".to_string(),
938 name: "Write".to_string(),
939 input: serde_json::json!({}),
940 },
941 ])),
942 model: None,
943 id: None,
944 message_type: None,
945 stop_reason: None,
946 stop_sequence: None,
947 usage: None,
948 };
949 let uses = msg.tool_uses();
950 assert_eq!(uses.len(), 2);
951 assert_eq!(uses[0].name, "Read");
952 assert_eq!(uses[1].name, "Write");
953 }
954
955 #[test]
956 fn test_message_tool_results() {
957 let msg = Message {
958 role: MessageRole::User,
959 content: Some(MessageContent::Parts(vec![
960 ContentPart::ToolResult {
961 tool_use_id: "t1".to_string(),
962 content: ToolResultContent::Text("file contents".to_string()),
963 is_error: false,
964 },
965 ContentPart::ToolResult {
966 tool_use_id: "t2".to_string(),
967 content: ToolResultContent::Text("error msg".to_string()),
968 is_error: true,
969 },
970 ])),
971 model: None,
972 id: None,
973 message_type: None,
974 stop_reason: None,
975 stop_sequence: None,
976 usage: None,
977 };
978 let results = msg.tool_results();
979 assert_eq!(results.len(), 2);
980 assert_eq!(results[0].tool_use_id, "t1");
981 assert_eq!(results[0].content.text(), "file contents");
982 assert!(!results[0].is_error);
983 assert_eq!(results[1].tool_use_id, "t2");
984 assert!(results[1].is_error);
985 }
986
987 #[test]
988 fn test_message_tool_results_empty() {
989 let msg = Message {
990 role: MessageRole::User,
991 content: Some(MessageContent::Text("hello".to_string())),
992 model: None,
993 id: None,
994 message_type: None,
995 stop_reason: None,
996 stop_sequence: None,
997 usage: None,
998 };
999 assert!(msg.tool_results().is_empty());
1000 }
1001
1002 #[test]
1003 fn test_message_role_checks() {
1004 let user_msg = Message {
1005 role: MessageRole::User,
1006 content: None,
1007 model: None,
1008 id: None,
1009 message_type: None,
1010 stop_reason: None,
1011 stop_sequence: None,
1012 usage: None,
1013 };
1014 assert!(user_msg.is_user());
1015 assert!(!user_msg.is_assistant());
1016 assert!(user_msg.is_role(MessageRole::User));
1017 }
1018
1019 #[test]
1022 fn test_entry_text() {
1023 let entry: ConversationEntry = serde_json::from_str(
1024 r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"Hello there"}}"#,
1025 )
1026 .unwrap();
1027 assert_eq!(entry.text(), "Hello there");
1028 }
1029
1030 #[test]
1031 fn test_entry_text_no_message() {
1032 let entry: ConversationEntry = serde_json::from_str(
1033 r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z"}"#,
1034 )
1035 .unwrap();
1036 assert_eq!(entry.text(), "");
1037 }
1038
1039 #[test]
1040 fn test_entry_role() {
1041 let entry: ConversationEntry = serde_json::from_str(
1042 r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"hi"}}"#,
1043 )
1044 .unwrap();
1045 assert_eq!(entry.role(), Some(&MessageRole::User));
1046 }
1047
1048 #[test]
1049 fn test_entry_stop_reason() {
1050 let entry: ConversationEntry = serde_json::from_str(
1051 r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"done","stopReason":"end_turn"}}"#,
1052 )
1053 .unwrap();
1054 assert_eq!(entry.stop_reason(), Some("end_turn"));
1055 }
1056
1057 #[test]
1060 fn test_stop_reason_snake_case() {
1061 let entry: ConversationEntry = serde_json::from_str(
1062 r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"done","stop_reason":"end_turn","stop_sequence":null}}"#,
1063 )
1064 .unwrap();
1065 assert_eq!(entry.stop_reason(), Some("end_turn"));
1066 assert!(entry.message.as_ref().unwrap().stop_sequence.is_none());
1067 }
1068
1069 #[test]
1070 fn test_usage_snake_case() {
1071 let entry: ConversationEntry = serde_json::from_str(
1072 r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"hi","usage":{"input_tokens":1200,"output_tokens":350,"cache_creation_input_tokens":100,"cache_read_input_tokens":500,"service_tier":"standard"}}}"#,
1073 )
1074 .unwrap();
1075 let usage = entry.message.unwrap().usage.unwrap();
1076 assert_eq!(usage.input_tokens, Some(1200));
1077 assert_eq!(usage.output_tokens, Some(350));
1078 assert_eq!(usage.cache_creation_input_tokens, Some(100));
1079 assert_eq!(usage.cache_read_input_tokens, Some(500));
1080 assert_eq!(usage.service_tier.as_deref(), Some("standard"));
1081 }
1082
1083 #[test]
1084 fn test_cache_creation_snake_case() {
1085 let json = r#"{"ephemeral_5m_input_tokens":10,"ephemeral_1h_input_tokens":20}"#;
1086 let cc: CacheCreation = serde_json::from_str(json).unwrap();
1087 assert_eq!(cc.ephemeral_5m_input_tokens, Some(10));
1088 assert_eq!(cc.ephemeral_1h_input_tokens, Some(20));
1089 }
1090
1091 #[test]
1092 fn test_full_assistant_entry_snake_case() {
1093 let json = r#"{"parentUuid":"abc","isSidechain":false,"userType":"external","cwd":"/project","sessionId":"sess-1","version":"2.1.37","message":{"model":"claude-opus-4-6","id":"msg_123","type":"message","role":"assistant","content":[{"type":"text","text":"Done."}],"stop_reason":"end_turn","stop_sequence":null,"usage":{"input_tokens":3,"cache_creation_input_tokens":4561,"cache_read_input_tokens":17868,"cache_creation":{"ephemeral_5m_input_tokens":0,"ephemeral_1h_input_tokens":4561},"output_tokens":4,"service_tier":"standard"}},"requestId":"req_123","type":"assistant","uuid":"u1","timestamp":"2024-01-01T00:00:00Z"}"#;
1095 let entry: ConversationEntry = serde_json::from_str(json).unwrap();
1096 let msg = entry.message.unwrap();
1097 assert_eq!(msg.stop_reason.as_deref(), Some("end_turn"));
1098 assert!(msg.stop_sequence.is_none());
1099 let usage = msg.usage.unwrap();
1100 assert_eq!(usage.input_tokens, Some(3));
1101 assert_eq!(usage.output_tokens, Some(4));
1102 assert_eq!(usage.cache_creation_input_tokens, Some(4561));
1103 assert_eq!(usage.cache_read_input_tokens, Some(17868));
1104 assert_eq!(usage.service_tier.as_deref(), Some("standard"));
1105 let cc = usage.cache_creation.unwrap();
1106 assert_eq!(cc.ephemeral_5m_input_tokens, Some(0));
1107 assert_eq!(cc.ephemeral_1h_input_tokens, Some(4561));
1108 }
1109
1110 #[test]
1111 fn test_entry_model() {
1112 let entry: ConversationEntry = serde_json::from_str(
1113 r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"hi","model":"claude-opus-4-6"}}"#,
1114 )
1115 .unwrap();
1116 assert_eq!(entry.model(), Some("claude-opus-4-6"));
1117 }
1118
1119 #[test]
1122 fn test_conversation_title() {
1123 let convo = create_test_conversation();
1124 let title = convo.title(4).unwrap();
1125 assert_eq!(title, "Hell...");
1126 }
1127
1128 #[test]
1129 fn test_conversation_title_short() {
1130 let convo = create_test_conversation();
1131 let title = convo.title(100).unwrap();
1132 assert_eq!(title, "Hello");
1133 }
1134
1135 #[test]
1136 fn test_conversation_first_user_text() {
1137 let convo = create_test_conversation();
1138 assert_eq!(convo.first_user_text(), Some("Hello".to_string()));
1139 }
1140
1141 #[test]
1142 fn test_conversation_title_empty() {
1143 let convo = Conversation::new("empty".to_string());
1144 assert!(convo.title(50).is_none());
1145 }
1146}