codewhale-tui 0.9.8

Terminal UI for open-source and open-weight coding models
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
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
//! Fuzzy file-picker modal (Ctrl+P).
//!
//! Opens an overlay populated with workspace-relative paths discovered by a
//! single-pass `WalkBuilder` walk (depth from `mention_walk_depth`, default
//! 10, `0` = unlimited; hidden=true, follow_links=false,
//! `.gitignore` honored). Subsequent keystrokes filter the cached candidate
//! list in memory using a small subsequence + first-letter-bonus scorer — no
//! per-keystroke disk traversal.
//!
//! Enter emits a [`ViewEvent::FilePickerSelected`] which the UI handler turns
//! into an `@<path>` insertion at the composer cursor.

use std::cell::RefCell;
use std::collections::HashSet;
use std::path::Path;
use std::sync::{Arc, Mutex};

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
use ignore::WalkBuilder;
use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::Style,
    text::{Line, Span},
    widgets::{Paragraph, Widget},
};

use crate::localization::{Locale, MessageId, tr};
use crate::palette;
use crate::tui::menu_style;
use crate::tui::views::{
    ActionHint, ModalKind, ModalView, ViewAction, ViewEvent, render_modal_footer,
    render_panel_scroll_rail, render_underwater_surface,
};
use crate::workspace_discovery::{DISCOVERY_ALWAYS_DIRS, path_is_excluded_from_discovery};

/// Maximum number of candidates collected from the initial walk. Keeps memory
/// bounded for very large monorepos; matches the limits codex-rs uses for the
/// equivalent overlay.
const MAX_CANDIDATES: usize = 20_000;

/// Default walk depth used by the picker's own tests. Production callers pass
/// the configured `mention_walk_depth` (default 10, `0` = unlimited) through
/// [`FilePickerView::new_with_relevance_and_depth`], mirroring the `Workspace`
/// fuzzy index default (`DEFAULT_COMPLETIONS_WALK_DEPTH`).
#[cfg(test)]
const WALK_DEPTH: usize = 10;

/// Visible candidate rows in the overlay.
const VISIBLE_ROWS: usize = 14;

const MODIFIED_BOOST: i32 = 360;
const MENTIONED_BOOST: i32 = 240;
const TOOL_BOOST: i32 = 160;

/// Working-set hints captured when the picker opens.
///
/// The picker keeps this as plain path strings so filtering stays in-memory and
/// per-keystroke work remains the same shape as the original fuzzy search.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FilePickerRelevance {
    modified: HashSet<String>,
    mentioned: HashSet<String>,
    tool: HashSet<String>,
}

impl FilePickerRelevance {
    pub fn mark_modified(&mut self, path: impl Into<String>) {
        let path = path.into();
        if !path.is_empty() {
            self.modified.insert(path);
        }
    }

    pub fn mark_mentioned(&mut self, path: impl Into<String>) {
        let path = path.into();
        if !path.is_empty() {
            self.mentioned.insert(path);
        }
    }

    pub fn mark_tool(&mut self, path: impl Into<String>) {
        let path = path.into();
        if !path.is_empty() {
            self.tool.insert(path);
        }
    }

    fn boost_for(&self, path: &str) -> i32 {
        let mut boost = 0;
        if self.modified.contains(path) {
            boost += MODIFIED_BOOST;
        }
        if self.mentioned.contains(path) {
            boost += MENTIONED_BOOST;
        }
        if self.tool.contains(path) {
            boost += TOOL_BOOST;
        }
        boost
    }

    fn markers_for(&self, path: &str) -> String {
        let mut markers = String::with_capacity(3);
        markers.push(if self.modified.contains(path) {
            'M'
        } else {
            ' '
        });
        markers.push(if self.mentioned.contains(path) {
            '@'
        } else {
            ' '
        });
        markers.push(if self.tool.contains(path) { 'T' } else { ' ' });
        markers
    }
}

pub struct FilePickerView {
    /// All workspace-relative candidate paths, captured once at construction.
    candidates: Vec<String>,
    /// Working-set relevance hints, captured once at construction.
    relevance: FilePickerRelevance,
    /// Filtered indices into `candidates`, sorted by descending score.
    filtered: Vec<usize>,
    /// User's typed query (lowercased on each refilter).
    query: String,
    /// Selected row within `filtered`.
    selected: usize,
    /// Top of the visible window within `filtered`.
    scroll: usize,
    /// Exact visible row targets from the last render for mouse parity.
    last_row_hitboxes: RefCell<Vec<(u16, usize)>>,
    /// UI locale captured from the app at construction (#4057 wave 2).
    locale: Locale,
    /// True until the background workspace scan delivers (#3905). The picker
    /// paints immediately in this state instead of blocking the event loop on
    /// a `git status` subprocess and a 20k-file walk.
    is_loading: bool,
    /// Where the background scan drops its result. `None` once drained, or
    /// when the scan ran synchronously (no tokio runtime, i.e. unit tests).
    loading_cell: Option<Arc<Mutex<Option<WorkspaceScan>>>>,
}

