claude-hindsight 1.1.0

20/20 hindsight for your Claude Code sessions
Documentation
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
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Projects browser view
//!
//! Shows all discovered projects with statistics and allows drilling down into sessions.

use crate::config::Config;
use crate::error::Result;
use crate::storage::{GlobalAnalytics, ProjectStats, SessionIndex};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    layout::{Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph},
    Frame,
};

/// Projects view state
pub struct ProjectsView {
    /// All project statistics
    pub projects: Vec<ProjectStats>,

    /// List selection state
    pub list_state: ListState,

    /// Filter query
    pub filter_query: String,

    /// Whether we're in filter input mode
    pub filter_mode: bool,

    /// Status message
    pub status_message: String,

    /// Global analytics across all sessions
    pub analytics: GlobalAnalytics,

    /// Application configuration
    pub config: Config,
}

impl ProjectsView {
    /// Create a new projects view
    pub fn new(config: &Config) -> Result<Self> {
        let index = SessionIndex::new()?;
        let projects = index.get_all_project_stats()?;
        let analytics = index.get_global_analytics()?;

        let mut list_state = ListState::default();
        if !projects.is_empty() {
            list_state.select(Some(0));
        }

        let status_message = format!("{} projects found", projects.len());

        Ok(ProjectsView {
            projects,
            list_state,
            filter_query: String::new(),
            filter_mode: false,
            status_message,
            analytics,
            config: config.clone(),
        })
    }

    /// Refresh project statistics
    pub fn refresh(&mut self) -> Result<()> {
        let index = SessionIndex::new()?;
        self.projects = index.get_all_project_stats()?;
        self.analytics = index.get_global_analytics()?;

        // Reset selection if empty
        if self.projects.is_empty() {
            self.list_state.select(None);
        } else if self.list_state.selected().is_none() {
            self.list_state.select(Some(0));
        }

        self.status_message = format!("{} projects found", self.projects.len());
        Ok(())
    }

    /// Handle keyboard input
    pub fn handle_key(&mut self, key: KeyEvent) -> Result<ProjectAction> {
        // Handle filter input mode
        if self.filter_mode {
            return self.handle_filter_input(key);
        }

        match (key.code, key.modifiers) {
            // Navigation
            (KeyCode::Char('j'), KeyModifiers::NONE) | (KeyCode::Down, _) => {
                self.next();
                Ok(ProjectAction::None)
            }
            (KeyCode::Char('k'), KeyModifiers::NONE) | (KeyCode::Up, _) => {
                self.previous();
                Ok(ProjectAction::None)
            }

            // Jump to top/bottom
            (KeyCode::Char('g'), KeyModifiers::NONE) | (KeyCode::Home, _) => {
                self.select_first();
                Ok(ProjectAction::None)
            }
            (KeyCode::Char('G'), KeyModifiers::SHIFT) | (KeyCode::End, _) => {
                self.select_last();
                Ok(ProjectAction::None)
            }

            // Select project (drill down to sessions)
            (KeyCode::Enter, KeyModifiers::NONE) => {
                if let Some(project) = self.selected_project() {
                    Ok(ProjectAction::SelectProject(project.project_name.clone()))
                } else {
                    Ok(ProjectAction::None)
                }
            }

            // Start filter
            (KeyCode::Char('/'), KeyModifiers::NONE) => {
                self.filter_mode = true;
                self.status_message = "Filter: ".to_string();
                Ok(ProjectAction::None)
            }

            // Refresh
            (KeyCode::Char('r'), KeyModifiers::NONE) => {
                self.refresh()?;
                self.status_message = "Refreshed project list".to_string();
                Ok(ProjectAction::None)
            }

            // Quit
            (KeyCode::Char('q'), KeyModifiers::NONE) => Ok(ProjectAction::Quit),

            _ => Ok(ProjectAction::None),
        }
    }

    /// Handle filter input
    fn handle_filter_input(&mut self, key: KeyEvent) -> Result<ProjectAction> {
        match key.code {
            KeyCode::Enter => {
                self.filter_mode = false;
                self.apply_filter()?;
                Ok(ProjectAction::None)
            }
            KeyCode::Esc => {
                self.filter_mode = false;
                self.filter_query.clear();
                self.refresh()?;
                self.status_message = "Filter cancelled".to_string();
                Ok(ProjectAction::None)
            }
            KeyCode::Backspace => {
                self.filter_query.pop();
                self.status_message = format!("Filter: {}", self.filter_query);
                Ok(ProjectAction::None)
            }
            KeyCode::Char(c) => {
                self.filter_query.push(c);
                self.status_message = format!("Filter: {}", self.filter_query);
                Ok(ProjectAction::None)
            }
            _ => Ok(ProjectAction::None),
        }
    }

