arf-console 0.4.3

A cross-platform R console written in Rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
//! Interactive history browser for viewing and managing command history.
//!
//! This module provides a terminal-based browser for viewing, filtering,
//! and batch-deleting command history entries stored in SQLite.

use super::copy_to_clipboard;
use super::text_utils::{
    display_width, exceeds_width, pad_to_width, scroll_display, truncate_to_width,
};
use super::{
    MinimumSize, TextScrollState, check_terminal_too_small, render_size_warning,
    with_alternate_screen,
};
use crate::fuzzy::fuzzy_match;
use chrono::TimeZone;
use crossterm::{
    ExecutableCommand, cursor,
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers, MouseEventKind},
    queue,
    style::Stylize,
    terminal::{self, BeginSynchronizedUpdate, ClearType, EndSynchronizedUpdate},
};
use reedline::{HistoryItem, HistoryItemId};
use rusqlite::{Connection, OpenFlags, params_from_iter};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::time::Duration;

/// Maximum number of history entries to load from database.
const MAX_ENTRIES: i64 = 10000;

/// Minimum terminal size for the history browser.
///
/// Width: at 70 columns the column layout (prefix 29 + cmd 20 + cwd + host + spacing)
/// fits without overflow. Below that, columns overlap.
/// Height: 7 lines of chrome + 3 minimum content rows = 10.
const MIN_SIZE: MinimumSize = MinimumSize { cols: 70, rows: 10 };

/// Database mode for history browser.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HistoryDbMode {
    /// R command history.
    R,
    /// Shell command history.
    Shell,
}

impl HistoryDbMode {
    /// Display name for the mode.
    pub fn display_name(&self) -> &'static str {
        match self {
            HistoryDbMode::R => "R",
            HistoryDbMode::Shell => "Shell",
        }
    }
}

/// Result of running the history browser.
#[derive(Debug, Clone)]
#[allow(dead_code)] // Variants provide useful API even if not all fields are read
pub enum HistoryBrowserResult {
    /// User exited without action.
    Cancelled,
    /// User copied a command to clipboard.
    Copied(String),
}

/// Parsed filter with optional prefix filters.
#[derive(Debug, Default)]
struct HistoryFilter {
    /// Raw query string (for display).
    raw_query: String,
    /// Cursor position in the query string.
    cursor_pos: usize,
    /// Hostname filter (from `host:xxx`).
    hostname: Option<String>,
    /// CWD prefix filter (from `cwd:/path`).
    cwd_prefix: Option<String>,
    /// Exit status filter (from `exit:N`).
    exit_status: Option<i64>,
    /// Command pattern for fuzzy search (remaining text after prefix filters).
    command_pattern: String,
}

impl HistoryFilter {
    /// Parse a query string into filter components.
    fn parse(query: &str) -> Self {
        let mut filter = HistoryFilter {
            raw_query: query.to_string(),
            cursor_pos: query.chars().count(),
            ..Default::default()
        };

        let mut remaining_parts = Vec::new();

        for part in query.split_whitespace() {
            if let Some(hostname) = part.strip_prefix("host:") {
                filter.hostname = Some(hostname.to_string());
            } else if let Some(cwd) = part.strip_prefix("cwd:") {
                filter.cwd_prefix = Some(cwd.to_string());
            } else if let Some(status) = part.strip_prefix("exit:") {
                if let Ok(n) = status.parse::<i64>() {
                    filter.exit_status = Some(n);
                } else {
                    remaining_parts.push(part);
                }
            } else {
                remaining_parts.push(part);
            }
        }

        filter.command_pattern = remaining_parts.join(" ");
        filter
    }

    /// Re-parse prefix filters from the current raw_query.
    /// Call this after modifying `raw_query` or `cursor_pos` in-place.
    fn reparse(&mut self) {
        let parsed = Self::parse(&self.raw_query);
        self.hostname = parsed.hostname;
        self.cwd_prefix = parsed.cwd_prefix;
        self.exit_status = parsed.exit_status;
        self.command_pattern = parsed.command_pattern;
    }
}

/// A history item with selection state.
struct BrowsableHistoryItem {
    /// The actual history item.
    item: HistoryItem,
    /// Whether this item is selected for deletion.
    selected: bool,
}

/// Interactive history browser.
struct HistoryBrowser {
    /// All loaded history entries.
    entries: Vec<BrowsableHistoryItem>,
    /// Filtered entries as (index, score) pairs.
    filtered: Vec<(usize, u32)>,
    /// Current filter state.
    filter: HistoryFilter,
    /// Cursor position in the list.
    cursor: usize,
    /// Scroll offset for the list.
    scroll_offset: usize,
    /// Feedback message to display.
    feedback_message: Option<String>,
    /// Database mode (R or Shell).
    db_mode: HistoryDbMode,
    /// Path to the history database.
    db_path: PathBuf,
    /// Scroll animation state for the selected item's long text.
    text_scroll: TextScrollState,
    /// Whether we're showing the delete confirmation dialog.
    show_delete_dialog: bool,
    /// Whether filter input mode is active.
    /// When true, all character input goes to the filter text.
    /// When false, single-char keybindings (q, d, y, etc.) work as navigation/commands.
    filter_active: bool,
    /// Cached count of selected entries (maintained by toggle/select/unselect/delete).
    cached_selected_count: usize,
}