/// What the off-thread workspace scan produces: the candidate paths and the
/// git-reported modified paths, which are the only two blocking parts of
/// building this picker.
struct WorkspaceScan {
    candidates: Vec<String>,
    modified: Vec<String>,
}

impl FilePickerView {
    /// Build a picker with working-set relevance hints, using the default
    /// walk depth ([`WALK_DEPTH`]). Test-only convenience; production code uses
    /// [`FilePickerView::new_with_relevance_and_depth`] with the configured
    /// `mention_walk_depth`.
    #[cfg(test)]
    pub fn new_with_relevance(workspace_root: &Path, relevance: FilePickerRelevance) -> Self {
        Self::new_with_relevance_and_depth(workspace_root, relevance, WALK_DEPTH, Locale::En)
    }

    /// Build a picker with working-set relevance hints and an explicit walk
    /// depth. A depth of `0` disables the depth limit so files in deeply
    /// nested workspaces (>= 6 levels) remain discoverable (#2488).
    pub fn new_with_relevance_and_depth(
        workspace_root: &Path,
        relevance: FilePickerRelevance,
        walk_depth: usize,
        locale: Locale,
    ) -> Self {
        let max_depth = if walk_depth == 0 {
            None
        } else {
            Some(walk_depth)
        };

        // Outside a tokio runtime (plain unit tests) do the work inline, so
        // tests keep observing a fully-populated picker from the constructor.
        if tokio::runtime::Handle::try_current().is_err() {
            let candidates = collect_candidates(workspace_root, max_depth);
            let mut relevance = relevance;
            for path in crate::tui::file_picker_relevance::modified_workspace_paths(workspace_root)
            {
                relevance.mark_modified(path);
            }
            let mut view = Self {
                candidates,
                relevance,
                filtered: Vec::new(),
                query: String::new(),
                selected: 0,
                scroll: 0,
                last_row_hitboxes: RefCell::new(Vec::new()),
                locale,
                is_loading: false,
                loading_cell: None,
            };
            view.refilter();
            return view;
        }

        // Both halves of the scan are blocking: `git status` is a subprocess,
        // and the walk visits up to MAX_CANDIDATES paths. Neither belongs on
        // the event loop — Ctrl+P used to freeze the whole TUI until both
        // finished (#3905), the same failure #3899/#3900 fixed for the
        // adjacent @-mention and file-tree paths.
        let loading_cell = Arc::new(Mutex::new(None));
        let cell = loading_cell.clone();
        let root = workspace_root.to_path_buf();
        crate::utils::spawn_blocking_supervised("file-picker-scan", move || {
            let scan = WorkspaceScan {
                candidates: collect_candidates(&root, max_depth),
                modified: crate::tui::file_picker_relevance::modified_workspace_paths(&root),
            };
            if let Ok(mut guard) = cell.lock() {
                *guard = Some(scan);
            }
        });

        let mut view = Self {
            candidates: Vec::new(),
            relevance,
            filtered: Vec::new(),
            query: String::new(),
            selected: 0,
            scroll: 0,
            last_row_hitboxes: RefCell::new(Vec::new()),
            locale,
            is_loading: true,
            loading_cell: Some(loading_cell),
        };
        view.refilter();
        view
    }

    /// Drain the background scan if it has landed. Called from `tick`, which
    /// the view stack runs on the top view every loop iteration.
    fn poll_loading(&mut self) {
        if !self.is_loading {
            return;
        }
        // Take the Arc out temporarily to avoid a double-borrow of self.
        let Some(cell) = self.loading_cell.take() else {
            self.is_loading = false;
            return;
        };
        let scan = cell.lock().ok().and_then(|mut guard| guard.take());
        match scan {
            Some(scan) => {
                self.candidates = scan.candidates;
                for path in scan.modified {
                    self.relevance.mark_modified(path);
                }
                self.is_loading = false;
                // The user may already have typed while the scan ran; refilter
                // against the query they actually have, not an empty one.
                self.refilter();
            }
            None => self.loading_cell = Some(cell),
        }
    }

