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    /// Per-tool token attribution: tool name -> tokens
436    /// Proportionally distributed from message-level token counts
437    #[serde(default)]
438    pub tool_token_usage: std::collections::HashMap<String, u64>,
439}
440
441impl SessionMetadata {
442    /// Create a minimal metadata from just file path
443    pub fn from_path(path: PathBuf, project_path: ProjectId) -> Self {
444        let id = SessionId::new(
445            path.file_stem()
446                .and_then(|s| s.to_str())
447                .unwrap_or("unknown")
448                .to_string(),
449        );
450
451        let file_size_bytes = std::fs::metadata(&path).map(|m| m.len()).unwrap_or(0);
452
453        Self {
454            id,
455            file_path: path,
456            project_path,
457            first_timestamp: None,
458            last_timestamp: None,
459            message_count: 0,
460            total_tokens: 0,
461            input_tokens: 0,
462            output_tokens: 0,
463            cache_creation_tokens: 0,
464            cache_read_tokens: 0,
465            models_used: Vec::new(),
466            file_size_bytes,
467            first_user_message: None,
468            has_subagents: false,
469            duration_seconds: None,
470            branch: None,
471            tool_usage: std::collections::HashMap::new(),
472            tool_token_usage: std::collections::HashMap::new(),
473        }
474    }
475
476    /// Human-readable duration
477    pub fn duration_display(&self) -> String {
478        match self.duration_seconds {
479            Some(s) if s >= 3600 => format!("{}h {}m", s / 3600, (s % 3600) / 60),
480            Some(s) if s >= 60 => format!("{}m {}s", s / 60, s % 60),
481            Some(s) => format!("{}s", s),
482            None => "unknown".to_string(),
483        }
484    }
485
486    /// Human-readable file size
487    pub fn size_display(&self) -> String {
488        let bytes = self.file_size_bytes;
489        if bytes >= 1_000_000 {
490            format!("{:.1} MB", bytes as f64 / 1_000_000.0)
491        } else if bytes >= 1_000 {
492            format!("{:.1} KB", bytes as f64 / 1_000.0)
493        } else {
494            format!("{} B", bytes)
495        }
496    }
497}
498
499/// A single conversation message extracted from session JSONL
500///
501/// Simplified representation for display in conversation viewer.
502#[derive(Debug, Clone, Serialize, Deserialize)]
503pub struct ConversationMessage {
504    /// Message role (User, Assistant, System)
505    pub role: MessageRole,
506
507    /// Text content (extracted from SessionLine.message.content)
508    pub content: String,
509
510    /// Timestamp when message was sent
511    pub timestamp: Option<DateTime<Utc>>,
512
513    /// Model used (for assistant messages)
514    pub model: Option<String>,
515
516    /// Token usage (for assistant messages)
517    pub tokens: Option<TokenUsage>,
518
519    /// Tool calls made in this message (if any)
520    #[serde(default)]
521    pub tool_calls: Vec<ToolCall>,
522
523    /// Tool results received (if any)
524    #[serde(default)]
525    pub tool_results: Vec<ToolResult>,
526}
527
528/// A tool call made by the assistant
529#[derive(Debug, Clone, Serialize, Deserialize)]
530pub struct ToolCall {
531    /// Tool name (e.g., "Read", "Bash", "Edit")
532    pub name: String,
533
534    /// Tool call ID for matching with results
535    pub id: String,
536
537    /// Input parameters as JSON
538    pub input: serde_json::Value,
539}
540
541/// Result of a tool call execution
542#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct ToolResult {
544    /// Tool call ID this result corresponds to
545    pub tool_call_id: String,
546
547    /// Whether the tool succeeded
548    pub is_error: bool,
549
550    /// Output content
551    pub content: String,
552}
553
554/// Full session content with metadata + messages
555///
556/// Returned by SessionContentParser for lazy-loaded session display.
557#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct SessionContent {
559    /// Messages in chronological order
560    pub messages: Vec<ConversationMessage>,
561
562    /// Session metadata (from cache or index)
563    pub metadata: SessionMetadata,
564}
565
566#[cfg(test)]
567mod tests {
568    use super::*;
569
570    #[test]
571    fn test_token_usage_total() {
572        let usage = TokenUsage {
573            input_tokens: 100,
574            output_tokens: 50,
575            ..Default::default()
576        };
577        assert_eq!(usage.total(), 150);
578    }
579
580    #[test]
581    fn test_session_metadata_duration_display() {
582        let mut meta =
583            SessionMetadata::from_path(PathBuf::from("/test.jsonl"), ProjectId::from("test"));
584
585        meta.duration_seconds = Some(90);
586        assert_eq!(meta.duration_display(), "1m 30s");
587
588        meta.duration_seconds = Some(3665);
589        assert_eq!(meta.duration_display(), "1h 1m");
590
591        meta.duration_seconds = Some(45);
592        assert_eq!(meta.duration_display(), "45s");
593    }
594
595    #[test]
596    fn test_session_metadata_size_display() {
597        let mut meta =
598            SessionMetadata::from_path(PathBuf::from("/test.jsonl"), ProjectId::from("test"));
599
600        meta.file_size_bytes = 500;
601        assert_eq!(meta.size_display(), "500 B");
602
603        meta.file_size_bytes = 5_000;
604        assert_eq!(meta.size_display(), "5.0 KB");
605
606        meta.file_size_bytes = 2_500_000;
607        assert_eq!(meta.size_display(), "2.5 MB");
608    }
609}
610
611#[cfg(test)]
612mod token_tests {
613    use super::*;
614
615    #[test]
616    fn test_real_claude_token_format_deserialization() {
617        // CRITICAL: Real format from Claude Code v2.1.29+
618        let json = r#"{
619            "input_tokens": 10,
620            "cache_creation_input_tokens": 64100,
621            "cache_read_input_tokens": 19275,
622            "cache_creation": {
623                "ephemeral_5m_input_tokens": 0,
624                "ephemeral_1h_input_tokens": 64100
625            },
626            "output_tokens": 1,
627            "service_tier": "standard"
628        }"#;
629
630        let result: Result<TokenUsage, _> = serde_json::from_str(json);
631
632        assert!(
633            result.is_ok(),
634            "Deserialization MUST succeed for real Claude format. Error: {:?}",
635            result.err()
636        );
637
638        let usage = result.unwrap();
639        assert_eq!(usage.input_tokens, 10);
640        assert_eq!(usage.output_tokens, 1);
641        assert_eq!(usage.cache_read_tokens, 19275);
642        assert_eq!(usage.cache_write_tokens, 64100);
643
644        let total = usage.total();
645        assert_eq!(total, 83386, "Total should be 10+1+19275+64100 = 83386");
646    }
647}