claude-dashboard 0.2.0

A terminal TUI dashboard that renders Claude Code usage reports with token stats, project breakdowns, and language distribution.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

// --- stats-cache.json types ---

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StatsCache {
    pub version: u32,
    #[serde(default)]
    pub last_computed_date: Option<String>,
    #[serde(default)]
    pub daily_activity: Vec<DailyActivity>,
    #[serde(default)]
    pub daily_model_tokens: Vec<DailyModelTokens>,
    #[serde(default)]
    pub model_usage: HashMap<String, ModelUsage>,
    #[serde(default)]
    pub total_sessions: u64,
    #[serde(default)]
    pub total_messages: u64,
    #[serde(default)]
    pub longest_session: Option<LongestSession>,
    #[serde(default)]
    pub first_session_date: Option<String>,
    #[serde(default)]
    pub hour_counts: HashMap<String, u64>,
    #[serde(default)]
    pub total_speculation_time_saved_ms: u64,
}#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyActivity {
    pub date: String,
    #[serde(default)]
    pub message_count: u64,
    #[serde(default)]
    pub session_count: u64,
    #[serde(default)]
    pub tool_call_count: u64,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DailyModelTokens {
    pub date: String,
    #[serde(default)]
    pub tokens_by_model: HashMap<String, u64>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ModelUsage {
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default)]
    pub web_search_requests: u64,
    #[serde(default)]
    pub cost_usd: f64,
    #[serde(default)]
    pub context_window: u64,
    #[serde(default)]
    pub max_output_tokens: u64,
}

impl ModelUsage {
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens + self.output_tokens + self.cache_read_input_tokens + self.cache_creation_input_tokens
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct LongestSession {
    #[serde(default)]
    pub session_id: String,
    #[serde(default)]
    pub duration: u64,
    #[serde(default)]
    pub message_count: u64,
    #[serde(default)]
    pub timestamp: Option<String>,
}

// --- history.jsonl types ---

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct HistoryEntry {
    pub display: String,
    pub timestamp: i64,
    pub project: String,
    #[serde(default)]
    pub session_id: String,
}

// --- Session JSONL types ---

#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
pub enum SessionEvent {
    #[serde(rename = "user")]
    User {
        #[serde(default)]
        uuid: String,
        #[serde(default)]
        timestamp: Option<String>,
        #[serde(default)]
        message: Option<serde_json::Value>,
        #[serde(default)]
        session_id: Option<String>,
    },
    #[serde(rename = "assistant")]
    Assistant {
        #[serde(default)]
        uuid: String,
        #[serde(default)]
        timestamp: Option<String>,
        #[serde(default)]
        message: Option<AssistantMessage>,
        #[serde(default)]
        session_id: Option<String>,
    },
    #[serde(other)]
    Unknown,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct AssistantMessage {
    #[serde(default)]
    pub model: String,
    #[serde(default)]
    pub usage: Option<TokenUsage>,
    #[serde(default)]
    pub content: Option<Vec<serde_json::Value>>,
}

#[derive(Debug, Deserialize, Serialize)]
pub struct TokenUsage {
    #[serde(default)]
    pub input_tokens: u64,
    #[serde(default)]
    pub output_tokens: u64,
    #[serde(default)]
    pub cache_read_input_tokens: u64,
    #[serde(default)]
    pub cache_creation_input_tokens: u64,
    #[serde(default)]
    pub server_tool_use: Option<ServerToolUse>,
}

impl TokenUsage {
    pub fn total_tokens(&self) -> u64 {
        self.input_tokens + self.output_tokens + self.cache_read_input_tokens + self.cache_creation_input_tokens
    }
}

#[derive(Debug, Deserialize, Serialize)]
pub struct ServerToolUse {
    #[serde(default)]
    pub web_search_requests: u64,
    #[serde(default)]
    pub web_fetch_requests: u64,
}

// --- Project directory info ---

#[derive(Debug, Clone)]
pub struct ProjectDir {
    pub display_name: String,
    pub full_path: String,
    pub session_files: Vec<PathBuf>,
    /// True if full_path came from history.jsonl or was decoded reliably.
    /// False when the encoded name suffered non-ASCII loss (e.g. Chinese chars
    /// mapped to dashes) and the real path is unrecoverable.
    pub path_resolved: bool,
}

// --- Per-model token detail (breakdown + tool usage) ---

#[derive(Debug, Clone, Default)]
pub struct ModelTokenDetail {
    pub total_tokens: u64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_input_tokens: u64,
    pub cache_creation_input_tokens: u64,
    pub web_search_requests: u64,
    pub web_fetch_requests: u64,
    pub tool_call_count: u64,
    pub tool_calls: HashMap<String, u64>,
}

impl ModelTokenDetail {
    /// 缓存命中率:cache_read / (input + cache_read)
    pub fn cache_hit_rate(&self) -> f64 {
        let denom = self.input_tokens + self.cache_read_input_tokens;
        if denom > 0 {
            self.cache_read_input_tokens as f64 / denom as f64
        } else {
            0.0
        }
    }

