Skip to main content

ccboard_core/models/
session.rs

1//! Session models for JSONL session files
2
3use chrono::{DateTime, Utc};
4use rusqlite::types::{FromSql, FromSqlError, ToSql, ToSqlOutput, ValueRef};
5use serde::{Deserialize, Serialize};
6use serde_json::Value;
7use std::borrow::{Borrow, Cow};
8use std::fmt;
9use std::ops::{Deref, Index, Range, RangeFrom, RangeFull, RangeTo};
10use std::path::PathBuf;
11
12/// Newtype for Session ID - zero-cost type safety
13#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(transparent)]
15pub struct SessionId(String);
16
17impl SessionId {
18    /// Create a new SessionId
19    pub fn new(id: String) -> Self {
20        Self(id)
21    }
22
23    /// Get reference to inner string
24    pub fn as_str(&self) -> &str {
25        &self.0
26    }
27
28    /// Extract inner String, consuming self
29    pub fn into_inner(self) -> String {
30        self.0
31    }
32
33    /// Check if the session ID is empty
34    pub fn is_empty(&self) -> bool {
35        self.0.is_empty()
36    }
37
38    /// Get an iterator over the characters
39    pub fn chars(&self) -> std::str::Chars<'_> {
40        self.0.chars()
41    }
42
43    /// Check if the session ID starts with a given pattern
44    pub fn starts_with(&self, pattern: &str) -> bool {
45        self.0.starts_with(pattern)
46    }
47
48    /// Get the length of the session ID
49    pub fn len(&self) -> usize {
50        self.0.len()
51    }
52}
53
54impl From<String> for SessionId {
55    fn from(s: String) -> Self {
56        Self(s)
57    }
58}
59
60impl From<&str> for SessionId {
61    fn from(s: &str) -> Self {
62        Self(s.to_string())
63    }
64}
65
66impl fmt::Display for SessionId {
67    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
68        write!(f, "{}", self.0)
69    }
70}
71
72impl AsRef<str> for SessionId {
73    fn as_ref(&self) -> &str {
74        &self.0
75    }
76}
77
78impl PartialEq<str> for SessionId {
79    fn eq(&self, other: &str) -> bool {
80        self.0 == other
81    }
82}
83
84impl PartialEq<&str> for SessionId {
85    fn eq(&self, other: &&str) -> bool {
86        self.0 == *other
87    }
88}
89
90impl PartialEq<String> for SessionId {
91    fn eq(&self, other: &String) -> bool {
92        &self.0 == other
93    }
94}
95
96impl ToSql for SessionId {
97    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
98        Ok(ToSqlOutput::from(self.0.as_str()))
99    }
100}
101
102impl FromSql for SessionId {
103    fn column_result(value: ValueRef<'_>) -> Result<Self, FromSqlError> {
104        value.as_str().map(SessionId::from)
105    }
106}
107
108impl Borrow<str> for SessionId {
109    fn borrow(&self) -> &str {
110        &self.0
111    }
112}
113
114impl Deref for SessionId {
115    type Target = str;
116
117    fn deref(&self) -> &Self::Target {
118        &self.0
119    }
120}
121
122impl Index<RangeFull> for SessionId {
123    type Output = str;
124
125    fn index(&self, _index: RangeFull) -> &Self::Output {
126        &self.0
127    }
128}
129
130impl Index<Range<usize>> for SessionId {
131    type Output = str;
132
133    fn index(&self, index: Range<usize>) -> &Self::Output {
134        &self.0[index]
135    }
136}
137
138impl Index<RangeFrom<usize>> for SessionId {
139    type Output = str;
140
141    fn index(&self, index: RangeFrom<usize>) -> &Self::Output {
142        &self.0[index]
143    }
144}
145
146impl Index<RangeTo<usize>> for SessionId {
147    type Output = str;
148
149    fn index(&self, index: RangeTo<usize>) -> &Self::Output {
150        &self.0[index]
151    }
152}
153
154impl<'a> From<&'a SessionId> for Cow<'a, str> {
155    fn from(id: &'a SessionId) -> Self {
156        Cow::Borrowed(id.as_str())
157    }
158}
159
160/// Newtype for Project ID - zero-cost type safety
161#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
162#[serde(transparent)]
163pub struct ProjectId(String);
164
165impl ProjectId {
166    /// Create a new ProjectId
167    pub fn new(id: String) -> Self {
168        Self(id)
169    }
170
171    /// Get reference to inner string
172    pub fn as_str(&self) -> &str {
173        &self.0
174    }
175
176    /// Extract inner String, consuming self
177    pub fn into_inner(self) -> String {
178        self.0
179    }
180
181    /// Get the length of the project ID
182    pub fn len(&self) -> usize {
183        self.0.len()
184    }
185
186    /// Check if the project ID is empty
187    #[allow(dead_code)]
188    pub fn is_empty(&self) -> bool {
189        self.0.is_empty()
190    }
191
192    /// Convert to lowercase
193    pub fn to_lowercase(&self) -> String {
194        self.0.to_lowercase()
195    }
196}
197
198impl From<String> for ProjectId {
199    fn from(s: String) -> Self {
200        Self(s)
201    }
202}
203
204impl From<&str> for ProjectId {
205    fn from(s: &str) -> Self {
206        Self(s.to_string())
207    }
208}
209
210impl fmt::Display for ProjectId {
211    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
212        write!(f, "{}", self.0)
213    }
214}
215
216impl AsRef<str> for ProjectId {
217    fn as_ref(&self) -> &str {
218        &self.0
219    }
220}
221
222impl ToSql for ProjectId {
223    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
224        Ok(ToSqlOutput::from(self.0.as_str()))
225    }
226}
227
228impl FromSql for ProjectId {
229    fn column_result(value: ValueRef<'_>) -> Result<Self, FromSqlError> {
230        value.as_str().map(ProjectId::from)
231    }
232}
233
234impl Deref for ProjectId {
235    type Target = str;
236
237    fn deref(&self) -> &Self::Target {
238        &self.0
239    }
240}
241
242impl<'a> From<&'a ProjectId> for Cow<'a, str> {
243    fn from(id: &'a ProjectId) -> Self {
244        Cow::Borrowed(id.as_str())
245    }
246}
247
248/// Message role in conversation
249#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
250#[serde(rename_all = "lowercase")]
251pub enum MessageRole {
252    #[default]
253    User,
254    Assistant,
255    System,
256}
257
258/// A single line from a session JSONL file
259#[derive(Debug, Clone, Default, Serialize, Deserialize)]
260#[serde(rename_all = "camelCase")]
261pub struct SessionLine {
262    /// Session ID
263    #[serde(default)]
264    pub session_id: Option<String>,
265
266    /// Event type: "user", "assistant", "file-history-snapshot", "session_end", etc.
267    #[serde(rename = "type")]
268    pub line_type: String,
269
270    /// Timestamp of the event
271    #[serde(default)]
272    pub timestamp: Option<DateTime<Utc>>,
273
274    /// Current working directory
275    #[serde(default)]
276    pub cwd: Option<String>,
277
278    /// Git branch (if available)
279    #[serde(default)]
280    pub git_branch: Option<String>,
281
282    /// Message content (for user/assistant types)
283    #[serde(default)]
284    pub message: Option<SessionMessage>,
285
286    /// Model used (for assistant messages)
287    #[serde(default)]
288    pub model: Option<String>,
289
290    /// Token usage for this message
291    #[serde(default)]
292    pub usage: Option<TokenUsage>,
293
294    /// Summary data (for session_end type)
295    #[serde(default)]
296    pub summary: Option<SessionSummary>,
297
298    /// Parent session ID (for subagents)
299    #[serde(default)]
300    pub parent_session_id: Option<String>,
301}
302
303/// Message content in a session
304#[derive(Debug, Clone, Serialize, Deserialize)]
305#[serde(rename_all = "camelCase")]
306pub struct SessionMessage {
307    /// Role: "user" or "assistant"
308    #[serde(default)]
309    pub role: Option<String>,
310
311    /// Text content (can be String or Array of content blocks in newer Claude Code versions)
312    #[serde(default)]
313    pub content: Option<Value>,
314
315    /// Tool calls made
316    #[serde(default)]
317    pub tool_calls: Option<Vec<serde_json::Value>>,
318
319    /// Tool results
320    #[serde(default)]
321    pub tool_results: Option<Vec<serde_json::Value>>,
322
323    /// Token usage (for assistant messages)
324    #[serde(default)]
325    pub usage: Option<TokenUsage>,
326}
327
328/// Token usage for a message
329#[derive(Debug, Clone, Default, Serialize, Deserialize)]
330pub struct TokenUsage {
331    #[serde(default)]
332    pub input_tokens: u64,
333
334    #[serde(default)]
335    pub output_tokens: u64,
336
337    /// Cache read tokens (from cache_read_input_tokens in JSONL)
338    #[serde(default, alias = "cache_read_input_tokens")]
339    pub cache_read_tokens: u64,
340
341    /// Cache creation tokens (from cache_creation_input_tokens in JSONL)
342    #[serde(default, alias = "cache_creation_input_tokens")]
343    pub cache_write_tokens: u64,
344}
345
346impl TokenUsage {
347    /// Total tokens including cache reads and writes
348    ///
349    /// This is the sum of all token types:
350    /// - input_tokens: Regular input tokens (not cached)
351    /// - output_tokens: Generated tokens
352    /// - cache_read_tokens: Tokens read from cache (cache hits)
353    /// - cache_write_tokens: Tokens written to cache (cache creation)
354    pub fn total(&self) -> u64 {
355        self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens
356    }
357}
358
359/// Summary at session end
360#[derive(Debug, Clone, Default, Serialize, Deserialize)]
361#[serde(rename_all = "camelCase")]
362pub struct SessionSummary {
363    #[serde(default)]
364    pub total_tokens: u64,
365    #[serde(default)]
366    pub total_input_tokens: u64,
367    #[serde(default)]
368    pub total_output_tokens: u64,
369    #[serde(default)]
370    pub total_cache_read_tokens: u64,
371    #[serde(default)]
372    pub total_cache_write_tokens: u64,
373    #[serde(default)]
374    pub message_count: u64,
375    #[serde(default)]
376    pub duration_seconds: Option<u64>,
377    #[serde(default)]
378    pub models_used: Option<Vec<String>>,
379}
380
381/// Metadata extracted from a session without full parse
382///
383/// Created by streaming the JSONL until session_end event.
384#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct SessionMetadata {
386    /// Session ID (from filename or content)
387    pub id: SessionId,
388
389    /// Full path to the JSONL file
390    pub file_path: PathBuf,
391
392    /// Project path (extracted from directory structure)
393    pub project_path: ProjectId,
394
395    /// First timestamp in session
396    pub first_timestamp: Option<DateTime<Utc>>,
397
398    /// Last timestamp in session
399    pub last_timestamp: Option<DateTime<Utc>>,
400
401    /// Total message count (from summary or counted)
402    pub message_count: u64,
403
404    /// Total tokens (from summary)
405    pub total_tokens: u64,
406
407    /// Token breakdown for precise pricing
408    pub input_tokens: u64,
409    pub output_tokens: u64,
410    pub cache_creation_tokens: u64,
411    pub cache_read_tokens: u64,
412
413    /// Models used in this session
414    pub models_used: Vec<String>,
415
416    /// File size in bytes
417    pub file_size_bytes: u64,
418
419    /// Preview of first user message (truncated to 200 chars)
420    pub first_user_message: Option<String>,
421
422    /// Whether this session spawned subagents
423    pub has_subagents: bool,
424
425    /// Duration in seconds (from summary)
426    pub duration_seconds: Option<u64>,
427
428    /// Git branch name (normalized, extracted from first gitBranch in session)
429    pub branch: Option<String>,
430
431    /// Tool usage statistics: tool name -> call count
432    /// Extracted from tool_calls in assistant messages during session scan
433    pub tool_usage: std::collections::HashMap<String, usize>,
434}
435
436impl SessionMetadata {
437    /// Create a minimal metadata from just file path
438    pub fn from_path(path: PathBuf, project_path: ProjectId) -> Self {
439        let id = SessionId::new(
440            path.file_stem()
441                .and_then(|s| s.to_str())
442                .unwrap_or("unknown")
443                .to_string(),
444        );
445
446        let file_size_bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
447
448        Self {
449            id,
450            file_path: path,
451            project_path,
452            first_timestamp: None,
453            last_timestamp: None,
454            message_count: 0,
455            total_tokens: 0,
456            input_tokens: 0,
457            output_tokens: 0,
458            cache_creation_tokens: 0,
459            cache_read_tokens: 0,
460            models_used: Vec::new(),
461            file_size_bytes,
462            first_user_message: None,
463            has_subagents: false,
464            duration_seconds: None,
465            branch: None,
466            tool_usage: std::collections::HashMap::new(),
467        }
468    }
469
470    /// Human-readable duration
471    pub fn duration_display(&self) -> String {
472        match self.duration_seconds {
473            Some(s) if s >= 3600 => format!("{}h {}m", s / 3600, (s % 3600) / 60),
474            Some(s) if s >= 60 => format!("{}m {}s", s / 60, s % 60),
475            Some(s) => format!("{}s", s),
476            None => "unknown".to_string(),
477        }
478    }
479
480    /// Human-readable file size
481    pub fn size_display(&self) -> String {
482        let bytes = self.file_size_bytes;
483        if bytes >= 1_000_000 {
484            format!("{:.1} MB", bytes as f64 / 1_000_000.0)
485        } else if bytes >= 1_000 {
486            format!("{:.1} KB", bytes as f64 / 1_000.0)
487        } else {
488            format!("{} B", bytes)
489        }
490    }
491}
492
493/// A single conversation message extracted from session JSONL
494///
495/// Simplified representation for display in conversation viewer.
496#[derive(Debug, Clone, Serialize, Deserialize)]
497pub struct ConversationMessage {
498    /// Message role (User, Assistant, System)
499    pub role: MessageRole,
500
501    /// Text content (extracted from SessionLine.message.content)
502    pub content: String,
503
504    /// Timestamp when message was sent
505    pub timestamp: Option<DateTime<Utc>>,
506
507    /// Model used (for assistant messages)
508    pub model: Option<String>,
509
510    /// Token usage (for assistant messages)
511    pub tokens: Option<TokenUsage>,
512
513    /// Tool calls made in this message (if any)
514    #[serde(default)]
515    pub tool_calls: Vec<ToolCall>,
516
517    /// Tool results received (if any)
518    #[serde(default)]
519    pub tool_results: Vec<ToolResult>,
520}
521
522/// A tool call made by the assistant
523#[derive(Debug, Clone, Serialize, Deserialize)]
524pub struct ToolCall {
525    /// Tool name (e.g., "Read", "Bash", "Edit")
526    pub name: String,
527
528    /// Tool call ID for matching with results
529    pub id: String,
530
531    /// Input parameters as JSON
532    pub input: serde_json::Value,
533}
534
535/// Result of a tool call execution
536#[derive(Debug, Clone, Serialize, Deserialize)]
537pub struct ToolResult {
538    /// Tool call ID this result corresponds to
539    pub tool_call_id: String,
540
541    /// Whether the tool succeeded
542    pub is_error: bool,
543
544    /// Output content
545    pub content: String,
546}
547
548/// Full session content with metadata + messages
549///
550/// Returned by SessionContentParser for lazy-loaded session display.
551#[derive(Debug, Clone, Serialize, Deserialize)]
552pub struct SessionContent {
553    /// Messages in chronological order
554    pub messages: Vec<ConversationMessage>,
555
556    /// Session metadata (from cache or index)
557    pub metadata: SessionMetadata,
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    #[test]
565    fn test_token_usage_total() {
566        let usage = TokenUsage {
567            input_tokens: 100,
568            output_tokens: 50,
569            ..Default::default()
570        };
571        assert_eq!(usage.total(), 150);
572    }
573
574    #[test]
575    fn test_session_metadata_duration_display() {
576        let mut meta =
577            SessionMetadata::from_path(PathBuf::from("/test.jsonl"), ProjectId::from("test"));
578
579        meta.duration_seconds = Some(90);
580        assert_eq!(meta.duration_display(), "1m 30s");
581
582        meta.duration_seconds = Some(3665);
583        assert_eq!(meta.duration_display(), "1h 1m");
584
585        meta.duration_seconds = Some(45);
586        assert_eq!(meta.duration_display(), "45s");
587    }
588
589    #[test]
590    fn test_session_metadata_size_display() {
591        let mut meta =
592            SessionMetadata::from_path(PathBuf::from("/test.jsonl"), ProjectId::from("test"));
593
594        meta.file_size_bytes = 500;
595        assert_eq!(meta.size_display(), "500 B");
596
597        meta.file_size_bytes = 5_000;
598        assert_eq!(meta.size_display(), "5.0 KB");
599
600        meta.file_size_bytes = 2_500_000;
601        assert_eq!(meta.size_display(), "2.5 MB");
602    }
603}
604
605#[cfg(test)]
606mod token_tests {
607    use super::*;
608
609    #[test]
610    fn test_real_claude_token_format_deserialization() {
611        // CRITICAL: Real format from Claude Code v2.1.29+
612        let json = r#"{
613            "input_tokens": 10,
614            "cache_creation_input_tokens": 64100,
615            "cache_read_input_tokens": 19275,
616            "cache_creation": {
617                "ephemeral_5m_input_tokens": 0,
618                "ephemeral_1h_input_tokens": 64100
619            },
620            "output_tokens": 1,
621            "service_tier": "standard"
622        }"#;
623
624        let result: Result<TokenUsage, _> = serde_json::from_str(json);
625
626        assert!(
627            result.is_ok(),
628            "Deserialization MUST succeed for real Claude format. Error: {:?}",
629            result.err()
630        );
631
632        let usage = result.unwrap();
633        assert_eq!(usage.input_tokens, 10);
634        assert_eq!(usage.output_tokens, 1);
635        assert_eq!(usage.cache_read_tokens, 19275);
636        assert_eq!(usage.cache_write_tokens, 64100);
637
638        let total = usage.total();
639        assert_eq!(total, 83386, "Total should be 10+1+19275+64100 = 83386");
640    }
641}