    fn refilter(&mut self) {
        let query = self.query.trim().to_lowercase();
        let mut scored: Vec<(usize, i32, i32, i32)> = if query.is_empty() {
            self.candidates
                .iter()
                .enumerate()
                .map(|(idx, path)| {
                    let boost = self.relevance.boost_for(path);
                    (idx, boost, 0, boost)
                })
                .collect()
        } else {
            self.candidates
                .iter()
                .enumerate()
                .filter_map(|(idx, path)| {
                    score(&query, path).map(|fuzzy| {
                        let boost = self.relevance.boost_for(path);
                        (idx, fuzzy + boost, fuzzy, boost)
                    })
                })
                .collect()
        };

        // Higher scores first; tie-break by ascending path length, then lex order
        // so shorter / more central matches surface above deep nested ones.
        scored.sort_by(|a, b| {
            b.1.cmp(&a.1)
                .then_with(|| b.2.cmp(&a.2))
                .then_with(|| b.3.cmp(&a.3))
                .then_with(|| self.candidates[a.0].len().cmp(&self.candidates[b.0].len()))
                .then_with(|| self.candidates[a.0].cmp(&self.candidates[b.0]))
        });

        self.filtered = scored.into_iter().map(|(idx, _, _, _)| idx).collect();
        if self.filtered.is_empty() {
            self.selected = 0;
            self.scroll = 0;
        } else if self.selected >= self.filtered.len() {
            self.selected = self.filtered.len() - 1;
        }
        self.adjust_scroll();
    }

    fn adjust_scroll(&mut self) {
        if self.filtered.is_empty() {
            self.scroll = 0;
            return;
        }
        if self.selected < self.scroll {
            self.scroll = self.selected;
        } else if self.selected >= self.scroll + VISIBLE_ROWS {
            self.scroll = self.selected + 1 - VISIBLE_ROWS;
        }
    }

    fn move_selection(&mut self, delta: isize) {
        if self.filtered.is_empty() {
            return;
        }
        self.selected = crate::tui::list_nav::wrap_index(self.selected, self.filtered.len(), delta);
        self.adjust_scroll();
    }

    fn selected_path(&self) -> Option<&str> {
        let idx = *self.filtered.get(self.selected)?;
        self.candidates.get(idx).map(String::as_str)
    }

    /// Visible candidate count for tests / diagnostics.
    #[cfg(test)]
    pub fn visible_count(&self) -> usize {
        self.filtered.len()
    }

    #[cfg(test)]
    pub fn query(&self) -> &str {
        &self.query
    }

    #[cfg(test)]
    pub fn selected_for_test(&self) -> Option<&str> {
        self.selected_path()
    }

    #[cfg(test)]
    pub fn markers_for_test(&self, path: &str) -> String {
        self.relevance.markers_for(path)
    }
}

impl ModalView for FilePickerView {
    fn kind(&self) -> ModalKind {
        ModalKind::FilePicker
    }

    fn as_any_mut(&mut self) -> &mut dyn std::any::Any {
        self
    }