    #[allow(dead_code)]
    pub fn total_tool_requests(&self) -> u64 {
        self.tool_call_count + self.web_search_requests + self.web_fetch_requests
    }
}

// --- Session summary (aggregated from JSONL) ---

#[derive(Debug, Clone)]
pub struct SessionSummary {
    pub project_name: String,
    pub model: String,
    pub total_tokens: u64,
    pub input_tokens: u64,
    pub output_tokens: u64,
    pub cache_read_input_tokens: u64,
    pub cache_creation_input_tokens: u64,
    pub web_search_requests: u64,
    pub web_fetch_requests: u64,
    pub tool_call_count: u64,
    pub tool_calls: HashMap<String, u64>,
}

// --- Aggregate data for a view ---

#[derive(Debug, Clone, Default)]
pub struct ViewData {
    pub total_sessions: u64,
    pub total_messages: u64,
    pub total_tokens: u64,
    pub model_tokens: HashMap<String, u64>,
    pub model_token_detail: HashMap<String, ModelTokenDetail>,
    pub project_tokens: HashMap<String, u64>,
    pub daily_activity: Vec<DailyActivity>,
    pub total_web_search_requests: u64,
    pub total_web_fetch_requests: u64,
    pub total_tool_calls: u64,
    pub tool_calls: HashMap<String, u64>,
    pub longest_session_secs: u64,
    pub avg_session_secs: u64,
    pub peak_period: String,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_deserialize_assistant_with_tool_use() {
        let json = r#"{"type":"assistant","uuid":"abc","timestamp":"2026-04-15T10:30:00Z","message":{"model":"opus","usage":{"input_tokens":100,"output_tokens":50},"content":[{"type":"tool_use","name":"Bash","input":{"command":"ls"}},{"type":"text","text":"done"},{"type":"tool_use","name":"Read","input":{"file":"a.txt"}}]}}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        match event {
            SessionEvent::Assistant { message, .. } => {
                let msg = message.unwrap();
                let tool_calls = msg.content.as_ref()
                    .map(|blocks| blocks.iter().filter(|b| {
                        b.get("type").and_then(|t| t.as_str()) == Some("tool_use")
                    }).count())
                    .unwrap_or(0);
                assert_eq!(tool_calls, 2, "Should find 2 tool_use blocks in content");
            }
            _ => panic!("Expected Assistant event"),
        }
    }

    #[test]
    fn test_deserialize_assistant_without_content() {
        let json = r#"{"type":"assistant","uuid":"abc","timestamp":"2026-04-15T10:30:00Z","message":{"model":"opus","usage":{"input_tokens":100,"output_tokens":50}}}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        match event {
            SessionEvent::Assistant { message, .. } => {
                let msg = message.unwrap();
                let tool_calls = msg.content.as_ref()
                    .map(|blocks| blocks.iter().filter(|b| {
                        b.get("type").and_then(|t| t.as_str()) == Some("tool_use")
                    }).count())
                    .unwrap_or(0);
                assert_eq!(tool_calls, 0, "No content means no tool calls");
            }
            _ => panic!("Expected Assistant event"),
        }
    }

    #[test]
    fn test_model_usage_total_tokens() {
        let mu = ModelUsage {
            input_tokens: 1000,
            output_tokens: 500,
            cache_read_input_tokens: 300,
            cache_creation_input_tokens: 200,
            web_search_requests: 0,
            cost_usd: 0.0,
            context_window: 0,
            max_output_tokens: 0,
        };
        assert_eq!(mu.total_tokens(), 2000);
    }

    #[test]
    fn test_token_usage_total_tokens() {
        let tu = TokenUsage {
            input_tokens: 100,
            output_tokens: 50,
            cache_read_input_tokens: 25,
            cache_creation_input_tokens: 25,
            server_tool_use: None,
        };
        assert_eq!(tu.total_tokens(), 200);
    }

