claude-hindsight 2.0.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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
//! Fuzzy search modal inspired by fzf and Telescope
//!
//! A beautiful, context-aware search overlay that can be triggered from any view.

use crate::error::Result;
use crate::parser::{parse_session, ExecutionNode};
use crate::storage::{SessionFile, SessionIndex};
use chrono::TimeZone;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{
    layout::{Alignment, Constraint, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, List, ListItem, ListState, Paragraph, Wrap},
    Frame,
};

/// Search context - determines what we're searching
#[derive(Debug, Clone, PartialEq)]
pub enum SearchContext {
    /// Search all sessions globally
    Global,
    /// Search sessions within a specific project
    Project(String),
    /// Search within a specific session's content
    Session(String),
}

/// A single search result item
#[derive(Debug, Clone)]
pub struct SearchResultItem {
    /// Display title
    pub title: String,
    /// Subtitle/secondary info
    pub subtitle: String,
    /// Preview text (shown in preview pane)
    pub preview: String,
    /// Identifier for selection (session_id, node_uuid, etc.)
    pub id: String,
    /// Match score (higher = better match)
    #[allow(dead_code)]
    pub score: f64,
}

/// Search modal state
pub struct SearchModal {
    /// Current search context
    pub context: SearchContext,

    /// Search query input
    pub query: String,

    /// Cursor position in input
    pub cursor_pos: usize,

    /// All matching results
    pub results: Vec<SearchResultItem>,

    /// List state for result selection
    pub list_state: ListState,

    /// Whether search is active
    pub is_active: bool,

    /// Status message
    pub status: String,

    /// Total results before filtering
    pub total_results: usize,
}

impl SearchModal {
    /// Create a new search modal
    pub fn new(context: SearchContext) -> Self {
        let mut list_state = ListState::default();
        list_state.select(Some(0));

        SearchModal {
            context,
            query: String::new(),
            cursor_pos: 0,
            results: Vec::new(),
            list_state,
            is_active: false,
            status: String::new(),
            total_results: 0,
        }
    }

    /// Activate the search modal
    pub fn activate(&mut self) {
        self.is_active = true;
        self.query.clear();
        self.cursor_pos = 0;
        self.results.clear();
        self.list_state.select(Some(0));
        self.update_search().ok(); // Initial load
    }

    /// Deactivate the search modal
    pub fn deactivate(&mut self) {
        self.is_active = false;
    }