    /// Apply filter
    fn apply_filter(&mut self) -> Result<()> {
        let index = SessionIndex::new()?;
        let all_projects = index.get_all_project_stats()?;

        if self.filter_query.is_empty() {
            self.projects = all_projects;
        } else {
            let query = self.filter_query.to_lowercase();
            self.projects = all_projects
                .into_iter()
                .filter(|p| p.project_name.to_lowercase().contains(&query))
                .collect();
        }

        // Reset selection
        if !self.projects.is_empty() {
            self.list_state.select(Some(0));
        } else {
            self.list_state.select(None);
        }

        self.status_message = format!("{} projects match filter", self.projects.len());
        Ok(())
    }

    /// Get selected project
    pub fn selected_project(&self) -> Option<&ProjectStats> {
        self.list_state
            .selected()
            .and_then(|i| self.projects.get(i))
    }

    /// Select next project
    fn next(&mut self) {
        if self.projects.is_empty() {
            return;
        }

        let i = match self.list_state.selected() {
            Some(i) => {
                if i >= self.projects.len() - 1 {
                    i
                } else {
                    i + 1
                }
            }
            None => 0,
        };
        self.list_state.select(Some(i));
    }

    /// Select previous project
    fn previous(&mut self) {
        if self.projects.is_empty() {
            return;
        }

        let i = match self.list_state.selected() {
            Some(i) => {
                if i == 0 {
                    0
                } else {
                    i - 1
                }
            }
            None => 0,
        };
        self.list_state.select(Some(i));
    }

    /// Select first project
    fn select_first(&mut self) {
        if !self.projects.is_empty() {
            self.list_state.select(Some(0));
        }
    }

    /// Select last project
    fn select_last(&mut self) {
        if !self.projects.is_empty() {
            self.list_state.select(Some(self.projects.len() - 1));
        }
    }

    /// Render the projects view
    pub fn render(&mut self, f: &mut Frame, area: Rect) {
        let chunks = Layout::default()
            .direction(ratatui::layout::Direction::Vertical)
            .constraints([
                Constraint::Length(12), // Welcome header (taller for new ASCII art)
                Constraint::Min(0),     // Content area (projects + analytics)
                Constraint::Length(3),  // Status bar
            ])
            .split(area);

        // Render welcome header
        self.render_header(f, chunks[0]);

        // Split content area horizontally: projects list (left) and analytics panel (right)
        let content_chunks = Layout::default()
            .direction(ratatui::layout::Direction::Horizontal)
            .constraints([
                Constraint::Percentage(65), // Projects list
                Constraint::Percentage(35), // Analytics panel
            ])
            .split(chunks[1]);

        // Render project list
        self.render_list(f, content_chunks[0]);

        // Render analytics panel
        self.render_analytics_panel(f, content_chunks[1]);

        // Render status bar
        self.render_status(f, chunks[2]);
    }