impl HistoryBrowser {
    /// Create a new history browser.
    fn new(entries: Vec<HistoryItem>, db_mode: HistoryDbMode, db_path: PathBuf) -> Self {
        let browsable: Vec<BrowsableHistoryItem> = entries
            .into_iter()
            .map(|item| BrowsableHistoryItem {
                item,
                selected: false,
            })
            .collect();
        let filtered: Vec<(usize, u32)> =
            browsable.iter().enumerate().map(|(i, _)| (i, 0)).collect();

        HistoryBrowser {
            entries: browsable,
            filtered,
            filter: HistoryFilter::default(),
            cursor: 0,
            scroll_offset: 0,
            feedback_message: None,
            db_mode,
            db_path,
            text_scroll: TextScrollState::new(),
            show_delete_dialog: false,
            filter_active: false,
            cached_selected_count: 0,
        }
    }

    /// Update the filtered list based on the current filter.
    fn update_filter(&mut self) {
        if self.filter.command_pattern.is_empty()
            && self.filter.hostname.is_none()
            && self.filter.cwd_prefix.is_none()
            && self.filter.exit_status.is_none()
        {
            // No filter - show all entries
            self.filtered = self
                .entries
                .iter()
                .enumerate()
                .map(|(i, _)| (i, 0))
                .collect();
        } else {
            let mut results: Vec<(usize, u32)> = self
                .entries
                .iter()
                .enumerate()
                .filter_map(|(idx, entry)| {
                    // Apply hostname filter
                    if let Some(ref hostname) = self.filter.hostname {
                        if let Some(ref item_host) = entry.item.hostname {
                            if !item_host.contains(hostname) {
                                return None;
                            }
                        } else {
                            return None;
                        }
                    }

                    // Apply cwd prefix filter
                    if let Some(ref cwd_prefix) = self.filter.cwd_prefix {
                        if let Some(ref item_cwd) = entry.item.cwd {
                            if !item_cwd.starts_with(cwd_prefix) {
                                return None;
                            }
                        } else {
                            return None;
                        }
                    }

                    // Apply exit status filter
                    if let Some(exit_status) = self.filter.exit_status
                        && entry.item.exit_status != Some(exit_status)
                    {
                        return None;
                    }

                    // Apply fuzzy command pattern filter
                    if !self.filter.command_pattern.is_empty() {
                        if let Some(m) =
                            fuzzy_match(&self.filter.command_pattern, &entry.item.command_line)
                        {
                            return Some((idx, m.score));
                        }
                        return None;
                    }

                    Some((idx, 0))
                })
                .collect();

            // Sort by score (descending) if we have fuzzy scores
            if !self.filter.command_pattern.is_empty() {
                results.sort_by_key(|entry| std::cmp::Reverse(entry.1));
            }

            self.filtered = results;
        }

        // Reset cursor and scroll
        self.cursor = 0;
        self.scroll_offset = 0;
    }

    /// Count of currently selected items (cached).
    fn selected_count(&self) -> usize {
        self.cached_selected_count
    }

    /// Toggle selection for the item at cursor.
    fn toggle_selection(&mut self) {
        if let Some(&(idx, _)) = self.filtered.get(self.cursor) {
            let entry = &mut self.entries[idx];
            entry.selected = !entry.selected;
            if entry.selected {
                self.cached_selected_count += 1;
            } else {
                self.cached_selected_count = self.cached_selected_count.saturating_sub(1);
            }
        }
    }

    /// Select all visible (filtered) items.
    fn select_all_visible(&mut self) {
        for &(idx, _) in &self.filtered {
            if !self.entries[idx].selected {
                self.entries[idx].selected = true;
                self.cached_selected_count += 1;
            }
        }
    }

    /// Unselect all items.
    fn unselect_all(&mut self) {
        for entry in &mut self.entries {
            entry.selected = false;
        }
        self.cached_selected_count = 0;
    }

    /// Delete all selected items from the database.
    ///
    /// Opens a separate read-write connection and executes a single batch DELETE.
    /// This avoids using `SqliteBackedHistory::with_file()` which would create a
    /// competing WAL connection alongside the main REPL's history connection,
    /// risking cache inconsistency and database corruption.
    fn delete_selected(&mut self) -> io::Result<()> {
        // Collect IDs to delete
        let ids_to_delete: Vec<i64> = self
            .entries
            .iter()
            .filter(|e| e.selected)
            .filter_map(|e| e.item.id)
            .map(|id| id.0)
            .collect();

        if ids_to_delete.is_empty() {
            return Ok(());
        }

        // Open a direct connection for the delete operation only.
        // We intentionally avoid SqliteBackedHistory::with_file() here because it
        // sets journal_mode=wal and runs DDL (CREATE TABLE IF NOT EXISTS), which
        // conflicts with the main REPL's active WAL connection to the same database.
        let db = Connection::open(&self.db_path).map_err(io::Error::other)?;
        db.busy_timeout(std::time::Duration::from_secs(5))
            .map_err(io::Error::other)?;

        // Batch delete in a single statement
        let placeholders: Vec<&str> = ids_to_delete.iter().map(|_| "?").collect();
        let sql = format!(
            "DELETE FROM history WHERE id IN ({})",
            placeholders.join(", ")
        );
        db.execute(&sql, params_from_iter(&ids_to_delete))
            .map_err(io::Error::other)?;

        // Remove deleted entries from our list
        let feedback = format!("Deleted {} entries", ids_to_delete.len());
        self.entries.retain(|e| !e.selected);
        self.cached_selected_count = 0;

        // Rebuild filtered list
        self.update_filter();

        // Adjust cursor if needed
        if self.cursor >= self.filtered.len() && !self.filtered.is_empty() {
            self.cursor = self.filtered.len() - 1;
        }

        self.feedback_message = Some(feedback);
        Ok(())
    }

    /// Move cursor up by one row.
    fn move_cursor_up(&mut self) {
        if self.cursor > 0 {
            self.cursor -= 1;
            if self.cursor < self.scroll_offset {
                self.scroll_offset = self.cursor;
            }
        }
    }