    /// Handle keyboard input
    pub fn handle_key(&mut self, key: KeyEvent) -> Result<SearchAction> {
        if !self.is_active {
            return Ok(SearchAction::None);
        }

        match (key.code, key.modifiers) {
            // Exit search
            (KeyCode::Esc, _) | (KeyCode::Char('c'), KeyModifiers::CONTROL) => {
                self.deactivate();
                Ok(SearchAction::Cancel)
            }

            // Select result
            (KeyCode::Enter, _) => {
                if let Some(selected) = self.list_state.selected() {
                    if let Some(result) = self.results.get(selected) {
                        let action = match &self.context {
                            SearchContext::Global | SearchContext::Project(_) => {
                                SearchAction::SelectSession(result.id.clone())
                            }
                            SearchContext::Session(_) => {
                                SearchAction::SelectNode(result.id.clone())
                            }
                        };
                        self.deactivate();
                        return Ok(action);
                    }
                }
                Ok(SearchAction::None)
            }

            // Navigate results
            (KeyCode::Down, _) | (KeyCode::Char('j'), KeyModifiers::CONTROL) => {
                self.next_result();
                Ok(SearchAction::None)
            }
            (KeyCode::Up, _) | (KeyCode::Char('k'), KeyModifiers::CONTROL) => {
                self.previous_result();
                Ok(SearchAction::None)
            }

            // Edit query
            (KeyCode::Char(c), KeyModifiers::NONE) | (KeyCode::Char(c), KeyModifiers::SHIFT) => {
                self.query.insert(self.cursor_pos, c);
                self.cursor_pos += 1;
                self.run_search();
                Ok(SearchAction::None)
            }
            (KeyCode::Backspace, _) => {
                if self.cursor_pos > 0 {
                    self.query.remove(self.cursor_pos - 1);
                    self.cursor_pos -= 1;
                    self.run_search();
                }
                Ok(SearchAction::None)
            }
            (KeyCode::Delete, _) => {
                if self.cursor_pos < self.query.len() {
                    self.query.remove(self.cursor_pos);
                    self.run_search();
                }
                Ok(SearchAction::None)
            }
            (KeyCode::Left, _) => {
                if self.cursor_pos > 0 {
                    self.cursor_pos -= 1;
                }
                Ok(SearchAction::None)
            }
            (KeyCode::Right, _) => {
                if self.cursor_pos < self.query.len() {
                    self.cursor_pos += 1;
                }
                Ok(SearchAction::None)
            }
            (KeyCode::Home, _) | (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
                self.cursor_pos = 0;
                Ok(SearchAction::None)
            }
            (KeyCode::End, _) | (KeyCode::Char('e'), KeyModifiers::CONTROL) => {
                self.cursor_pos = self.query.len();
                Ok(SearchAction::None)
            }

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

    /// Move to next result
    fn next_result(&mut self) {
        if self.results.is_empty() {
            return;
        }
        let selected = self.list_state.selected().unwrap_or(0);
        let next = if selected >= self.results.len() - 1 {
            0
        } else {
            selected + 1
        };
        self.list_state.select(Some(next));
    }

    /// Move to previous result
    fn previous_result(&mut self) {
        if self.results.is_empty() {
            return;
        }
        let selected = self.list_state.selected().unwrap_or(0);
        let prev = if selected == 0 {
            self.results.len() - 1
        } else {
            selected - 1
        };
        self.list_state.select(Some(prev));
    }

    /// Run search and surface any error in the status bar instead of crashing.
    fn run_search(&mut self) {
        if let Err(e) = self.update_search() {
            self.results.clear();
            self.status = format!("Search error: {}", e);
        }
    }

    /// Update search results based on current query
    fn update_search(&mut self) -> Result<()> {
        match &self.context.clone() {
            SearchContext::Global => self.search_global_sessions(),
            SearchContext::Project(project) => self.search_project_sessions(project),
            SearchContext::Session(session_id) => self.search_session_content(session_id),
        }
    }

    /// Search all sessions globally
    fn search_global_sessions(&mut self) -> Result<()> {
        let (text, errors_only, tool) = parse_query(&self.query);
        let index = SessionIndex::new()?;
        let results = index.search_sessions(&text, None, errors_only, tool.as_deref())?;
        self.total_results = results.len();
        self.results = results.iter().map(session_to_result_item).collect();
        self.status = format!("{} sessions", self.results.len());
        if !self.results.is_empty() {
            self.list_state.select(Some(0));
        }
        Ok(())
    }

    /// Search sessions within a project
    fn search_project_sessions(&mut self, project: &str) -> Result<()> {
        let (text, errors_only, tool) = parse_query(&self.query);
        let index = SessionIndex::new()?;
        let results = index.search_sessions(&text, Some(project), errors_only, tool.as_deref())?;
        self.total_results = results.len();
        self.results = results.iter().map(session_to_result_item).collect();
        self.status = format!("{} sessions in {}", self.results.len(), project);
        if !self.results.is_empty() {
            self.list_state.select(Some(0));
        }
        Ok(())
    }

    /// Search within a specific session's content
    fn search_session_content(&mut self, session_id: &str) -> Result<()> {
        // Load the session
        let index = SessionIndex::new()?;
        let session_file = index
            .find_by_id(session_id)?
            .ok_or_else(|| crate::error::HindsightError::SessionNotFound(session_id.to_string()))?;

        let session = parse_session(&session_file.path)?;

        self.total_results = session.nodes.len();

        // Filter nodes based on query
        let query_lower = self.query.to_lowercase();
        let matching_nodes: Vec<(usize, &ExecutionNode)> = if self.query.is_empty() {
            // Show all nodes if no query
            session.nodes.iter().enumerate().collect()
        } else {
            // Search in node content
            session
                .nodes
                .iter()
                .enumerate()
                .filter(|(_, node)| {
                    // Get the actual categorized type (same logic as display)
                    let category = get_node_category(node);

                    // Search in categorized type
                    if category.to_lowercase().contains(&query_lower) {
                        return true;
                    }

                    // Search in tool name
                    if let Some(ref tool_use) = node.tool_use {
                        if tool_use.name.to_lowercase().contains(&query_lower) {
                            return true;
                        }
                    }

                    // Search in message content (handles both string and block array)
                    if let Some(ref message) = node.message {
                        let text = message.text_content();
                        if text.to_lowercase().contains(&query_lower) {
                            return true;
                        }
                        // Also search tool names in typed blocks
                        for block in message.content_blocks() {
                            if let crate::parser::models::ContentBlock::ToolUse { name, .. } = block
                            {
                                if name.to_lowercase().contains(&query_lower) {
                                    return true;
                                }
                            }
                        }
                    }

                    // Search in thinking content
                    if let Some(ref thinking) = node.thinking {
                        if thinking.to_lowercase().contains(&query_lower) {
                            return true;
                        }
                    }

                    // Search in tool result content
                    if let Some(ref tool_result) = node.tool_result {
                        if let Some(ref content) = tool_result.content {
                            if content.to_lowercase().contains(&query_lower) {
                                return true;
                            }
                        }
                    }

                    false
                })
                .collect()
        };

        // Convert to search results
        self.results = matching_nodes
            .iter()
            .take(100) // Limit to 100 results for performance
            .map(|(idx, node)| node_to_result_item(*idx, node))
            .collect();

        // Update status
        self.status = if self.results.len() == self.total_results {
            format!("{} nodes", self.total_results)
        } else {
            format!("{}/{} nodes", self.results.len(), self.total_results)
        };

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

        Ok(())
    }

    /// Render the search modal as an overlay
    pub fn render(&mut self, f: &mut Frame, area: Rect) {
        if !self.is_active {
            return;
        }

        // Create centered modal area (80% width, 70% height)
        let modal_area = centered_rect(80, 70, area);

        // Render background only for modal area (not full screen)
        use ratatui::widgets::Clear;
        let background = Block::default().style(Style::default().bg(Color::Rgb(40, 42, 54))); // Dracula-inspired background
        f.render_widget(Clear, modal_area);
        f.render_widget(background, modal_area);

        // Add padding (1 cell on all sides)
        let padded_area = Rect {
            x: modal_area.x + 1,
            y: modal_area.y + 1,
            width: modal_area.width.saturating_sub(2),
            height: modal_area.height.saturating_sub(2),
        };

        // Split modal into sections
        let chunks = Layout::vertical([
            Constraint::Length(3), // Input box
            Constraint::Length(1), // Separator
            Constraint::Min(10),   // Results list
            Constraint::Length(1), // Separator
            Constraint::Length(8), // Preview pane
            Constraint::Length(1), // Status bar
        ])
        .split(padded_area);

        // Render input box
        self.render_input(f, chunks[0]);

        // Render results list
        self.render_results(f, chunks[2]);

        // Render preview
        self.render_preview(f, chunks[4]);

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

    /// Render the search input box
    fn render_input(&self, f: &mut Frame, area: Rect) {
        let context_name = match &self.context {
            SearchContext::Global => "Search: All Sessions",
            SearchContext::Project(p) => &format!("Search: Project {}", p),
            SearchContext::Session(_) => "Search: Session Content",
        };

        let title = format!(" {} ", context_name);

        let input_text = if self.query.is_empty() {
            Span::styled(
                "Type to search...",
                Style::default()
                    .fg(Color::DarkGray)
                    .add_modifier(Modifier::ITALIC),
            )
        } else {
            Span::styled(
                &self.query,
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD),
            )
        };

        let input = Paragraph::new(Line::from(vec![
            Span::styled(
                " > ",
                Style::default()
                    .fg(Color::Green)
                    .add_modifier(Modifier::BOLD),
            ),
            input_text,
        ]))
        .block(
            Block::default()
                .borders(Borders::ALL)
                .title(title)
                .border_style(
                    Style::default()
                        .fg(Color::Cyan)
                        .add_modifier(Modifier::BOLD),
                ),
        );

        f.render_widget(input, area);

        // Position cursor (after the prompt)
        f.set_cursor_position((area.x + 4 + self.cursor_pos as u16, area.y + 1));
    }

    /// Render the results list
    fn render_results(&mut self, f: &mut Frame, area: Rect) {
        let items: Vec<ListItem> = self
            .results
            .iter()
            .map(|result| {
                // Color-code based on node type
                let title_color = if result.title.contains("[TOOL]") {
                    Color::Yellow
                } else if result.title.contains("[USER]") {
                    Color::Green
                } else if result.title.contains("[ASSISTANT]") {
                    Color::Cyan
                } else if result.title.contains("[THINKING]") {
                    Color::Magenta
                } else if result.title.contains("[RESULT]") {
                    if result.title.contains("ERROR") {
                        Color::Red
                    } else {
                        Color::Blue
                    }
                } else {
                    Color::White
                };

                let title_span = Span::styled(
                    &result.title,
                    Style::default()
                        .fg(title_color)
                        .add_modifier(Modifier::BOLD),
                );
                let subtitle_span = Span::styled(
                    format!(" │ {}", result.subtitle),
                    Style::default().fg(Color::Gray),
                );

                ListItem::new(Line::from(vec![title_span, subtitle_span]))
            })
            .collect();

        let title = if self.results.is_empty() {
            " No Results ".to_string()
        } else {
            format!(" Results ({}/{}) ", self.results.len(), self.total_results)
        };

        let list = List::new(items)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(title)
                    .border_style(Style::default().fg(Color::White)),
            )
            .highlight_style(
                Style::default()
                    .bg(Color::Rgb(40, 40, 60))
                    .fg(Color::Yellow)
                    .add_modifier(Modifier::BOLD),
            )
            .highlight_symbol("  ");

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

    /// Render the preview pane
    fn render_preview(&self, f: &mut Frame, area: Rect) {
        let preview_text = if let Some(selected) = self.list_state.selected() {
            if let Some(result) = self.results.get(selected) {
                &result.preview
            } else {
                "No preview available"
            }
        } else {
            "No preview available"
        };

        let preview = Paragraph::new(preview_text)
            .block(
                Block::default()
                    .borders(Borders::ALL)
                    .title(" Preview ")
                    .border_style(Style::default().fg(Color::White)),
            )
            .wrap(Wrap { trim: false })
            .style(Style::default().fg(Color::White));

        f.render_widget(preview, area);
    }

    /// Render the status bar
    fn render_status(&self, f: &mut Frame, area: Rect) {
        let help_text = " Enter: Select | Up/Down: Navigate | Esc: Cancel ";

        let status = Paragraph::new(Line::from(vec![
            Span::styled(&self.status, Style::default().fg(Color::Cyan)),
            Span::raw(
                " ".repeat(
                    area.width
                        .saturating_sub(self.status.len() as u16 + help_text.len() as u16 + 3)
                        as usize,
                ),
            ),
            Span::styled(help_text, Style::default().fg(Color::Gray)),
        ]))
        .alignment(Alignment::Left)
        .style(Style::default().bg(Color::Rgb(20, 20, 30)));

        f.render_widget(status, area);
    }
}

/// Action returned by search modal
#[derive(Debug, Clone)]
pub enum SearchAction {
    None,
    Cancel,
    SelectSession(String),
    SelectNode(String),
}

/// Parse a search query into (text, errors_only, tool) parts.
///
/// Supported syntax:
///   `errors`   → errors_only = true
///   `@ToolName` → tool filter
///   anything else → free-text search
fn parse_query(q: &str) -> (String, bool, Option<String>) {
    let q = q.trim();
    if q.eq_ignore_ascii_case("errors") {
        return (String::new(), true, None);
    }
    if let Some(tool) = q.strip_prefix('@') {
        return (String::new(), false, Some(tool.to_string()));
    }
    (q.to_string(), false, None)
}

/// Convert a SessionFile to a SearchResultItem
fn session_to_result_item(s: &SessionFile) -> SearchResultItem {
    let short_id = &s.session_id[..8.min(s.session_id.len())];
    let msg_preview = s.first_message.as_deref().unwrap_or("(no message)");
    let msg_short: String = msg_preview.chars().take(55).collect();
    let model = s.model.as_deref().unwrap_or("-");
    let updated = format_time_ago(s.modified_at);
    let age = format_time_ago(s.created_at);

    SearchResultItem {
        title: format!("{}  {}", short_id, s.project_name),
        subtitle: msg_short,
        preview: format!(
            "Project:  {}\nMessage:  {}\nModel:    {}\nErrors:   {}\nUpdated:  {}\nAge:      {}",
            s.project_name,
            msg_preview,
            model,
            s.error_count,
            updated,
            age,
        ),
        id: s.session_id.clone(),
        score: 1.0,
    }
}

/// Get the categorized type of a node (matches display logic)
fn get_node_category(node: &ExecutionNode) -> String {
    if node.tool_use.is_some() {
        "tool".to_string()
    } else if node.tool_result.is_some() {
        "result".to_string()
    } else if node.thinking.is_some() {
        "thinking".to_string()
    } else if node.message.is_some() {
        let node_type_lower = node.node_type.to_lowercase();
        if node_type_lower.contains("user") {
            "user".to_string()
        } else if node_type_lower.contains("assistant") {
            "assistant".to_string()
        } else {
            node.node_type.clone()
        }
    } else {
        node.node_type.clone()
    }
}

/// Convert an ExecutionNode to a SearchResultItem
fn node_to_result_item(index: usize, node: &ExecutionNode) -> SearchResultItem {
    let node_type = &node.node_type;
    let node_type_lower = node_type.to_lowercase();

    // Build title and subtitle based on node type
    // Match by actual content, not just type string
    let (title, subtitle) = if node.tool_use.is_some() {
        // This is a tool use node
        let tool_name = node
            .tool_use
            .as_ref()
            .map(|t| t.name.clone())
            .unwrap_or_else(|| "Unknown".to_string());

        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [TOOL] {}", index + 1, tool_name),
            format!("{} • tool use", time),
        )
    } else if node.tool_result.is_some() {
        // This is a tool result node
        let status = node
            .tool_result
            .as_ref()
            .and_then(|r| r.is_error)
            .map(|is_err| if is_err { "ERROR" } else { "OK" })
            .unwrap_or("RESULT");

        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [RESULT] {}", index + 1, status),
            format!("{} • tool result", time),
        )
    } else if node.thinking.is_some() {
        // This is a thinking node
        let preview = node
            .thinking
            .as_ref()
            .map(|t| {
                let preview: String = t.chars().take(60).collect();
                if t.len() > 60 {
                    format!("{}...", preview)
                } else {
                    preview
                }
            })
            .unwrap_or_else(|| "Thinking...".to_string());

        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [THINKING] {}", index + 1, preview),
            format!("{} • thinking", time),
        )
    } else if node.message.is_some() && node_type_lower.contains("user") {
        // This is a user message node
        let preview = node
            .message
            .as_ref()
            .map(|m| {
                let text = m.text_content();
                if text.is_empty() {
                    "User message".to_string()
                } else {
                    let p: String = text.chars().take(60).collect();
                    if text.len() > 60 {
                        format!("{}...", p)
                    } else {
                        p
                    }
                }
            })
            .unwrap_or_else(|| "User message".to_string());

        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [USER] {}", index + 1, preview),
            format!("{} • user message", time),
        )
    } else if node.message.is_some() && node_type_lower.contains("assistant") {
        // This is an assistant message node
        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [ASSISTANT]", index + 1),
            format!("{} • assistant response", time),
        )
    } else {
        // Fallback for other node types
        let time = node
            .timestamp
            .map(format_timestamp)
            .unwrap_or_else(|| "??:??:??".to_string());

        (
            format!("#{} [{}]", index + 1, node_type.to_uppercase()),
            format!("{} • {}", time, node_type),
        )
    };

    // Build preview
    let preview = build_node_preview(node);

    // Use UUID as ID, fallback to index
    let id = node.uuid.clone().unwrap_or_else(|| index.to_string());

    SearchResultItem {
        title,
        subtitle,
        preview,
        id,
        score: 1.0,
    }
}