    /// Render the welcome header with ASCII art
    fn render_header(&self, f: &mut Frame, area: Rect) {
        // Calculate horizontal padding for centering (assuming ~80 char width for content)
        let content_width = 85;
        let padding = (area.width.saturating_sub(content_width)) / 2;
        let pad = " ".repeat(padding as usize);

        let header_text = vec![
            Line::from(""),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "██╗  ██╗██╗███╗   ██╗██████╗ ███████╗██╗ ██████╗ ██╗  ██╗████████╗",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "██║  ██║██║████╗  ██║██╔══██╗██╔════╝██║██╔════╝ ██║  ██║╚══██╔══╝",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "███████║██║██╔██╗ ██║██║  ██║███████╗██║██║  ███╗███████║   ██║   ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "██╔══██║██║██║╚██╗██║██║  ██║╚════██║██║██║   ██║██╔══██║   ██║   ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "██║  ██║██║██║ ╚████║██████╔╝███████║██║╚██████╔╝██║  ██║   ██║   ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw(&pad),
                Span::styled(
                    "╚═╝  ╚═╝╚═╝╚═╝  ╚═══╝╚═════╝ ╚══════╝╚═╝ ╚═════╝ ╚═╝  ╚═╝   ╚═╝   ",
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(""),
            Line::from(vec![
                Span::raw(" ".repeat((area.width as usize).saturating_sub(76) / 2)),
                Span::styled(
                    "A powerful observability tool for Claude Code. Debug sessions,",
                    Style::default().fg(Color::Gray),
                ),
            ]),
            Line::from(vec![
                Span::raw(" ".repeat((area.width as usize).saturating_sub(76) / 2)),
                Span::styled(
                    "analyze costs, and understand Claude's decision-making process.",
                    Style::default().fg(Color::Gray),
                ),
            ]),
            Line::from(""),
        ];

        let header = Paragraph::new(header_text)
            .block(Block::default())
            .alignment(ratatui::layout::Alignment::Left);

        f.render_widget(header, area);
    }

    /// Render the project list
    fn render_list(&mut self, f: &mut Frame, area: Rect) {
        let items: Vec<ListItem> = self
            .projects
            .iter()
            .map(|project| {
                let size_mb = project.total_size as f64 / 1_000_000.0;
                let time_ago = format_time_ago(project.last_activity);

                let line = Line::from(vec![
                    Span::raw("  "),
                    Span::styled(
                        format!("{:22}", project.project_name),
                        Style::default()
                            .fg(Color::Cyan)
                            .add_modifier(Modifier::BOLD),
                    ),
                    Span::styled(
                        format!("{:4} sessions", project.session_count),
                        Style::default().fg(Color::Yellow),
                    ),
                    Span::raw("    "),
                    Span::styled(
                        format!("{:8.1} MB", size_mb),
                        Style::default().fg(Color::Green),
                    ),
                    Span::raw("    "),
                    Span::styled(
                        format!("{:>12}", time_ago),
                        Style::default().fg(Color::DarkGray),
                    ),
                ]);

                ListItem::new(line)
            })
            .collect();

        let title = if self.projects.is_empty() {
            "Projects (none found - run 'hindsight init' first)"
        } else {
            "Projects"
        };

        let list = List::new(items)
            .block(Block::default().borders(Borders::ALL).title(title))
            .highlight_style(
                Style::default()
                    .fg(Color::Black)
                    .bg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("");

        f.render_stateful_widget(list, area, &mut self.list_state);
    }

    /// Render analytics panel
    fn render_analytics_panel(&self, f: &mut Frame, area: Rect) {
        let size_mb = self.analytics.total_size as f64 / 1_000_000.0;

        let mut lines = vec![
            Line::from(""),
            // Overview section
            Line::from(vec![Span::styled(
                " Overview",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )]),
            Line::from(""),
            Line::from(vec![
                Span::raw("  Total Sessions: "),
                Span::styled(
                    format!("{}", self.analytics.total_sessions),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw("  Total Projects: "),
                Span::styled(
                    format!("{}", self.analytics.total_projects),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw("  Total Size:     "),
                Span::styled(
                    format!("{:.1} MB", size_mb),
                    Style::default()
                        .fg(Color::Green)
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(vec![
                Span::raw("  Total Errors:   "),
                Span::styled(
                    format!("{}", self.analytics.total_errors),
                    Style::default()
                        .fg(if self.analytics.total_errors > 0 {
                            Color::Red
                        } else {
                            Color::Green
                        })
                        .add_modifier(Modifier::BOLD),
                ),
            ]),
            Line::from(""),
        ];

        // Activity section (conditional based on config)
        if self.config.analytics.show_activity {
            lines.push(Line::from(vec![Span::styled(
                " Activity",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )]));
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::raw("  This Week:      "),
                Span::styled(
                    format!("{}", self.analytics.sessions_this_week),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(" sessions"),
            ]));
            lines.push(Line::from(vec![
                Span::raw("  Today:          "),
                Span::styled(
                    format!("{}", self.analytics.sessions_today),
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw(" sessions"),
            ]));
            lines.push(Line::from(""));
        }

        // Session Types section (conditional based on config)
        if self.config.analytics.show_subagent_count {
            lines.push(Line::from(vec![Span::styled(
                " Session Types",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )]));
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::raw("  With Subagents: "),
                Span::styled(
                    format!("{}", self.analytics.subagent_count),
                    Style::default()
                        .fg(Color::Magenta)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
            lines.push(Line::from(""));
        }

        // Most Active Project
        if let Some(ref project) = self.analytics.most_active_project {
            lines.push(Line::from(vec![Span::styled(
                " Most Active",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )]));
            lines.push(Line::from(""));
            lines.push(Line::from(vec![
                Span::raw("  "),
                Span::styled(
                    project,
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
            ]));
            lines.push(Line::from(""));
        }

        // Top Tools section (conditional based on config)
        if self.config.analytics.show_top_tools {
            lines.push(Line::from(vec![Span::styled(
                " Top Tools",
                Style::default()
                    .fg(Color::Cyan)
                    .add_modifier(Modifier::BOLD),
            )]));
            lines.push(Line::from(""));

            if !self.analytics.top_tools.is_empty() {
                // Limit to configured number of tools
                let tools_to_show = self
                    .analytics
                    .top_tools
                    .iter()
                    .take(self.config.analytics.tools_limit);

                for (tool, count) in tools_to_show {
                    let tool_name = if tool.len() > 12 {
                        format!("{}...", &tool[..9])
                    } else {
                        tool.clone()
                    };

                    lines.push(Line::from(vec![
                        Span::raw("  "),
                        Span::styled(
                            format!("{:12}", tool_name),
                            Style::default().fg(Color::Blue),
                        ),
                        Span::styled(
                            format!("{:>4}", count),
                            Style::default()
                                .fg(Color::Yellow)
                                .add_modifier(Modifier::BOLD),
                        ),
                    ]));
                }
            } else {
                lines.push(Line::from(vec![
                    Span::raw("  "),
                    Span::styled("Analyzing...", Style::default().fg(Color::DarkGray)),
                ]));
            }
        }

        let paragraph = Paragraph::new(lines)
            .block(Block::default().borders(Borders::ALL).title("Analytics"))
            .alignment(ratatui::layout::Alignment::Left);

        f.render_widget(paragraph, area);
    }

    /// Render status bar
    fn render_status(&self, f: &mut Frame, area: Rect) {
        let shortcuts = if self.projects.is_empty() {
            vec![Line::from(vec![
                Span::styled(
                    " Tip: ",
                    Style::default()
                        .fg(Color::Yellow)
                        .add_modifier(Modifier::BOLD),
                ),
                Span::raw("Run "),
                Span::styled("claude-hindsight init", Style::default().fg(Color::Cyan)),
                Span::raw(" to discover Claude Code sessions"),
            ])]
        } else {
            vec![Line::from(vec![
                Span::styled(" ↑↓", Style::default().fg(Color::Cyan)),
                Span::raw(" navigate  "),
                Span::styled("Enter", Style::default().fg(Color::Cyan)),
                Span::raw(" select  "),
                Span::styled("/", Style::default().fg(Color::Cyan)),
                Span::raw(" search (text | @tool | errors)  "),
                Span::styled("r", Style::default().fg(Color::Cyan)),
                Span::raw(" refresh  "),
                Span::styled("q", Style::default().fg(Color::Cyan)),
                Span::raw(" quit"),
            ])]
        };

        let mut text = shortcuts;
        if !self.status_message.is_empty() {
            text.push(Line::from(vec![
                Span::styled(" ", Style::default()),
                Span::styled(
                    self.status_message.as_str(),
                    Style::default().fg(Color::Yellow),
                ),
            ]));
        }

        let status = Paragraph::new(text).block(Block::default().borders(Borders::ALL));

        f.render_widget(status, area);
    }
}

/// Actions that can be triggered from the projects view
#[derive(Debug)]
pub enum ProjectAction {
    None,
    SelectProject(String),
    Quit,
}

/// Format timestamp as relative time
fn format_time_ago(timestamp: Option<i64>) -> String {
    let timestamp = match timestamp {
        Some(t) => t,
        None => return "never".to_string(),
    };

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    let diff = now - timestamp;

    if diff < 60 {
        format!("{}s ago", diff)
    } else if diff < 3600 {
        format!("{}m ago", diff / 60)
    } else if diff < 86400 {
        format!("{}h ago", diff / 3600)
    } else {
        format!("{}d ago", diff / 86400)
    }
}