    /// Move cursor down by one row.
    fn move_cursor_down(&mut self) {
        let visible_rows = visible_result_rows();
        if self.cursor + 1 < self.filtered.len() {
            self.cursor += 1;
            if self.cursor >= self.scroll_offset + visible_rows {
                self.scroll_offset = self.cursor - visible_rows + 1;
            }
        }
    }

    /// Move cursor up by one page.
    fn move_page_up(&mut self) {
        if self.filtered.is_empty() {
            return;
        }
        let page_size = visible_result_rows();
        self.cursor = self.cursor.saturating_sub(page_size);
        self.scroll_offset = self.scroll_offset.saturating_sub(page_size);
    }

    /// Move cursor down by one page.
    fn move_page_down(&mut self) {
        if self.filtered.is_empty() {
            return;
        }
        let page_size = visible_result_rows();
        let max_cursor = self.filtered.len() - 1;
        self.cursor = (self.cursor + page_size).min(max_cursor);
        let max_scroll = self.filtered.len().saturating_sub(page_size);
        self.scroll_offset = (self.scroll_offset + page_size).min(max_scroll);
    }

    /// Move cursor to the first entry.
    fn move_to_top(&mut self) {
        self.cursor = 0;
        self.scroll_offset = 0;
    }

    /// Move cursor to the last entry.
    fn move_to_bottom(&mut self) {
        if !self.filtered.is_empty() {
            self.cursor = self.filtered.len() - 1;
            let visible_rows = visible_result_rows();
            if self.cursor >= visible_rows {
                self.scroll_offset = self.cursor - visible_rows + 1;
            }
        }
    }

    /// Get the command line at the current cursor position.
    fn current_command(&self) -> Option<&str> {
        self.filtered
            .get(self.cursor)
            .map(|&(idx, _)| self.entries[idx].item.command_line.as_str())
    }

    /// Run the browser and return the result.
    fn run(&mut self) -> io::Result<HistoryBrowserResult> {
        with_alternate_screen(|| self.run_inner())
    }