    fn handle_key(&mut self, key: KeyEvent) -> ViewAction {
        match key.code {
            KeyCode::Esc => ViewAction::Close,
            KeyCode::Enter => {
                if let Some(path) = self.selected_path() {
                    let path = path.to_string();
                    return ViewAction::EmitAndClose(ViewEvent::FilePickerSelected { path });
                }
                ViewAction::Close
            }
            KeyCode::Up => {
                self.move_selection(-1);
                ViewAction::None
            }
            KeyCode::Down => {
                self.move_selection(1);
                ViewAction::None
            }
            KeyCode::PageUp => {
                self.move_selection(-(VISIBLE_ROWS as isize));
                ViewAction::None
            }
            KeyCode::PageDown => {
                self.move_selection(VISIBLE_ROWS as isize);
                ViewAction::None
            }
            KeyCode::Backspace => {
                self.query.pop();
                self.selected = 0;
                self.scroll = 0;
                self.refilter();
                ViewAction::None
            }
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.query.clear();
                self.selected = 0;
                self.scroll = 0;
                self.refilter();
                ViewAction::None
            }
            KeyCode::Char(ch)
                if !key.modifiers.contains(KeyModifiers::CONTROL)
                    && !key.modifiers.contains(KeyModifiers::ALT)
                    && !ch.is_control() =>
            {
                self.query.push(ch);
                self.selected = 0;
                self.scroll = 0;
                self.refilter();
                ViewAction::None
            }
            _ => ViewAction::None,
        }
    }

    fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction {
        match mouse.kind {
            MouseEventKind::ScrollUp => {
                self.move_selection(-1);
                ViewAction::None
            }
            MouseEventKind::ScrollDown => {
                self.move_selection(1);
                ViewAction::None
            }
            MouseEventKind::Down(MouseButton::Left) => {
                let hit = self
                    .last_row_hitboxes
                    .borrow()
                    .iter()
                    .find_map(|(y, idx)| (*y == mouse.row).then_some(*idx));
                let Some(idx) = hit else {
                    return ViewAction::None;
                };
                if idx == self.selected {
                    if let Some(path) = self.selected_path() {
                        return ViewAction::EmitAndClose(ViewEvent::FilePickerSelected {
                            path: path.to_string(),
                        });
                    }
                } else {
                    self.selected = idx;
                    self.adjust_scroll();
                }
                ViewAction::None
            }
            _ => ViewAction::None,
        }
    }

    fn tick(&mut self) -> ViewAction {
        self.poll_loading();
        ViewAction::None
    }

    fn render(&self, area: Rect, buf: &mut Buffer) {
        let match_count = self.filtered.len();
        let title = if match_count == 1 {
            tr(self.locale, MessageId::FilePickerMatchSingular).into_owned()
        } else {
            tr(self.locale, MessageId::FilePickerMatchesPlural)
                .replace("{count}", &match_count.to_string())
        };
        let inner = render_underwater_surface(area, buf, title);

        let content = render_modal_footer(
            inner,
            buf,
            &[
                ActionHint::new("↑/↓", "move"),
                ActionHint::new("Enter", "insert @path"),
                ActionHint::new("Esc", "cancel"),
            ],
        );
        let visible = VISIBLE_ROWS.min(content.height.saturating_sub(2) as usize);
        let content = render_panel_scroll_rail(
            content,
            buf,
            self.filtered.len(),
            self.scroll,
            visible,
            true,
        );

        let mut lines: Vec<Line<'static>> = Vec::new();
        // Query line.
        lines.push(Line::from(vec![
            Span::styled("> ", Style::default().fg(palette::WHALE_INFO).bold()),
            Span::raw(self.query.clone()),
            Span::styled(
                " ",
                Style::default()
                    .fg(palette::WHALE_BG)
                    .bg(palette::WHALE_INFO),
            ),
        ]));
        lines.push(Line::from(""));

        let end = (self.scroll + visible).min(self.filtered.len());
        self.last_row_hitboxes.borrow_mut().clear();
        if self.is_loading {
            // "No matches" would be a lie while the walk is still running.
            lines.push(Line::from(Span::styled(
                format!("  {}", tr(self.locale, MessageId::FilePickerScanning)),
                Style::default().fg(palette::TEXT_MUTED),
            )));
        } else if self.filtered.is_empty() {
            lines.push(Line::from(Span::styled(
                "  No matches",
                Style::default().fg(palette::TEXT_MUTED),
            )));
        } else {
            for idx in self.scroll..end {
                let path = &self.candidates[self.filtered[idx]];
                let selected = idx == self.selected;
                let style = if selected {
                    menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT)
                } else {
                    Style::default().fg(palette::TEXT_PRIMARY)
                };
                let prefix = format!("{} ", crate::tui::glyphs::selection_marker(selected));
                let marker_field = if content.width >= 18 {
                    format!("{} ", self.relevance.markers_for(path))
                } else {
                    String::new()
                };
                let reserved = prefix.chars().count() + marker_field.chars().count();
                let display =
                    truncate_path(path, (content.width as usize).saturating_sub(reserved));
                let mut line = Line::from(format!("{prefix}{marker_field}{display}"));
                line.style = style;
                let y = content
                    .y
                    .saturating_add(u16::try_from(lines.len()).unwrap_or(u16::MAX));
                self.last_row_hitboxes.borrow_mut().push((y, idx));
                lines.push(line);
            }
        }

        Paragraph::new(lines)
            .style(Style::default().fg(palette::TEXT_PRIMARY))
            .render(content, buf);
    }
}

fn truncate_path(path: &str, max: usize) -> String {
    if max == 0 {
        return String::new();
    }
    if path.chars().count() <= max {
        return path.to_string();
    }
    let take = max.saturating_sub(1);
    let truncated: String = path
        .chars()
        .rev()
        .take(take)
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    format!("{truncated}")
}

