1use 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
14#[serde(transparent)]
15pub struct SessionId(String);
16
17impl SessionId {
18 pub fn new(id: String) -> Self {
20 Self(id)
21 }
22
23 pub fn as_str(&self) -> &str {
25 &self.0
26 }
27
28 pub fn into_inner(self) -> String {
30 self.0
31 }
32
33 pub fn is_empty(&self) -> bool {
35 self.0.is_empty()
36 }
37
38 pub fn chars(&self) -> std::str::Chars<'_> {
40 self.0.chars()
41 }
42
43 pub fn starts_with(&self, pattern: &str) -> bool {
45 self.0.starts_with(pattern)
46 }
47
48 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#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
162#[serde(transparent)]
163pub struct ProjectId(String);
164
165impl ProjectId {
166 pub fn new(id: String) -> Self {
168 Self(id)
169 }
170
171 pub fn as_str(&self) -> &str {
173 &self.0
174 }
175
176 pub fn into_inner(self) -> String {
178 self.0
179 }
180
181 pub fn len(&self) -> usize {
183 self.0.len()
184 }
185
186 #[allow(dead_code)]
188 pub fn is_empty(&self) -> bool {
189 self.0.is_empty()
190 }
191
192 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#[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#[derive(Debug, Clone, Default, Serialize, Deserialize)]
260#[serde(rename_all = "camelCase")]
261pub struct SessionLine {
262 #[serde(default)]
264 pub session_id: Option<String>,
265
266 #[serde(rename = "type")]
268 pub line_type: String,
269
270 #[serde(default)]
272 pub timestamp: Option<DateTime<Utc>>,
273
274 #[serde(default)]
276 pub cwd: Option<String>,
277
278 #[serde(default)]
280 pub git_branch: Option<String>,
281
282 #[serde(default)]
284 pub message: Option<SessionMessage>,
285
286 #[serde(default)]
288 pub model: Option<String>,
289
290 #[serde(default)]
292 pub usage: Option<TokenUsage>,
293
294 #[serde(default)]
296 pub summary: Option<SessionSummary>,
297
298 #[serde(default)]
300 pub parent_session_id: Option<String>,
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
305#[serde(rename_all = "camelCase")]
306pub struct SessionMessage {
307 #[serde(default)]
309 pub role: Option<String>,
310
311 #[serde(default)]
313 pub content: Option<Value>,
314
315 #[serde(default)]
317 pub tool_calls: Option<Vec<serde_json::Value>>,
318
319 #[serde(default)]
321 pub tool_results: Option<Vec<serde_json::Value>>,
322
323 #[serde(default)]
325 pub usage: Option<TokenUsage>,
326}
327
328#[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 #[serde(default, alias = "cache_read_input_tokens")]
339 pub cache_read_tokens: u64,
340
341 #[serde(default, alias = "cache_creation_input_tokens")]
343 pub cache_write_tokens: u64,
344}
345
346impl TokenUsage {
347 pub fn total(&self) -> u64 {
355 self.input_tokens + self.output_tokens + self.cache_read_tokens + self.cache_write_tokens
356 }
357}
358
359#[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#[derive(Debug, Clone, Serialize, Deserialize)]
385pub struct SessionMetadata {
386 pub id: SessionId,
388
389 pub file_path: PathBuf,
391
392 pub project_path: ProjectId,
394
395 pub first_timestamp: Option<DateTime<Utc>>,
397
398 pub last_timestamp: Option<DateTime<Utc>>,
400
401 pub message_count: u64,
403
404 pub total_tokens: u64,
406
407 pub input_tokens: u64,
409 pub output_tokens: u64,
410 pub cache_creation_tokens: u64,
411 pub cache_read_tokens: u64,
412
413 pub models_used: Vec<String>,
415
416 pub file_size_bytes: u64,
418
419 pub first_user_message: Option<String>,
421
422 pub has_subagents: bool,
424
425 pub duration_seconds: Option<u64>,
427
428 pub branch: Option<String>,
430
431 pub tool_usage: std::collections::HashMap<String, usize>,
434
435 #[serde(default)]
438 pub tool_token_usage: std::collections::HashMap<String, u64>,
439}
440
441impl SessionMetadata {
442 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 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
503pub struct ConversationMessage {
504 pub role: MessageRole,
506
507 pub content: String,
509
510 pub timestamp: Option<DateTime<Utc>>,
512
513 pub model: Option<String>,
515
516 pub tokens: Option<TokenUsage>,
518
519 #[serde(default)]
521 pub tool_calls: Vec<ToolCall>,
522
523 #[serde(default)]
525 pub tool_results: Vec<ToolResult>,
526}
527
528#[derive(Debug, Clone, Serialize, Deserialize)]
530pub struct ToolCall {
531 pub name: String,
533
534 pub id: String,
536
537 pub input: serde_json::Value,
539}
540
541#[derive(Debug, Clone, Serialize, Deserialize)]
543pub struct ToolResult {
544 pub tool_call_id: String,
546
547 pub is_error: bool,
549
550 pub content: String,
552}
553
554#[derive(Debug, Clone, Serialize, Deserialize)]
558pub struct SessionContent {
559 pub messages: Vec<ConversationMessage>,
561
562 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 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}