    fn run_inner(&mut self) -> io::Result<HistoryBrowserResult> {
        let mut stdout = io::stdout();
        let poll_timeout = Duration::from_millis(50);
        let mut needs_redraw = true;
        let mut too_small;

        loop {
            // Update animation state
            if self.update_text_scroll() {
                needs_redraw = true;
            }

            too_small = check_terminal_too_small(&MIN_SIZE).is_some();
            if needs_redraw {
                self.render(&mut stdout)?;
                needs_redraw = false;
            }

            if event::poll(poll_timeout)? {
                let ev = event::read()?;
                log::trace!("history_browser: received event: {:?}", ev);
                match ev {
                    Event::Key(key) => {
                        if key.kind != KeyEventKind::Press {
                            continue;
                        }

                        needs_redraw = true;

                        // When the terminal is too small, only accept exit keys
                        // to prevent input from leaking into filter or other state.
                        if too_small {
                            match (key.code, key.modifiers) {
                                (KeyCode::Esc, _)
                                | (KeyCode::Char('q'), KeyModifiers::NONE)
                                | (KeyCode::Char('c'), KeyModifiers::CONTROL)
                                | (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
                                    return Ok(HistoryBrowserResult::Cancelled);
                                }
                                _ => continue,
                            }
                        }

                        self.feedback_message = None;

                        // Handle delete confirmation dialog
                        if self.show_delete_dialog {
                            match key.code {
                                KeyCode::Enter => {
                                    self.show_delete_dialog = false;
                                    self.delete_selected()?;
                                }
                                KeyCode::Esc | KeyCode::Char('n') | KeyCode::Char('N') => {
                                    self.show_delete_dialog = false;
                                    self.feedback_message = Some("Delete cancelled".to_string());
                                }
                                _ => {}
                            }
                            continue;
                        }

                        if self.filter_active {
                            // Filter mode: all char input goes to filter text
                            match (key.code, key.modifiers) {
                                // Confirm filter and return to normal mode
                                (KeyCode::Enter, _) => {
                                    self.filter_active = false;
                                }

                                // Clear filter and return to normal mode
                                (KeyCode::Esc, _) => {
                                    self.filter.raw_query.clear();
                                    self.filter.cursor_pos = 0;
                                    self.filter.reparse();
                                    self.update_filter();
                                    self.filter_active = false;
                                }

                                // Ctrl+C exits the browser entirely
                                (KeyCode::Char('c'), KeyModifiers::CONTROL)
                                | (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
                                    return Ok(HistoryBrowserResult::Cancelled);
                                }

                                // Navigation still works in filter mode
                                (KeyCode::Up, _) | (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
                                    self.move_cursor_up();
                                }
                                (KeyCode::Down, _)
                                | (KeyCode::Char('n'), KeyModifiers::CONTROL) => {
                                    self.move_cursor_down();
                                }
                                // PageUp/PageDown only (no Ctrl+B/F which conflict
                                // with Emacs cursor movement in text input context)
                                (KeyCode::PageUp, _) => {
                                    self.move_page_up();
                                }
                                (KeyCode::PageDown, _) => {
                                    self.move_page_down();
                                }
                                // Alt+Home/End: list navigation
                                (KeyCode::Home, m) if m.contains(KeyModifiers::ALT) => {
                                    self.move_to_top();
                                }
                                (KeyCode::End, m) if m.contains(KeyModifiers::ALT) => {
                                    self.move_to_bottom();
                                }
                                // Plain Home/End: move cursor within filter input
                                (KeyCode::Home, _) => {
                                    self.filter.cursor_pos = 0;
                                }
                                (KeyCode::End, _) => {
                                    self.filter.cursor_pos = self.filter.raw_query.chars().count();
                                }
                                (KeyCode::Tab, _) => {
                                    self.toggle_selection();
                                }
                                (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
                                    self.select_all_visible();
                                }
                                (KeyCode::Char('u'), KeyModifiers::CONTROL) => {
                                    self.unselect_all();
                                }

                                // Backspace
                                (KeyCode::Backspace, _) => {
                                    if self.filter.cursor_pos > 0
                                        && let Some((byte_pos, _)) = self
                                            .filter
                                            .raw_query
                                            .char_indices()
                                            .nth(self.filter.cursor_pos - 1)
                                    {
                                        self.filter.raw_query.remove(byte_pos);
                                        self.filter.cursor_pos -= 1;
                                        self.filter.reparse();
                                        self.update_filter();
                                    }
                                }

                                // Delete
                                (KeyCode::Delete, _) => {
                                    if let Some((byte_pos, _)) = self
                                        .filter
                                        .raw_query
                                        .char_indices()
                                        .nth(self.filter.cursor_pos)
                                    {
                                        self.filter.raw_query.remove(byte_pos);
                                        self.filter.reparse();
                                        self.update_filter();
                                    }
                                }

                                // Cursor movement
                                (KeyCode::Left, KeyModifiers::NONE)
                                    if self.filter.cursor_pos > 0 =>
                                {
                                    self.filter.cursor_pos -= 1;
                                }
                                (KeyCode::Right, KeyModifiers::NONE) => {
                                    let query_len = self.filter.raw_query.chars().count();
                                    if self.filter.cursor_pos < query_len {
                                        self.filter.cursor_pos += 1;
                                    }
                                }

                                // Character input
                                (KeyCode::Char(c), KeyModifiers::NONE | KeyModifiers::SHIFT) => {
                                    let byte_pos = self
                                        .filter
                                        .raw_query
                                        .char_indices()
                                        .nth(self.filter.cursor_pos)
                                        .map(|(i, _)| i)
                                        .unwrap_or(self.filter.raw_query.len());
                                    self.filter.raw_query.insert(byte_pos, c);
                                    self.filter.cursor_pos += 1;
                                    self.filter.reparse();
                                    self.update_filter();
                                }

                                _ => {}
                            }
                        } else {
                            // Normal mode: single-char keybindings work
                            match (key.code, key.modifiers) {
                                // Exit
                                (KeyCode::Esc, _) | (KeyCode::Char('q'), KeyModifiers::NONE) => {
                                    return Ok(HistoryBrowserResult::Cancelled);
                                }
                                (KeyCode::Char('c'), KeyModifiers::CONTROL)
                                | (KeyCode::Char('d'), KeyModifiers::CONTROL) => {
                                    return Ok(HistoryBrowserResult::Cancelled);
                                }

                                // Enter filter mode
                                (KeyCode::Char('/'), KeyModifiers::NONE) => {
                                    self.filter_active = true;
                                }

                                // Navigation - up
                                (KeyCode::Up, _)
                                | (KeyCode::Char('k'), KeyModifiers::NONE)
                                | (KeyCode::Char('p'), KeyModifiers::CONTROL) => {
                                    self.move_cursor_up();
                                }

                                // Navigation - down
                                (KeyCode::Down, _)
                                | (KeyCode::Char('j'), KeyModifiers::NONE)
                                | (KeyCode::Char('n'), KeyModifiers::CONTROL) => {
                                    self.move_cursor_down();
                                }

                                // Page up
                                (KeyCode::PageUp, _)
                                | (KeyCode::Char('b'), KeyModifiers::CONTROL) => {
                                    self.move_page_up();
                                }

                                // Page down
                                (KeyCode::PageDown, _)
                                | (KeyCode::Char('f'), KeyModifiers::CONTROL) => {
                                    self.move_page_down();
                                }

                                // Home / go to top
                                (KeyCode::Home, _) | (KeyCode::Char('g'), KeyModifiers::NONE) => {
                                    self.move_to_top();
                                }

                                // End / go to bottom
                                (KeyCode::End, _) | (KeyCode::Char('G'), KeyModifiers::SHIFT) => {
                                    self.move_to_bottom();
                                }

                                // Toggle selection
                                (KeyCode::Tab, _) => {
                                    self.toggle_selection();
                                }

                                // Toggle selection and move down
                                (KeyCode::Char(' '), KeyModifiers::NONE) => {
                                    self.toggle_selection();
                                    self.move_cursor_down();
                                }

                                // Select all visible
                                (KeyCode::Char('a'), KeyModifiers::CONTROL) => {
                                    self.select_all_visible();
                                }

                                // Unselect all
                                (KeyCode::Char('u'), KeyModifiers::CONTROL) => {
                                    self.unselect_all();
                                }

                                // Delete selected (show confirmation)
                                (KeyCode::Char('d'), KeyModifiers::NONE) => {
                                    if self.selected_count() > 0 {
                                        self.show_delete_dialog = true;
                                    } else {
                                        self.feedback_message =
                                            Some("No items selected".to_string());
                                    }
                                }

                                // Copy and exit
                                (KeyCode::Enter, _) => {
                                    if let Some(cmd) = self.current_command() {
                                        let cmd = cmd.to_string();
                                        if copy_to_clipboard(&cmd).is_ok() {
                                            return Ok(HistoryBrowserResult::Copied(cmd));
                                        } else {
                                            self.feedback_message =
                                                Some("Failed to copy".to_string());
                                        }
                                    }
                                }

                                // Copy and stay
                                (KeyCode::Char('y'), KeyModifiers::NONE) => {
                                    if let Some(cmd) = self.current_command() {
                                        if copy_to_clipboard(cmd).is_ok() {
                                            self.feedback_message =
                                                Some("Copied to clipboard".to_string());
                                        } else {
                                            self.feedback_message =
                                                Some("Failed to copy".to_string());
                                        }
                                    }
                                }

                                _ => {}
                            }
                        }
                    }
                    Event::Mouse(mouse) => match mouse.kind {
                        MouseEventKind::ScrollUp => {
                            needs_redraw = true;
                            self.move_cursor_up();
                        }
                        MouseEventKind::ScrollDown => {
                            needs_redraw = true;
                            self.move_cursor_down();
                        }
                        _ => {}
                    },
                    Event::Resize(_, _) => {
                        needs_redraw = true;
                    }
                    _ => {}
                }
            }
        }
    }