/// Single-pass walk that collects workspace-relative paths. `max_depth` of
/// `None` walks the whole tree (still bounded by `MAX_CANDIDATES` and
/// `.gitignore`); `Some(n)` caps the recursion at `n` levels.
fn collect_candidates(root: &Path, max_depth: Option<usize>) -> Vec<String> {
    let mut builder = WalkBuilder::new(root);
    builder
        .hidden(true)
        .follow_links(false)
        .max_depth(max_depth)
        .git_ignore(true)
        .git_exclude(true)
        .git_global(true);

    let mut out: Vec<String> = Vec::new();
    for entry in builder.build().flatten() {
        if !entry.file_type().is_some_and(|ft| ft.is_file()) {
            continue;
        }
        let path = entry.path();
        let rel = path.strip_prefix(root).unwrap_or(path);
        if rel.as_os_str().is_empty() {
            continue;
        }
        let display = path_to_workspace_string(rel);
        if !display.is_empty() {
            out.push(display);
        }
        if out.len() >= MAX_CANDIDATES {
            break;
        }
    }

    // Whitelist AI-tool dot-directories so they're discoverable even when
    // gitignored. Walk each one separately with gitignore disabled.
    for dir in DISCOVERY_ALWAYS_DIRS {
        let dot_dir = root.join(dir);
        if !dot_dir.is_dir() {
            continue;
        }
        let mut dot_builder = WalkBuilder::new(&dot_dir);
        dot_builder
            .hidden(true)
            .follow_links(false)
            .git_ignore(false)
            .ignore(false)
            .max_depth(max_depth.map(|d| d.saturating_sub(1)));
        for entry in dot_builder.build().flatten() {
            // Exclude machine-generated bulk (e.g. .deepseek/snapshots/).
            if path_is_excluded_from_discovery(root, entry.path()) {
                continue;
            }
            if !entry.file_type().is_some_and(|ft| ft.is_file()) {
                continue;
            }
            let path = entry.path();
            let rel = path.strip_prefix(root).unwrap_or(path);
            if rel.as_os_str().is_empty() {
                continue;
            }
            let display = path_to_workspace_string(rel);
            if !display.is_empty() {
                out.push(display);
            }
            if out.len() >= MAX_CANDIDATES {
                break;
            }
        }
    }

    out.sort();
    out
}

fn path_to_workspace_string(path: &Path) -> String {
    // Use forward-slash separators for cross-platform display, matching how
    // @-mentions are spelled in the composer.
    let mut out = String::new();
    for (idx, comp) in path.components().enumerate() {
        if idx > 0 {
            out.push('/');
        }
        out.push_str(&comp.as_os_str().to_string_lossy());
    }
    out
}

