rab-agent 0.1.7

rab is a lightweight, extensible, Rust-based coding agent.
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
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
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
use std::path::Path;
use std::process::{Command, Stdio};
use std::sync::Arc;

use crate::tui::components::select_list::SelectItem;

/// A suggestion item for autocomplete.
#[derive(Debug, Clone)]
pub struct AutocompleteItem {
    pub value: String,
    pub label: String,
    pub description: Option<String>,
}

impl From<AutocompleteItem> for SelectItem {
    fn from(item: AutocompleteItem) -> Self {
        let mut si = SelectItem::new(item.value, item.label);
        if let Some(desc) = item.description {
            si = si.with_description(desc);
        }
        si
    }
}

/// Suggestions returned by an autocomplete provider.
#[derive(Debug, Clone)]
pub struct AutocompleteSuggestions {
    pub items: Vec<AutocompleteItem>,
    /// The prefix that was matched (e.g., "/" or "src/").
    pub prefix: String,
}

/// A slash command definition.
#[derive(Clone)]
#[allow(clippy::type_complexity)]
pub struct SlashCommand {
    pub name: String,
    pub description: Option<String>,
    pub argument_hint: Option<String>,
    /// Static argument completions (pi-compat: `getArgumentCompletions`).
    /// When set, these are filtered by the typed prefix and shown.
    /// When None and `get_argument_completions` is also None, file completion is used.
    pub argument_completions: Option<Vec<AutocompleteItem>>,
    /// Dynamic argument completions callback (pi-style `getArgumentCompletions`).
    /// Called with the typed argument prefix, returns matching items.
    /// Takes precedence over `argument_completions` when set.
    pub get_argument_completions: Option<Arc<dyn Fn(&str) -> Vec<AutocompleteItem> + Send + Sync>>,
}

/// Provider that generates autocomplete suggestions.
pub trait AutocompleteProvider {
    /// Characters that should naturally trigger this provider at token boundaries.
    fn trigger_characters(&self) -> &[char];

    /// Get suggestions for the current text/cursor position.
    /// Returns None if no suggestions available.
    fn get_suggestions(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
        force: bool,
    ) -> Option<AutocompleteSuggestions>;

    /// Apply the selected completion item.
    fn apply_completion(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
        item: &AutocompleteItem,
        prefix: &str,
    ) -> (Vec<String>, usize, usize);

    /// Whether to trigger file completion on Tab.
    fn should_trigger_file_completion(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
    ) -> bool;
}

// ── fd helpers (pi-compat) ───────────────────────────────────────────

/// Find the `fd` binary in PATH.
fn find_fd() -> Option<String> {
    std::env::var("PATH").ok().and_then(|path| {
        for dir in path.split(':') {
            for name in &["fd", "fdfind"] {
                let p = format!("{}/{}", dir, name);
                if std::path::Path::new(&p).is_file() {
                    return Some(p);
                }
            }
        }
        None
    })
}

/// Build the fd query from a user-typed path prefix (matches pi's buildFdPathQuery).
fn build_fd_path_query(query: &str) -> String {
    let normalized = query.replace('\\', "/");
    if !normalized.contains('/') {
        return normalized;
    }
    let has_trailing = normalized.ends_with('/');
    let trimmed = normalized.trim_matches('/');
    if trimmed.is_empty() {
        return normalized;
    }
    let sep = "[\\\\/]";
    let segments: Vec<&str> = trimmed.split('/').filter(|s| !s.is_empty()).collect();
    let mut pattern = segments
        .iter()
        .map(|s| regex::escape(s))
        .collect::<Vec<_>>()
        .join(sep);
    if has_trailing {
        pattern.push_str(sep);
    }
    pattern
}

