Skip to main content

toolpath_claude/
types.rs

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    /// Catch-all for unknown content types
115    #[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/// A reference to a tool use entry within a content part.
146#[derive(Debug)]
147pub struct ToolUseRef<'a> {
148    pub id: &'a str,
149    pub name: &'a str,
150    pub input: &'a Value,
151}
152
153/// A reference to a tool result entry within a content part.
154#[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    /// Collapsed text content, joining all text parts with newlines.
163    ///
164    /// Returns an empty string if content is `None` or contains no text parts.
165    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    /// Thinking blocks, if any.
181    ///
182    /// Returns `None` when the message has no thinking content (not an empty vec).
183    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    /// Tool use entries, if any.
203    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    /// Tool result entries, if any.
218    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    /// Whether this message has the given role.
241    pub fn is_role(&self, role: MessageRole) -> bool {
242        self.role == role
243    }
244
245    /// Whether this is a user message.
246    pub fn is_user(&self) -> bool {
247        self.role == MessageRole::User
248    }
249
250    /// Whether this is an assistant message.
251    pub fn is_assistant(&self) -> bool {
252        self.role == MessageRole::Assistant
253    }
254}
255
256impl ConversationEntry {
257    /// Role of the message, if present.
258    pub fn role(&self) -> Option<&MessageRole> {
259        self.message.as_ref().map(|m| &m.role)
260    }
261
262    /// Collapsed text content of the message.
263    ///
264    /// Delegates to [`Message::text`]. Returns an empty string if no message is present.
265    pub fn text(&self) -> String {
266        self.message.as_ref().map(|m| m.text()).unwrap_or_default()
267    }
268
269    /// Thinking blocks from the message, if any.
270    pub fn thinking(&self) -> Option<Vec<&str>> {
271        self.message.as_ref().and_then(|m| m.thinking())
272    }
273
274    /// Tool use entries from the message, if any.
275    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    /// Stop reason, if present.
283    pub fn stop_reason(&self) -> Option<&str> {
284        self.message.as_ref().and_then(|m| m.stop_reason.as_deref())
285    }
286
287    /// Model name, if present.
288    pub fn model(&self) -> Option<&str> {
289        self.message.as_ref().and_then(|m| m.model.as_deref())
290    }
291}
292
293impl ContentPart {
294    /// Returns a short summary of this content part.
295    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// Claude's JSONL envelope is camelCase (`parentUuid`, `sessionId`, etc.),
346// but the embedded `message.usage` object is forwarded straight from the
347// Anthropic API — which is snake_case. Mismatching this breaks the UI's
348// context-window readout (it parses `input_tokens` etc. and renders NaN
349// when they're absent).
350#[derive(Debug, Clone, Serialize, Deserialize)]
351#[serde(rename_all = "snake_case")]
352pub struct Usage {
353    pub input_tokens: Option<u32>,
354    pub output_tokens: Option<u32>,
355    pub cache_creation_input_tokens: Option<u32>,
356    pub cache_read_input_tokens: Option<u32>,
357    pub cache_creation: Option<CacheCreation>,
358    pub service_tier: Option<String>,
359}
360
361#[derive(Debug, Clone, Serialize, Deserialize)]
362#[serde(rename_all = "snake_case")]
363pub struct CacheCreation {
364    pub ephemeral_5m_input_tokens: Option<u32>,
365    pub ephemeral_1h_input_tokens: Option<u32>,
366}
367
368#[derive(Debug, Clone, Serialize, Deserialize)]
369pub struct HistoryEntry {
370    pub display: String,
371
372    #[serde(rename = "pastedContents", default)]
373    pub pasted_contents: HashMap<String, Value>,
374
375    pub timestamp: i64,
376
377    #[serde(skip_serializing_if = "Option::is_none")]
378    pub project: Option<String>,
379
380    #[serde(rename = "sessionId", skip_serializing_if = "Option::is_none")]
381    pub session_id: Option<String>,
382}
383
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct Conversation {
386    pub session_id: String,
387    pub project_path: Option<String>,
388    pub entries: Vec<ConversationEntry>,
389    pub started_at: Option<DateTime<Utc>>,
390    pub last_activity: Option<DateTime<Utc>>,
391    /// Segment IDs when this conversation spans multiple files.
392    /// Empty for single-segment conversations.
393    #[serde(default, skip_serializing_if = "Vec::is_empty")]
394    pub session_ids: Vec<String>,
395    /// Raw preamble entries (e.g., permission-mode) that precede
396    /// conversation entries in the JSONL file. These are not
397    /// `ConversationEntry` objects — they have different shapes.
398    #[serde(default, skip_serializing_if = "Vec::is_empty")]
399    pub preamble: Vec<serde_json::Value>,
400}
401
402impl Conversation {
403    pub fn new(session_id: String) -> Self {
404        Self {
405            session_id,
406            project_path: None,
407            entries: Vec::new(),
408            started_at: None,
409            last_activity: None,
410            session_ids: Vec::new(),
411            preamble: Vec::new(),
412        }
413    }
414
415    pub fn add_entry(&mut self, entry: ConversationEntry) {
416        if let Ok(timestamp) = entry.timestamp.parse::<DateTime<Utc>>() {
417            if self.started_at.is_none() || Some(timestamp) < self.started_at {
418                self.started_at = Some(timestamp);
419            }
420            if self.last_activity.is_none() || Some(timestamp) > self.last_activity {
421                self.last_activity = Some(timestamp);
422            }
423        }
424
425        if self.project_path.is_none() {
426            self.project_path = entry.cwd.clone();
427        }
428
429        self.entries.push(entry);
430    }
431
432    pub fn user_messages(&self) -> Vec<&ConversationEntry> {
433        self.entries
434            .iter()
435            .filter(|e| {
436                e.entry_type == "user"
437                    && e.message
438                        .as_ref()
439                        .map(|m| m.role == MessageRole::User)
440                        .unwrap_or(false)
441            })
442            .collect()
443    }
444
445    pub fn assistant_messages(&self) -> Vec<&ConversationEntry> {
446        self.entries
447            .iter()
448            .filter(|e| {
449                e.entry_type == "assistant"
450                    && e.message
451                        .as_ref()
452                        .map(|m| m.role == MessageRole::Assistant)
453                        .unwrap_or(false)
454            })
455            .collect()
456    }
457
458    pub fn tool_uses(&self) -> Vec<(&ConversationEntry, &ContentPart)> {
459        let mut results = Vec::new();
460
461        for entry in &self.entries {
462            if let Some(message) = &entry.message
463                && let Some(MessageContent::Parts(parts)) = &message.content
464            {
465                for part in parts {
466                    if matches!(part, ContentPart::ToolUse { .. }) {
467                        results.push((entry, part));
468                    }
469                }
470            }
471        }
472
473        results
474    }
475
476    pub fn message_count(&self) -> usize {
477        self.entries.iter().filter(|e| e.message.is_some()).count()
478    }
479
480    pub fn duration(&self) -> Option<chrono::Duration> {
481        match (self.started_at, self.last_activity) {
482            (Some(start), Some(end)) => Some(end - start),
483            _ => None,
484        }
485    }
486
487    /// Returns entries after the given UUID.
488    /// If the UUID is not found, returns all entries (for full sync).
489    /// If the UUID is the last entry, returns an empty vec.
490    pub fn entries_since(&self, since_uuid: &str) -> Vec<ConversationEntry> {
491        match self.entries.iter().position(|e| e.uuid == since_uuid) {
492            Some(idx) => self.entries.iter().skip(idx + 1).cloned().collect(),
493            None => self.entries.clone(),
494        }
495    }
496
497    /// Returns the UUID of the last entry, if any.
498    pub fn last_uuid(&self) -> Option<&str> {
499        self.entries.last().map(|e| e.uuid.as_str())
500    }
501
502    /// Text of the first user message, truncated to `max_len` characters.
503    pub fn title(&self, max_len: usize) -> Option<String> {
504        self.first_user_text().map(|text| {
505            if text.chars().count() > max_len {
506                let truncated: String = text.chars().take(max_len).collect();
507                format!("{}...", truncated)
508            } else {
509                text
510            }
511        })
512    }
513
514    /// Full text of the first user message, untruncated.
515    pub fn first_user_text(&self) -> Option<String> {
516        self.entries.iter().find_map(|e| {
517            e.message.as_ref().and_then(|msg| {
518                if msg.is_user() {
519                    let text = msg.text();
520                    if text.is_empty() { None } else { Some(text) }
521                } else {
522                    None
523                }
524            })
525        })
526    }
527}
528
529#[derive(Debug, Clone, Serialize, Deserialize)]
530pub struct ConversationMetadata {
531    pub session_id: String,
532    /// Parent directory of `file_path`, unsanitized.
533    pub project_path: String,
534    pub file_path: std::path::PathBuf,
535    pub message_count: usize,
536    pub started_at: Option<DateTime<Utc>>,
537    pub last_activity: Option<DateTime<Utc>>,
538    /// First non-empty user-prompt text. Used as a human-readable title.
539    #[serde(default, skip_serializing_if = "Option::is_none")]
540    pub first_user_message: Option<String>,
541}
542
543#[cfg(test)]
544mod tests {
545    use super::*;
546
547    fn create_test_conversation() -> Conversation {
548        let mut convo = Conversation::new("test-session".to_string());
549
550        let entries = vec![
551            r#"{"uuid":"uuid-1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"Hello"}}"#,
552            r#"{"uuid":"uuid-2","type":"assistant","timestamp":"2024-01-01T00:00:01Z","message":{"role":"assistant","content":"Hi"}}"#,
553            r#"{"uuid":"uuid-3","type":"user","timestamp":"2024-01-01T00:00:02Z","message":{"role":"user","content":"How are you?"}}"#,
554            r#"{"uuid":"uuid-4","type":"assistant","timestamp":"2024-01-01T00:00:03Z","message":{"role":"assistant","content":"I'm good!"}}"#,
555        ];
556
557        for entry_json in entries {
558            let entry: ConversationEntry = serde_json::from_str(entry_json).unwrap();
559            convo.add_entry(entry);
560        }
561
562        convo
563    }
564
565    #[test]
566    fn test_entries_since_middle() {
567        let convo = create_test_conversation();
568
569        // Get entries since uuid-2 (should return uuid-3, uuid-4)
570        let since = convo.entries_since("uuid-2");
571
572        assert_eq!(since.len(), 2);
573        assert_eq!(since[0].uuid, "uuid-3");
574        assert_eq!(since[1].uuid, "uuid-4");
575    }
576
577    #[test]
578    fn test_entries_since_first() {
579        let convo = create_test_conversation();
580
581        // Get entries since uuid-1 (should return uuid-2, uuid-3, uuid-4)
582        let since = convo.entries_since("uuid-1");
583
584        assert_eq!(since.len(), 3);
585        assert_eq!(since[0].uuid, "uuid-2");
586    }
587
588    #[test]
589    fn test_entries_since_last() {
590        let convo = create_test_conversation();
591
592        // Get entries since last UUID (should return empty)
593        let since = convo.entries_since("uuid-4");
594
595        assert!(since.is_empty());
596    }
597
598    #[test]
599    fn test_entries_since_unknown() {
600        let convo = create_test_conversation();
601
602        // Get entries since unknown UUID (should return all entries)
603        let since = convo.entries_since("unknown-uuid");
604
605        assert_eq!(since.len(), 4);
606    }
607
608    #[test]
609    fn test_last_uuid() {
610        let convo = create_test_conversation();
611
612        assert_eq!(convo.last_uuid(), Some("uuid-4"));
613    }
614
615    #[test]
616    fn test_last_uuid_empty() {
617        let convo = Conversation::new("empty-session".to_string());
618
619        assert_eq!(convo.last_uuid(), None);
620    }
621
622    // ── Conversation methods ───────────────────────────────────────────
623
624    #[test]
625    fn test_user_messages() {
626        let convo = create_test_conversation();
627        let users = convo.user_messages();
628        assert_eq!(users.len(), 2);
629        assert!(users.iter().all(|e| e.entry_type == "user"));
630    }
631
632    #[test]
633    fn test_assistant_messages() {
634        let convo = create_test_conversation();
635        let assistants = convo.assistant_messages();
636        assert_eq!(assistants.len(), 2);
637        assert!(assistants.iter().all(|e| e.entry_type == "assistant"));
638    }
639
640    #[test]
641    fn test_message_count() {
642        let convo = create_test_conversation();
643        assert_eq!(convo.message_count(), 4);
644    }
645
646    #[test]
647    fn test_duration() {
648        let convo = create_test_conversation();
649        let dur = convo.duration().unwrap();
650        assert_eq!(dur.num_seconds(), 3); // 00:00:00 to 00:00:03
651    }
652
653    #[test]
654    fn test_duration_empty_conversation() {
655        let convo = Conversation::new("empty".to_string());
656        assert!(convo.duration().is_none());
657    }
658
659    #[test]
660    fn test_add_entry_tracks_timestamps() {
661        let mut convo = Conversation::new("test".to_string());
662        let entry: ConversationEntry = serde_json::from_str(
663            r#"{"uuid":"u1","type":"user","timestamp":"2024-06-15T10:00:00Z","message":{"role":"user","content":"hi"}}"#
664        ).unwrap();
665        convo.add_entry(entry);
666
667        assert!(convo.started_at.is_some());
668        assert!(convo.last_activity.is_some());
669        assert_eq!(convo.started_at, convo.last_activity);
670    }
671
672    #[test]
673    fn test_add_entry_sets_project_path() {
674        let mut convo = Conversation::new("test".to_string());
675        let entry: ConversationEntry = serde_json::from_str(
676            r#"{"uuid":"u1","type":"user","timestamp":"2024-06-15T10:00:00Z","cwd":"/home/user/project","message":{"role":"user","content":"hi"}}"#
677        ).unwrap();
678        convo.add_entry(entry);
679        assert_eq!(convo.project_path.as_deref(), Some("/home/user/project"));
680    }
681
682    #[test]
683    fn test_tool_uses() {
684        let mut convo = Conversation::new("test".to_string());
685        let entry: ConversationEntry = serde_json::from_str(
686            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"}}]}}"#
687        ).unwrap();
688        convo.add_entry(entry);
689
690        let uses = convo.tool_uses();
691        assert_eq!(uses.len(), 1);
692        match uses[0].1 {
693            ContentPart::ToolUse { name, .. } => assert_eq!(name, "Read"),
694            _ => panic!("Expected ToolUse"),
695        }
696    }
697
698    #[test]
699    fn test_tool_uses_empty() {
700        let convo = create_test_conversation();
701        // The test conversation uses MessageContent::Text, no tool uses
702        let uses = convo.tool_uses();
703        assert!(uses.is_empty());
704    }
705
706    // ── ContentPart::summary ───────────────────────────────────────────
707
708    #[test]
709    fn test_content_part_summary_text_short() {
710        let part = ContentPart::Text {
711            text: "Hello world".to_string(),
712        };
713        assert_eq!(part.summary(), "Hello world");
714    }
715
716    #[test]
717    fn test_content_part_summary_text_long() {
718        let long = "A".repeat(200);
719        let part = ContentPart::Text { text: long };
720        let summary = part.summary();
721        assert!(summary.ends_with("..."));
722        assert!(summary.chars().count() <= 100);
723    }
724
725    #[test]
726    fn test_content_part_summary_thinking() {
727        let part = ContentPart::Thinking {
728            thinking: "deep thought".to_string(),
729            signature: None,
730        };
731        assert_eq!(part.summary(), "[thinking]");
732    }
733
734    #[test]
735    fn test_content_part_summary_tool_use() {
736        let part = ContentPart::ToolUse {
737            id: "t1".to_string(),
738            name: "Write".to_string(),
739            input: serde_json::json!({}),
740        };
741        assert_eq!(part.summary(), "[tool_use: Write]");
742    }
743
744    #[test]
745    fn test_content_part_summary_tool_result_short() {
746        let part = ContentPart::ToolResult {
747            tool_use_id: "t1".to_string(),
748            content: ToolResultContent::Text("OK".to_string()),
749            is_error: false,
750        };
751        assert_eq!(part.summary(), "[result: OK]");
752    }
753
754    #[test]
755    fn test_content_part_summary_tool_result_error() {
756        let part = ContentPart::ToolResult {
757            tool_use_id: "t1".to_string(),
758            content: ToolResultContent::Text("fail".to_string()),
759            is_error: true,
760        };
761        assert_eq!(part.summary(), "[error: fail]");
762    }
763
764    #[test]
765    fn test_content_part_summary_tool_result_long() {
766        let long = "X".repeat(200);
767        let part = ContentPart::ToolResult {
768            tool_use_id: "t1".to_string(),
769            content: ToolResultContent::Text(long),
770            is_error: false,
771        };
772        let summary = part.summary();
773        assert!(summary.starts_with("[result:"));
774        assert!(summary.ends_with("...]"));
775    }
776
777    #[test]
778    fn test_content_part_summary_unknown() {
779        let part = ContentPart::Unknown;
780        assert_eq!(part.summary(), "[unknown]");
781    }
782
783    // ── ToolResultContent::text ────────────────────────────────────────
784
785    #[test]
786    fn test_tool_result_content_text_string() {
787        let c = ToolResultContent::Text("hello".to_string());
788        assert_eq!(c.text(), "hello");
789    }
790
791    #[test]
792    fn test_tool_result_content_text_parts() {
793        let c = ToolResultContent::Parts(vec![
794            ToolResultPart {
795                text: Some("line1".to_string()),
796            },
797            ToolResultPart { text: None },
798            ToolResultPart {
799                text: Some("line2".to_string()),
800            },
801        ]);
802        assert_eq!(c.text(), "line1\nline2");
803    }
804
805    // ── MessageRole::from_str ──────────────────────────────────────────
806
807    #[test]
808    fn test_message_role_from_str() {
809        assert_eq!("user".parse::<MessageRole>().unwrap(), MessageRole::User);
810        assert_eq!(
811            "assistant".parse::<MessageRole>().unwrap(),
812            MessageRole::Assistant
813        );
814        assert_eq!(
815            "system".parse::<MessageRole>().unwrap(),
816            MessageRole::System
817        );
818    }
819
820    #[test]
821    fn test_message_role_from_str_case_insensitive() {
822        assert_eq!("USER".parse::<MessageRole>().unwrap(), MessageRole::User);
823        assert_eq!(
824            "Assistant".parse::<MessageRole>().unwrap(),
825            MessageRole::Assistant
826        );
827    }
828
829    #[test]
830    fn test_message_role_from_str_invalid() {
831        assert!("invalid".parse::<MessageRole>().is_err());
832    }
833
834    // ── Message convenience methods ──────────────────────────────────
835
836    #[test]
837    fn test_message_text_from_string() {
838        let msg = Message {
839            role: MessageRole::User,
840            content: Some(MessageContent::Text("Hello world".to_string())),
841            model: None,
842            id: None,
843            message_type: None,
844            stop_reason: None,
845            stop_sequence: None,
846            usage: None,
847        };
848        assert_eq!(msg.text(), "Hello world");
849    }
850
851    #[test]
852    fn test_message_text_from_parts() {
853        let msg = Message {
854            role: MessageRole::Assistant,
855            content: Some(MessageContent::Parts(vec![
856                ContentPart::Text {
857                    text: "First".to_string(),
858                },
859                ContentPart::Thinking {
860                    thinking: "hmm".to_string(),
861                    signature: None,
862                },
863                ContentPart::Text {
864                    text: "Second".to_string(),
865                },
866            ])),
867            model: None,
868            id: None,
869            message_type: None,
870            stop_reason: None,
871            stop_sequence: None,
872            usage: None,
873        };
874        assert_eq!(msg.text(), "First\nSecond");
875    }
876
877    #[test]
878    fn test_message_text_none() {
879        let msg = Message {
880            role: MessageRole::User,
881            content: None,
882            model: None,
883            id: None,
884            message_type: None,
885            stop_reason: None,
886            stop_sequence: None,
887            usage: None,
888        };
889        assert_eq!(msg.text(), "");
890    }
891
892    #[test]
893    fn test_message_thinking() {
894        let msg = Message {
895            role: MessageRole::Assistant,
896            content: Some(MessageContent::Parts(vec![
897                ContentPart::Thinking {
898                    thinking: "deep thought".to_string(),
899                    signature: None,
900                },
901                ContentPart::Text {
902                    text: "answer".to_string(),
903                },
904                ContentPart::Thinking {
905                    thinking: "more thought".to_string(),
906                    signature: None,
907                },
908            ])),
909            model: None,
910            id: None,
911            message_type: None,
912            stop_reason: None,
913            stop_sequence: None,
914            usage: None,
915        };
916        let thinking = msg.thinking().unwrap();
917        assert_eq!(thinking, vec!["deep thought", "more thought"]);
918    }
919
920    #[test]
921    fn test_message_thinking_none() {
922        let msg = Message {
923            role: MessageRole::User,
924            content: Some(MessageContent::Text("hi".to_string())),
925            model: None,
926            id: None,
927            message_type: None,
928            stop_reason: None,
929            stop_sequence: None,
930            usage: None,
931        };
932        assert!(msg.thinking().is_none());
933    }
934
935    #[test]
936    fn test_message_tool_uses() {
937        let msg = Message {
938            role: MessageRole::Assistant,
939            content: Some(MessageContent::Parts(vec![
940                ContentPart::ToolUse {
941                    id: "t1".to_string(),
942                    name: "Read".to_string(),
943                    input: serde_json::json!({"file": "test.rs"}),
944                },
945                ContentPart::Text {
946                    text: "checking".to_string(),
947                },
948                ContentPart::ToolUse {
949                    id: "t2".to_string(),
950                    name: "Write".to_string(),
951                    input: serde_json::json!({}),
952                },
953            ])),
954            model: None,
955            id: None,
956            message_type: None,
957            stop_reason: None,
958            stop_sequence: None,
959            usage: None,
960        };
961        let uses = msg.tool_uses();
962        assert_eq!(uses.len(), 2);
963        assert_eq!(uses[0].name, "Read");
964        assert_eq!(uses[1].name, "Write");
965    }
966
967    #[test]
968    fn test_message_tool_results() {
969        let msg = Message {
970            role: MessageRole::User,
971            content: Some(MessageContent::Parts(vec![
972                ContentPart::ToolResult {
973                    tool_use_id: "t1".to_string(),
974                    content: ToolResultContent::Text("file contents".to_string()),
975                    is_error: false,
976                },
977                ContentPart::ToolResult {
978                    tool_use_id: "t2".to_string(),
979                    content: ToolResultContent::Text("error msg".to_string()),
980                    is_error: true,
981                },
982            ])),
983            model: None,
984            id: None,
985            message_type: None,
986            stop_reason: None,
987            stop_sequence: None,
988            usage: None,
989        };
990        let results = msg.tool_results();
991        assert_eq!(results.len(), 2);
992        assert_eq!(results[0].tool_use_id, "t1");
993        assert_eq!(results[0].content.text(), "file contents");
994        assert!(!results[0].is_error);
995        assert_eq!(results[1].tool_use_id, "t2");
996        assert!(results[1].is_error);
997    }
998
999    #[test]
1000    fn test_message_tool_results_empty() {
1001        let msg = Message {
1002            role: MessageRole::User,
1003            content: Some(MessageContent::Text("hello".to_string())),
1004            model: None,
1005            id: None,
1006            message_type: None,
1007            stop_reason: None,
1008            stop_sequence: None,
1009            usage: None,
1010        };
1011        assert!(msg.tool_results().is_empty());
1012    }
1013
1014    #[test]
1015    fn test_message_role_checks() {
1016        let user_msg = Message {
1017            role: MessageRole::User,
1018            content: None,
1019            model: None,
1020            id: None,
1021            message_type: None,
1022            stop_reason: None,
1023            stop_sequence: None,
1024            usage: None,
1025        };
1026        assert!(user_msg.is_user());
1027        assert!(!user_msg.is_assistant());
1028        assert!(user_msg.is_role(MessageRole::User));
1029    }
1030
1031    // ── ConversationEntry convenience methods ────────────────────────
1032
1033    #[test]
1034    fn test_entry_text() {
1035        let entry: ConversationEntry = serde_json::from_str(
1036            r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"Hello there"}}"#,
1037        )
1038        .unwrap();
1039        assert_eq!(entry.text(), "Hello there");
1040    }
1041
1042    #[test]
1043    fn test_entry_text_no_message() {
1044        let entry: ConversationEntry = serde_json::from_str(
1045            r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z"}"#,
1046        )
1047        .unwrap();
1048        assert_eq!(entry.text(), "");
1049    }
1050
1051    #[test]
1052    fn test_entry_role() {
1053        let entry: ConversationEntry = serde_json::from_str(
1054            r#"{"uuid":"u1","type":"user","timestamp":"2024-01-01T00:00:00Z","message":{"role":"user","content":"hi"}}"#,
1055        )
1056        .unwrap();
1057        assert_eq!(entry.role(), Some(&MessageRole::User));
1058    }
1059
1060    #[test]
1061    fn test_entry_stop_reason() {
1062        let entry: ConversationEntry = serde_json::from_str(
1063            r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"done","stopReason":"end_turn"}}"#,
1064        )
1065        .unwrap();
1066        assert_eq!(entry.stop_reason(), Some("end_turn"));
1067    }
1068
1069    // ── Snake_case deserialization (real JSONL format) ─────────────
1070
1071    #[test]
1072    fn test_stop_reason_snake_case() {
1073        let entry: ConversationEntry = serde_json::from_str(
1074            r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"done","stop_reason":"end_turn","stop_sequence":null}}"#,
1075        )
1076        .unwrap();
1077        assert_eq!(entry.stop_reason(), Some("end_turn"));
1078        assert!(entry.message.as_ref().unwrap().stop_sequence.is_none());
1079    }
1080
1081    #[test]
1082    fn test_usage_snake_case() {
1083        let entry: ConversationEntry = serde_json::from_str(
1084            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"}}}"#,
1085        )
1086        .unwrap();
1087        let usage = entry.message.unwrap().usage.unwrap();
1088        assert_eq!(usage.input_tokens, Some(1200));
1089        assert_eq!(usage.output_tokens, Some(350));
1090        assert_eq!(usage.cache_creation_input_tokens, Some(100));
1091        assert_eq!(usage.cache_read_input_tokens, Some(500));
1092        assert_eq!(usage.service_tier.as_deref(), Some("standard"));
1093    }
1094
1095    #[test]
1096    fn test_cache_creation_snake_case() {
1097        let json = r#"{"ephemeral_5m_input_tokens":10,"ephemeral_1h_input_tokens":20}"#;
1098        let cc: CacheCreation = serde_json::from_str(json).unwrap();
1099        assert_eq!(cc.ephemeral_5m_input_tokens, Some(10));
1100        assert_eq!(cc.ephemeral_1h_input_tokens, Some(20));
1101    }
1102
1103    #[test]
1104    fn test_full_assistant_entry_snake_case() {
1105        // Matches the actual JSONL format written by Claude Code
1106        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"}"#;
1107        let entry: ConversationEntry = serde_json::from_str(json).unwrap();
1108        let msg = entry.message.unwrap();
1109        assert_eq!(msg.stop_reason.as_deref(), Some("end_turn"));
1110        assert!(msg.stop_sequence.is_none());
1111        let usage = msg.usage.unwrap();
1112        assert_eq!(usage.input_tokens, Some(3));
1113        assert_eq!(usage.output_tokens, Some(4));
1114        assert_eq!(usage.cache_creation_input_tokens, Some(4561));
1115        assert_eq!(usage.cache_read_input_tokens, Some(17868));
1116        assert_eq!(usage.service_tier.as_deref(), Some("standard"));
1117        let cc = usage.cache_creation.unwrap();
1118        assert_eq!(cc.ephemeral_5m_input_tokens, Some(0));
1119        assert_eq!(cc.ephemeral_1h_input_tokens, Some(4561));
1120    }
1121
1122    #[test]
1123    fn test_entry_model() {
1124        let entry: ConversationEntry = serde_json::from_str(
1125            r#"{"uuid":"u1","type":"assistant","timestamp":"2024-01-01T00:00:00Z","message":{"role":"assistant","content":"hi","model":"claude-opus-4-6"}}"#,
1126        )
1127        .unwrap();
1128        assert_eq!(entry.model(), Some("claude-opus-4-6"));
1129    }
1130
1131    // ── Conversation title/first_user_text ───────────────────────────
1132
1133    #[test]
1134    fn test_conversation_title() {
1135        let convo = create_test_conversation();
1136        let title = convo.title(4).unwrap();
1137        assert_eq!(title, "Hell...");
1138    }
1139
1140    #[test]
1141    fn test_conversation_title_short() {
1142        let convo = create_test_conversation();
1143        let title = convo.title(100).unwrap();
1144        assert_eq!(title, "Hello");
1145    }
1146
1147    #[test]
1148    fn test_conversation_first_user_text() {
1149        let convo = create_test_conversation();
1150        assert_eq!(convo.first_user_text(), Some("Hello".to_string()));
1151    }
1152
1153    #[test]
1154    fn test_conversation_title_empty() {
1155        let convo = Conversation::new("empty".to_string());
1156        assert!(convo.title(50).is_none());
1157    }
1158}