/// Subsequence scorer with first-letter and boundary bonuses.
///
/// Returns `None` if `query` is not a subsequence of `path` (case-insensitive),
/// otherwise a positive score where higher is better.
///
/// Heuristics (kept deliberately small and predictable):
/// * +25 for each match that lands at the start of the path or right after a
///   boundary character (`/`, `_`, `-`, `.`, ` `).
/// * +10 if the very first character of the query matches the first character
///   of the path.
/// * +5 per consecutive match (rewards contiguous runs like typing "main" and
///   matching `main.rs`).
/// * Penalty proportional to the gap between consecutive matches keeps tightly
///   matched candidates above scattered ones.
pub fn score(query: &str, path: &str) -> Option<i32> {
    if query.is_empty() {
        return Some(0);
    }
    let q: Vec<char> = query.chars().flat_map(char::to_lowercase).collect();
    let p: Vec<char> = path.chars().flat_map(char::to_lowercase).collect();
    if q.len() > p.len() {
        return None;
    }

    let mut qi = 0usize;
    let mut score: i32 = 0;
    let mut last_match: Option<usize> = None;
    let mut consecutive = 0i32;

    for (i, ch) in p.iter().enumerate() {
        if qi >= q.len() {
            break;
        }
        if *ch == q[qi] {
            // Boundary / start bonus.
            if i == 0 {
                score += 25;
                if qi == 0 {
                    score += 10;
                }
            } else if matches!(p[i - 1], '/' | '_' | '-' | '.' | ' ') {
                score += 25;
            } else {
                score += 1;
            }

            // Consecutive bonus.
            if last_match == Some(i.saturating_sub(1)) {
                consecutive += 1;
                score += 5 * consecutive;
            } else {
                consecutive = 0;
            }

            // Gap penalty.
            if let Some(prev) = last_match {
                let gap = i - prev - 1;
                score -= gap as i32;
            }

            last_match = Some(i);
            qi += 1;
        }
    }

    if qi == q.len() { Some(score) } else { None }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::time::Duration;
    use tempfile::TempDir;

    #[test]
    fn score_subsequence_match() {
        // Identical query matches start with high bonus.
        let a = score("main", "main.rs").unwrap();
        let b = score("main", "src/very/deep/main.rs").unwrap();
        assert!(a > b, "a={a} b={b}");
    }

    #[test]
    fn score_rejects_non_subsequence() {
        assert!(score("zzz", "main.rs").is_none());
        assert!(score("xyz", "src/lib.rs").is_none());
    }

    #[test]
    fn score_boundary_bonus_beats_substring() {
        // "fp" matches the boundary letters in "file_picker.rs" but only the
        // first letter in "filepicker.rs" — so the boundary candidate should
        // win.
        let boundary = score("fp", "src/file_picker.rs").unwrap();
        let inline = score("fp", "src/filepicker.rs");
        // inline doesn't even contain 'p' immediately following 'f'? It does:
        // f-i-l-e-p-i-c-k-e-r — 'p' is preceded by 'e' (no boundary), so it
        // gets only the +1 path score, while boundary gets +25 for the 'p'
        // following the underscore.
        if let Some(inline_score) = inline {
            assert!(
                boundary > inline_score,
                "boundary={boundary} inline={inline_score}"
            );
        }
    }

    #[test]
    fn score_case_insensitive() {
        assert!(score("MAIN", "main.rs").is_some());
        assert!(score("main", "MAIN.RS").is_some());
    }

    #[test]
    fn score_empty_query_returns_zero() {
        assert_eq!(score("", "anything").unwrap(), 0);
    }

    #[test]
    fn picker_typing_narrows_candidates() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/main.rs"), "").unwrap();
        fs::write(root.join("src/lib.rs"), "").unwrap();
        fs::write(root.join("README.md"), "").unwrap();
        fs::write(root.join("Cargo.toml"), "").unwrap();

        let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default());
        // Empty query -> all 4 files visible.
        assert_eq!(view.visible_count(), 4, "expected all 4 candidates");

        // Typing "main" should narrow to just src/main.rs.
        for ch in "main".chars() {
            view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
        }
        assert_eq!(view.query(), "main");
        let visible = view.visible_count();
        assert_eq!(visible, 1, "expected exactly 1 match for 'main'");
        let selected = view.selected_for_test().expect("selected path");
        assert!(selected.ends_with("main.rs"), "selected = {selected}");
    }

    #[test]
    fn picker_empty_query_prioritizes_working_set_files() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/main.rs"), "").unwrap();
        fs::write(root.join("src/lib.rs"), "").unwrap();
        fs::write(root.join("README.md"), "").unwrap();

        let mut relevance = FilePickerRelevance::default();
        relevance.mark_modified("src/lib.rs");
        let view = FilePickerView::new_with_relevance(root, relevance);

        assert_eq!(view.selected_for_test(), Some("src/lib.rs"));
        assert_eq!(view.markers_for_test("src/lib.rs"), "M  ");
    }

    #[test]
    fn picker_fuzzy_query_keeps_working_set_boosts() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/alpha.rs"), "").unwrap();
        fs::write(root.join("src/zeta.rs"), "").unwrap();

        let mut relevance = FilePickerRelevance::default();
        relevance.mark_mentioned("src/zeta.rs");
        relevance.mark_tool("src/zeta.rs");
        let mut view = FilePickerView::new_with_relevance(root, relevance);
        for ch in "rs".chars() {
            view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
        }

        assert_eq!(view.selected_for_test(), Some("src/zeta.rs"));
        assert_eq!(view.markers_for_test("src/zeta.rs"), " @T");
    }

    #[test]
    fn picker_backspace_widens_candidates() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::write(root.join("a.txt"), "").unwrap();
        fs::write(root.join("b.txt"), "").unwrap();

        let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default());
        view.handle_key(KeyEvent::new(KeyCode::Char('a'), KeyModifiers::NONE));
        assert_eq!(view.visible_count(), 1);
        view.handle_key(KeyEvent::new(KeyCode::Backspace, KeyModifiers::NONE));
        assert_eq!(view.visible_count(), 2);
    }

    #[test]
    fn picker_enter_emits_event() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::write(root.join("only.txt"), "").unwrap();

        let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default());
        let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
        match action {
            ViewAction::EmitAndClose(ViewEvent::FilePickerSelected { path }) => {
                assert!(path.ends_with("only.txt"));
            }
            other => panic!("expected EmitAndClose(FilePickerSelected), got {other:?}"),
        }
    }

    #[test]
    fn picker_esc_closes_without_emit() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::write(root.join("only.txt"), "").unwrap();

        let mut view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default());
        let action = view.handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
        assert!(matches!(action, ViewAction::Close));
    }

    #[test]
    fn picker_honors_gitignore() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        // .gitignore filtering only kicks in inside a git repo or with an
        // explicit `.ignore` file. Use `.ignore` which `WalkBuilder` honors
        // even outside of git.
        fs::write(root.join(".ignore"), "skipme.txt\n").unwrap();
        fs::write(root.join("keepme.txt"), "").unwrap();
        fs::write(root.join("skipme.txt"), "").unwrap();

        let view = FilePickerView::new_with_relevance(root, FilePickerRelevance::default());
        let visible: Vec<_> = view
            .filtered
            .iter()
            .map(|i| view.candidates[*i].as_str())
            .collect();
        assert!(visible.iter().any(|p| p.ends_with("keepme.txt")));
        assert!(
            !visible.iter().any(|p| p.ends_with("skipme.txt")),
            "skipme.txt should be filtered by .ignore: {visible:?}"
        );
    }

    #[test]
    fn picker_finds_deeply_nested_files_within_walk_depth() {
        // #2488: a file inside a 6-level-deep directory sits at component depth
        // 7 and was excluded by the old depth-6 cap. The default depth (10) now
        // reaches it, and `0` (unlimited) reaches arbitrarily deep files.
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        let nested = root.join("a/b/c/d/e/f");
        fs::create_dir_all(&nested).unwrap();
        fs::write(nested.join("deep.rs"), "deep").unwrap();
        let deeper = root.join("a/b/c/d/e/f/g/h/i/j/k");
        fs::create_dir_all(&deeper).unwrap();
        fs::write(deeper.join("very_deep.rs"), "deeper").unwrap();

        // The old default (6) misses the depth-7 file — the reported bug.
        let shallow = collect_candidates(root, Some(6));
        assert!(
            !shallow.iter().any(|p| p == "a/b/c/d/e/f/deep.rs"),
            "depth-6 cap should miss the depth-7 file: {shallow:?}"
        );

        // The new default reaches files inside a 6-level-deep directory.
        let default = collect_candidates(root, Some(WALK_DEPTH));
        assert!(
            default.iter().any(|p| p == "a/b/c/d/e/f/deep.rs"),
            "default walk depth should reach depth-7 files: {default:?}"
        );

        // Unlimited (mention_walk_depth = 0) reaches arbitrarily deep files.
        let unlimited = collect_candidates(root, None);
        assert!(
            unlimited
                .iter()
                .any(|p| p == "a/b/c/d/e/f/g/h/i/j/k/very_deep.rs"),
            "unlimited walk should reach very deep files: {unlimited:?}"
        );
    }

    #[test]
    fn picker_skips_generated_worktree_bulk_inside_unignored_dot_dirs() {
        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/main.rs"), "fn main() {}").unwrap();

        fs::create_dir_all(root.join(".deepseek/commands")).unwrap();
        fs::write(root.join(".deepseek/commands/build.md"), "build").unwrap();
        fs::create_dir_all(root.join(".deepseek/snapshots/deadbeef/.git/objects")).unwrap();
        fs::write(
            root.join(".deepseek/snapshots/deadbeef/.git/objects/snapshot.pack"),
            "pack",
        )
        .unwrap();

        fs::create_dir_all(root.join(".claude/commands")).unwrap();
        fs::write(root.join(".claude/commands/test.md"), "test").unwrap();
        fs::create_dir_all(root.join(".claude/worktrees/agent/src")).unwrap();
        fs::write(
            root.join(".claude/worktrees/agent/src/agent-only.md"),
            "agent",
        )
        .unwrap();

        let candidates = collect_candidates(root, Some(WALK_DEPTH));

        assert!(candidates.iter().any(|path| path == "src/main.rs"));
        assert!(
            candidates
                .iter()
                .any(|path| path == ".deepseek/commands/build.md"),
            "normal .deepseek command files should stay discoverable: {candidates:?}",
        );
        assert!(
            candidates
                .iter()
                .any(|path| path == ".claude/commands/test.md"),
            "normal .claude command files should stay discoverable: {candidates:?}",
        );
        assert!(
            candidates
                .iter()
                .all(|path| !path.starts_with(".deepseek/snapshots/")),
            "snapshot side repo files must not enter picker candidates: {candidates:?}",
        );
        assert!(
            candidates
                .iter()
                .all(|path| !path.starts_with(".claude/worktrees/")),
            ".claude worktree files must not enter picker candidates: {candidates:?}",
        );
    }

    /// The four terminal sizes the v0.8.66 modal blocker (#3732) requires
    /// every overlay to remain readable and fully operable at.
    const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)];

    #[test]
    fn file_picker_is_usable_and_opaque_at_blocker_sizes() {
        use crate::tui::views::ViewStack;
        use ratatui::{buffer::Buffer, layout::Rect};
        use unicode_width::UnicodeWidthStr;

        let dir = TempDir::new().expect("tempdir");
        let root = dir.path();
        fs::create_dir_all(root.join("src")).unwrap();
        fs::write(root.join("src/main.rs"), "").unwrap();
        fs::write(root.join("src/lib.rs"), "").unwrap();
        fs::write(root.join("README.md"), "").unwrap();

        for (w, h) in BLOCKER_SIZES {
            let area = Rect::new(0, 0, w, h);
            let mut buf = Buffer::empty(area);
            for y in 0..h {
                for x in 0..w {
                    buf[(x, y)].set_symbol("X");
                }
            }
            let mut stack = ViewStack::new();
            stack.push(FilePickerView::new_with_relevance(
                root,
                FilePickerRelevance::default(),
            ));
            stack.render(area, &mut buf);

            let rows: Vec<String> = (0..h)
                .map(|y| {
                    (0..w)
                        .map(|x| buf[(x, y)].symbol().to_string())
                        .collect::<String>()
                })
                .collect();
            let text = rows.join("\n");

            for label in ["move", "insert @path", "cancel"] {
                assert!(text.contains(label), "{w}x{h}: missing footer '{label}'");
            }
            assert!(
                !text.contains('X'),
                "{w}x{h}: background bleed-through into modal surface"
            );
            assert_eq!(
                buf[(w / 2, h / 2)].bg,
                palette::WHALE_BG,
                "{w}x{h}: modal interior must be opaque"
            );
            for (y, row) in rows.iter().enumerate() {
                assert!(
                    UnicodeWidthStr::width(row.trim_end()) <= w as usize,
                    "{w}x{h}: row {y} overflows width: {row:?}"
                );
            }
        }
    }

    /// #3905: opening the picker used to block the event loop on a `git status`
    /// subprocess plus a walk of up to MAX_CANDIDATES paths, freezing the whole
    /// TUI between Ctrl+P and the picker appearing.
    ///
    /// Asserting "fast" by wall clock would be a flaky proxy for the real
    /// contract, so this asserts the structural property instead: inside a
    /// runtime the constructor returns a paintable view that has not yet done
    /// the scan, and the results arrive later through `tick`.
    #[tokio::test]
    async fn opening_the_picker_does_not_block_on_the_workspace_scan() {
        let ws = TempDir::new().unwrap();
        fs::create_dir_all(ws.path().join("src")).unwrap();
        for i in 0..200 {
            fs::write(ws.path().join("src").join(format!("f{i}.rs")), "x").unwrap();
        }

        let mut view = FilePickerView::new_with_relevance_and_depth(
            ws.path(),
            FilePickerRelevance::default(),
            WALK_DEPTH,
            Locale::En,
        );

        assert!(
            view.is_loading,
            "the constructor must hand back a paintable view, not a finished scan"
        );
        assert!(
            view.candidates.is_empty(),
            "no walk may have run on the calling thread"
        );

        // The view is renderable in the loading state — this is the frame the
        // user sees immediately after Ctrl+P.
        let area = Rect::new(0, 0, 60, 20);
        let mut buf = Buffer::empty(area);
        view.render(area, &mut buf);

        for _ in 0..500 {
            view.tick();
            if !view.is_loading {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }

        assert!(!view.is_loading, "the background scan must land via tick");
        assert_eq!(
            view.candidates.len(),
            200,
            "every workspace file is discovered once the scan lands"
        );
        assert_eq!(
            view.filtered.len(),
            200,
            "results are refiltered after the scan, not left empty"
        );
    }

    /// A query typed while the scan was still running must survive it.
    #[tokio::test]
    async fn a_query_typed_during_the_scan_is_applied_when_results_land() {
        let ws = TempDir::new().unwrap();
        fs::write(ws.path().join("alpha.rs"), "x").unwrap();
        fs::write(ws.path().join("beta.rs"), "x").unwrap();

        let mut view = FilePickerView::new_with_relevance_and_depth(
            ws.path(),
            FilePickerRelevance::default(),
            WALK_DEPTH,
            Locale::En,
        );
        assert!(view.is_loading);

        for ch in "alpha".chars() {
            view.handle_key(KeyEvent::new(KeyCode::Char(ch), KeyModifiers::NONE));
        }

        for _ in 0..500 {
            view.tick();
            if !view.is_loading {
                break;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }

        assert!(!view.is_loading);
        assert_eq!(view.query, "alpha");
        let matched: Vec<&str> = view
            .filtered
            .iter()
            .map(|i| view.candidates[*i].as_str())
            .collect();
        assert_eq!(
            matched,
            vec!["alpha.rs"],
            "the scan must refilter against the query the user already typed"
        );
    }
}