/// Build a preview text for a node
fn build_node_preview(node: &ExecutionNode) -> String {
    let mut preview = String::new();

    // Show the categorized type (same as display logic)
    let category = get_node_category(node);
    preview.push_str(&format!("Type: {}\n", category));

    if let Some(ref uuid) = node.uuid {
        preview.push_str(&format!("UUID: {}\n", uuid));
    }

    if let Some(ref tool_use) = node.tool_use {
        preview.push_str(&format!("Tool: {}\n", tool_use.name));
        preview.push_str(&format!(
            "Input: {}\n",
            serde_json::to_string_pretty(&tool_use.input).unwrap_or_default()
        ));
    }

    if let Some(ref message) = node.message {
        // Text content (handles legacy string + blocks)
        let text = message.text_content();
        if !text.is_empty() {
            preview.push_str(&format!("Content:\n{}\n", truncate_string(&text, 500)));
        }
        // Tool names in typed blocks
        for block in message.content_blocks() {
            if let crate::parser::models::ContentBlock::ToolUse { name, input, .. } = block {
                preview.push_str(&format!(
                    "Tool: {}\nInput: {}\n",
                    name,
                    serde_json::to_string_pretty(input).unwrap_or_default()
                ));
            }
        }
    }

    if let Some(ref thinking) = node.thinking {
        let preview_text = truncate_string(thinking, 500);
        preview.push_str(&format!("Thinking:\n{}\n", preview_text));
    }

    if let Some(ref tool_result) = node.tool_result {
        if let Some(is_error) = tool_result.is_error {
            preview.push_str(&format!(
                "Status: {}\n",
                if is_error { "ERROR" } else { "OK" }
            ));
        }
        if let Some(ref content) = tool_result.content {
            let preview_text = truncate_string(content, 300);
            preview.push_str(&format!("Result:\n{}\n", preview_text));
        }
    }

    preview
}