    #[test]
    fn test_deserialize_assistant_event() {
        let json = r#"{"type":"assistant","uuid":"abc","timestamp":"2026-04-15T10:30:00Z","message":{"model":"opus","usage":{"input_tokens":100,"output_tokens":50}}}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        match event {
            SessionEvent::Assistant { timestamp, message, .. } => {
                assert_eq!(timestamp.unwrap(), "2026-04-15T10:30:00Z");
                let msg = message.unwrap();
                assert_eq!(msg.model, "opus");
                let usage = msg.usage.unwrap();
                assert_eq!(usage.input_tokens, 100);
                assert_eq!(usage.output_tokens, 50);
            }
            _ => panic!("Expected Assistant event"),
        }
    }

    #[test]
    fn test_deserialize_user_event() {
        let json = r#"{"type":"user","uuid":"xyz","timestamp":"2026-04-15T09:00:00Z","message":{"role":"user","content":"hello"}}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        match event {
            SessionEvent::User { timestamp, .. } => {
                assert_eq!(timestamp.unwrap(), "2026-04-15T09:00:00Z");
            }
            _ => panic!("Expected User event"),
        }
    }

    #[test]
    fn test_deserialize_unknown_event_type() {
        // Unknown types map to SessionEvent::Unknown
        let json = r#"{"type":"some-new-type","data":"foo"}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        assert!(matches!(event, SessionEvent::Unknown));
    }

    #[test]
    fn test_deserialize_history_entry() {
        let json = r#"{"display":"test msg","timestamp":1712345678000,"project":"D:\\dev\\example","sessionId":"abc123"}"#;
        let entry: HistoryEntry = serde_json::from_str(json).unwrap();
        assert_eq!(entry.display, "test msg");
        assert_eq!(entry.project, "D:\\dev\\example");
        assert_eq!(entry.session_id, "abc123");
    }

    #[test]
    fn test_deserialize_stats_cache_empty() {
        let json = r#"{"version":3}"#;
        let stats: StatsCache = serde_json::from_str(json).unwrap();
        assert_eq!(stats.version, 3);
        assert!(stats.daily_activity.is_empty());
        assert!(stats.model_usage.is_empty());
    }

    #[test]
    fn test_deserialize_daily_model_tokens() {
        let json = r#"{"date":"2026-04-15","tokensByModel":{"opus":1000,"sonnet":500}}"#;
        let dmt: DailyModelTokens = serde_json::from_str(json).unwrap();
        assert_eq!(dmt.date, "2026-04-15");
        assert_eq!(dmt.tokens_by_model.get("opus").unwrap(), &1000);
        assert_eq!(dmt.tokens_by_model.get("sonnet").unwrap(), &500);
    }

    #[test]
    fn test_deserialize_daily_model_tokens_empty() {
        let json = r#"{"date":"2026-04-15","tokensByModel":{}}"#;
        let dmt: DailyModelTokens = serde_json::from_str(json).unwrap();
        assert_eq!(dmt.date, "2026-04-15");
        assert!(dmt.tokens_by_model.is_empty());
    }

    #[test]
    fn test_deserialize_stats_cache_with_daily_model_tokens() {
        let json = r#"{"version":3,"dailyModelTokens":[{"date":"2026-04-15","tokensByModel":{"opus":100}},{"date":"2026-04-16","tokensByModel":{"sonnet":200}}]}"#;
        let stats: StatsCache = serde_json::from_str(json).unwrap();
        assert_eq!(stats.daily_model_tokens.len(), 2);
        assert_eq!(stats.daily_model_tokens[0].date, "2026-04-15");
        assert_eq!(stats.daily_model_tokens[0].tokens_by_model.get("opus").unwrap(), &100);
    }

    // --- ModelTokenDetail ---

    #[test]
    fn test_model_token_detail_cache_hit_rate() {
        let mut detail = ModelTokenDetail::default();
        detail.input_tokens = 800;
        detail.cache_read_input_tokens = 200;
        let rate = detail.cache_hit_rate();
        assert!((rate - 0.2).abs() < 1e-9);
    }

    #[test]
    fn test_model_token_detail_cache_hit_rate_zero() {
        let detail = ModelTokenDetail::default();
        assert_eq!(detail.cache_hit_rate(), 0.0);
    }

    #[test]
    fn test_model_token_detail_cache_hit_rate_full() {
        let mut detail = ModelTokenDetail::default();
        detail.input_tokens = 0;
        detail.cache_read_input_tokens = 1000;
        assert_eq!(detail.cache_hit_rate(), 1.0);
    }

    #[test]
    fn test_model_token_detail_total_tool_requests() {
        let mut detail = ModelTokenDetail::default();
        detail.tool_call_count = 50;
        detail.web_search_requests = 10;
        detail.web_fetch_requests = 5;
        assert_eq!(detail.total_tool_requests(), 65);
    }

    #[test]
    fn test_model_token_detail_total_tool_requests_zero() {
        let detail = ModelTokenDetail::default();
        assert_eq!(detail.total_tool_requests(), 0);
    }

    // --- ServerToolUse deserialization ---

    #[test]
    fn test_deserialize_token_usage_with_server_tool_use() {
        let json = r#"{"input_tokens":100,"output_tokens":50,"cache_read_input_tokens":25,"cache_creation_input_tokens":10,"server_tool_use":{"web_search_requests":3,"web_fetch_requests":2}}"#;
        let usage: TokenUsage = serde_json::from_str(json).unwrap();
        assert_eq!(usage.input_tokens, 100);
        let stu = usage.server_tool_use.unwrap();
        assert_eq!(stu.web_search_requests, 3);
        assert_eq!(stu.web_fetch_requests, 2);
    }

    #[test]
    fn test_deserialize_token_usage_without_server_tool_use() {
        let json = r#"{"input_tokens":100,"output_tokens":50}"#;
        let usage: TokenUsage = serde_json::from_str(json).unwrap();
        assert_eq!(usage.input_tokens, 100);
        assert!(usage.server_tool_use.is_none());
    }

    // --- StatsCache full deserialization ---

    #[test]
    fn test_deserialize_stats_cache_full() {
        let json = r#"{
            "version": 3,
            "lastComputedDate": "2026-05-30",
            "totalSessions": 42,
            "totalMessages": 500,
            "firstSessionDate": "2025-11-04T08:34:16.259Z",
            "totalSpeculationTimeSavedMs": 12345,
            "modelUsage": {
                "opus": {
                    "inputTokens": 10000,
                    "outputTokens": 5000,
                    "cacheReadInputTokens": 3000,
                    "cacheCreationInputTokens": 1000,
                    "webSearchRequests": 10,
                    "costUsd": 1.5,
                    "contextWindow": 200000,
                    "maxOutputTokens": 8192
                }
            },
            "hourCounts": {"10": 50, "14": 80, "22": 30},
            "longestSession": {
                "sessionId": "abc123",
                "duration": 7200,
                "messageCount": 100,
                "timestamp": "2026-04-15T10:00:00Z"
            }
        }"#;
        let stats: StatsCache = serde_json::from_str(json).unwrap();
        assert_eq!(stats.version, 3);
        assert_eq!(stats.last_computed_date.as_deref(), Some("2026-05-30"));
        assert_eq!(stats.total_sessions, 42);
        assert_eq!(stats.total_messages, 500);
        assert_eq!(stats.first_session_date.as_deref(), Some("2025-11-04T08:34:16.259Z"));
        assert_eq!(stats.total_speculation_time_saved_ms, 12345);

        let opus = stats.model_usage.get("opus").unwrap();
        assert_eq!(opus.input_tokens, 10000);
        assert_eq!(opus.cost_usd, 1.5);
        assert_eq!(opus.context_window, 200000);

        assert_eq!(stats.hour_counts.get("14").unwrap(), &80);

        let longest = stats.longest_session.unwrap();
        assert_eq!(longest.session_id, "abc123");
        assert_eq!(longest.duration, 7200);
        assert_eq!(longest.message_count, 100);
    }

    // --- HistoryEntry edge cases ---

    #[test]
    fn test_deserialize_history_entry_missing_session_id() {
        let json = r#"{"display":"test","timestamp":1234567890,"project":"/test"}"#;
        let entry: HistoryEntry = serde_json::from_str(json).unwrap();
        assert_eq!(entry.session_id, "");
    }

    // --- DailyActivity deserialization ---

    #[test]
    fn test_deserialize_daily_activity() {
        let json = r#"{"date":"2026-04-15","messageCount":25,"sessionCount":3,"toolCallCount":10}"#;
        let da: DailyActivity = serde_json::from_str(json).unwrap();
        assert_eq!(da.date, "2026-04-15");
        assert_eq!(da.message_count, 25);
        assert_eq!(da.session_count, 3);
        assert_eq!(da.tool_call_count, 10);
    }

    #[test]
    fn test_deserialize_daily_activity_defaults() {
        let json = r#"{"date":"2026-04-15"}"#;
        let da: DailyActivity = serde_json::from_str(json).unwrap();
        assert_eq!(da.date, "2026-04-15");
        assert_eq!(da.message_count, 0);
        assert_eq!(da.session_count, 0);
        assert_eq!(da.tool_call_count, 0);
    }

    // --- ModelUsage zero defaults ---

    #[test]
    fn test_model_usage_total_tokens_zero() {
        let mu = ModelUsage {
            input_tokens: 0,
            output_tokens: 0,
            cache_read_input_tokens: 0,
            cache_creation_input_tokens: 0,
            web_search_requests: 0,
            cost_usd: 0.0,
            context_window: 0,
            max_output_tokens: 0,
        };
        assert_eq!(mu.total_tokens(), 0);
    }

    // --- SessionEvent with tool_use name extraction ---

    #[test]
    fn test_tool_use_name_extraction() {
        let json = r#"{"type":"assistant","uuid":"x","timestamp":"2026-04-15T10:30:00Z","message":{"model":"opus","usage":{"input_tokens":10,"output_tokens":5},"content":[{"type":"tool_use","name":"Bash","input":{"command":"ls"}},{"type":"tool_use","name":"Read","input":{"file":"a.txt"}},{"type":"tool_use","name":"Bash","input":{"command":"pwd"}},{"type":"text","text":"output"}]}}"#;
        let event: SessionEvent = serde_json::from_str(json).unwrap();
        match event {
            SessionEvent::Assistant { message, .. } => {
                let msg = message.unwrap();
                let blocks = msg.content.unwrap();
                let mut tool_names: Vec<String> = blocks.iter()
                    .filter(|b| b.get("type").and_then(|t| t.as_str()) == Some("tool_use"))
                    .filter_map(|b| b.get("name").and_then(|n| n.as_str()))
                    .map(|s| s.to_string())
                    .collect();
                tool_names.sort();
                assert_eq!(tool_names, vec!["Bash", "Bash", "Read"]);
            }
            _ => panic!("Expected Assistant event"),
        }
    }

    // --- ViewData default ---

    #[test]
    fn test_view_data_default() {
        let vd = ViewData::default();
        assert_eq!(vd.total_sessions, 0);
        assert_eq!(vd.total_messages, 0);
        assert_eq!(vd.total_tokens, 0);
        assert!(vd.model_tokens.is_empty());
        assert!(vd.model_token_detail.is_empty());
        assert!(vd.project_tokens.is_empty());
        assert!(vd.daily_activity.is_empty());
        assert_eq!(vd.peak_period, "");
    }

    #[test]
    fn test_parse_real_session_file_from_disk() {
        let claude_dir = crate::utils::find_claude_dir(None);
        if claude_dir.is_none() {
            eprintln!("Skipping: no .claude directory found");
            return;
        }
        let projects_dir = claude_dir.unwrap().join("projects");
        if !projects_dir.exists() {
            eprintln!("Skipping: projects dir not found");
            return;
        }

        use std::fs;
        use std::io::{BufRead, BufReader};

        let mut total_events = 0u64;
        let mut assistant_events = 0u64;
        let mut total_tokens = 0u64;
        let mut total_tool_calls = 0u64;
        let mut model_counts: std::collections::HashMap<String, u64> = std::collections::HashMap::new();

        if let Ok(proj_entries) = fs::read_dir(&projects_dir) {
            for proj_entry in proj_entries {
                if let Ok(proj) = proj_entry {
                    let proj_path = proj.path();
                    if !proj_path.is_dir() { continue; }
                    if let Ok(session_entries) = fs::read_dir(&proj_path) {
                        for session_entry in session_entries {
                            if let Ok(sess) = session_entry {
                                let sess_path = sess.path();
                                if sess_path.extension().map(|e| e == "jsonl").unwrap_or(false) {
                                    if let Ok(file) = fs::File::open(&sess_path) {
                                        let reader = BufReader::new(file);
                                        for line in reader.lines() {
                                            if let Ok(line) = line {
                                                if line.trim().is_empty() { continue; }
                                                total_events += 1;
                                                if let Ok(SessionEvent::Assistant { message, .. }) =
                                                    serde_json::from_str::<SessionEvent>(&line)
                                                {
                                                    assistant_events += 1;
                                                    if let Some(msg) = message {
                                                        if let Some(usage) = msg.usage {
                                                            let t = usage.total_tokens();
                                                            total_tokens += t;
                                                            *model_counts.entry(msg.model).or_insert(0) += t;
                                                        }
                                                        let tc = msg.content.as_ref()
                                                            .map(|blocks| blocks.iter().filter(|b| {
                                                                b.get("type").and_then(|t| t.as_str()) == Some("tool_use")
                                                            }).count() as u64)
                                                            .unwrap_or(0);
                                                        total_tool_calls += tc;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        eprintln!("Total lines: {}, Assistant: {}, Tokens: {}M, Tool calls: {}",
            total_events, assistant_events, total_tokens as f64 / 1e6, total_tool_calls);
        assert!(total_events > 0);
        assert!(assistant_events > 0);
    }
}