    /// Update the text scroll animation state.
    fn update_text_scroll(&mut self) -> bool {
        self.text_scroll.update(self.cursor)
    }

    fn render(&self, stdout: &mut io::Stdout) -> io::Result<()> {
        if let Some((cols, rows)) = check_terminal_too_small(&MIN_SIZE) {
            return render_size_warning(stdout, cols, rows, &MIN_SIZE);
        }

        queue!(stdout, BeginSynchronizedUpdate)?;
        stdout.execute(cursor::MoveTo(0, 0))?;
        stdout.execute(cursor::Hide)?;

        let (cols, _rows) = terminal::size().unwrap_or((80, 24));
        let width = cols as usize;

        // Header with mode and entry count
        let selected_count = self.selected_count();
        let selected_info = if selected_count > 0 {
            format!(" [{} selected]", selected_count)
        } else {
            String::new()
        };
        let header = format!(
            "─ History Browser [{}] [{} entries]{} ─",
            self.db_mode.display_name(),
            self.filtered.len(),
            selected_info
        );
        let padded_header = format!("{:─<width$}", header, width = width);
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        println!("\r{}", padded_header.dark_grey());

        // Filter input
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        if self.filter_active {
            // Show cursor in filter mode
            let before_cursor: String = self
                .filter
                .raw_query
                .chars()
                .take(self.filter.cursor_pos)
                .collect();
            let after_cursor: String = self
                .filter
                .raw_query
                .chars()
                .skip(self.filter.cursor_pos)
                .collect();
            let filter_line = format!("  Filter: {}_{}", before_cursor, after_cursor);
            println!("\r{}", pad_to_width(&filter_line, width));
        } else if self.filter.raw_query.is_empty() {
            // No filter text, show placeholder
            println!(
                "\r{}",
                pad_to_width("  Filter: (press / to filter)", width).dark_grey()
            );
        } else {
            // Show filter text without cursor
            let filter_line = format!("  Filter: {}", self.filter.raw_query);
            println!("\r{}", pad_to_width(&filter_line, width));
        }

        // Separator
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        println!("\r{}", "─".repeat(width).dark_grey());

        // Calculate layout
        let (cmd_width, cwd_width, host_width) = calculate_layout(width);
        let visible_rows = visible_result_rows();

        // Column headers
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        let col_headers = format!(
            "       {:<16} {:>4} {} {} {}",
            "Date",
            "Exit",
            pad_to_width("Command", cmd_width),
            pad_to_width("Directory", cwd_width),
            pad_to_width("Host", host_width),
        );
        println!("\r{}", pad_to_width(&col_headers, width).dark_grey());

        // Results
        for i in 0..visible_rows {
            stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
            let idx = self.scroll_offset + i;
            if idx < self.filtered.len() {
                let (entry_idx, _score) = self.filtered[idx];
                let entry = &self.entries[entry_idx];
                let is_current = idx == self.cursor;

                // Selection checkbox
                let checkbox = if entry.selected { "[x]" } else { "[ ]" };
                let cursor_marker = if is_current { " > " } else { "   " };

                // Format timestamp in local time
                let timestamp = entry
                    .item
                    .start_timestamp
                    .map(|ts| {
                        ts.with_timezone(&chrono::Local)
                            .format("%Y-%m-%d %H:%M")
                            .to_string()
                    })
                    .unwrap_or_else(|| "                ".to_string());

                // Exit status
                let exit_str = match entry.item.exit_status {
                    Some(code) => format!("{:>4}", code),
                    None => "   -".to_string(),
                };

                // Command text with scrolling for selected item
                // Convert multiline commands to single line for display
                let cmd = flatten_multiline(&entry.item.command_line);
                let display_cmd = if is_current && exceeds_width(&cmd, cmd_width) {
                    let (scrolled, _) =
                        scroll_display(&cmd, cmd_width, self.text_scroll.scroll_pos);
                    scrolled
                } else {
                    truncate_to_width(&cmd, cmd_width)
                };

                // CWD (basename only, with scrolling for current row)
                let cwd_full = entry.item.cwd.as_deref().unwrap_or("");
                let cwd_short = std::path::Path::new(cwd_full)
                    .file_name()
                    .and_then(|f| f.to_str())
                    .unwrap_or(cwd_full);
                let display_cwd = if is_current && exceeds_width(cwd_short, cwd_width) {
                    let (scrolled, _) =
                        scroll_display(cwd_short, cwd_width, self.text_scroll.scroll_pos);
                    scrolled
                } else {
                    truncate_to_width(cwd_short, cwd_width)
                };

                // Hostname (truncated)
                let host = entry.item.hostname.as_deref().unwrap_or("");
                let display_host = truncate_to_width(host, host_width);

                // Build prefix base (cursor + checkbox + timestamp, without exit)
                let prefix_base = format!("{}{} {} ", cursor_marker, checkbox, timestamp);
                let padded_cmd = pad_to_width(&display_cmd, cmd_width);
                let padded_cwd = pad_to_width(&display_cwd, cwd_width);

                if is_current {
                    let content = format!(
                        "{}{} {} {} {}",
                        prefix_base, exit_str, padded_cmd, padded_cwd, display_host
                    );
                    let line = pad_to_width(&content, width);
                    println!("\r{}", line.reverse());
                } else if entry.selected {
                    let content = format!(
                        "{}{} {} {} {}",
                        prefix_base, exit_str, padded_cmd, padded_cwd, display_host
                    );
                    let line = pad_to_width(&content, width);
                    println!("\r{}", line.yellow());
                } else {
                    // Style exit status red if non-zero, cwd and hostname dark grey
                    let styled_exit = if matches!(entry.item.exit_status, Some(code) if code != 0) {
                        format!("{}", exit_str.as_str().red())
                    } else {
                        exit_str.clone()
                    };
                    // Padding: prefix_base, exit, cmd, cwd are fixed-width (no ANSI);
                    // only hostname may be shorter than its allocated width.
                    let content_width = display_width(&prefix_base)
                        + 4
                        + 1
                        + cmd_width
                        + 1
                        + cwd_width
                        + 1
                        + display_width(&display_host);
                    let padding_len = width.saturating_sub(content_width);
                    print!(
                        "\r{}{} {} {} {}{}\n",
                        prefix_base,
                        styled_exit,
                        padded_cmd,
                        padded_cwd.dark_grey(),
                        display_host.dark_grey(),
                        " ".repeat(padding_len)
                    );
                }
            } else {
                println!("\r{}", " ".repeat(width));
            }
        }

        // Footer separator
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        println!("\r{}", "─".repeat(width).dark_grey());

        // Footer line 1: filter syntax help
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        let syntax_help = "  Filter: host:<name> cwd:<path> exit:<N> <text>  (space = AND)";
        println!("\r{}", pad_to_width(syntax_help, width).dark_grey());

        // Footer line 2: keybindings or feedback message
        stdout.execute(terminal::Clear(ClearType::CurrentLine))?;
        if self.show_delete_dialog {
            let dialog_msg = format!(
                "  Delete {} selected entries? (Enter=confirm, Esc=cancel)",
                selected_count
            );
            println!("\r{}", pad_to_width(&dialog_msg, width).yellow().bold());
        } else if let Some(ref msg) = self.feedback_message {
            println!("\r{}", pad_to_width(&format!("  {}", msg), width));
        } else {
            let footer = if self.filter_active {
                "  Enter confirm | Esc clear | ↑↓/PgUp/PgDn navigate | Tab select"
            } else {
                "  / filter | Space/Tab select | d delete | y copy | Enter copy+exit | q exit"
            };
            println!("\r{}", pad_to_width(footer, width).dark_grey());
        }

        queue!(stdout, EndSynchronizedUpdate)?;
        stdout.flush()?;
        Ok(())
    }
}

