Skip to main content

pxh/recall/
tui.rs

1use std::collections::hash_map::Entry as MapEntry;
2use std::collections::{HashMap, HashSet};
3use std::fs::File;
4use std::io::{BufWriter, Write};
5use std::time::{Duration, Instant};
6
7use anyhow::Result;
8use crossterm::{
9    cursor::{Hide, MoveTo, Show},
10    event::{self, Event, KeyCode, KeyEvent, KeyModifiers},
11    execute, queue,
12    style::{Attribute, Color, ResetColor, SetAttribute, SetBackgroundColor, SetForegroundColor},
13    terminal::{self, Clear, ClearType, EnterAlternateScreen, LeaveAlternateScreen},
14};
15
16#[cfg(not(target_os = "windows"))]
17use crossterm::event::{
18    KeyboardEnhancementFlags, PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
19};
20use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
21
22use super::command::{FilterMode, HostFilter};
23use super::engine::{HistoryEntry, SearchEngine, format_relative_time};
24use super::query::RecallQuery;
25use crate::config::{KeymapMode, PreviewConfig, RecallConfig};
26
27const SCROLL_MARGIN: usize = 5;
28
29/// Base64-encode bytes for OSC 52 clipboard escape.
30fn base64_encode(input: &[u8]) -> String {
31    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
32    let mut output = String::with_capacity(input.len().div_ceil(3) * 4);
33    for chunk in input.chunks(3) {
34        let b0 = chunk[0] as u32;
35        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
36        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
37        let triple = (b0 << 16) | (b1 << 8) | b2;
38        output.push(ALPHABET[(triple >> 18 & 0x3F) as usize] as char);
39        output.push(ALPHABET[(triple >> 12 & 0x3F) as usize] as char);
40        if chunk.len() > 1 {
41            output.push(ALPHABET[(triple >> 6 & 0x3F) as usize] as char);
42        } else {
43            output.push('=');
44        }
45        if chunk.len() > 2 {
46            output.push(ALPHABET[(triple & 0x3F) as usize] as char);
47        } else {
48            output.push('=');
49        }
50    }
51    output
52}
53
54/// Sanitize a string for safe terminal display by removing ANSI escape sequences
55/// and control characters that could affect cursor position or terminal state.
56fn sanitize_for_display(s: &str) -> String {
57    let mut result = String::with_capacity(s.len());
58    let mut chars = s.chars().peekable();
59
60    while let Some(c) = chars.next() {
61        match c {
62            '\x1b' => {
63                match chars.peek() {
64                    // CSI: \x1b[ ... letter
65                    Some(&'[') => {
66                        chars.next();
67                        while let Some(&c) = chars.peek() {
68                            chars.next();
69                            if c.is_ascii_alphabetic() {
70                                break;
71                            }
72                        }
73                    }
74                    // OSC: \x1b] ... (BEL or ST)
75                    Some(&']') => {
76                        chars.next();
77                        while let Some(c) = chars.next() {
78                            if c == '\x07' {
79                                break;
80                            }
81                            if c == '\x1b' && chars.peek() == Some(&'\\') {
82                                chars.next();
83                                break;
84                            }
85                        }
86                    }
87                    // DCS: \x1bP ... ST (\x1b\\)
88                    Some(&'P') => {
89                        chars.next();
90                        while let Some(c) = chars.next() {
91                            if c == '\x1b' && chars.peek() == Some(&'\\') {
92                                chars.next();
93                                break;
94                            }
95                        }
96                    }
97                    // Any other ESC + char: skip one char (SS2, SS3, etc.)
98                    Some(_) => {
99                        chars.next();
100                    }
101                    None => {}
102                }
103            }
104            '\n' | '\r' | '\t' => result.push(' '),
105            // C0 and C1 controls: C1 (U+0080-U+009F) includes CSI (U+009B) and
106            // OSC (U+009D), which can inject terminal commands in 8-bit modes
107            '\x00'..='\x08'
108            | '\x0b'..='\x0c'
109            | '\x0e'..='\x1f'
110            | '\x7f'
111            | '\u{0080}'..='\u{009F}' => {}
112            _ => result.push(c),
113        }
114    }
115
116    result
117}
118
119const PREVIEW_HEIGHT: usize = 5; // Height of preview pane in lines
120const FLASH_DURATION_MS: u64 = 100; // Duration of visual flash in milliseconds
121
122/// Deduplicate history entries by command string, keeping the most recent occurrence.
123/// Entries are already sorted by timestamp (most recent first), so we keep the first
124/// occurrence of each command, accumulating the number of collapsed duplicates in
125/// its `use_count` for the frequency component of scoring. Trailing whitespace is
126/// ignored for dedup since "df -h" and "df -h " are visually identical and
127/// semantically the same.
128fn deduplicate_entries(entries: Vec<HistoryEntry>) -> Vec<HistoryEntry> {
129    let mut index: HashMap<String, usize> = HashMap::new();
130    let mut deduped: Vec<HistoryEntry> = Vec::new();
131    for entry in entries {
132        match index.entry(entry.command.trim_end().to_string()) {
133            MapEntry::Occupied(slot) => deduped[*slot.get()].use_count += entry.use_count,
134            MapEntry::Vacant(slot) => {
135                slot.insert(deduped.len());
136                deduped.push(entry);
137            }
138        }
139    }
140    deduped
141}
142
143/// A candidate entry set as loaded for a particular DB-level query
144/// (None = the broad, unfiltered recency window).
145struct EntrySnapshot {
146    db_query: Option<RecallQuery>,
147    entries: Vec<HistoryEntry>,
148}
149
150/// Bounded cache of candidate sets from previous DB loads. Backspacing (or
151/// re-typing) a query restores a previous set by moving it out of the cache
152/// instead of re-scanning the table, which costs ~100ms at 500k rows.
153#[derive(Default)]
154struct EntryCache {
155    snapshots: Vec<EntrySnapshot>,
156}
157
158impl EntryCache {
159    const CAP: usize = 8;
160
161    /// Whether a set loaded with `db_query` is guaranteed to contain every
162    /// row the DB would return for `query`. A narrow set covers queries
163    /// whose prefilter conditions imply its own (`RecallQuery::covers`, the
164    /// same relation the LIKE patterns are built from); the broad set covers
165    /// exactly the queries that don't want a DB dig, since it is
166    /// window-limited.
167    fn covers(db_query: Option<&RecallQuery>, query: &RecallQuery, wants_prefilter: bool) -> bool {
168        match (db_query, wants_prefilter) {
169            (None, false) => true,
170            (Some(prev), true) => prev.covers(query),
171            _ => false,
172        }
173    }
174
175    /// Remove and return the narrowest cached set covering `query`.
176    /// Narrowest = fewest entries for the fuzzy stage to re-rank.
177    fn take_covering(
178        &mut self,
179        query: &RecallQuery,
180        wants_prefilter: bool,
181    ) -> Option<EntrySnapshot> {
182        let idx = self
183            .snapshots
184            .iter()
185            .enumerate()
186            .filter(|(_, s)| Self::covers(s.db_query.as_ref(), query, wants_prefilter))
187            .max_by_key(|(_, s)| s.db_query.as_ref().map_or(0, RecallQuery::specificity))
188            .map(|(i, _)| i)?;
189        Some(self.snapshots.remove(idx))
190    }
191
192    /// Store a snapshot, replacing any existing one for the same db_query
193    /// and evicting the oldest when full.
194    fn store(&mut self, snap: EntrySnapshot) {
195        self.snapshots.retain(|s| s.db_query != snap.db_query);
196        if self.snapshots.len() >= Self::CAP {
197            self.snapshots.remove(0);
198        }
199        self.snapshots.push(snap);
200    }
201
202    fn clear(&mut self) {
203        self.snapshots.clear();
204    }
205}
206
207/// Highlight matching portions of a command for display (substring matching).
208/// Returns spans with (text, is_highlight) pairs.
209/// Only used in tests now - fuzzy matching uses highlight_command_with_indices.
210#[cfg(test)]
211fn highlight_command(cmd: &str, query: &str, max_len: usize) -> Vec<(String, bool)> {
212    if query.is_empty() {
213        let truncated = if cmd.chars().count() > max_len {
214            let t: String = cmd.chars().take(max_len.saturating_sub(3)).collect();
215            format!("{t}...")
216        } else {
217            cmd.to_string()
218        };
219        return vec![(truncated, false)];
220    }
221
222    let cmd_lower = cmd.to_lowercase();
223    let query_lower = query.to_lowercase();
224    let mut spans = Vec::new();
225    let mut pos = 0;
226    let cmd_chars: Vec<char> = cmd.chars().collect();
227    let mut total_len = 0;
228
229    while let Some(match_start) = cmd_lower[pos..].find(&query_lower) {
230        let abs_start = pos + match_start;
231        let abs_end = abs_start + query_lower.len();
232
233        // Add non-matching text before this match
234        if abs_start > pos {
235            let text: String = cmd_chars
236                [char_pos_from_byte(cmd, pos)..char_pos_from_byte(cmd, abs_start)]
237                .iter()
238                .collect();
239            let text_len = text.chars().count();
240            if total_len + text_len > max_len.saturating_sub(3) {
241                let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
242                let truncated: String = text.chars().take(remaining).collect();
243                spans.push((truncated, false));
244                spans.push(("...".to_string(), false));
245                return spans;
246            }
247            total_len += text_len;
248            spans.push((text, false));
249        }
250
251        // Add matching text
252        let match_text: String = cmd_chars
253            [char_pos_from_byte(cmd, abs_start)..char_pos_from_byte(cmd, abs_end)]
254            .iter()
255            .collect();
256        let match_len = match_text.chars().count();
257        if total_len + match_len > max_len.saturating_sub(3) {
258            let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
259            let truncated: String = match_text.chars().take(remaining).collect();
260            spans.push((truncated, true));
261            spans.push(("...".to_string(), false));
262            return spans;
263        }
264        total_len += match_len;
265        spans.push((match_text, true));
266
267        pos = abs_end;
268    }
269
270    // Add remaining text after last match
271    if pos < cmd.len() {
272        let text: String = cmd_chars[char_pos_from_byte(cmd, pos)..].iter().collect();
273        let text_len = text.chars().count();
274        if total_len + text_len > max_len {
275            let remaining = max_len.saturating_sub(3).saturating_sub(total_len);
276            let truncated: String = text.chars().take(remaining).collect();
277            spans.push((truncated, false));
278            spans.push(("...".to_string(), false));
279        } else {
280            spans.push((text, false));
281        }
282    }
283
284    spans
285}
286
287/// Convert byte position to char position in a string.
288#[cfg(test)]
289fn char_pos_from_byte(s: &str, byte_pos: usize) -> usize {
290    s[..byte_pos].chars().count()
291}
292
293/// Highlight a command using pre-computed match indices from fuzzy matching.
294/// Returns spans with (text, is_highlight) pairs.
295/// Terminal columns a character occupies: 2 for East Asian wide, 0 for
296/// combining marks and controls.
297fn char_width(c: char) -> usize {
298    c.width().unwrap_or(0)
299}
300
301/// Cut `s` to at most `max_width` terminal columns, ending in "..." when cut.
302fn truncate_to_width(s: &str, max_width: usize) -> String {
303    if s.width() <= max_width {
304        return s.to_string();
305    }
306    let budget = max_width.saturating_sub(3);
307    let mut width = 0;
308    let kept: String = s
309        .chars()
310        .take_while(|&c| {
311            width += char_width(c);
312            width <= budget
313        })
314        .collect();
315    format!("{kept}...")
316}
317
318fn highlight_command_with_indices(
319    cmd: &str,
320    match_indices: &[u32],
321    max_len: usize,
322) -> Vec<(String, bool)> {
323    if cmd.is_empty() {
324        return vec![];
325    }
326
327    // Build a set of matched character positions for O(1) lookup
328    let match_set: HashSet<u32> = match_indices.iter().copied().collect();
329
330    let mut spans = Vec::new();
331    let mut current_span = String::new();
332    let mut current_is_match = false;
333
334    // A command that fits is never cut; one that does not loses enough
335    // columns to make room for the "..." suffix.
336    let budget = if cmd.width() <= max_len { max_len } else { max_len.saturating_sub(3) };
337    let mut width = 0;
338    for (i, c) in cmd.chars().enumerate() {
339        width += char_width(c);
340        if width > budget {
341            // Truncate with ellipsis
342            if !current_span.is_empty() {
343                spans.push((current_span, current_is_match));
344            }
345            spans.push(("...".to_string(), false));
346            return spans;
347        }
348
349        let is_match = match_set.contains(&(i as u32));
350
351        if is_match != current_is_match && !current_span.is_empty() {
352            spans.push((std::mem::take(&mut current_span), current_is_match));
353        }
354
355        current_is_match = is_match;
356        current_span.push(c);
357    }
358
359    if !current_span.is_empty() {
360        spans.push((current_span, current_is_match));
361    }
362
363    spans
364}
365
366fn format_duration(secs: i64) -> String {
367    if secs < 60 {
368        format!("{secs}s")
369    } else if secs < 3600 {
370        format!("{}m {}s", secs / 60, secs % 60)
371    } else {
372        format!("{}h {}m {}s", secs / 3600, (secs % 3600) / 60, secs % 60)
373    }
374}
375
376/// The pure recall UI state machine: entries, cache, query, selection,
377/// scroll, keymaps, and frame rendering -- everything except the terminal
378/// itself. Constructible without a tty, so key handling, scroll math, cache
379/// coverage, and drawing (into any `Write`) are all unit-testable.
380pub struct RecallState {
381    engine: SearchEngine,
382    filter_mode: FilterMode,
383    host_filter: HostFilter,
384    entries: Vec<HistoryEntry>,
385    /// Filtered indices with match positions: (entry_index, match_char_indices)
386    filtered_indices: Vec<(usize, Vec<u32>)>,
387    query: String,
388    selected_index: usize,
389    scroll_offset: usize, // Index of entry at top of visible area
390    term_height: u16,
391    term_width: u16,
392    keymap_mode: KeymapMode,
393    show_preview: bool,
394    preview_config: PreviewConfig,
395    shell_mode: bool, // When true, outputs command for shell execution; when false, prints details
396    db_query_used: Option<RecallQuery>, // Tracks the query passed to the last DB load
397    entry_cache: EntryCache, // Previous candidate sets, restored on backspace
398    flash_until: Option<Instant>, // For visual feedback on unrecognized keys
399    status_message: Option<(String, Instant)>,
400    needs_redraw: bool,
401}
402
403/// The terminal adapter: raw mode, /dev/tty, keyboard enhancement, and the
404/// restore-exactly-once guard. The only piece of recall that needs a real
405/// terminal; everything behind it renders to a plain `Write`.
406struct RecallTerminal {
407    tty: File,
408    cleaned_up: bool, // Terminal already restored; Drop must not repeat it
409    keyboard_enhanced: bool,
410}
411
412/// Switch the terminal into recall mode: alternate screen, hidden cursor,
413/// and (off Windows) the kitty keyboard protocol for instant Escape.
414/// Returns whether keyboard enhancement was requested, for the matching pop.
415///
416/// The alternate screen comes first: the kitty protocol keeps one flag stack
417/// per screen, so the push and the pop in `leave_recall_screen` must both
418/// happen on the alternate screen or the shell inherits the flags.
419fn enter_recall_screen(w: &mut impl Write) -> Result<bool> {
420    execute!(
421        w,
422        EnterAlternateScreen,
423        Hide,
424        Clear(ClearType::All),
425        Clear(ClearType::Purge),
426        MoveTo(0, 0)
427    )?;
428
429    #[cfg(not(target_os = "windows"))]
430    let keyboard_enhanced = execute!(
431        w,
432        PushKeyboardEnhancementFlags(KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES)
433    )
434    .is_ok();
435    #[cfg(target_os = "windows")]
436    let keyboard_enhanced = false;
437
438    w.flush()?;
439    Ok(keyboard_enhanced)
440}
441
442/// Undo `enter_recall_screen`.
443fn leave_recall_screen(w: &mut impl Write, keyboard_enhanced: bool) -> Result<()> {
444    #[cfg(not(target_os = "windows"))]
445    if keyboard_enhanced {
446        let _ = execute!(w, PopKeyboardEnhancementFlags);
447    }
448    #[cfg(target_os = "windows")]
449    let _ = keyboard_enhanced;
450    execute!(w, Show, LeaveAlternateScreen)?;
451    Ok(())
452}
453
454impl RecallTerminal {
455    fn new() -> Result<Self> {
456        terminal::enable_raw_mode()?;
457        let mut tty = File::options().read(true).write(true).open("/dev/tty")?;
458        let keyboard_enhanced = enter_recall_screen(&mut tty)?;
459
460        Ok(RecallTerminal { tty, cleaned_up: false, keyboard_enhanced })
461    }
462
463    fn cleanup(&mut self) -> Result<()> {
464        self.cleaned_up = true;
465        leave_recall_screen(&mut self.tty, self.keyboard_enhanced)?;
466        terminal::disable_raw_mode()?;
467        Ok(())
468    }
469
470    /// Copy text to the user's clipboard via an OSC 52 escape sequence.
471    fn write_clipboard(&mut self, text: &str) {
472        let encoded = base64_encode(text.as_bytes());
473        let _ = write!(self.tty, "\x1b]52;c;{encoded}\x07");
474        let _ = self.tty.flush();
475    }
476}
477
478impl Drop for RecallTerminal {
479    fn drop(&mut self) {
480        if self.cleaned_up {
481            return;
482        }
483        let _ = leave_recall_screen(&mut self.tty, self.keyboard_enhanced);
484        let _ = terminal::disable_raw_mode();
485    }
486}
487
488/// The interactive recall UI: a `RecallState` driven by events from a
489/// `RecallTerminal`.
490pub struct RecallTui {
491    state: RecallState,
492    terminal: RecallTerminal,
493}
494
495impl RecallTui {
496    pub fn new(
497        engine: SearchEngine,
498        initial_mode: FilterMode,
499        initial_query: Option<String>,
500        config: &RecallConfig,
501        shell_mode: bool,
502    ) -> Result<Self> {
503        // Build the state (including the initial DB load) before touching the
504        // terminal, so failures leave the terminal untouched.
505        let mut state = RecallState::new(engine, initial_mode, initial_query, config, shell_mode)?;
506        let terminal = RecallTerminal::new()?;
507        let (term_width, term_height) = terminal::size()?;
508        state.set_dimensions(term_width, term_height);
509        state.adjust_scroll_for_selection();
510        Ok(RecallTui { state, terminal })
511    }
512
513    fn draw_frame(&mut self) -> Result<()> {
514        // Get fresh terminal size each frame
515        let (term_width, term_height) = terminal::size()?;
516        self.state.set_dimensions(term_width, term_height);
517        // Use buffered writer to batch all terminal writes into a single syscall
518        let mut w = BufWriter::new(&self.terminal.tty);
519        self.state.draw(&mut w)
520    }
521
522    pub fn run(&mut self) -> Result<Option<String>> {
523        loop {
524            if self.state.expire_timed_effects() {
525                self.state.needs_redraw = true;
526            }
527
528            if self.state.needs_redraw {
529                self.draw_frame()?;
530                self.state.needs_redraw = false;
531            }
532
533            if !event::poll(Duration::from_millis(100))? {
534                continue;
535            }
536
537            match event::read()? {
538                Event::Key(key) => {
539                    self.state.needs_redraw = true;
540                    let action = self.state.handle_key(key)?;
541                    match action {
542                        KeyAction::Continue => continue,
543                        KeyAction::Copy(text) => {
544                            self.terminal.write_clipboard(&text);
545                            continue;
546                        }
547                        KeyAction::Select | KeyAction::Edit | KeyAction::EditBeginning => {
548                            self.terminal.cleanup()?;
549                            if !self.state.shell_mode {
550                                self.state.print_entry_details();
551                                return Ok(None);
552                            }
553                            let prefix = match action {
554                                KeyAction::Select => "run",
555                                KeyAction::EditBeginning => "edit-a",
556                                _ => "edit",
557                            };
558                            let result = self
559                                .state
560                                .get_selected_command()
561                                .map(|cmd| format!("{prefix}:{cmd}"));
562                            return Ok(result);
563                        }
564                        KeyAction::Cancel => {
565                            self.terminal.cleanup()?;
566                            return Ok(None);
567                        }
568                    }
569                }
570                Event::Resize(_, _) => {
571                    self.state.needs_redraw = true;
572                }
573                _ => {}
574            }
575        }
576    }
577
578    /// Draw once and exit (for profiling)
579    pub fn draw_once(&mut self) -> Result<()> {
580        self.draw_frame()?;
581        self.terminal.cleanup()?;
582        Ok(())
583    }
584}
585
586impl RecallState {
587    fn new(
588        mut engine: SearchEngine,
589        initial_mode: FilterMode,
590        initial_query: Option<String>,
591        config: &RecallConfig,
592        shell_mode: bool,
593    ) -> Result<Self> {
594        let query = initial_query.as_deref().unwrap_or("").to_string();
595        let host_filter = HostFilter::default();
596        let parsed_query = RecallQuery::parse(&query);
597        let db_query_used =
598            (query.len() >= 3 && parsed_query.has_prefilter()).then(|| parsed_query.clone());
599        let mut entries = deduplicate_entries(engine.load_entries(
600            initial_mode,
601            host_filter,
602            db_query_used.as_ref(),
603        )?);
604        entries.truncate(engine.result_limit());
605
606        // Apply initial fuzzy filtering
607        let filtered_indices = if query.is_empty() {
608            (0..entries.len()).map(|i| (i, Vec::new())).collect()
609        } else {
610            engine.filter_entries(&entries, &parsed_query)
611        };
612
613        Ok(RecallState {
614            engine,
615            filter_mode: initial_mode,
616            host_filter,
617            entries,
618            filtered_indices,
619            query,
620            selected_index: 0,
621            scroll_offset: 0,
622            term_height: 0,
623            term_width: 0,
624            keymap_mode: config.initial_keymap_mode(),
625            show_preview: config.show_preview,
626            preview_config: config.preview.clone(),
627            shell_mode,
628            db_query_used,
629            entry_cache: EntryCache::default(),
630            flash_until: None,
631            status_message: None,
632            needs_redraw: true,
633        })
634    }
635
636    fn set_dimensions(&mut self, width: u16, height: u16) {
637        self.term_width = width;
638        self.term_height = height;
639    }
640
641    /// Clear expired timed effects (status message, flash); returns true if
642    /// anything changed and a redraw is needed.
643    fn expire_timed_effects(&mut self) -> bool {
644        let mut changed = false;
645        if let Some((_, until)) = self.status_message
646            && Instant::now() >= until
647        {
648            self.status_message = None;
649            changed = true;
650        }
651        if let Some(until) = self.flash_until
652            && Instant::now() >= until
653        {
654            self.flash_until = None;
655            changed = true;
656        }
657        changed
658    }
659
660    fn results_height(&self) -> usize {
661        let base = self.term_height.saturating_sub(2) as usize;
662        if self.show_preview { base.saturating_sub(PREVIEW_HEIGHT) } else { base }
663    }
664
665    fn adjust_scroll_for_selection(&mut self) {
666        let results_height = self.results_height();
667        if results_height == 0 || self.filtered_indices.is_empty() {
668            self.scroll_offset = 0;
669            return;
670        }
671
672        // In our layout, entry 0 (most recent) is at the bottom visually.
673        // scroll_offset is the entry index shown at the TOP of the visible area.
674        // Higher scroll_offset means we're showing older entries.
675        //
676        // Visible range: scroll_offset.saturating_sub(results_height - 1) to scroll_offset
677        // But actually, let's think of it differently:
678        //   - The bottom of the visible area shows entry index `bottom_visible`
679        //   - The top shows entry index `bottom_visible + results_height - 1`
680        //
681        // Let's use `view_bottom` as the entry index shown at the bottom of results area.
682        // Visible entries: view_bottom to view_bottom + results_height - 1
683
684        // Calculate current view bounds based on scroll_offset
685        // scroll_offset represents the entry at the bottom of the visible area
686        let view_bottom = self.scroll_offset;
687        let view_top = view_bottom + results_height.saturating_sub(1);
688
689        // Check if selected is within the visible range with margins
690        if self.selected_index < view_bottom + SCROLL_MARGIN {
691            // Selection is too close to bottom, scroll down (show newer entries)
692            self.scroll_offset = self.selected_index.saturating_sub(SCROLL_MARGIN);
693        } else if self.selected_index > view_top.saturating_sub(SCROLL_MARGIN) {
694            // Selection is too close to top, scroll up (show older entries)
695            let new_view_top = self.selected_index + SCROLL_MARGIN;
696            self.scroll_offset = new_view_top.saturating_sub(results_height.saturating_sub(1));
697        }
698
699        // Clamp scroll_offset to valid range
700        let max_scroll = self.filtered_indices.len().saturating_sub(results_height);
701        self.scroll_offset = self.scroll_offset.min(max_scroll);
702    }
703
704    /// Reload entries from database and re-apply fuzzy filtering.
705    /// Called when mode (directory/global) or host filter changes, which
706    /// invalidates previously cached candidate sets. (Deletion keeps the
707    /// live set and clears the cache in place instead.)
708    /// Always loads the broad set (no query filter at DB level).
709    fn reload_entries(&mut self) {
710        self.entry_cache.clear();
711        match self.engine.load_entries(self.filter_mode, self.host_filter, None) {
712            Ok(entries) => {
713                let mut deduped = deduplicate_entries(entries);
714                deduped.truncate(self.engine.result_limit());
715                self.entries = deduped;
716                self.db_query_used = None;
717            }
718            Err(e) => {
719                eprintln!("pxh recall: failed to reload entries: {e}");
720                self.flash();
721                return;
722            }
723        }
724        self.update_filtered_indices();
725    }
726
727    /// Apply fuzzy filtering to the current entries based on query. The
728    /// query is parsed once here; the same parse drives both the candidate
729    /// coverage check and the fuzzy stage, so the two cannot disagree about
730    /// atom semantics.
731    fn update_filtered_indices(&mut self) {
732        let query = RecallQuery::parse(&self.query);
733        self.ensure_entries_cover_query(&query);
734
735        if query.is_empty() {
736            self.filtered_indices = (0..self.entries.len()).map(|i| (i, Vec::new())).collect();
737        } else {
738            self.filtered_indices = self.engine.filter_entries(&self.entries, &query);
739        }
740
741        if self.selected_index >= self.filtered_indices.len() {
742            self.selected_index = 0;
743        }
744        self.adjust_scroll_for_selection();
745    }
746
747    /// Ensure `self.entries` is a valid candidate superset for the current
748    /// query, hitting the database only when no previously loaded set covers
749    /// it. Queries >= 3 chars with at least one prefilterable atom want a
750    /// DB-level LIKE dig so old commands beyond the initial result_limit
751    /// window are included; shorter queries (and ones with no prefilterable
752    /// atoms, e.g. pure negation "!vim") want the broad recency window.
753    /// Appending to a query is covered by the current set (LIKE '%abc%' is a
754    /// superset of LIKE '%abcd%'); backspacing restores the previous set from
755    /// the cache. Only divergent edits reach the database.
756    fn ensure_entries_cover_query(&mut self, query: &RecallQuery) {
757        let wants_prefilter = query.raw().len() >= 3 && query.has_prefilter();
758        if EntryCache::covers(self.db_query_used.as_ref(), query, wants_prefilter) {
759            return;
760        }
761
762        if let Some(snap) = self.entry_cache.take_covering(query, wants_prefilter) {
763            let prev = self.take_current_snapshot();
764            self.entry_cache.store(prev);
765            self.entries = snap.entries;
766            self.db_query_used = snap.db_query;
767            return;
768        }
769
770        let db_query = wants_prefilter.then(|| query.clone());
771        match self.engine.load_entries(self.filter_mode, self.host_filter, db_query.as_ref()) {
772            Ok(entries) => {
773                let mut deduped = deduplicate_entries(entries);
774                deduped.truncate(self.engine.result_limit());
775                let prev = self.take_current_snapshot();
776                self.entry_cache.store(prev);
777                self.entries = deduped;
778                self.db_query_used = db_query;
779            }
780            Err(e) => {
781                eprintln!("pxh recall: failed to reload entries: {e}");
782                self.flash();
783            }
784        }
785    }
786
787    /// Move the current candidate set out of `self` for caching.
788    fn take_current_snapshot(&mut self) -> EntrySnapshot {
789        EntrySnapshot {
790            db_query: self.db_query_used.take(),
791            entries: std::mem::take(&mut self.entries),
792        }
793    }
794
795    /// Trigger a brief visual flash for feedback on unrecognized keys
796    fn flash(&mut self) {
797        self.flash_until = Some(Instant::now() + Duration::from_millis(FLASH_DURATION_MS));
798    }
799
800    /// Check if flash effect is currently active
801    fn is_flashing(&self) -> bool {
802        self.flash_until.is_some_and(|until| Instant::now() < until)
803    }
804
805    /// Stage the selected command for a clipboard copy. The terminal adapter
806    /// performs the actual OSC 52 write; state only records the feedback.
807    fn copy_selected(&mut self) -> KeyAction {
808        match self.get_selected_command() {
809            Some(cmd) => {
810                self.status_message =
811                    Some(("(copied)".to_string(), Instant::now() + Duration::from_secs(1)));
812                KeyAction::Copy(cmd)
813            }
814            None => KeyAction::Continue,
815        }
816    }
817
818    /// Delete all database rows matching the selected entry's command text,
819    /// since the recall list is deduplicated by command.
820    fn delete_selected_entry(&mut self) {
821        let Some(&(entry_idx, _)) = self.filtered_indices.get(self.selected_index) else {
822            return;
823        };
824        let command = self.entries[entry_idx].command.clone();
825        if let Ok(n) = self.engine.delete_entries_by_command(&command) {
826            // Cached candidate sets may still contain the deleted rows;
827            // drop them so a later backspace can't resurrect the command.
828            self.entry_cache.clear();
829            self.entries.remove(entry_idx);
830            // Rebuild filtered indices -- adjust all indices >= entry_idx
831            self.filtered_indices.retain_mut(|(idx, _)| {
832                if *idx == entry_idx {
833                    return false;
834                }
835                if *idx > entry_idx {
836                    *idx -= 1;
837                }
838                true
839            });
840            if self.selected_index >= self.filtered_indices.len() && self.selected_index > 0 {
841                self.selected_index -= 1;
842            }
843            self.status_message =
844                Some((format!("(deleted {n})"), Instant::now() + Duration::from_secs(1)));
845        }
846    }
847
848    fn toggle_host_filter(&mut self) {
849        self.host_filter = match self.host_filter {
850            HostFilter::ThisHost => HostFilter::AllHosts,
851            HostFilter::AllHosts => HostFilter::ThisHost,
852        };
853        self.reload_entries();
854    }
855
856    fn toggle_filter_mode(&mut self) {
857        self.filter_mode = match self.filter_mode {
858            FilterMode::Directory => FilterMode::Global,
859            FilterMode::Global => FilterMode::Directory,
860        };
861        self.reload_entries();
862    }
863
864    fn print_entry_details(&self) {
865        let Some(entry) = self
866            .filtered_indices
867            .get(self.selected_index)
868            .and_then(|(idx, _)| self.entries.get(*idx))
869        else {
870            return;
871        };
872
873        let mut stdout = std::io::stdout();
874
875        // Command (bold)
876        let _ = execute!(stdout, SetAttribute(Attribute::Bold));
877        println!("{}", sanitize_for_display(&entry.command));
878        let _ = execute!(stdout, SetAttribute(Attribute::Reset));
879
880        // Timestamp
881        if let Some(ts) = entry.timestamp {
882            let datetime =
883                crate::format_local_time(ts, crate::TIME_FORMAT).unwrap_or_else(|| "?".to_string());
884            let relative = format_relative_time(Some(ts));
885            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
886            print!("  Time: ");
887            let _ = execute!(stdout, ResetColor);
888            println!("{datetime} ({relative} ago)");
889        }
890
891        // Directory
892        if let Some(ref dir) = entry.working_directory {
893            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
894            print!("   Dir: ");
895            let _ = execute!(stdout, ResetColor);
896            println!("{}", sanitize_for_display(&String::from_utf8_lossy(dir)));
897        }
898
899        // Exit status
900        if let Some(status) = entry.exit_status {
901            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
902            print!("Status: ");
903            let _ = execute!(stdout, ResetColor);
904            if status == 0 {
905                let _ = execute!(stdout, SetForegroundColor(Color::Green));
906                println!("0 (success)");
907            } else {
908                let _ = execute!(stdout, SetForegroundColor(Color::Red));
909                println!("{status} (error)");
910            }
911            let _ = execute!(stdout, ResetColor);
912        }
913
914        // Duration
915        if let Some(secs) = entry.duration_secs {
916            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
917            print!("  Took: ");
918            let _ = execute!(stdout, ResetColor);
919            println!("{}", format_duration(secs));
920        }
921
922        // Hostname
923        if let Some(ref host) = entry.hostname {
924            let _ = execute!(stdout, SetForegroundColor(Color::Cyan));
925            print!("  Host: ");
926            let _ = execute!(stdout, ResetColor);
927            println!("{}", sanitize_for_display(&String::from_utf8_lossy(host)));
928        }
929    }
930
931    fn get_selected_command(&self) -> Option<String> {
932        self.filtered_indices
933            .get(self.selected_index)
934            .and_then(|(idx, _)| self.entries.get(*idx))
935            .map(|e| e.command.clone())
936    }
937
938    fn handle_key(&mut self, key: KeyEvent) -> Result<KeyAction> {
939        match self.keymap_mode {
940            KeymapMode::Emacs => self.handle_key_emacs(key),
941            KeymapMode::VimInsert => self.handle_key_vim_insert(key),
942            KeymapMode::VimNormal => self.handle_key_vim_normal(key),
943        }
944    }
945
946    /// Handle common keys that work in all modes
947    fn handle_common_key(&mut self, key: KeyEvent) -> Option<KeyAction> {
948        match key.code {
949            KeyCode::Enter => Some(KeyAction::Select),
950            KeyCode::Tab => Some(KeyAction::Edit),
951            KeyCode::Char('c' | 'd') if key.modifiers.contains(KeyModifiers::CONTROL) => {
952                Some(KeyAction::Cancel)
953            }
954            KeyCode::Char('r') if key.modifiers.contains(KeyModifiers::CONTROL) => {
955                self.move_selection_up();
956                Some(KeyAction::Continue)
957            }
958            KeyCode::Up => {
959                self.move_selection_up();
960                Some(KeyAction::Continue)
961            }
962            KeyCode::Down => {
963                self.move_selection_down();
964                Some(KeyAction::Continue)
965            }
966            KeyCode::PageUp => {
967                self.page_up();
968                Some(KeyAction::Continue)
969            }
970            KeyCode::PageDown => {
971                self.page_down();
972                Some(KeyAction::Continue)
973            }
974            KeyCode::Char(c @ '1'..='9') if key.modifiers.contains(KeyModifiers::ALT) => {
975                let num = c.to_digit(10).unwrap() as usize;
976                // Alt-1 selects current, Alt-2 selects next older, etc.
977                let target_index = self.selected_index + (num - 1);
978                if target_index < self.filtered_indices.len() {
979                    self.selected_index = target_index;
980                    return Some(KeyAction::Select);
981                }
982                Some(KeyAction::Continue)
983            }
984            KeyCode::Char('h') if key.modifiers.contains(KeyModifiers::CONTROL) => {
985                self.toggle_host_filter();
986                Some(KeyAction::Continue)
987            }
988            KeyCode::Char('g') if key.modifiers.contains(KeyModifiers::CONTROL) => {
989                self.toggle_filter_mode();
990                Some(KeyAction::Continue)
991            }
992            KeyCode::Char('e') if key.modifiers.contains(KeyModifiers::CONTROL) => {
993                Some(KeyAction::Edit)
994            }
995            KeyCode::Char('a') if key.modifiers.contains(KeyModifiers::CONTROL) => {
996                Some(KeyAction::EditBeginning)
997            }
998            KeyCode::Char('y') if key.modifiers.contains(KeyModifiers::CONTROL) => {
999                Some(self.copy_selected())
1000            }
1001            KeyCode::Char('k') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1002                self.delete_selected_entry();
1003                Some(KeyAction::Continue)
1004            }
1005            _ => None,
1006        }
1007    }
1008
1009    fn handle_key_emacs(&mut self, key: KeyEvent) -> Result<KeyAction> {
1010        // Check common keys first
1011        if let Some(action) = self.handle_common_key(key) {
1012            return Ok(action);
1013        }
1014
1015        match key.code {
1016            KeyCode::Esc => Ok(KeyAction::Cancel),
1017            KeyCode::Char('p') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1018                self.move_selection_up();
1019                Ok(KeyAction::Continue)
1020            }
1021            KeyCode::Char('n') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1022                self.move_selection_down();
1023                Ok(KeyAction::Continue)
1024            }
1025            KeyCode::Backspace => {
1026                self.delete_last_char();
1027                Ok(KeyAction::Continue)
1028            }
1029            KeyCode::Right => Ok(KeyAction::Edit),
1030            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1031                self.clear_query();
1032                Ok(KeyAction::Continue)
1033            }
1034            KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1035                self.delete_last_word();
1036                Ok(KeyAction::Continue)
1037            }
1038            KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::ALT) => {
1039                Ok(self.copy_selected())
1040            }
1041            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
1042                self.flash();
1043                Ok(KeyAction::Continue)
1044            }
1045            KeyCode::Char(c) => {
1046                self.insert_char(c);
1047                Ok(KeyAction::Continue)
1048            }
1049            _ => Ok(KeyAction::Continue),
1050        }
1051    }
1052
1053    fn handle_key_vim_insert(&mut self, key: KeyEvent) -> Result<KeyAction> {
1054        // Check common keys first
1055        if let Some(action) = self.handle_common_key(key) {
1056            return Ok(action);
1057        }
1058
1059        match key.code {
1060            KeyCode::Esc => {
1061                self.keymap_mode = KeymapMode::VimNormal;
1062                Ok(KeyAction::Continue)
1063            }
1064            KeyCode::Backspace => {
1065                self.delete_last_char();
1066                Ok(KeyAction::Continue)
1067            }
1068            KeyCode::Right => Ok(KeyAction::Edit),
1069            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1070                self.clear_query();
1071                Ok(KeyAction::Continue)
1072            }
1073            KeyCode::Char('w') if key.modifiers.contains(KeyModifiers::CONTROL) => {
1074                self.delete_last_word();
1075                Ok(KeyAction::Continue)
1076            }
1077            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
1078                self.flash();
1079                Ok(KeyAction::Continue)
1080            }
1081            KeyCode::Char(c) => {
1082                self.insert_char(c);
1083                Ok(KeyAction::Continue)
1084            }
1085            _ => Ok(KeyAction::Continue),
1086        }
1087    }
1088
1089    fn handle_key_vim_normal(&mut self, key: KeyEvent) -> Result<KeyAction> {
1090        // Check common keys first
1091        if let Some(action) = self.handle_common_key(key) {
1092            return Ok(action);
1093        }
1094
1095        match key.code {
1096            KeyCode::Esc => Ok(KeyAction::Cancel),
1097            KeyCode::Char('j') => {
1098                self.move_selection_down();
1099                Ok(KeyAction::Continue)
1100            }
1101            KeyCode::Char('k') => {
1102                self.move_selection_up();
1103                Ok(KeyAction::Continue)
1104            }
1105            KeyCode::Char('l') | KeyCode::Right => Ok(KeyAction::Edit),
1106            KeyCode::Char('i' | 'a' | 'A' | 'I') => {
1107                self.keymap_mode = KeymapMode::VimInsert;
1108                Ok(KeyAction::Continue)
1109            }
1110            KeyCode::Char('x' | 'X') => {
1111                self.delete_last_char();
1112                Ok(KeyAction::Continue)
1113            }
1114            KeyCode::Char(_) if key.modifiers.contains(KeyModifiers::CONTROL) => {
1115                self.flash();
1116                Ok(KeyAction::Continue)
1117            }
1118            _ => Ok(KeyAction::Continue),
1119        }
1120    }
1121
1122    // Helper methods for selection movement and query editing
1123
1124    fn move_selection_up(&mut self) {
1125        if self.selected_index + 1 < self.filtered_indices.len() {
1126            self.selected_index += 1;
1127            self.adjust_scroll_for_selection();
1128        }
1129    }
1130
1131    fn move_selection_down(&mut self) {
1132        if self.selected_index > 0 {
1133            self.selected_index -= 1;
1134            self.adjust_scroll_for_selection();
1135        }
1136    }
1137
1138    fn page_up(&mut self) {
1139        let page = self.results_height().saturating_sub(2);
1140        let max_index = self.filtered_indices.len().saturating_sub(1);
1141        self.selected_index = (self.selected_index + page).min(max_index);
1142        self.adjust_scroll_for_selection();
1143    }
1144
1145    fn page_down(&mut self) {
1146        let page = self.results_height().saturating_sub(2);
1147        self.selected_index = self.selected_index.saturating_sub(page);
1148        self.adjust_scroll_for_selection();
1149    }
1150
1151    fn insert_char(&mut self, c: char) {
1152        self.query.push(c);
1153        self.update_filtered_indices();
1154    }
1155
1156    fn delete_last_char(&mut self) {
1157        if self.query.pop().is_some() {
1158            self.update_filtered_indices();
1159        }
1160    }
1161
1162    fn clear_query(&mut self) {
1163        if !self.query.is_empty() {
1164            self.query.clear();
1165            self.update_filtered_indices();
1166        }
1167    }
1168
1169    fn delete_last_word(&mut self) {
1170        if !self.query.is_empty() {
1171            let trimmed_len = self.query.trim_end().len();
1172            let word_start = self.query[..trimmed_len]
1173                .char_indices()
1174                .rev()
1175                .find(|(_, c)| c.is_whitespace())
1176                .map_or(0, |(i, c)| i + c.len_utf8());
1177            self.query.truncate(word_start);
1178            self.update_filtered_indices();
1179        }
1180    }
1181
1182    fn draw_preview<W: Write>(&self, w: &mut W, start_y: u16, width: u16) -> Result<()> {
1183        // Get the selected entry
1184        let entry = self
1185            .filtered_indices
1186            .get(self.selected_index)
1187            .and_then(|(idx, _)| self.entries.get(*idx));
1188
1189        // Draw separator line
1190        queue!(w, MoveTo(0, start_y), Clear(ClearType::CurrentLine))?;
1191        queue!(w, SetForegroundColor(Color::DarkGrey))?;
1192        write!(w, "{}", "─".repeat(width as usize))?;
1193        queue!(w, ResetColor)?;
1194
1195        // If no entry selected, clear the rest and return
1196        let Some(entry) = entry else {
1197            for row in 1..PREVIEW_HEIGHT {
1198                queue!(w, MoveTo(0, start_y + row as u16), Clear(ClearType::CurrentLine))?;
1199            }
1200            return Ok(());
1201        };
1202
1203        // Line 1: Full command (can truncate)
1204        queue!(w, MoveTo(0, start_y + 1), Clear(ClearType::CurrentLine))?;
1205        let safe_cmd = sanitize_for_display(&entry.command);
1206        let cmd_display = truncate_to_width(&safe_cmd, (width as usize).saturating_sub(2));
1207        write!(w, "  {cmd_display}")?;
1208
1209        // Line 2: Directory and timestamp
1210        queue!(w, MoveTo(0, start_y + 2), Clear(ClearType::CurrentLine))?;
1211        let mut info_parts: Vec<String> = Vec::new();
1212
1213        if self.preview_config.show_directory
1214            && let Some(ref dir) = entry.working_directory
1215        {
1216            info_parts
1217                .push(format!("Dir: {}", sanitize_for_display(&String::from_utf8_lossy(dir))));
1218        }
1219
1220        if self.preview_config.show_timestamp
1221            && let Some(ts) = entry.timestamp
1222        {
1223            let datetime =
1224                crate::format_local_time(ts, crate::TIME_FORMAT).unwrap_or_else(|| "?".to_string());
1225            info_parts.push(format!("Time: {datetime}"));
1226        }
1227
1228        queue!(w, SetForegroundColor(Color::DarkGrey))?;
1229        write!(w, "  {}", info_parts.join("  "))?;
1230        queue!(w, ResetColor)?;
1231
1232        // Line 3: Exit status, duration, hostname
1233        queue!(w, MoveTo(0, start_y + 3), Clear(ClearType::CurrentLine))?;
1234        let mut status_parts: Vec<String> = Vec::new();
1235
1236        if self.preview_config.show_exit_status
1237            && let Some(status) = entry.exit_status
1238        {
1239            let status_str = if status == 0 {
1240                "Status: 0 (ok)".to_string()
1241            } else {
1242                format!("Status: {status} (error)")
1243            };
1244            status_parts.push(status_str);
1245        }
1246
1247        if self.preview_config.show_duration
1248            && let Some(secs) = entry.duration_secs
1249        {
1250            status_parts.push(format!("Duration: {}", format_duration(secs)));
1251        }
1252
1253        if self.preview_config.show_hostname
1254            && let Some(ref host) = entry.hostname
1255        {
1256            status_parts
1257                .push(format!("Host: {}", sanitize_for_display(&String::from_utf8_lossy(host))));
1258        }
1259
1260        queue!(w, SetForegroundColor(Color::DarkGrey))?;
1261        write!(w, "  {}", status_parts.join("  "))?;
1262        queue!(w, ResetColor)?;
1263
1264        // Line 4: Bottom separator (blank or separator)
1265        queue!(w, MoveTo(0, start_y + 4), Clear(ClearType::CurrentLine))?;
1266
1267        Ok(())
1268    }
1269
1270    /// Render a full frame into `w` using the current dimensions (see
1271    /// `set_dimensions`). Generic over the writer so tests can render into a
1272    /// buffer; the live path hands in a buffered /dev/tty.
1273    fn draw<W: Write>(&mut self, w: &mut W) -> Result<()> {
1274        let (term_width, term_height) = (self.term_width, self.term_height);
1275        let results_height = self.results_height();
1276        let preview_start_y = results_height as u16;
1277        let input_y = term_height.saturating_sub(2);
1278        let help_y = term_height.saturating_sub(1);
1279
1280        // Check if we're in flash mode for visual feedback
1281        let flashing = self.is_flashing();
1282
1283        // Disable line wrap during render to prevent visual glitches
1284        write!(w, "\x1b[?7l")?;
1285
1286        // Draw each line, clearing as we go (avoids full-screen clear flicker)
1287        // Results area: rows 0 to results_height-1
1288        // Layout: oldest at top (row 0), newest at bottom (row results_height-1)
1289        // scroll_offset is the entry index shown at the bottom of the visible area
1290        for row in 0..results_height {
1291            queue!(w, MoveTo(0, row as u16), Clear(ClearType::CurrentLine))?;
1292
1293            // Calculate which entry to show at this row
1294            // Row 0 (top) shows oldest visible entry
1295            // Row results_height-1 (bottom) shows entry at scroll_offset
1296            let offset_from_bottom = results_height - 1 - row;
1297            let entry_index = self.scroll_offset + offset_from_bottom;
1298
1299            if entry_index >= self.filtered_indices.len() {
1300                continue;
1301            }
1302
1303            let (idx, ref match_indices) = self.filtered_indices[entry_index];
1304            let entry = &self.entries[idx];
1305            let time_str = format_relative_time(entry.timestamp);
1306            let is_selected = entry_index == self.selected_index;
1307
1308            // Calculate quick-select number (1-9) relative to selection
1309            // Alt-1 = selected, Alt-2 = selected+1 (next older), etc.
1310            let quick_num =
1311                if entry_index >= self.selected_index && entry_index < self.selected_index + 9 {
1312                    Some(entry_index - self.selected_index + 1)
1313                } else {
1314                    None
1315                };
1316
1317            if is_selected {
1318                queue!(w, SetBackgroundColor(Color::DarkGrey))?;
1319            }
1320
1321            // Draw quick-select indicator or selection marker
1322            if let Some(n) = quick_num {
1323                queue!(w, SetForegroundColor(Color::Yellow))?;
1324                write!(w, "{n}")?;
1325                queue!(w, ResetColor)?;
1326                if is_selected {
1327                    queue!(w, SetBackgroundColor(Color::DarkGrey))?;
1328                    write!(w, ">")?;
1329                } else {
1330                    write!(w, " ")?;
1331                }
1332            } else if is_selected {
1333                write!(w, " >")?;
1334            } else {
1335                write!(w, "  ")?;
1336            }
1337
1338            queue!(w, SetForegroundColor(Color::DarkGrey))?;
1339            write!(w, "{time_str}  ")?;
1340            queue!(w, ResetColor)?;
1341
1342            if is_selected {
1343                queue!(w, SetBackgroundColor(Color::DarkGrey))?;
1344            }
1345
1346            // Show host suffix for entries from other hosts (in AllHosts mode).
1347            // Right-aligned so command text stays column-aligned across rows.
1348            let host_suffix = if self.host_filter == HostFilter::AllHosts {
1349                entry.hostname.as_ref().and_then(|h| {
1350                    if self.engine.is_this_host(h) {
1351                        None
1352                    } else {
1353                        let short =
1354                            String::from_utf8_lossy(h).split('.').next().unwrap_or("?").to_string();
1355                        Some(format!(" @{short}"))
1356                    }
1357                })
1358            } else {
1359                None
1360            };
1361            let suffix_len = host_suffix.as_ref().map_or(0, |s| s.width());
1362
1363            // Sanitize and truncate command to fit (handle UTF-8 safely)
1364            let safe_cmd = sanitize_for_display(&entry.command);
1365            let prefix_len = 9; // "n>" + " XXx  "
1366            let max_cmd_len = term_width.saturating_sub(prefix_len + suffix_len as u16) as usize;
1367
1368            // Render command with highlighted fuzzy matches
1369            let spans = highlight_command_with_indices(&safe_cmd, match_indices, max_cmd_len);
1370            for (text, is_match) in spans {
1371                if is_match {
1372                    queue!(w, SetAttribute(Attribute::Bold))?;
1373                    queue!(w, SetForegroundColor(Color::Cyan))?;
1374                }
1375                write!(w, "{text}")?;
1376                if is_match {
1377                    queue!(w, SetAttribute(Attribute::Reset))?;
1378                    queue!(w, ResetColor)?;
1379                    if is_selected {
1380                        queue!(w, SetBackgroundColor(Color::DarkGrey))?;
1381                    }
1382                }
1383            }
1384
1385            // Draw right-aligned host suffix
1386            if let Some(suffix) = host_suffix {
1387                let suffix_x = term_width.saturating_sub(suffix_len as u16);
1388                queue!(w, MoveTo(suffix_x, row as u16), SetForegroundColor(Color::Magenta))?;
1389                write!(w, "{suffix}")?;
1390            }
1391
1392            queue!(w, ResetColor)?;
1393        }
1394
1395        // Draw preview pane if enabled
1396        if self.show_preview {
1397            self.draw_preview(w, preview_start_y, term_width)?;
1398        }
1399
1400        // Draw input line
1401        queue!(w, MoveTo(0, input_y), Clear(ClearType::CurrentLine))?;
1402        write!(w, "> {}", sanitize_for_display(&self.query))?;
1403
1404        // Draw mode indicators on same line (host filter + dir/global)
1405        let host_str = match self.host_filter {
1406            HostFilter::ThisHost => {
1407                let hostname = self.engine.primary_hostname();
1408                let short_host =
1409                    String::from_utf8_lossy(hostname).split('.').next().unwrap_or("?").to_string();
1410                format!("[{short_host}]")
1411            }
1412            HostFilter::AllHosts => "[All Hosts]".to_string(),
1413        };
1414        let dir_str = match self.filter_mode {
1415            FilterMode::Directory => {
1416                let dir = self.engine.working_directory();
1417                let name = dir
1418                    .file_name()
1419                    .map_or_else(|| "?".to_string(), |s| s.to_string_lossy().to_string());
1420                format!("[Dir: {name}]")
1421            }
1422            FilterMode::Global => "[Global]".to_string(),
1423        };
1424        let mode_str = format!("{host_str} {dir_str}");
1425        let mode_x = term_width.saturating_sub(mode_str.width() as u16 + 1);
1426        queue!(w, MoveTo(mode_x, input_y), SetForegroundColor(Color::Cyan))?;
1427        write!(w, "{mode_str}")?;
1428        queue!(w, ResetColor)?;
1429
1430        // Draw help line (mode-aware, flashes on unrecognized keys)
1431        queue!(w, MoveTo(0, help_y), Clear(ClearType::CurrentLine))?;
1432        if flashing {
1433            // Flash effect: invert the help line colors
1434            queue!(w, SetBackgroundColor(Color::White), SetForegroundColor(Color::Black))?;
1435        } else {
1436            queue!(w, SetForegroundColor(Color::DarkGrey))?;
1437        }
1438        let help_text = match self.keymap_mode {
1439            KeymapMode::Emacs => {
1440                "↑↓/^R Nav  Enter Run  ^A/^E Edit  ^G Dir  ^H Host  ^C/^D Quit  Alt-1-9"
1441            }
1442            KeymapMode::VimInsert | KeymapMode::VimNormal => {
1443                "j/k Nav  Enter Run  ^A/^E Edit  ^G Dir  ^H Host  ^C/^D Quit  Esc Mode  Alt-1-9"
1444            }
1445        };
1446        write!(w, "{help_text}")?;
1447        queue!(w, ResetColor)?;
1448
1449        // Show status message if active
1450        match self.status_message {
1451            Some((_, until)) if Instant::now() >= until => {
1452                self.status_message = None;
1453            }
1454            Some((ref msg, _)) => {
1455                queue!(w, SetForegroundColor(Color::Yellow))?;
1456                write!(w, " {msg}")?;
1457                queue!(w, ResetColor)?;
1458            }
1459            None => {}
1460        }
1461
1462        // Position cursor at end of query in input line
1463        queue!(w, MoveTo(2 + self.query.width() as u16, input_y))?;
1464
1465        // Re-enable line wrap
1466        write!(w, "\x1b[?7h")?;
1467
1468        // Single flush writes all buffered content
1469        w.flush()?;
1470        Ok(())
1471    }
1472}
1473
1474#[derive(Debug, PartialEq)]
1475enum KeyAction {
1476    Continue,
1477    /// Copy this text to the clipboard (an OSC 52 write only the terminal
1478    /// adapter can perform).
1479    Copy(String),
1480    Select,
1481    Edit,
1482    EditBeginning,
1483    Cancel,
1484}
1485
1486#[cfg(test)]
1487mod tests {
1488    use super::*;
1489
1490    /// Byte offset of `needle` in `hay`, panicking with the surrounding output
1491    /// if it is missing.
1492    fn offset_of(hay: &[u8], needle: &str) -> usize {
1493        hay.windows(needle.len())
1494            .position(|w| w == needle.as_bytes())
1495            .unwrap_or_else(|| panic!("{needle:?} not in {:?}", String::from_utf8_lossy(hay)))
1496    }
1497
1498    /// The kitty keyboard protocol keeps a separate flag stack per screen, so
1499    /// the push and pop must both happen while the alternate screen is active.
1500    /// Pushing on the main screen and popping on the alternate one leaves the
1501    /// shell with Ctrl and Alt broken until `reset` (seen in Ghostty).
1502    #[cfg(not(target_os = "windows"))]
1503    #[test]
1504    fn keyboard_enhancement_is_pushed_and_popped_inside_alternate_screen() {
1505        let mut out = Vec::new();
1506        let enhanced = enter_recall_screen(&mut out).unwrap();
1507        assert!(enhanced);
1508        let alt_on = offset_of(&out, "\x1b[?1049h");
1509        let push = offset_of(&out, "\x1b[>1u");
1510        assert!(alt_on < push, "push keyboard flags before entering alternate screen");
1511
1512        let mut out = Vec::new();
1513        leave_recall_screen(&mut out, true).unwrap();
1514        let pop = offset_of(&out, "\x1b[<1u");
1515        let alt_off = offset_of(&out, "\x1b[?1049l");
1516        assert!(pop < alt_off, "pop keyboard flags after leaving alternate screen");
1517    }
1518
1519    #[test]
1520    fn test_sanitize_preserves_normal_text() {
1521        assert_eq!(sanitize_for_display("hello world"), "hello world");
1522        assert_eq!(sanitize_for_display("ls -la /tmp"), "ls -la /tmp");
1523    }
1524
1525    #[test]
1526    fn test_sanitize_preserves_box_drawing() {
1527        // Box-drawing characters should pass through
1528        assert_eq!(sanitize_for_display("┌History───┐"), "┌History───┐");
1529        assert_eq!(sanitize_for_display("│ cell │"), "│ cell │");
1530        assert_eq!(sanitize_for_display("└───────┘"), "└───────┘");
1531    }
1532
1533    #[test]
1534    fn test_sanitize_preserves_unicode() {
1535        assert_eq!(sanitize_for_display("héllo wörld"), "héllo wörld");
1536        assert_eq!(sanitize_for_display("日本語"), "日本語");
1537        assert_eq!(sanitize_for_display("emoji 🎉 test"), "emoji 🎉 test");
1538    }
1539
1540    #[test]
1541    fn test_sanitize_strips_c1_controls() {
1542        // U+009B is CSI in 8-bit terminal mode, U+009D is OSC
1543        assert_eq!(sanitize_for_display("hello\u{009B}31mworld"), "hello31mworld");
1544        assert_eq!(sanitize_for_display("test\u{009D}inject\u{009C}end"), "testinjectend");
1545        // U+0085 NEL, U+008E SS2
1546        assert_eq!(sanitize_for_display("a\u{0085}b\u{008E}c"), "abc");
1547    }
1548
1549    #[test]
1550    fn test_sanitize_strips_ansi_escape_sequences() {
1551        // Color codes
1552        assert_eq!(sanitize_for_display("\x1b[31mred\x1b[0m"), "red");
1553        assert_eq!(sanitize_for_display("\x1b[1;32mbold green\x1b[0m"), "bold green");
1554
1555        // Cursor movement
1556        assert_eq!(sanitize_for_display("\x1b[H"), ""); // cursor home
1557        assert_eq!(sanitize_for_display("\x1b[2J"), ""); // clear screen
1558        assert_eq!(sanitize_for_display("\x1b[10;20H"), ""); // cursor position
1559
1560        // Mixed content
1561        assert_eq!(sanitize_for_display("before\x1b[31mred\x1b[0mafter"), "beforeredafter");
1562    }
1563
1564    #[test]
1565    fn test_sanitize_converts_newlines_to_spaces() {
1566        assert_eq!(sanitize_for_display("line1\nline2"), "line1 line2");
1567        assert_eq!(sanitize_for_display("line1\r\nline2"), "line1  line2");
1568        assert_eq!(sanitize_for_display("a\nb\nc"), "a b c");
1569    }
1570
1571    #[test]
1572    fn test_sanitize_converts_tabs_to_spaces() {
1573        assert_eq!(sanitize_for_display("col1\tcol2"), "col1 col2");
1574        assert_eq!(sanitize_for_display("\t\tindented"), "  indented");
1575    }
1576
1577    #[test]
1578    fn test_sanitize_strips_control_characters() {
1579        // Bell, backspace, etc.
1580        assert_eq!(sanitize_for_display("hello\x07world"), "helloworld"); // bell
1581        assert_eq!(sanitize_for_display("hello\x08world"), "helloworld"); // backspace
1582        assert_eq!(sanitize_for_display("a\x00b\x01c"), "abc"); // null and other low controls
1583        assert_eq!(sanitize_for_display("test\x7fdelete"), "testdelete"); // DEL
1584    }
1585
1586    #[test]
1587    fn test_sanitize_handles_binary_garbage() {
1588        // Simulate binary data that might corrupt terminal
1589        let binary_garbage = "cmd\x1b[2J\x1b[H\x00\x01\x02\x03visible\x1b[31m";
1590        assert_eq!(sanitize_for_display(binary_garbage), "cmdvisible");
1591    }
1592
1593    #[test]
1594    fn test_sanitize_handles_incomplete_escape_sequences() {
1595        // Incomplete escape at end of string
1596        assert_eq!(sanitize_for_display("text\x1b"), "text");
1597        assert_eq!(sanitize_for_display("text\x1b["), "text");
1598        assert_eq!(sanitize_for_display("text\x1b[123"), "text");
1599    }
1600
1601    #[test]
1602    fn test_sanitize_strips_osc_sequences() {
1603        // OSC title change: \x1b]0;title\x07
1604        assert_eq!(sanitize_for_display("\x1b]0;My Title\x07visible"), "visible");
1605        // OSC with ST terminator: \x1b]0;title\x1b\\
1606        assert_eq!(sanitize_for_display("\x1b]2;Title\x1b\\visible"), "visible");
1607        // OSC 52 clipboard: \x1b]52;c;base64\x07
1608        assert_eq!(sanitize_for_display("\x1b]52;c;SGVsbG8=\x07after"), "after");
1609    }
1610
1611    #[test]
1612    fn test_sanitize_strips_dcs_sequences() {
1613        assert_eq!(sanitize_for_display("\x1bPsome data\x1b\\visible"), "visible");
1614    }
1615
1616    #[test]
1617    fn test_sanitize_strips_other_esc_sequences() {
1618        // SS2/SS3
1619        assert_eq!(sanitize_for_display("\x1bNvisible"), "visible");
1620        assert_eq!(sanitize_for_display("\x1bOvisible"), "visible");
1621    }
1622
1623    #[test]
1624    fn test_sanitize_empty_string() {
1625        assert_eq!(sanitize_for_display(""), "");
1626    }
1627
1628    #[test]
1629    fn test_highlight_no_query() {
1630        // Empty query returns whole string unhighlighted
1631        let spans = highlight_command("ls -la", "", 100);
1632        assert_eq!(spans, vec![("ls -la".to_string(), false)]);
1633    }
1634
1635    #[test]
1636    fn test_highlight_single_match() {
1637        let spans = highlight_command("grep foo bar", "foo", 100);
1638        assert_eq!(
1639            spans,
1640            vec![
1641                ("grep ".to_string(), false),
1642                ("foo".to_string(), true),
1643                (" bar".to_string(), false),
1644            ]
1645        );
1646    }
1647
1648    #[test]
1649    fn test_highlight_case_insensitive() {
1650        let spans = highlight_command("grep FOO bar", "foo", 100);
1651        assert_eq!(
1652            spans,
1653            vec![
1654                ("grep ".to_string(), false),
1655                ("FOO".to_string(), true),
1656                (" bar".to_string(), false),
1657            ]
1658        );
1659    }
1660
1661    #[test]
1662    fn test_highlight_multiple_matches() {
1663        let spans = highlight_command("foo bar foo", "foo", 100);
1664        assert_eq!(
1665            spans,
1666            vec![
1667                ("foo".to_string(), true),
1668                (" bar ".to_string(), false),
1669                ("foo".to_string(), true),
1670            ]
1671        );
1672    }
1673
1674    #[test]
1675    fn test_highlight_at_start() {
1676        let spans = highlight_command("foo bar", "foo", 100);
1677        assert_eq!(spans, vec![("foo".to_string(), true), (" bar".to_string(), false),]);
1678    }
1679
1680    #[test]
1681    fn test_highlight_at_end() {
1682        let spans = highlight_command("bar foo", "foo", 100);
1683        assert_eq!(spans, vec![("bar ".to_string(), false), ("foo".to_string(), true),]);
1684    }
1685
1686    #[test]
1687    fn test_highlight_truncation() {
1688        // When command is too long, it should be truncated with "..."
1689        let spans = highlight_command("very long command here", "", 10);
1690        assert_eq!(spans, vec![("very lo...".to_string(), false)]);
1691    }
1692
1693    #[test]
1694    fn test_highlight_no_match() {
1695        // Query not found - return whole string unhighlighted
1696        let spans = highlight_command("ls -la", "xyz", 100);
1697        assert_eq!(spans, vec![("ls -la".to_string(), false)]);
1698    }
1699
1700    #[test]
1701    fn test_highlight_multibyte_query() {
1702        // Query with multi-byte UTF-8 characters
1703        let spans = highlight_command("find 日本語 here", "日本語", 100);
1704        assert_eq!(
1705            spans,
1706            vec![
1707                ("find ".to_string(), false),
1708                ("日本語".to_string(), true),
1709                (" here".to_string(), false),
1710            ]
1711        );
1712    }
1713
1714    #[test]
1715    fn test_highlight_multibyte_command() {
1716        // ASCII query in command with multi-byte chars
1717        let spans = highlight_command("echo 日本語 foo bar", "foo", 100);
1718        assert_eq!(
1719            spans,
1720            vec![
1721                ("echo 日本語 ".to_string(), false),
1722                ("foo".to_string(), true),
1723                (" bar".to_string(), false),
1724            ]
1725        );
1726    }
1727
1728    #[test]
1729    fn test_highlight_empty_command() {
1730        // Empty command returns empty spans (nothing to display)
1731        let spans = highlight_command("", "foo", 100);
1732        assert!(spans.is_empty());
1733    }
1734
1735    #[test]
1736    fn test_highlight_empty_both() {
1737        // Empty command with empty query returns the empty string
1738        let spans = highlight_command("", "", 100);
1739        assert_eq!(spans, vec![(String::new(), false)]);
1740    }
1741
1742    #[test]
1743    fn test_deduplicate_empty_list() {
1744        use super::deduplicate_entries;
1745        let deduped = deduplicate_entries(vec![]);
1746        assert!(deduped.is_empty());
1747    }
1748
1749    #[test]
1750    fn test_deduplicate_keeps_first_occurrence() {
1751        use super::deduplicate_entries;
1752        use crate::recall::engine::HistoryEntry;
1753
1754        let entries = vec![
1755            HistoryEntry {
1756                id: 1,
1757                command: "cmd1".to_string(),
1758                timestamp: Some(100),
1759                working_directory: None,
1760                exit_status: None,
1761                duration_secs: None,
1762                hostname: None,
1763                use_count: 1,
1764            },
1765            HistoryEntry {
1766                id: 2,
1767                command: "cmd2".to_string(),
1768                timestamp: Some(90),
1769                working_directory: None,
1770                exit_status: None,
1771                duration_secs: None,
1772                hostname: None,
1773                use_count: 1,
1774            },
1775            HistoryEntry {
1776                id: 3,
1777                command: "cmd1".to_string(), // duplicate
1778                timestamp: Some(80),
1779                working_directory: None,
1780                exit_status: None,
1781                duration_secs: None,
1782                hostname: None,
1783                use_count: 1,
1784            },
1785        ];
1786
1787        let deduped = deduplicate_entries(entries);
1788        assert_eq!(deduped.len(), 2);
1789        assert_eq!(deduped[0].command, "cmd1");
1790        assert_eq!(deduped[0].timestamp, Some(100)); // kept first (most recent)
1791        assert_eq!(deduped[1].command, "cmd2");
1792        assert_eq!(deduped[0].use_count, 2, "collapsed duplicates should be counted");
1793        assert_eq!(deduped[1].use_count, 1);
1794    }
1795
1796    /// A RecallState over an in-memory DB seeded with `commands` -- no
1797    /// terminal involved, which is the whole point of the state/terminal
1798    /// split.
1799    fn test_state(commands: &[&str]) -> RecallState {
1800        use crate::recall::engine::SearchEngine;
1801        let conn = rusqlite::Connection::open_in_memory().unwrap();
1802        crate::initialize_base_schema(&conn).unwrap();
1803        crate::run_schema_migrations(&conn).unwrap();
1804        for (i, cmd) in commands.iter().enumerate() {
1805            conn.execute(
1806                "INSERT INTO command_history (session_id, full_command, shellname, hostname,
1807                                              start_unix_timestamp)
1808                 VALUES (1, CAST(? AS blob), 'zsh', CAST('host1' AS blob), ?)",
1809                rusqlite::params![cmd, 1000 + i as i64],
1810            )
1811            .unwrap();
1812        }
1813        let engine = SearchEngine::new(
1814            conn,
1815            std::path::PathBuf::from("/tmp"),
1816            vec![bstr::BString::from("host1")],
1817            100,
1818        );
1819        let mut state =
1820            RecallState::new(engine, FilterMode::Global, None, &RecallConfig::default(), true)
1821                .unwrap();
1822        state.set_dimensions(80, 24);
1823        state
1824    }
1825
1826    fn press(state: &mut RecallState, code: KeyCode, modifiers: KeyModifiers) -> KeyAction {
1827        state.handle_key(KeyEvent::new(code, modifiers)).unwrap()
1828    }
1829
1830    fn type_str(state: &mut RecallState, s: &str) {
1831        for c in s.chars() {
1832            press(state, KeyCode::Char(c), KeyModifiers::NONE);
1833        }
1834    }
1835
1836    fn visible_commands(state: &RecallState) -> Vec<String> {
1837        state.filtered_indices.iter().map(|(idx, _)| state.entries[*idx].command.clone()).collect()
1838    }
1839
1840    #[test]
1841    fn test_delete_selected_entry_invalidates_cached_candidate_sets() {
1842        // Regression: Ctrl-K deleted the entry from the DB and the live set,
1843        // but cached candidate snapshots kept it -- so backspacing to a query
1844        // served from the cache resurrected the deleted command, which could
1845        // then be selected and run.
1846        let mut state = test_state(&["ghost-cmd", "alpha", "beta"]);
1847
1848        // Type a >=3-char digging query; the broad set gets cached.
1849        type_str(&mut state, "gho");
1850        assert_eq!(visible_commands(&state), ["ghost-cmd"]);
1851
1852        // Ctrl-K the selected (only) match.
1853        press(&mut state, KeyCode::Char('k'), KeyModifiers::CONTROL);
1854        assert!(visible_commands(&state).is_empty());
1855
1856        // Backspace to a query the cache can serve.
1857        for _ in 0..3 {
1858            press(&mut state, KeyCode::Backspace, KeyModifiers::NONE);
1859        }
1860        assert!(
1861            !visible_commands(&state).iter().any(|c| c == "ghost-cmd"),
1862            "deleted command must not resurrect from a cached candidate set"
1863        );
1864    }
1865
1866    #[test]
1867    fn test_emacs_query_editing_updates_filter() {
1868        let mut state = test_state(&["alpha one", "beta two", "gamma three"]);
1869        assert_eq!(visible_commands(&state).len(), 3);
1870
1871        type_str(&mut state, "beta");
1872        assert_eq!(visible_commands(&state), ["beta two"]);
1873
1874        // Ctrl-W deletes the last word; everything matches again.
1875        press(&mut state, KeyCode::Char('w'), KeyModifiers::CONTROL);
1876        assert_eq!(state.query, "");
1877        assert_eq!(visible_commands(&state).len(), 3);
1878
1879        type_str(&mut state, "gamma");
1880        press(&mut state, KeyCode::Char('u'), KeyModifiers::CONTROL);
1881        assert_eq!(state.query, "");
1882        assert_eq!(visible_commands(&state).len(), 3);
1883    }
1884
1885    #[test]
1886    fn test_emacs_enter_and_escape_actions() {
1887        let mut state = test_state(&["alpha"]);
1888        assert_eq!(press(&mut state, KeyCode::Enter, KeyModifiers::NONE), KeyAction::Select);
1889        assert_eq!(press(&mut state, KeyCode::Esc, KeyModifiers::NONE), KeyAction::Cancel);
1890        assert_eq!(press(&mut state, KeyCode::Char('c'), KeyModifiers::CONTROL), KeyAction::Cancel);
1891        assert_eq!(press(&mut state, KeyCode::Tab, KeyModifiers::NONE), KeyAction::Edit);
1892        assert_eq!(
1893            press(&mut state, KeyCode::Char('a'), KeyModifiers::CONTROL),
1894            KeyAction::EditBeginning
1895        );
1896    }
1897
1898    #[test]
1899    fn test_vim_keymap_mode_transitions() {
1900        use crate::config::KeymapMode;
1901        let conn = rusqlite::Connection::open_in_memory().unwrap();
1902        crate::initialize_base_schema(&conn).unwrap();
1903        crate::run_schema_migrations(&conn).unwrap();
1904        let engine = SearchEngine::new(
1905            conn,
1906            std::path::PathBuf::from("/tmp"),
1907            vec![bstr::BString::from("host1")],
1908            100,
1909        );
1910        let config = RecallConfig { keymap: "vim".to_string(), ..RecallConfig::default() };
1911        let mut state = RecallState::new(engine, FilterMode::Global, None, &config, true).unwrap();
1912        state.set_dimensions(80, 24);
1913
1914        assert_eq!(state.keymap_mode, KeymapMode::VimInsert);
1915        press(&mut state, KeyCode::Esc, KeyModifiers::NONE);
1916        assert_eq!(state.keymap_mode, KeymapMode::VimNormal);
1917        // Esc in normal mode cancels; 'i' re-enters insert.
1918        press(&mut state, KeyCode::Char('i'), KeyModifiers::NONE);
1919        assert_eq!(state.keymap_mode, KeymapMode::VimInsert);
1920    }
1921
1922    #[test]
1923    fn test_quick_select_advances_selection() {
1924        let mut state = test_state(&["one", "two", "three", "four"]);
1925        // Alt-2 selects the entry after the current selection.
1926        assert_eq!(press(&mut state, KeyCode::Char('2'), KeyModifiers::ALT), KeyAction::Select);
1927        assert_eq!(state.selected_index, 1);
1928        // Alt-9 past the end is a no-op.
1929        assert_eq!(press(&mut state, KeyCode::Char('9'), KeyModifiers::ALT), KeyAction::Continue);
1930        assert_eq!(state.selected_index, 1);
1931    }
1932
1933    #[test]
1934    fn test_copy_selected_returns_command_and_sets_status() {
1935        let mut state = test_state(&["copy-me"]);
1936        match press(&mut state, KeyCode::Char('y'), KeyModifiers::CONTROL) {
1937            KeyAction::Copy(text) => assert_eq!(text, "copy-me"),
1938            other => panic!("expected Copy action, got {other:?}"),
1939        }
1940        assert!(state.status_message.is_some(), "copy should surface '(copied)' feedback");
1941    }
1942
1943    #[test]
1944    fn test_selection_stays_visible_and_scroll_clamps() {
1945        let commands: Vec<String> = (0..50).map(|i| format!("cmd-{i:02}")).collect();
1946        let refs: Vec<&str> = commands.iter().map(String::as_str).collect();
1947        let mut state = test_state(&refs);
1948        let height = state.results_height();
1949        assert!(height > 0);
1950
1951        // Walk selection through the whole list (Up = older): the selected
1952        // entry must always stay within the visible window and the scroll
1953        // offset within the valid range.
1954        for _ in 0..60 {
1955            press(&mut state, KeyCode::Up, KeyModifiers::NONE);
1956            let view_bottom = state.scroll_offset;
1957            let view_top = view_bottom + height - 1;
1958            assert!(
1959                (view_bottom..=view_top).contains(&state.selected_index),
1960                "selection {} outside visible window {view_bottom}..={view_top}",
1961                state.selected_index
1962            );
1963            assert!(state.scroll_offset <= state.filtered_indices.len().saturating_sub(height));
1964        }
1965        assert_eq!(state.selected_index, 49, "selection clamps at the oldest entry");
1966
1967        // And back down (newer) to the start.
1968        for _ in 0..60 {
1969            press(&mut state, KeyCode::Down, KeyModifiers::NONE);
1970        }
1971        assert_eq!(state.selected_index, 0);
1972        assert_eq!(state.scroll_offset, 0);
1973    }
1974
1975    #[test]
1976    fn test_page_up_down_bounded() {
1977        let commands: Vec<String> = (0..50).map(|i| format!("cmd-{i:02}")).collect();
1978        let refs: Vec<&str> = commands.iter().map(String::as_str).collect();
1979        let mut state = test_state(&refs);
1980
1981        press(&mut state, KeyCode::PageUp, KeyModifiers::NONE);
1982        assert!(state.selected_index > 0);
1983        for _ in 0..20 {
1984            press(&mut state, KeyCode::PageUp, KeyModifiers::NONE);
1985        }
1986        assert_eq!(state.selected_index, 49, "PageUp clamps at the oldest entry");
1987        for _ in 0..20 {
1988            press(&mut state, KeyCode::PageDown, KeyModifiers::NONE);
1989        }
1990        assert_eq!(state.selected_index, 0, "PageDown clamps at the newest entry");
1991    }
1992
1993    #[test]
1994    fn test_draw_renders_into_plain_buffer() {
1995        let mut state = test_state(&["hello world", "goodbye"]);
1996        type_str(&mut state, "hello");
1997
1998        let mut frame: Vec<u8> = Vec::new();
1999        state.draw(&mut frame).unwrap();
2000        let rendered = String::from_utf8_lossy(&frame);
2001        assert!(rendered.contains("> hello"), "input line with query");
2002        assert!(rendered.contains("hello world"), "matching command drawn");
2003        assert!(!rendered.contains("goodbye"), "non-matching command not drawn");
2004        assert!(rendered.contains("Enter Run"), "help line drawn");
2005
2006        // Degenerate dimensions must not panic.
2007        state.set_dimensions(5, 3);
2008        let mut tiny: Vec<u8> = Vec::new();
2009        state.draw(&mut tiny).unwrap();
2010        state.set_dimensions(0, 0);
2011        let mut zero: Vec<u8> = Vec::new();
2012        state.draw(&mut zero).unwrap();
2013    }
2014
2015    fn cache_snapshot(db_query: Option<&str>, n_entries: usize) -> EntrySnapshot {
2016        use crate::recall::engine::HistoryEntry;
2017        let entries = (0..n_entries)
2018            .map(|i| HistoryEntry {
2019                id: i as i64,
2020                command: format!("cmd-{i}"),
2021                timestamp: None,
2022                working_directory: None,
2023                hostname: None,
2024                exit_status: None,
2025                duration_secs: None,
2026                use_count: 1,
2027            })
2028            .collect();
2029        EntrySnapshot { db_query: db_query.map(RecallQuery::parse), entries }
2030    }
2031
2032    #[test]
2033    fn test_entry_cache_covers() {
2034        use super::EntryCache;
2035        let covers = |db_query: Option<&str>, query: &str, wants_prefilter: bool| {
2036            EntryCache::covers(
2037                db_query.map(RecallQuery::parse).as_ref(),
2038                &RecallQuery::parse(query),
2039                wants_prefilter,
2040            )
2041        };
2042        // Broad set covers any query that doesn't want a DB dig.
2043        assert!(covers(None, "ab", false));
2044        assert!(covers(None, "!vim", false));
2045        // Broad set cannot cover a dig: it's window-limited.
2046        assert!(!covers(None, "abc", true));
2047        // A narrow set covers queries whose conditions imply its own...
2048        assert!(covers(Some("abc"), "abc", true));
2049        assert!(covers(Some("abc"), "abcd", true));
2050        assert!(covers(Some("rs"), "rs/main", true), "separator append stays covered");
2051        assert!(covers(Some("push"), "git push", true), "atom order is irrelevant");
2052        // ...but not divergent or broader queries.
2053        assert!(!covers(Some("abc"), "abx", true));
2054        assert!(!covers(Some("abc"), "ab", false));
2055    }
2056
2057    #[test]
2058    fn test_entry_cache_takes_narrowest_covering() {
2059        let mut cache = EntryCache::default();
2060        cache.store(cache_snapshot(None, 3));
2061        cache.store(cache_snapshot(Some("git"), 2));
2062        cache.store(cache_snapshot(Some("git pu"), 1));
2063
2064        let raw = |snap: &EntrySnapshot| snap.db_query.as_ref().map(|q| q.raw().to_string());
2065        let hit = cache.take_covering(&RecallQuery::parse("git push"), true).unwrap();
2066        assert_eq!(raw(&hit).as_deref(), Some("git pu"), "narrowest covering set wins");
2067        assert_eq!(hit.entries.len(), 1);
2068
2069        // Taken snapshot is removed; the next-narrowest still serves.
2070        let hit = cache.take_covering(&RecallQuery::parse("git push"), true).unwrap();
2071        assert_eq!(raw(&hit).as_deref(), Some("git"));
2072
2073        // Broad snapshot serves short queries; then the cache is dry.
2074        let hit = cache.take_covering(&RecallQuery::parse("gi"), false).unwrap();
2075        assert!(hit.db_query.is_none());
2076        assert!(cache.take_covering(&RecallQuery::parse("gi"), false).is_none());
2077    }
2078
2079    #[test]
2080    fn test_entry_cache_store_replaces_and_stays_bounded() {
2081        let mut cache = EntryCache::default();
2082        cache.store(cache_snapshot(Some("abc"), 1));
2083        cache.store(cache_snapshot(Some("abc"), 5));
2084        let hit = cache.take_covering(&RecallQuery::parse("abc"), true).unwrap();
2085        assert_eq!(hit.entries.len(), 5, "same-query store should replace, not duplicate");
2086        assert!(cache.take_covering(&RecallQuery::parse("abc"), true).is_none());
2087
2088        for i in 0..20 {
2089            cache.store(cache_snapshot(Some(&format!("q{i}")), 1));
2090        }
2091        assert!(cache.snapshots.len() <= EntryCache::CAP, "cache should stay bounded");
2092        assert!(
2093            cache.take_covering(&RecallQuery::parse("q19"), true).is_some(),
2094            "most recent snapshots survive eviction"
2095        );
2096        assert!(
2097            cache.take_covering(&RecallQuery::parse("q0"), true).is_none(),
2098            "oldest snapshot evicted"
2099        );
2100    }
2101
2102    // Tests for highlight_command_with_indices (fuzzy match highlighting)
2103    #[test]
2104    fn test_fuzzy_highlight_no_indices() {
2105        use super::highlight_command_with_indices;
2106        // No match indices - whole string unhighlighted
2107        let spans = highlight_command_with_indices("git fetch origin", &[], 100);
2108        assert_eq!(spans, vec![("git fetch origin".to_string(), false)]);
2109    }
2110
2111    #[test]
2112    fn test_fuzzy_highlight_scattered_matches() {
2113        use super::highlight_command_with_indices;
2114        // "gfo" fuzzy matching "git fetch origin" -> indices 0, 4, 10
2115        let spans = highlight_command_with_indices("git fetch origin", &[0, 4, 10], 100);
2116        assert_eq!(
2117            spans,
2118            vec![
2119                ("g".to_string(), true),
2120                ("it ".to_string(), false),
2121                ("f".to_string(), true),
2122                ("etch ".to_string(), false),
2123                ("o".to_string(), true),
2124                ("rigin".to_string(), false),
2125            ]
2126        );
2127    }
2128
2129    #[test]
2130    fn test_fuzzy_highlight_contiguous_matches() {
2131        use super::highlight_command_with_indices;
2132        // Contiguous matches should be grouped
2133        let spans = highlight_command_with_indices("grep foo bar", &[5, 6, 7], 100);
2134        assert_eq!(
2135            spans,
2136            vec![
2137                ("grep ".to_string(), false),
2138                ("foo".to_string(), true),
2139                (" bar".to_string(), false),
2140            ]
2141        );
2142    }
2143
2144    #[test]
2145    fn test_fuzzy_highlight_truncates_by_display_width() {
2146        use super::highlight_command_with_indices;
2147        // Each CJK character occupies two terminal columns: with 8 columns and
2148        // "..." reserved, only two characters (4 columns) fit.
2149        let spans = highlight_command_with_indices("日本語テスト", &[], 8);
2150        assert_eq!(spans, vec![("日本".to_string(), false), ("...".to_string(), false)]);
2151    }
2152
2153    #[test]
2154    fn test_fuzzy_highlight_keeps_command_that_exactly_fits() {
2155        use super::highlight_command_with_indices;
2156        let spans = highlight_command_with_indices("0123456789", &[], 10);
2157        assert_eq!(spans, vec![("0123456789".to_string(), false)]);
2158    }
2159
2160    #[test]
2161    fn test_truncate_to_width() {
2162        assert_eq!(truncate_to_width("abc", 8), "abc");
2163        assert_eq!(truncate_to_width("0123456789", 10), "0123456789");
2164        assert_eq!(truncate_to_width("0123456789a", 10), "0123456...");
2165        assert_eq!(truncate_to_width("日本語テスト", 8), "日本...");
2166    }
2167
2168    #[test]
2169    fn test_fuzzy_highlight_truncation() {
2170        use super::highlight_command_with_indices;
2171        // Long command truncated with ellipsis
2172        // max_len=10 means we truncate at position 7 (10-3), leaving room for "..."
2173        let spans = highlight_command_with_indices("very long command here", &[0, 5], 10);
2174        assert_eq!(
2175            spans,
2176            vec![
2177                ("v".to_string(), true),
2178                ("ery ".to_string(), false),
2179                ("l".to_string(), true),
2180                ("o".to_string(), false),
2181                ("...".to_string(), false),
2182            ]
2183        );
2184    }
2185
2186    #[test]
2187    fn test_fuzzy_highlight_empty_command() {
2188        use super::highlight_command_with_indices;
2189        let spans = highlight_command_with_indices("", &[0, 1, 2], 100);
2190        assert!(spans.is_empty());
2191    }
2192
2193    #[test]
2194    fn test_fuzzy_highlight_match_at_start() {
2195        use super::highlight_command_with_indices;
2196        let spans = highlight_command_with_indices("foo bar", &[0, 1, 2], 100);
2197        assert_eq!(spans, vec![("foo".to_string(), true), (" bar".to_string(), false),]);
2198    }
2199
2200    #[test]
2201    fn test_fuzzy_highlight_match_at_end() {
2202        use super::highlight_command_with_indices;
2203        let spans = highlight_command_with_indices("foo bar", &[4, 5, 6], 100);
2204        assert_eq!(spans, vec![("foo ".to_string(), false), ("bar".to_string(), true),]);
2205    }
2206
2207    #[test]
2208    fn test_base64_encode() {
2209        assert_eq!(base64_encode(b"hello"), "aGVsbG8=");
2210        assert_eq!(base64_encode(b""), "");
2211        assert_eq!(base64_encode(b"a"), "YQ==");
2212        assert_eq!(base64_encode(b"ab"), "YWI=");
2213        assert_eq!(base64_encode(b"abc"), "YWJj");
2214        assert_eq!(base64_encode(b"echo hello world"), "ZWNobyBoZWxsbyB3b3JsZA==");
2215    }
2216
2217    #[test]
2218    fn test_delete_last_word_with_multibyte_whitespace() {
2219        // U+00A0 NBSP is 2 bytes in UTF-8: 0xC2 0xA0
2220        // Using rfind(is_whitespace).map(|i| i + 1) would land mid-char
2221        let mut query = "hello\u{00A0}world".to_string();
2222        let trimmed_len = query.trim_end().len();
2223        let word_start = query[..trimmed_len]
2224            .char_indices()
2225            .rev()
2226            .find(|(_, c)| c.is_whitespace())
2227            .map_or(0, |(i, c)| i + c.len_utf8());
2228        query.truncate(word_start); // should not panic
2229        assert_eq!(query, "hello\u{00A0}", "should truncate after the NBSP");
2230    }
2231}