/// Safely truncate a string at character boundaries, not byte boundaries
fn truncate_string(s: &str, max_chars: usize) -> String {
    if s.chars().count() <= max_chars {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max_chars).collect();
        format!("{}...", truncated)
    }
}

/// Format timestamp (milliseconds) as HH:MM:SS
fn format_timestamp(ts_ms: i64) -> String {
    let ts_s = ts_ms / 1000;
    let dt = chrono::Local.timestamp_opt(ts_s, 0);
    match dt.single() {
        Some(datetime) => datetime.format("%H:%M:%S").to_string(),
        None => "??:??:??".to_string(),
    }
}

/// Format timestamp as "time ago" string
fn format_time_ago(timestamp: i64) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);

    let diff = now - timestamp;

    if diff < 60 {
        "just now".to_string()
    } else if diff < 3600 {
        format!("{}m ago", diff / 60)
    } else if diff < 86400 {
        format!("{}h ago", diff / 3600)
    } else if diff < 604800 {
        format!("{}d ago", diff / 86400)
    } else {
        format!("{}w ago", diff / 604800)
    }
}

/// Create a centered rectangle
fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let popup_layout = Layout::vertical([
        Constraint::Percentage((100 - percent_y) / 2),
        Constraint::Percentage(percent_y),
        Constraint::Percentage((100 - percent_y) / 2),
    ])
    .split(area);

    Layout::horizontal([
        Constraint::Percentage((100 - percent_x) / 2),
        Constraint::Percentage(percent_x),
        Constraint::Percentage((100 - percent_x) / 2),
    ])
    .split(popup_layout[1])[1]
}