/// Load history entries from the database in read-only mode.
///
/// Using read-only mode avoids WAL (Write-Ahead Logging) conflicts with the
/// main REPL's history connection. This prevents "database disk image is malformed"
/// errors when browsing history while the REPL is actively using the database.
fn load_history(db_path: &Path) -> io::Result<Vec<HistoryItem>> {
    // Open in read-only mode to avoid WAL conflicts
    let db = Connection::open_with_flags(db_path, OpenFlags::SQLITE_OPEN_READ_ONLY)
        .map_err(io::Error::other)?;

    let mut stmt = db
        .prepare(
            "SELECT id, command_line, start_timestamp, hostname, cwd, duration_ms, exit_status
             FROM history
             ORDER BY id DESC
             LIMIT ?",
        )
        .map_err(io::Error::other)?;

    let items = stmt
        .query_map([MAX_ENTRIES], |row| {
            Ok(HistoryItem {
                id: Some(HistoryItemId::new(row.get(0)?)),
                command_line: row.get(1)?,
                start_timestamp: row
                    .get::<_, Option<i64>>(2)?
                    .and_then(|ms| chrono::Utc.timestamp_millis_opt(ms).single()),
                session_id: None,
                hostname: row.get(3)?,
                cwd: row.get(4)?,
                duration: row
                    .get::<_, Option<i64>>(5)?
                    .and_then(|ms| u64::try_from(ms).ok())
                    .map(std::time::Duration::from_millis),
                exit_status: row.get(6)?,
                more_info: None,
            })
        })
        .map_err(io::Error::other)?
        .collect::<Result<Vec<_>, _>>()
        .map_err(io::Error::other)?;

    Ok(items)
}

/// Calculate layout widths for the history browser columns.
///
/// Returns (cmd_width, cwd_width, host_width).
fn calculate_layout(cols: usize) -> (usize, usize, usize) {
    // Layout: " > [x] 2024-01-15 14:32    0 command...  /path/to/dir  hostname"
    // Prefix: cursor(3) + checkbox(3) + space(1) + timestamp(16) + space(1) + exit(4) + space(1) = 29
    let prefix_width = 29;
    let host_width = (cols / 8).clamp(5, 15);
    let cwd_width = (cols / 6).clamp(8, 20);
    let cmd_width = cols
        .saturating_sub(prefix_width + cwd_width + host_width + 2)
        .max(20);
    (cmd_width, cwd_width, host_width)
}

/// Calculate the number of visible result rows.
fn visible_result_rows() -> usize {
    let (_, rows) = terminal::size().unwrap_or((80, 24));
    // Reserve: header(1) + filter(1) + separator(1) + column_headers(1) + footer_separator(1) + footer(2) = 7
    rows.saturating_sub(7).max(3) as usize
}