/// Walk directory tree with `fd` (fast, respects .gitignore).
/// Mirrors pi's walkDirectoryWithFd().
fn walk_directory_with_fd(
    fd_path: &str,
    base_dir: &str,
    query: &str,
    max_results: usize,
) -> Vec<(String, bool)> {
    let mr = max_results.to_string();
    let mut cmd = Command::new(fd_path);
    cmd.arg("--base-directory")
        .arg(base_dir)
        .arg("--max-results")
        .arg(&mr)
        .arg("--type")
        .arg("f")
        .arg("--type")
        .arg("d")
        .arg("--follow")
        .arg("--hidden")
        .arg("--exclude")
        .arg(".git")
        .arg("--exclude")
        .arg(".git/*")
        .arg("--exclude")
        .arg(".git/**");

    if query.contains('/') {
        cmd.arg("--full-path");
    }

    if !query.is_empty() {
        cmd.arg(build_fd_path_query(query));
    }

    cmd.stdout(Stdio::piped()).stderr(Stdio::null());

    let output = match cmd.output() {
        Ok(o) => o,
        Err(_) => return Vec::new(),
    };

    if !output.status.success() {
        return Vec::new();
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    stdout
        .lines()
        .filter(|line| !line.is_empty())
        .filter_map(|line| {
            let display = line.replace('\\', "/");
            if display == ".git" || display.starts_with(".git/") || display.contains("/.git/") {
                return None;
            }
            let has_trailing = display.ends_with('/');
            let normalized = if has_trailing {
                &display[..display.len() - 1]
            } else {
                &display
            };
            Some((normalized.to_string(), has_trailing))
        })
        .collect()
}

/// Score an entry against the query (higher = better match).
/// Directories get a bonus to appear first.
fn score_entry(file_path: &str, query: &str, is_directory: bool) -> usize {
    let file_name = Path::new(file_path)
        .file_name()
        .map(|f| f.to_string_lossy().to_string())
        .unwrap_or_default();
    let lower_name = file_name.to_lowercase();
    let lower_query = query.to_lowercase();

    let mut score: usize = 0;
    if lower_name == lower_query {
        score = 100;
    } else if lower_name.starts_with(&lower_query) {
        score = 80;
    } else if lower_name.contains(&lower_query) {
        score = 50;
    } else if file_path.to_lowercase().contains(&lower_query) {
        score = 30;
    }
    if is_directory && score > 0 {
        score += 10;
    }
    score
}

// ── Quoted prefix helpers (pi-compat) ─────────────────────────────────

const PATH_DELIMITERS: &[char] = &[' ', '\t', '"', '\'', '='];

/// Find an unclosed `"` or `@"` start in the text before cursor.
/// Returns the start index and the prefix slice (including @ if present).
fn find_unclosed_quote_prefix(text: &str) -> Option<(usize, &str)> {
    let mut in_quotes = false;
    let mut quote_start = 0;
    for (i, c) in text.char_indices() {
        if c == '"' {
            in_quotes = !in_quotes;
            if in_quotes {
                quote_start = i;
            }
        }
    }
    if !in_quotes {
        return None;
    }
    // Check for @" prefix
    if quote_start > 0 && text.as_bytes().get(quote_start - 1) == Some(&b'@') {
        let before_at = if quote_start > 1 {
            &text[..quote_start - 1]
        } else {
            ""
        };
        if before_at.is_empty() || before_at.ends_with(PATH_DELIMITERS) {
            return Some((quote_start - 1, &text[quote_start - 1..]));
        }
    }
    // Check for plain " prefix (token boundary)
    let before = &text[..quote_start];
    if before.is_empty() || before.ends_with(PATH_DELIMITERS) {
        return Some((quote_start, &text[quote_start..]));
    }
    None
}

/// Parse a prefix (possibly with @ or "@) into its components.
/// Returns (stripped_query, is_at_prefix, is_quoted).
fn parse_completion_prefix(prefix: &str) -> (&str, bool, bool) {
    if let Some(stripped) = prefix.strip_prefix("@\"") {
        (stripped, true, true)
    } else if let Some(stripped) = prefix.strip_prefix('"') {
        (stripped, false, true)
    } else if let Some(stripped) = prefix.strip_prefix('@') {
        (stripped, true, false)
    } else {
        (prefix, false, false)
    }
}

/// Resolve a scoped fd query: split `src/au` into base_dir=`CWD/src/` and query=`au`.
fn resolve_scoped_fd_query(raw_query: &str, base_path: &str) -> Option<(String, String, String)> {
    let normalized = raw_query.replace('\\', "/");
    let slash_index = normalized.rfind('/')?;
    let display_base = normalized[..=slash_index].to_string();
    let query = normalized[slash_index + 1..].to_string();

    let base_dir = if let Some(stripped) = display_base.strip_prefix("~/") {
        let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
        format!("{}/{}", home, stripped)
    } else if display_base.starts_with('/') {
        display_base.clone()
    } else {
        format!("{}/{}", base_path, display_base)
    };

    if !Path::new(&base_dir).is_dir() {
        return None;
    }

    Some((base_dir, query, display_base))
}

// =============================================================================
// CombinedAutocompleteProvider - handles slash commands + file paths
// =============================================================================

/// Combined provider that handles slash commands and file path completion.
pub struct CombinedAutocompleteProvider {
    slash_commands: Vec<SlashCommand>,
    base_path: String,
    fd_path: Option<String>,
}

impl CombinedAutocompleteProvider {
    pub fn new(slash_commands: Vec<SlashCommand>, base_path: String) -> Self {
        let fd_path = find_fd();
        Self {
            slash_commands,
            base_path,
            fd_path,
        }
    }

    fn get_slash_suggestions(&self, prefix: &str) -> Option<AutocompleteSuggestions> {
        let lower_prefix = prefix.to_lowercase();
        let matching: Vec<AutocompleteItem> = self
            .slash_commands
            .iter()
            .filter(|cmd| cmd.name.to_lowercase().starts_with(&lower_prefix))
            .map(|cmd| {
                let desc = match (&cmd.description, &cmd.argument_hint) {
                    (Some(d), Some(h)) => Some(format!("{} - {}", h, d)),
                    (Some(d), None) => Some(d.clone()),
                    (None, Some(h)) => Some(h.clone()),
                    (None, None) => None,
                };
                AutocompleteItem {
                    value: cmd.name.clone(),
                    label: format!("/{}", cmd.name),
                    description: desc,
                }
            })
            .collect();

        if matching.is_empty() {
            return None;
        }
        Some(AutocompleteSuggestions {
            items: matching,
            prefix: format!("/{}", prefix),
        })
    }

    /// Fuzzy file search using `fd` (fast, respects .gitignore).
    /// Matches pi's getFuzzyFileSuggestions().
    fn get_fuzzy_file_suggestions(&self, query: &str) -> Option<AutocompleteSuggestions> {
        let fd_path = self.fd_path.as_ref()?;

        let (fd_base_dir, fd_query, display_base) = resolve_scoped_fd_query(query, &self.base_path)
            .unwrap_or_else(|| {
                // No scope - search from base_path with the full query
                (self.base_path.clone(), query.to_string(), String::new())
            });

        let entries = walk_directory_with_fd(fd_path, &fd_base_dir, &fd_query, 100);
        if entries.is_empty() {
            return None;
        }

        let scored: Vec<(String, bool, usize)> = entries
            .into_iter()
            .map(|(path, is_dir)| {
                let score = if fd_query.is_empty() {
                    1
                } else {
                    score_entry(&path, &fd_query, is_dir)
                };
                (path, is_dir, score)
            })
            .filter(|(_, _, score)| *score > 0)
            .collect();

        if scored.is_empty() {
            return None;
        }

        // Sort by score descending, then take top 20
        let mut scored = scored;
        scored.sort_by_key(|b| std::cmp::Reverse(b.2));
        scored.truncate(20);

        let items: Vec<AutocompleteItem> = scored
            .into_iter()
            .map(|(entry_path, is_dir, _score)| {
                let entry_name = Path::new(&entry_path)
                    .file_name()
                    .map(|f| f.to_string_lossy().to_string())
                    .unwrap_or_default();
                let display_path = if display_base.is_empty() {
                    entry_path.clone()
                } else {
                    format!("{}{}", display_base, entry_path)
                };
                let completion_path = if is_dir {
                    format!("{}/", display_path)
                } else {
                    display_path.clone()
                };
                AutocompleteItem {
                    value: completion_path,
                    label: format!("{}/", entry_name),
                    description: Some(display_path),
                }
            })
            .collect();

        Some(AutocompleteSuggestions {
            items,
            prefix: query.to_string(),
        })
    }

    fn get_file_suggestions(&self, prefix: &str) -> Option<AutocompleteSuggestions> {
        // Determine search directory and file prefix
        let expanded = if let Some(stripped) = prefix.strip_prefix("~/") {
            let home = std::env::var("HOME").unwrap_or_else(|_| "/tmp".into());
            format!("{}/{}", home, stripped)
        } else if prefix == "~" {
            std::env::var("HOME").unwrap_or_else(|_| "/tmp".into())
        } else if prefix.starts_with('/') {
            prefix.to_string()
        } else {
            format!("{}/{}", self.base_path, prefix)
        };

        let expanded_clone = expanded.clone();
        let (dir, file_prefix) = if expanded.ends_with('/') {
            (expanded_clone, String::new())
        } else {
            let p = Path::new(&expanded);
            let parent = p
                .parent()
                .map(|p| p.to_string_lossy().to_string())
                .unwrap_or("/".into());
            let file = p
                .file_name()
                .map(|f| f.to_string_lossy().to_string())
                .unwrap_or_default();
            (
                if parent.is_empty() {
                    "/".into()
                } else {
                    parent
                },
                file,
            )
        };

        let dir_path = Path::new(&dir);
        if !dir_path.exists() || !dir_path.is_dir() {
            return None;
        }

        let lower_prefix = file_prefix.to_lowercase();
        let mut items: Vec<AutocompleteItem> = Vec::new();

        if let Ok(entries) = std::fs::read_dir(dir_path) {
            for entry in entries.flatten() {
                let name = entry.file_name().to_string_lossy().to_string();
                if name == ".git" || (name.starts_with('.') && !file_prefix.starts_with('.')) {
                    continue;
                }
                if !name.to_lowercase().starts_with(&lower_prefix) {
                    continue;
                }
                let is_dir = entry.file_type().map(|t| t.is_dir()).unwrap_or(false);
                let suffix = if is_dir { "/" } else { "" };

                let display = if prefix.starts_with('/') {
                    let base_dir = dir.clone();
                    if base_dir.ends_with('/') {
                        format!("{}{}{}", base_dir, name, suffix)
                    } else {
                        format!("{}/{}{}", base_dir, name, suffix)
                    }
                } else if let Some(rel_part) = prefix.strip_prefix("~/") {
                    // When rel_part has a trailing slash (e.g., ".rab/agent/"),
                    // use it directly as the base to preserve the last folder.
                    // Path::new().parent() would strip it (e.g., ".rab/agent/" → ".rab").
                    let base = if rel_part.ends_with('/') {
                        format!("~/{}", rel_part)
                    } else {
                        let parent_path = Path::new(rel_part)
                            .parent()
                            .map(|p| p.to_string_lossy().to_string())
                            .unwrap_or_default();
                        if rel_part.is_empty() || parent_path.is_empty() || parent_path == "." {
                            "~/".to_string()
                        } else {
                            format!("~/{}/", parent_path)
                        }
                    };
                    format!("{}{}{}", base, name, suffix)
                } else if prefix == "~" {
                    format!("~/{}{}", name, suffix)
                } else if prefix.ends_with('/') {
                    format!("{}{}{}", prefix, name, suffix)
                } else if prefix.contains('/') {
                    let p = Path::new(prefix);
                    let parent = p
                        .parent()
                        .map(|p| p.to_string_lossy().to_string())
                        .unwrap_or_default();
                    let base = if parent.is_empty() || parent == "." {
                        String::new()
                    } else {
                        format!("{}/", parent)
                    };
                    if prefix.starts_with("./") && !base.starts_with("./") {
                        format!("./{}{}{}", base, name, suffix)
                    } else {
                        format!("{}{}{}", base, name, suffix)
                    }
                } else {
                    format!("{}{}", name, suffix)
                };

                items.push(AutocompleteItem {
                    value: display,
                    label: format!("{}{}", name, suffix),
                    description: None,
                });
            }
        }

        items.sort_by(|a, b| {
            let a_is_dir = a.value.ends_with('/');
            let b_is_dir = b.value.ends_with('/');
            if a_is_dir && !b_is_dir {
                std::cmp::Ordering::Less
            } else if !a_is_dir && b_is_dir {
                std::cmp::Ordering::Greater
            } else {
                a.label.to_lowercase().cmp(&b.label.to_lowercase())
            }
        });

        if items.is_empty() {
            return None;
        }
        Some(AutocompleteSuggestions {
            items,
            prefix: prefix.to_string(),
        })
    }
}

impl AutocompleteProvider for CombinedAutocompleteProvider {
    fn trigger_characters(&self) -> &[char] {
        &['/', '@', '#']
    }

    fn get_suggestions(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
        force: bool,
    ) -> Option<AutocompleteSuggestions> {
        let current_line = lines.get(cursor_line)?;
        let text_before = &current_line[..cursor_col.min(current_line.len())];

        // ── Slash command completion ──
        if text_before.starts_with('/') && !text_before.contains(' ') {
            let cmd = &text_before[1..];
            if let Some(suggestions) = self.get_slash_suggestions(cmd) {
                return Some(suggestions);
            }
            // No slash command match – fall through to file completion for absolute paths like /tmp
        }

        // ── Slash command argument completion ──
        if let Some(space_pos) = text_before.find(' ') {
            if space_pos == 0 {
                return None;
            }
            let cmd_name = &text_before[1..space_pos];
            let arg_text = &text_before[space_pos + 1..];
            for cmd in &self.slash_commands {
                if cmd.name == cmd_name {
                    // Check for dynamic argument completions callback (pi-style)
                    if let Some(ref get_completions) = cmd.get_argument_completions {
                        let items = get_completions(arg_text);
                        if !items.is_empty() {
                            return Some(AutocompleteSuggestions {
                                items,
                                prefix: arg_text.to_string(),
                            });
                        }
                    }
                    // Check for static argument completions (pi-compat)
                    if let Some(ref completions) = cmd.argument_completions {
                        let lower = arg_text.to_lowercase();
                        let filtered: Vec<AutocompleteItem> = completions
                            .iter()
                            .filter(|c| c.value.to_lowercase().starts_with(&lower))
                            .cloned()
                            .collect();
                        if !filtered.is_empty() {
                            return Some(AutocompleteSuggestions {
                                items: filtered,
                                prefix: arg_text.to_string(),
                            });
                        }
                    }
                    // Fall back to file path completion
                    if force
                        || arg_text.contains('/')
                        || arg_text.contains('.')
                        || arg_text.is_empty()
                    {
                        return self.get_file_suggestions(arg_text);
                    }
                    return None;
                }
            }
        }

        // ── Quoted prefix (@""" or """ for paths with spaces, pi-style) ──
        if let Some((_start, full_prefix)) = find_unclosed_quote_prefix(text_before) {
            let (query, _is_at, _is_quoted) = parse_completion_prefix(full_prefix);
            // Use fd for simple queries (no /) to find files anywhere
            if !query.contains('/')
                && !query.contains('.')
                && self.fd_path.is_some()
                && !query.is_empty()
                && let Some(suggestions) = self.get_fuzzy_file_suggestions(query)
            {
                return Some(suggestions);
            }
            return self.get_file_suggestions(query);
        }

        // ── @ and # file/attachment completion ──
        if let Some(pos) = text_before.rfind(['@', '#']) {
            let is_token_start =
                pos == 0 || text_before[..pos].ends_with(' ') || text_before[..pos].ends_with('\t');
            if is_token_start {
                let path = &text_before[pos + 1..];
                // If path doesn't contain / and fd is available, use fd for project-wide search
                if !path.contains('/')
                    && self.fd_path.is_some()
                    && !path.is_empty()
                    && let Some(suggestions) = self.get_fuzzy_file_suggestions(path)
                {
                    return Some(suggestions);
                }
                return self.get_file_suggestions(path);
            }
        }

        // ── ~ path completion (tilde expansion) ──
        if let Some(pos) = text_before.rfind('~') {
            let is_token_start =
                pos == 0 || text_before[..pos].ends_with(' ') || text_before[..pos].ends_with('\t');
            if is_token_start {
                let path = &text_before[pos..];
                return self.get_file_suggestions(path);
            }
        }

        // ── Absolute path completion (/) – automatic (non-force) fallback for paths
        //     that didn't match any slash command ──
        if text_before.starts_with('/') && !text_before.contains(' ') && text_before.len() > 1 {
            return self.get_file_suggestions(text_before);
        }

        // ── Forced completion (Tab) ──
        if force && self.should_trigger_file_completion(lines, cursor_line, cursor_col) {
            let last_space = text_before.rfind(|c: char| c.is_whitespace());
            let token = if let Some(pos) = last_space {
                &text_before[pos + 1..]
            } else {
                text_before
            };
            if !token.is_empty() {
                return self.get_file_suggestions(token);
            }
        }

        None
    }

    fn apply_completion(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
        item: &AutocompleteItem,
        prefix: &str,
    ) -> (Vec<String>, usize, usize) {
        let current_line = lines[cursor_line].clone();
        let prefix_start = cursor_col.saturating_sub(prefix.len());
        let before = &current_line[..prefix_start];
        let after = &current_line[cursor_col..];

        // Determine if this is a slash command completion or a file path completion.
        // Slash commands have item.value = "help" (no leading /, ~, or . path chars).
        // File paths have item.value = "/tmp/", "~/.rab/agent/", or "src/main.rs".
        let is_slash_command = prefix.starts_with('/')
            && !item.value.starts_with('/')
            && !item.value.starts_with('~')
            && !item.value.starts_with('.');

        let (new_line, new_col) = if is_slash_command {
            // Slash command: insert with trailing space
            (
                format!("{}/{} {}", before, item.value, after),
                before.len() + 1 + item.value.len() + 1,
            )
        } else {
            // File path: use the item value directly (it's already built by the provider)
            let item_val = &item.value;
            let suffix = if item_val.ends_with('/') { "" } else { " " };
            (
                format!("{}{}{}{}", before, item_val, suffix, after),
                before.len() + item_val.len() + suffix.len(),
            )
        };

        let mut new_lines = lines.to_vec();
        new_lines[cursor_line] = new_line;
        (new_lines, cursor_line, new_col)
    }

    fn should_trigger_file_completion(
        &self,
        lines: &[String],
        cursor_line: usize,
        cursor_col: usize,
    ) -> bool {
        let current_line = lines
            .get(cursor_line)
            .map(|l| &l[..cursor_col.min(l.len())]);
        match current_line {
            Some(text) => {
                // Only block Tab completion for known slash commands on line 0.
                // Absolute paths like /usr/share/ should still get file completion.
                if text.starts_with('/') && !text.contains(' ') && cursor_line == 0 {
                    let cmd_input = text[1..].trim();
                    if cmd_input.is_empty() {
                        // Just "/" — don't trigger file completion yet
                        return false;
                    }
                    // If text matches a known slash command, don't trigger file completion
                    if self
                        .slash_commands
                        .iter()
                        .any(|c| c.name.starts_with(cmd_input))
                    {
                        return false;
                    }
                    // Otherwise it's an absolute path — allow file completion
                }
                true
            }
            None => false,
        }
    }
}

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

    fn build_completion_value(
        path: &str,
        is_directory: bool,
        is_at_prefix: bool,
        is_quoted_prefix: bool,
    ) -> String {
        let needs_quotes = is_quoted_prefix || path.contains(' ');
        let at = if is_at_prefix { "@" } else { "" };
        let suffix = if is_directory { "/" } else { "" };
        if needs_quotes {
            format!("{}\"{}{}\"", at, path, suffix)
        } else {
            format!("{}{}{}", at, path, suffix)
        }
    }

    #[test]
    fn test_slash_suggestions() {
        let provider = CombinedAutocompleteProvider::new(
            vec![
                SlashCommand {
                    name: "help".into(),
                    description: Some("Show help".into()),
                    argument_hint: None,
                    argument_completions: None,
                    get_argument_completions: None,
                },
                SlashCommand {
                    name: "history".into(),
                    description: Some("Show history".into()),
                    argument_hint: None,
                    argument_completions: None,
                    get_argument_completions: None,
                },
            ],
            "/tmp".into(),
        );

        let lines = vec!["/he".into()];
        let result = provider.get_suggestions(&lines, 0, 3, false);
        assert!(result.is_some());
        let suggestions = result.unwrap();
        assert_eq!(suggestions.items.len(), 1);
        assert_eq!(suggestions.items[0].value, "help");
    }

    #[test]
    fn test_no_slash_matches() {
        let provider = CombinedAutocompleteProvider::new(
            vec![SlashCommand {
                name: "help".into(),
                description: None,
                argument_hint: None,
                argument_completions: None,
                get_argument_completions: None,
            }],
            "/tmp".into(),
        );

        let lines = vec!["/unknown".into()];
        let result = provider.get_suggestions(&lines, 0, 8, false);
        assert!(result.is_none());
    }

    #[test]
    fn test_trigger_characters() {
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        assert_eq!(provider.trigger_characters(), &['/', '@', '#']);
    }

    #[test]
    fn test_apply_completion_slash() {
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        let item = AutocompleteItem {
            value: "help".into(),
            label: "/help".into(),
            description: None,
        };
        let lines = vec!["/".into()];
        let (new_lines, new_line, new_col) = provider.apply_completion(&lines, 0, 1, &item, "/");
        assert_eq!(new_lines[0], "/help ");
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 6);
    }

    #[test]
    fn test_find_unclosed_quote_prefix_basic() {
        assert!(find_unclosed_quote_prefix("hello \"world").is_some());
        assert!(find_unclosed_quote_prefix("hello \"world\"").is_none());
        assert!(find_unclosed_quote_prefix("no quotes").is_none());
    }

    #[test]
    fn test_find_unclosed_quote_prefix_at() {
        let result = find_unclosed_quote_prefix("hello @\"path");
        assert!(result.is_some());
        let (_start, prefix) = result.unwrap();
        assert_eq!(&prefix[..1], "@");
    }

    #[test]
    fn test_parse_completion_prefix() {
        let (q, at, quoted) = parse_completion_prefix("@\"path");
        assert_eq!(q, "path");
        assert!(at);
        assert!(quoted);

        let (q, at, quoted) = parse_completion_prefix("\"path");
        assert_eq!(q, "path");
        assert!(!at);
        assert!(quoted);

        let (q, at, quoted) = parse_completion_prefix("@path");
        assert_eq!(q, "path");
        assert!(at);
        assert!(!quoted);

        let (q, at, quoted) = parse_completion_prefix("path");
        assert_eq!(q, "path");
        assert!(!at);
        assert!(!quoted);
    }

    #[test]
    fn test_build_completion_value() {
        let v = build_completion_value("foo.rs", false, true, false);
        assert_eq!(v, "@foo.rs");

        let v = build_completion_value("foo.rs", false, false, false);
        assert_eq!(v, "foo.rs");

        let v = build_completion_value("my dir/file.rs", false, true, false);
        assert_eq!(v, "@\"my dir/file.rs\"");
    }

    #[test]
    fn test_is_empty_items_on_empty_dir() {
        let tmp = std::env::temp_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], tmp.to_string_lossy().to_string());
        let result = provider.get_file_suggestions("");
        assert!(result.is_some(), "Should find files in temp dir");
    }

    #[test]
    fn test_build_fd_path_query() {
        assert_eq!(build_fd_path_query("hello"), "hello");
        assert_eq!(build_fd_path_query("src/main.rs"), "src[\\\\/]main\\.rs");
        assert!(build_fd_path_query("src/").ends_with("[\\\\/]"));
    }

    #[test]
    fn test_score_entry() {
        let s = score_entry("src/main.rs", "main", false);
        assert!(s > 0, "Should score positive for matching name");
        let s = score_entry("src/main.rs", "nomatch", false);
        assert_eq!(s, 0, "Should score zero for no match");
    }

    // ── Tests for fixed bugs ──

    #[test]
    fn test_apply_completion_absolute_path_no_double_slash() {
        // Bug 1: completing / → tmp/ should give /tmp/ not //tmp/
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        // Absolute path file completion (item.value starts with /)
        let item = AutocompleteItem {
            value: "/tmp/".into(),
            label: "tmp/".into(),
            description: None,
        };
        let lines = vec!["/".into()];
        let (new_lines, _new_line, _new_col) = provider.apply_completion(&lines, 0, 1, &item, "/");
        // Should NOT produce //tmp/
        assert_eq!(
            new_lines[0], "/tmp/",
            "Absolute path completion must not add extra slash"
        );
    }

    #[test]
    fn test_apply_completion_slash_command_still_works() {
        // Slash commands should still produce /cmd (with one slash)
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        let item = AutocompleteItem {
            value: "help".into(),
            label: "/help".into(),
            description: None,
        };
        let lines = vec!["/".into()];
        let (new_lines, _new_line, new_col) = provider.apply_completion(&lines, 0, 1, &item, "/");
        assert_eq!(new_lines[0], "/help ");
        assert_eq!(new_col, 6);
    }

    #[test]
    fn test_get_file_suggestions_absolute_path() {
        // Bug 1: get_suggestions for absolute paths like /tmp should work
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        let lines = vec!["/tmp".into()];
        let result = provider.get_suggestions(&lines, 0, 4, false);
        // /tmp is a directory, should show its contents
        assert!(
            result.is_some(),
            "Absolute path /tmp should produce suggestions"
        );
        let suggestions = result.unwrap();
        assert!(
            !suggestions.items.is_empty(),
            "Should have entries from /tmp"
        );
        assert_eq!(suggestions.prefix, "/tmp");
    }

    #[test]
    fn test_get_suggestions_slash_falls_through_to_file_completion() {
        // When no slash command matches, absolute paths should get file completion
        let provider = CombinedAutocompleteProvider::new(
            vec![SlashCommand {
                name: "help".into(),
                description: None,
                argument_hint: None,
                argument_completions: None,
                get_argument_completions: None,
            }],
            "/tmp".into(),
        );
        let lines = vec!["/tmp".into()];
        // /tmp doesn't match any slash command, should fall through to file completion
        let result = provider.get_suggestions(&lines, 0, 4, false);
        assert!(
            result.is_some(),
            "/tmp should fall through to file completion"
        );
    }

    #[test]
    fn test_get_suggestions_tilde_path() {
        // Bug 2: ~ paths should trigger file completion (non-force)
        let home = std::env::var("HOME").unwrap_or_default();
        if home.is_empty() || !std::path::Path::new(&home).is_dir() {
            // Skip if HOME is not set or not a directory
            return;
        }
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());
        let lines = vec!["~/".into()];
        let result = provider.get_suggestions(&lines, 0, 2, false);
        assert!(result.is_some(), "~ path should produce file suggestions");
    }

    #[test]
    fn test_hidden_file_filter_with_dot_prefix() {
        // Bug 2: when query starts with '.', hidden files should be shown
        let tmp = std::env::temp_dir();
        // Create a temp dir with a hidden file
        let dir = tmp.join("autocomplete_test_dot");
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join(".hidden_file"), "").unwrap();
        std::fs::write(dir.join("visible_file"), "").unwrap();
        std::fs::create_dir(dir.join(".hidden_dir")).unwrap();
        std::fs::create_dir(dir.join("visible_dir")).unwrap();

        let provider = CombinedAutocompleteProvider::new(vec![], dir.to_string_lossy().to_string());
        let dir_str = dir.to_string_lossy();

        // Query with dot prefix should show hidden files
        let result = provider.get_file_suggestions(&format!("{}/.h", dir_str));
        assert!(
            result.is_some(),
            "Dot prefix query should find hidden files"
        );
        if let Some(suggestions) = result {
            let values: Vec<&str> = suggestions.items.iter().map(|i| i.value.as_str()).collect();
            assert!(
                values.iter().any(|v| v.contains(".hidden")),
                "Should find .hidden_file or .hidden_dir, got: {:?}",
                values
            );
        }

        // Query without dot prefix should NOT show hidden files
        let result2 = provider.get_file_suggestions(&format!("{}/v", dir_str));
        assert!(result2.is_some(), "Non-dot prefix query should find files");
        if let Some(suggestions) = result2 {
            let values: Vec<&str> = suggestions.items.iter().map(|i| i.value.as_str()).collect();
            assert!(
                values.iter().any(|v| v.contains("visible")),
                "Should find visible_file or visible_dir"
            );
            assert!(
                !values.iter().any(|v| v.contains(".hidden")),
                "Should NOT find hidden files with non-dot prefix"
            );
        }

        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn test_get_suggestions_slash_command_still_works() {
        // Existing slash command completion should not be broken
        let provider = CombinedAutocompleteProvider::new(
            vec![SlashCommand {
                name: "help".into(),
                description: Some("Show help".into()),
                argument_hint: None,
                argument_completions: None,
                get_argument_completions: None,
            }],
            "/tmp".into(),
        );

        let lines = vec!["/he".into()];
        let result = provider.get_suggestions(&lines, 0, 3, false);
        assert!(result.is_some());
        let suggestions = result.unwrap();
        assert_eq!(suggestions.items.len(), 1);
        assert_eq!(suggestions.items[0].value, "help");
    }

    // ── Path completion regression tests ──

    /// Create a temp directory structure for path completion tests.
    /// Structure:
    ///   temp/
    ///     src/
    ///       autocomplete/
    ///         mod.rs
    ///       editor.rs
    ///       components/
    ///         select_list.rs
    fn setup_path_test_dir() -> (tempfile::TempDir, String) {
        let dir = tempfile::tempdir().expect("create temp dir");
        let root = dir.path().to_string_lossy().to_string();

        // Create structure
        std::fs::create_dir_all(format!("{}/src/autocomplete", root)).unwrap();
        std::fs::create_dir_all(format!("{}/src/components", root)).unwrap();
        std::fs::write(format!("{}/src/autocomplete/mod.rs", root), "").unwrap();
        std::fs::write(format!("{}/src/editor.rs", root), "").unwrap();
        std::fs::write(format!("{}/src/components/select_list.rs", root), "").unwrap();

        (dir, root)
    }

    #[test]
    fn test_get_file_suggestions_relative_path_with_folder() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Typed "src/au" -> should find "src/autocomplete/"
        let result = provider.get_file_suggestions("src/au");
        assert!(result.is_some(), "src/au should produce suggestions");
        let suggestions = result.unwrap();
        assert_eq!(
            suggestions.prefix, "src/au",
            "prefix should be the typed text"
        );
        assert!(
            !suggestions.items.is_empty(),
            "should have at least one item"
        );

        // The item value should include the full relative path
        let has_autocomplete = suggestions
            .items
            .iter()
            .any(|i| i.value == "src/autocomplete/");
        assert!(
            has_autocomplete,
            "should contain src/autocomplete/ as a completion candidate, got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_get_file_suggestions_relative_path_trailing_slash() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Typed "src/" -> should show contents of src/
        let result = provider.get_file_suggestions("src/");
        assert!(result.is_some(), "src/ should produce suggestions");
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "src/", "prefix should be src/");

        // Should contain entries like src/autocomplete/, src/editor.rs, src/components/
        let values: Vec<&str> = suggestions.items.iter().map(|i| i.value.as_str()).collect();
        assert!(
            values.contains(&"src/autocomplete/"),
            "should contain src/autocomplete/, got: {:?}",
            values
        );
        assert!(
            values.contains(&"src/editor.rs"),
            "should contain src/editor.rs, got: {:?}",
            values
        );
        assert!(
            values.contains(&"src/components/"),
            "should contain src/components/, got: {:?}",
            values
        );
    }

    #[test]
    fn test_get_file_suggestions_deep_path() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Typed "src/components/s" -> should find "src/components/select_list.rs"
        let result = provider.get_file_suggestions("src/components/s");
        assert!(
            result.is_some(),
            "src/components/s should produce suggestions"
        );
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "src/components/s");

        let has_select_list = suggestions
            .items
            .iter()
            .any(|i| i.value == "src/components/select_list.rs");
        assert!(
            has_select_list,
            "should contain src/components/select_list.rs, got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_get_suggestions_force_triggers_file_completion() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Simulate Tab (force=true) with "src/au" typed
        let lines = vec!["src/au".into()];
        let result = provider.get_suggestions(&lines, 0, 6, true);
        assert!(
            result.is_some(),
            "Force should trigger file completion for src/au"
        );
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "src/au");

        let has_autocomplete = suggestions
            .items
            .iter()
            .any(|i| i.value == "src/autocomplete/");
        assert!(
            has_autocomplete,
            "Should suggest src/autocomplete/, got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_get_suggestions_at_prefix_file_completion() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Typed "@src/au" should complete to "@src/autocomplete/"
        let lines = vec!["@src/au".into()];
        let result = provider.get_suggestions(&lines, 0, 7, false);
        assert!(result.is_some(), "@src/au should produce suggestions");
        let suggestions = result.unwrap();
        // Prefix should NOT include the @
        assert_eq!(suggestions.prefix, "src/au", "prefix should not include @");

        let has_autocomplete = suggestions
            .items
            .iter()
            .any(|i| i.value == "src/autocomplete/");
        assert!(
            has_autocomplete,
            "Should suggest src/autocomplete/, got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_apply_completion_relative_path_with_folder() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // User typed "src/au", cursor at end. Accept proposal "src/autocomplete/"
        let item = AutocompleteItem {
            value: "src/autocomplete/".into(),
            label: "autocomplete/".into(),
            description: None,
        };
        let lines = vec!["src/au".into()];
        let (new_lines, new_line, new_col) =
            provider.apply_completion(&lines, 0, 6, &item, "src/au");

        assert_eq!(
            new_lines[0], "src/autocomplete/",
            "Should replace src/au with src/autocomplete/"
        );
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 17); // "src/autocomplete/".len() = 17
    }

    #[test]
    fn test_apply_completion_relative_path_trailing_slash() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // User typed "src/", cursor at end. Accept proposal "src/autocomplete/"
        let item = AutocompleteItem {
            value: "src/autocomplete/".into(),
            label: "autocomplete/".into(),
            description: None,
        };
        let lines = vec!["src/".into()];
        let (new_lines, new_line, new_col) = provider.apply_completion(&lines, 0, 4, &item, "src/");

        assert_eq!(
            new_lines[0], "src/autocomplete/",
            "Should replace src/ with src/autocomplete/"
        );
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 17);
    }

    #[test]
    fn test_apply_completion_at_prefix() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // User typed "@src/au", cursor at end. Accept proposal "src/autocomplete/"
        let item = AutocompleteItem {
            value: "src/autocomplete/".into(),
            label: "autocomplete/".into(),
            description: None,
        };
        let lines = vec!["@src/au".into()];
        // cursor_col = 7 (position after "@src/au"), prefix = "src/au" (without @)
        let (new_lines, new_line, new_col) =
            provider.apply_completion(&lines, 0, 7, &item, "src/au");

        assert_eq!(
            new_lines[0], "@src/autocomplete/",
            "Should replace src/au with src/autocomplete/, keeping @ prefix"
        );
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 18); // "@src/autocomplete/".len() = 18
    }

    #[test]
    fn test_apply_completion_deep_path() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // User typed "src/components/s", cursor at end. Accept "src/components/select_list.rs"
        let item = AutocompleteItem {
            value: "src/components/select_list.rs".into(),
            label: "select_list.rs".into(),
            description: None,
        };
        let lines = vec!["src/components/s".into()];
        let (new_lines, new_line, new_col) =
            provider.apply_completion(&lines, 0, 16, &item, "src/components/s");

        assert_eq!(
            new_lines[0], "src/components/select_list.rs ",
            "Should complete deep path correctly"
        );
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 30); // "src/components/select_list.rs ".len() = 30
    }

    #[test]
    fn test_apply_completion_at_prefix_deep_path() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // User typed "@src/components/s", cursor at end. Accept "src/components/select_list.rs"
        let item = AutocompleteItem {
            value: "src/components/select_list.rs".into(),
            label: "select_list.rs".into(),
            description: None,
        };
        let lines = vec!["@src/components/s".into()];
        // cursor_col = 17 (position after "@src/components/s"), prefix = "src/components/s"
        let (new_lines, new_line, new_col) =
            provider.apply_completion(&lines, 0, 17, &item, "src/components/s");

        assert_eq!(
            new_lines[0], "@src/components/select_list.rs ",
            "Should complete deep @-path correctly"
        );
        assert_eq!(new_line, 0);
        assert_eq!(new_col, 31); // "@src/components/select_list.rs ".len() = 31
    }

    #[test]
    fn test_apply_completion_after_folder_completion_then_deeper() {
        // Regression: after completing src/ -> src/autocomplete/, then typing more to go deeper
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Step 1: complete src/ -> src/autocomplete/
        let item1 = AutocompleteItem {
            value: "src/autocomplete/".into(),
            label: "autocomplete/".into(),
            description: None,
        };
        let lines = vec!["src/".into()];
        let (new_lines, _, _) = provider.apply_completion(&lines, 0, 4, &item1, "src/");
        assert_eq!(new_lines[0], "src/autocomplete/");

        // Step 2: user types more, now text is "src/autocomplete/m"
        let text = format!("{}m", new_lines[0]);
        let cursor_col = text.len(); // "src/autocomplete/m" is 18 chars
        let lines2 = vec![text];
        // Get suggestions
        let result = provider.get_suggestions(&lines2, 0, cursor_col, true);
        assert!(
            result.is_some(),
            "src/autocomplete/m should produce suggestions"
        );
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "src/autocomplete/m");

        // Should find "src/autocomplete/mod.rs"
        let has_mod = suggestions
            .items
            .iter()
            .any(|i| i.value == "src/autocomplete/mod.rs");
        assert!(
            has_mod,
            "Should suggest src/autocomplete/mod.rs, got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );

        // Step 3: accept the completion
        let item2 = AutocompleteItem {
            value: "src/autocomplete/mod.rs".into(),
            label: "mod.rs".into(),
            description: None,
        };
        let (final_lines, _, _) =
            provider.apply_completion(&lines2, 0, cursor_col, &item2, "src/autocomplete/m");
        assert_eq!(
            final_lines[0], "src/autocomplete/mod.rs ",
            "After completing deeper, should keep the full path"
        );
    }

    /// Test that get_file_suggestions produces item values that, when passed
    /// back to apply_completion, produce the correct result (round-trip test).
    #[test]
    fn test_file_suggestions_roundtrip() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Get suggestions for "src/au"
        let result = provider.get_file_suggestions("src/au").unwrap();
        assert_eq!(result.prefix, "src/au");

        // For each suggestion, verify that apply_completion works correctly
        for item in &result.items {
            let lines = vec!["src/au".into()];
            let (new_lines, _, _) = provider.apply_completion(&lines, 0, 6, item, "src/au");
            let _expected_len = "src/au".len() + item.value.len() - "src/au".len();
            // The item.value should be the replacement text (replacing the prefix)
            // Since the prefix is at the start, the result should start with item.value
            assert!(
                new_lines[0].starts_with(item.value.trim_end_matches(' ')),
                "apply_completion({}, {:?}) should produce text starting with '{}', got '{}'",
                "src/au",
                item.value,
                item.value.trim_end_matches(' '),
                new_lines[0]
            );
        }
    }

    #[test]
    fn test_at_suggestions_roundtrip() {
        let (_dir, root) = setup_path_test_dir();
        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Get suggestions for "@src/au" (prefix should be "src/au")
        let lines = vec!["@src/au".into()];
        let result = provider.get_suggestions(&lines, 0, 7, false).unwrap();
        assert_eq!(result.prefix, "src/au");

        // For each suggestion, verify that apply_completion works correctly
        for item in &result.items {
            let lines = vec!["@src/au".into()];
            let (new_lines, _, _) = provider.apply_completion(&lines, 0, 7, item, "src/au");

            // The @ should be preserved, followed by the completion value
            assert!(
                new_lines[0].starts_with('@'),
                "apply_completion for @src/au should preserve @ prefix, got '{}'",
                new_lines[0]
            );
            // The @ should be followed by the completion value (minus trailing space)
            let after_at = &new_lines[0][1..];
            let trimmed = after_at.trim_end_matches(' ');
            assert_eq!(
                trimmed, item.value,
                "Text after @ should match item.value, got '{}' vs '{}'",
                trimmed, item.value
            );
        }
    }

    #[test]
    fn test_tilde_path_completion_does_not_drop_folder() {
        // Regression: completing ~/.rab/agent/skills must NOT produce ~/.rab/skills/
        let (_dir, root) = setup_path_test_dir();

        // Create a nested structure matching the user's scenario:
        //   temp/
        //     sub/
        //       deep/
        //         target/
        //           file.txt
        // To test: complete "sub/deep/tar" -> "sub/deep/target/"
        std::fs::create_dir_all(format!("{}/sub/deep/target", root)).unwrap();
        std::fs::write(format!("{}/sub/deep/target/file.txt", root), "").unwrap();

        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Test get_file_suggestions produces correct relative path
        let result = provider.get_file_suggestions("sub/deep/tar");
        assert!(result.is_some(), "sub/deep/tar should produce suggestions");
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "sub/deep/tar");

        let has_target = suggestions
            .items
            .iter()
            .any(|i| i.value == "sub/deep/target/");
        assert!(
            has_target,
            "Should suggest sub/deep/target/, not target/ alone. Got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );

        // Test apply_completion produces the full path
        let item = AutocompleteItem {
            value: "sub/deep/target/".into(),
            label: "target/".into(),
            description: None,
        };
        let lines = vec!["sub/deep/tar".into()];
        let (new_lines, _, _) = provider.apply_completion(&lines, 0, 12, &item, "sub/deep/tar");
        assert_eq!(
            new_lines[0], "sub/deep/target/",
            "Must produce sub/deep/target/ not target/ alone"
        );
    }

    #[test]
    fn test_nested_path_with_get_suggestions_force() {
        let (_dir, root) = setup_path_test_dir();

        std::fs::create_dir_all(format!("{}/sub/deep/target", root)).unwrap();
        std::fs::write(format!("{}/sub/deep/target/file.txt", root), "").unwrap();

        let provider = CombinedAutocompleteProvider::new(vec![], root.clone());

        // Simulate Tab (force) with "sub/deep/tar"
        let lines = vec!["sub/deep/tar".into()];
        let result = provider.get_suggestions(&lines, 0, 13, true);
        assert!(
            result.is_some(),
            "Force should trigger file completion for sub/deep/tar"
        );
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, "sub/deep/tar");

        let has_target = suggestions
            .items
            .iter()
            .any(|i| i.value == "sub/deep/target/");
        assert!(
            has_target,
            "Force should suggest sub/deep/target/. Got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );
    }

    #[test]
    fn test_nested_path_with_tilde_prefix() {
        // Test that ~/ path completion preserves nested folders
        let home = std::env::var("HOME").unwrap_or_default();
        if home.is_empty() {
            return;
        }

        // Create nested dir inside home
        let test_dir = std::path::Path::new(&home).join(".rab_test_autocomplete");
        let _ = std::fs::remove_dir_all(&test_dir);
        std::fs::create_dir_all(test_dir.join("sub/deep/target")).unwrap();
        std::fs::write(test_dir.join("sub/deep/target/file.txt"), "").unwrap();

        // The CWD doesn't matter for ~/ paths since we use HOME
        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());

        let tilde_path = format!("~/.rab_test_autocomplete/sub/deep/tar");
        let result = provider.get_file_suggestions(&tilde_path);
        assert!(result.is_some(), "~/ path should produce suggestions");
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, tilde_path);

        let expected_value = format!("~/.rab_test_autocomplete/sub/deep/target/");
        let has_target = suggestions.items.iter().any(|i| i.value == expected_value);
        assert!(
            has_target,
            "Should suggest ~/.rab_test_autocomplete/sub/deep/target/, not target/ alone. Got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );

        // Test apply_completion preserves the full ~/ path
        let item = AutocompleteItem {
            value: expected_value.clone(),
            label: "target/".into(),
            description: None,
        };
        let lines = vec![tilde_path.clone()];
        let cursor_col = tilde_path.len();
        let (new_lines, _, _) =
            provider.apply_completion(&lines, 0, cursor_col, &item, &tilde_path);
        assert_eq!(
            new_lines[0], expected_value,
            "Must preserve full ~/ path, not drop folders"
        );

        // Clean up
        let _ = std::fs::remove_dir_all(&test_dir);
    }

    #[test]
    fn test_tilde_path_with_trailing_slash_preserves_folder() {
        // Regression: completing "~/.rab/agent/" and selecting "skills"
        // should produce "~/.rab/agent/skills/", not "~/.rab/skills/"
        let home = std::env::var("HOME").unwrap_or_default();
        if home.is_empty() {
            return;
        }

        let test_dir = std::path::Path::new(&home).join(".rab_test_trailing");
        let _ = std::fs::remove_dir_all(&test_dir);
        // Create: ~/test_trailing/sub/deep/target/
        std::fs::create_dir_all(test_dir.join("sub/deep/target")).unwrap();
        std::fs::write(test_dir.join("sub/deep/target/file.txt"), "").unwrap();

        let provider = CombinedAutocompleteProvider::new(vec![], "/tmp".into());

        // User typed "~/.rab_test_trailing/sub/deep/" (trailing slash)
        let tilde_path = format!("~/.rab_test_trailing/sub/deep/");
        let result = provider.get_file_suggestions(&tilde_path);
        assert!(
            result.is_some(),
            "~/ path with trailing slash should produce suggestions"
        );
        let suggestions = result.unwrap();
        assert_eq!(suggestions.prefix, tilde_path);

        // The suggestion value should include the full path, not just the last component
        let expected_value = format!("~/.rab_test_trailing/sub/deep/target/");
        let has_target = suggestions.items.iter().any(|i| i.value == expected_value);
        assert!(
            has_target,
            "Must suggest full path ~/.rab_test_trailing/sub/deep/target/, not target/ alone. Got: {:?}",
            suggestions
                .items
                .iter()
                .map(|i| &i.value)
                .collect::<Vec<_>>()
        );

        // Test apply_completion with this prefix
        let item = AutocompleteItem {
            value: expected_value.clone(),
            label: "target/".into(),
            description: None,
        };
        let lines = vec![tilde_path.clone()];
        let cursor_col = tilde_path.len();
        let (new_lines, _, _) =
            provider.apply_completion(&lines, 0, cursor_col, &item, &tilde_path);
        assert_eq!(
            new_lines[0], expected_value,
            "Must produce full path, not drop the last folder"
        );

        // Clean up
        let _ = std::fs::remove_dir_all(&test_dir);
    }
}