/// Convert a multiline string to a single line for display.
/// Replaces newlines with a visible marker (↵) to indicate line breaks.
fn flatten_multiline(s: &str) -> String {
    if s.contains('\n') {
        s.replace('\n', "↵")
    } else {
        s.to_string()
    }
}

/// Run the history browser.
///
/// # Arguments
/// * `db_path` - Path to the SQLite history database
/// * `mode` - The database mode (R or Shell)
///
/// # Returns
/// The result of the browser interaction.
pub fn run_history_browser(
    db_path: &Path,
    mode: HistoryDbMode,
) -> io::Result<HistoryBrowserResult> {
    // Load history entries
    let entries = load_history(db_path)?;

    if entries.is_empty() {
        println!("# No history entries found.");
        return Ok(HistoryBrowserResult::Cancelled);
    }

    let mut browser = HistoryBrowser::new(entries, mode, db_path.to_path_buf());
    browser.run()
}

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

    #[test]
    fn test_history_filter_parse_empty() {
        let filter = HistoryFilter::parse("");
        assert!(filter.hostname.is_none());
        assert!(filter.cwd_prefix.is_none());
        assert!(filter.exit_status.is_none());
        assert!(filter.command_pattern.is_empty());
    }

    #[test]
    fn test_history_filter_parse_command_only() {
        let filter = HistoryFilter::parse("git push");
        assert!(filter.hostname.is_none());
        assert!(filter.cwd_prefix.is_none());
        assert!(filter.exit_status.is_none());
        assert_eq!(filter.command_pattern, "git push");
    }

    #[test]
    fn test_history_filter_parse_with_hostname() {
        let filter = HistoryFilter::parse("host:myserver git push");
        assert_eq!(filter.hostname, Some("myserver".to_string()));
        assert_eq!(filter.command_pattern, "git push");
    }

    #[test]
    fn test_history_filter_parse_with_cwd() {
        let filter = HistoryFilter::parse("cwd:/home/user git");
        assert_eq!(filter.cwd_prefix, Some("/home/user".to_string()));
        assert_eq!(filter.command_pattern, "git");
    }

    #[test]
    fn test_history_filter_parse_with_exit_status() {
        let filter = HistoryFilter::parse("exit:0 make");
        assert_eq!(filter.exit_status, Some(0));
        assert_eq!(filter.command_pattern, "make");
    }

    #[test]
    fn test_history_filter_parse_multiple_filters() {
        let filter = HistoryFilter::parse("host:server cwd:/project exit:1 test");
        assert_eq!(filter.hostname, Some("server".to_string()));
        assert_eq!(filter.cwd_prefix, Some("/project".to_string()));
        assert_eq!(filter.exit_status, Some(1));
        assert_eq!(filter.command_pattern, "test");
    }

    #[test]
    fn test_history_filter_parse_invalid_exit_status() {
        let filter = HistoryFilter::parse("exit:abc git");
        assert!(filter.exit_status.is_none());
        // Invalid exit:abc becomes part of command pattern
        assert_eq!(filter.command_pattern, "exit:abc git");
    }

    #[test]
    fn test_calculate_layout_standard_terminal() {
        let (cmd, cwd, host) = calculate_layout(120);
        assert!(cmd >= 20);
        assert!(cwd >= 8);
        assert!(host >= 5);
        // prefix(29) + cmd + space(1) + cwd + space(1) + host = total
        assert_eq!(29 + cmd + 1 + cwd + 1 + host, 120);
    }

    #[test]
    fn test_calculate_layout_80_columns() {
        let (cmd, cwd, host) = calculate_layout(80);
        assert!(cmd >= 20);
        assert!(cwd >= 8);
        assert!(host >= 5);
        assert_eq!(29 + cmd + 1 + cwd + 1 + host, 80);
    }

    #[test]
    fn test_calculate_layout_wide_terminal() {
        let (cmd, cwd, host) = calculate_layout(200);
        assert!(cmd >= 20);
        assert!(cwd <= 20, "cwd_width should be capped at 20, got {}", cwd);
        assert!(
            host <= 15,
            "host_width should be capped at 15, got {}",
            host
        );
        assert_eq!(29 + cmd + 1 + cwd + 1 + host, 200);
    }

    #[test]
    fn test_calculate_layout_narrow_terminal() {
        // Very narrow terminal: cmd_width floors at 20 so total exceeds cols
        let (cmd, cwd, host) = calculate_layout(50);
        assert_eq!(cmd, 20, "cmd_width should floor at 20");
        assert!(cwd >= 8);
        assert!(host >= 5);
        // Total overflows because cmd_width has a minimum of 20
        let total = 29 + cmd + 1 + cwd + 1 + host;
        assert!(
            total > 50,
            "narrow terminal should overflow, total={}",
            total
        );
    }

    #[test]
    fn test_truncate_to_width() {
        assert_eq!(truncate_to_width("hello", 10), "hello");
        assert_eq!(truncate_to_width("hello world", 8), "hello w…");
        assert_eq!(truncate_to_width("hi", 1), "…");
    }

    #[test]
    fn test_exceeds_width() {
        assert!(!exceeds_width("hello", 10));
        assert!(exceeds_width("hello world", 8));
    }

    #[test]
    fn test_scroll_display() {
        // Text that fits
        let (result, max) = scroll_display("hello", 10, 0);
        assert_eq!(result, "hello");
        assert_eq!(max, 0);

        // Text at start
        let (result, _) = scroll_display("hello world", 8, 0);
        assert_eq!(result, "hello w…");

        // Text at end
        let (result, _) = scroll_display("hello world", 8, 100);
        assert_eq!(result, "…o world");
    }

    #[test]
    fn test_db_mode_display_name() {
        assert_eq!(HistoryDbMode::R.display_name(), "R");
        assert_eq!(HistoryDbMode::Shell.display_name(), "Shell");
    }

    /// Create a temporary history database with test entries.
    /// Returns the temp dir (must be kept alive) and the db path.
    ///
    /// NOTE: The schema here must match reedline's `SqliteBackedHistory` table
    /// definition. If reedline changes its schema, this helper must be updated.
    fn create_test_db(entries: &[(&str, Option<&str>)]) -> (tempfile::TempDir, PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let db_path = dir.path().join("test_history.db");
        let db = Connection::open(&db_path).unwrap();
        db.execute_batch(
            "CREATE TABLE IF NOT EXISTS history (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                command_line TEXT NOT NULL,
                start_timestamp INTEGER,
                session_id INTEGER,
                hostname TEXT,
                cwd TEXT,
                duration_ms INTEGER,
                exit_status INTEGER,
                more_info TEXT
            ) STRICT;",
        )
        .unwrap();
        for (cmd, hostname) in entries {
            db.execute(
                "INSERT INTO history (command_line, hostname) VALUES (?, ?)",
                rusqlite::params![cmd, hostname],
            )
            .unwrap();
        }
        (dir, db_path)
    }

    #[test]
    fn test_load_history_returns_entries_in_desc_order() {
        let (_dir, db_path) = create_test_db(&[
            ("first_cmd", Some("host1")),
            ("second_cmd", Some("host2")),
            ("third_cmd", None),
        ]);

        let items = load_history(&db_path).unwrap();
        assert_eq!(items.len(), 3);
        // Descending order by id
        assert_eq!(items[0].command_line, "third_cmd");
        assert_eq!(items[1].command_line, "second_cmd");
        assert_eq!(items[2].command_line, "first_cmd");
        // Hostname preserved
        assert_eq!(items[1].hostname.as_deref(), Some("host2"));
        assert!(items[0].hostname.is_none());
    }

    #[test]
    fn test_load_history_empty_db() {
        let (_dir, db_path) = create_test_db(&[]);
        let items = load_history(&db_path).unwrap();
        assert!(items.is_empty());
    }

    #[test]
    fn test_delete_selected_removes_from_db_and_entries() {
        let (_dir, db_path) = create_test_db(&[("cmd_a", None), ("cmd_b", None), ("cmd_c", None)]);

        let entries = load_history(&db_path).unwrap();
        let mut browser = HistoryBrowser::new(entries, HistoryDbMode::R, db_path.clone());

        // Select the first item (cmd_c, id=3) and the third item (cmd_a, id=1)
        browser.cursor = 0;
        browser.toggle_selection();
        browser.cursor = 2;
        browser.toggle_selection();
        assert_eq!(browser.selected_count(), 2);

        browser.delete_selected().unwrap();

        // Only cmd_b should remain in the browser
        assert_eq!(browser.entries.len(), 1);
        assert_eq!(browser.entries[0].item.command_line, "cmd_b");
        assert_eq!(browser.selected_count(), 0);

        // Verify database state
        let remaining = load_history(&db_path).unwrap();
        assert_eq!(remaining.len(), 1);
        assert_eq!(remaining[0].command_line, "cmd_b");
    }

    #[test]
    fn test_delete_selected_no_selection_is_noop() {
        let (_dir, db_path) = create_test_db(&[("cmd_a", None)]);
        let entries = load_history(&db_path).unwrap();
        let mut browser = HistoryBrowser::new(entries, HistoryDbMode::R, db_path.clone());

        browser.delete_selected().unwrap();

        assert_eq!(browser.entries.len(), 1);
        let remaining = load_history(&db_path).unwrap();
        assert_eq!(remaining.len(), 1);
    }

    #[test]
    fn test_delete_selected_all_entries() {
        let (_dir, db_path) = create_test_db(&[("cmd_a", None), ("cmd_b", None)]);
        let entries = load_history(&db_path).unwrap();
        let mut browser = HistoryBrowser::new(entries, HistoryDbMode::R, db_path.clone());

        browser.select_all_visible();
        assert_eq!(browser.selected_count(), 2);

        browser.delete_selected().unwrap();

        assert!(browser.entries.is_empty());
        assert!(browser.filtered.is_empty());
        let remaining = load_history(&db_path).unwrap();
        assert!(remaining.is_empty());
    }

    #[test]
    fn test_flatten_multiline() {
        // Single line - unchanged
        assert_eq!(flatten_multiline("hello"), "hello");
        assert_eq!(flatten_multiline("git push"), "git push");

        // Multiline - newlines replaced with marker
        assert_eq!(flatten_multiline("line1\nline2"), "line1↵line2");
        assert_eq!(
            flatten_multiline("function() {\n  print(1)\n}"),
            "function() {↵  print(1)↵}"
        );

        // Empty string
        assert_eq!(flatten_multiline(""), "");
    }

    #[test]
    fn test_cwd_basename_extraction() {
        use std::path::Path;

        // Helper matching the logic in render()
        fn basename(cwd: &str) -> String {
            Path::new(cwd)
                .file_name()
                .and_then(|f| f.to_str())
                .unwrap_or(cwd)
                .to_string()
        }

        assert_eq!(basename("/home/user/project"), "project");
        assert_eq!(
            basename("/home/user/my-long-directory-name"),
            "my-long-directory-name"
        );
        assert_eq!(basename("/"), "/");
        assert_eq!(basename(""), "");
        assert_eq!(basename("/foo/bar/baz"), "baz");
        // file_name() returns None for "..", so full path is used as fallback
        assert_eq!(basename("/foo/.."), "/foo/..");
        // file_name() strips trailing "." and returns the parent component
        assert_eq!(basename("/foo/."), "foo");
    }
}