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
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
// ── Input bar widget ──────────────────────────────────────────────────────────
//
// Multi-line input with history, cursor tracking, mode/model label,
// and tab completion for slash commands.
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
use crate::tui::cell::{Color, Style};
use crate::tui::event::{Event, Key, KeyEvent};
use crate::tui::layout::Rect;
use crate::tui::screen::Screen;
use crate::tui::widget::{Action, Widget, styles, truncate_str_width};
use std::collections::HashMap;
/// Find the byte offset of the start of the previous word, stopping at newlines.
fn word_start_backward(text: &str, cursor: usize) -> usize {
let before = &text[..cursor];
let trimmed = before.trim_end_matches(|c: char| c.is_whitespace() && c != '\n');
if trimmed.len() < before.len() {
trimmed
.rfind(|c: char| c.is_whitespace() || c == '\n')
.map(|p| p + 1)
.unwrap_or(0)
} else {
before
.rfind(|c: char| c.is_whitespace() || c == '\n')
.map(|p| p + 1)
.unwrap_or(0)
}
}
/// Find the byte offset after the next word, including trailing whitespace (but not newlines).
fn word_end_forward(text: &str, cursor: usize) -> usize {
let after = &text[cursor..];
let word_end = after
.find(|c: char| c.is_whitespace() || c == '\n')
.unwrap_or(after.len());
let whitespace_skipped = after[word_end..]
.chars()
.take_while(|c| c.is_whitespace() && *c != '\n')
.count();
cursor + word_end + whitespace_skipped
}
/// A single visual row of input text, with byte range and screen column.
struct InputRow<'a> {
/// The text slice to display on this row.
text: &'a str,
/// Byte offset of `text` within the full content.
byte_offset: usize,
/// Screen column where this row starts.
col: u16,
}
/// Compute the visual rows for input content, accounting for the prompt on
/// the first line and Unicode display widths. Each row fits within
/// `available_width` columns.
fn input_rows<'a>(
content: &'a str,
prompt_width: u16,
area_x: u16,
available_width: u16,
) -> Vec<InputRow<'a>> {
let mut rows = Vec::new();
let mut first_line = true;
let mut byte_offset = 0usize;
for line in content.split_inclusive('\n') {
let (line_text, _has_newline) = if let Some(stripped) = line.strip_suffix('\n') {
(stripped, true)
} else {
(line, false)
};
let left_col = if first_line {
area_x + prompt_width
} else {
area_x
};
first_line = false;
// Split the logical line into wrapped visual rows.
let mut row_start = 0usize;
let mut row_width = 0usize;
let first_line_indent = if row_start == 0 && left_col > area_x {
prompt_width as usize
} else {
0
};
for (idx, ch) in line_text.char_indices() {
let w = ch.width().unwrap_or(1);
if w == 0 {
// Combining marks don't occupy columns; skip for wrapping.
continue;
}
if row_width + first_line_indent + w > available_width as usize && row_width > 0 {
let end = idx;
rows.push(InputRow {
text: &line_text[row_start..end],
byte_offset: byte_offset + row_start,
col: left_col,
});
row_start = idx;
row_width = 0;
}
row_width += w;
}
// Push the final row for this logical line.
rows.push(InputRow {
text: &line_text[row_start..],
byte_offset: byte_offset + row_start,
col: left_col,
});
byte_offset += line.len();
}
rows
}
/// Spinner animation frames (Braille patterns).
const STREAMING_FRAMES: &[&str] = &["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
/// The input bar at the bottom of the screen.
///
/// Displays a prompt with mode and model labels, and accepts
/// multi-line text input. Enter submits, Shift+Enter inserts a newline.
/// Tab completes slash commands when the input starts with `/`.
///
/// In confirmation mode, the input bar shows a `[y/n/a]?` prompt
/// and only accepts y (approve), n (deny), or a (approve all) keys.
///
/// When the model is streaming/thinking, the input bar shows a spinner
/// animation and label, blocking all input except Ctrl+C (interrupt)
/// and Ctrl+D (quit).
pub struct InputBarWidget {
/// Current input text.
content: String,
/// Cursor position (byte offset in content).
cursor: usize,
/// Scroll offset for the input area (for multi-line input).
scroll_offset: usize,
/// Input history (previous messages).
history: Vec<String>,
/// Current position in history navigation (None = not navigating).
history_index: Option<usize>,
/// The mode label to display (e.g., "agent").
mode_label: String,
/// The mode color.
mode_color: Color,
/// The model name to display.
model_name: String,
/// Whether the input bar is focused.
focused: bool,
/// Current tab-completion state: index into the list of matching completions.
/// `None` means we're not in tab-completion cycling mode.
tab_cycle_index: Option<usize>,
/// The prefix that was being completed when Tab cycling started.
tab_cycle_prefix: String,
/// Whether the last completion was a subcommand completion.
tab_cycle_subcommand: bool,
/// Whether the input bar is in confirmation mode (y/n/a).
confirming: bool,
/// Whether the input bar is in question mode (user must answer a question).
questioning: bool,
/// The number of predefined answers for the current question.
question_answer_count: usize,
/// Kill ring for Ctrl+K/U/W/Y emacs-style editing.
kill_ring: String,
/// All known command names (primary + aliases), for tab completion.
command_names: Vec<String>,
/// Subcommand completions for commands that take arguments.
subcommands: HashMap<String, Vec<String>>,
/// Whether the model is currently streaming/thinking.
streaming: bool,
/// The label to show while streaming (e.g., "Thinking", "Responding").
streaming_label: String,
/// Current spinner frame index (cycles through STREAMING_FRAMES).
streaming_frame: usize,
}
impl InputBarWidget {
pub fn new(mode_label: &str, model_name: &str) -> Self {
Self::with_commands(mode_label, model_name, Vec::new(), HashMap::new())
}
/// Create an `InputBarWidget` with command names and subcommand completions
/// for tab completion, typically sourced from the binary's `CommandRegistry`.
pub fn with_commands(
mode_label: &str,
model_name: &str,
command_names: Vec<String>,
subcommands: HashMap<String, Vec<String>>,
) -> Self {
let mode_color = match mode_label {
"casual" => styles::MODE_CASUAL_FG,
"planning" => styles::MODE_PLANNING_FG,
"agent" => styles::MODE_AGENT_FG,
"research" => styles::MODE_RESEARCH_FG,
_ => Color::WHITE,
};
Self {
content: String::new(),
cursor: 0,
scroll_offset: 0,
history: Vec::new(),
history_index: None,
mode_label: mode_label.to_string(),
mode_color,
model_name: model_name.to_string(),
focused: true,
tab_cycle_index: None,
tab_cycle_prefix: String::new(),
tab_cycle_subcommand: false,
confirming: false,
questioning: false,
question_answer_count: 0,
kill_ring: String::new(),
command_names,
subcommands,
streaming: false,
streaming_label: String::from("Thinking"),
streaming_frame: 0,
}
}
/// Get the current input text and clear the buffer.
pub fn take_input(&mut self) -> String {
let text = self.content.clone();
if !text.is_empty() {
self.history.push(text.clone());
}
self.content.clear();
self.cursor = 0;
self.scroll_offset = 0;
self.history_index = None;
text
}
/// Set the input text (e.g., from --prompt flag).
pub fn set_input(&mut self, text: &str) {
self.content = text.to_string();
self.cursor = self.content.len();
}
/// Update the mode label and model name.
pub fn update_labels(&mut self, mode_label: &str, model_name: &str) {
self.mode_label = mode_label.to_string();
self.mode_color = match mode_label {
"casual" => styles::MODE_CASUAL_FG,
"planning" => styles::MODE_PLANNING_FG,
"agent" => styles::MODE_AGENT_FG,
"research" => styles::MODE_RESEARCH_FG,
_ => Color::WHITE,
};
self.model_name = model_name.to_string();
}
/// Set command names and subcommand completions for tab completion.
pub fn set_command_completions(
&mut self,
command_names: Vec<String>,
subcommands: HashMap<String, Vec<String>>,
) {
self.command_names = command_names;
self.subcommands = subcommands;
}
/// Total visual height of the input content for the given area width.
///
/// When streaming, always returns 2 (border + spinner row) regardless of
/// content since input is blocked.
pub fn content_height(&self, area_width: u16) -> u16 {
if self.streaming {
return 2; // border + spinner row
}
let prompt = format!("[{}] ", self.mode_label);
let prompt_width = prompt.width() as u16;
let available = area_width.saturating_sub(prompt_width).max(1);
let rows = input_rows(&self.content, prompt_width, 0, available).len() as u16;
// Reserve one row for the top border and at least one row of content.
rows.max(1) + 1
}
/// Check if the current input starts with a slash (for command detection).
pub fn is_command_input(&self) -> bool {
self.content.starts_with('/')
}
/// Enter or exit confirmation mode.
///
/// In confirmation mode, the input bar shows a `[y/n/a]?` prompt
/// and only accepts y (approve), n (deny), or a (approve all) keys.
pub fn set_confirming(&mut self, confirming: bool) {
self.confirming = confirming;
if confirming {
self.content.clear();
self.cursor = 0;
}
}
/// Check if the input bar is in confirmation mode.
pub fn is_confirming(&self) -> bool {
self.confirming
}
/// Enter or exit question mode.
///
/// In question mode, the input bar shows a prompt for the user to
/// type a number (1-N) or custom text, then press Enter.
pub fn set_questioning(&mut self, questioning: bool, answer_count: usize) {
self.questioning = questioning;
self.question_answer_count = answer_count;
if questioning {
self.content.clear();
self.cursor = 0;
}
}
/// Check if the input bar is in question mode.
pub fn is_questioning(&self) -> bool {
self.questioning
}
/// Set the streaming state (model is thinking/responding).
///
/// When streaming, the input bar shows a spinner animation and label,
/// and blocks all text input. Only Ctrl+C (interrupt) and Ctrl+D (quit)
/// are accepted.
pub fn set_streaming(&mut self, streaming: bool) {
self.streaming = streaming;
if streaming {
self.streaming_frame = 0;
}
}
/// Check if the input bar is in streaming mode.
pub fn is_streaming(&self) -> bool {
self.streaming
}
/// Set the streaming label (e.g., "Thinking", "Responding").
pub fn set_streaming_label(&mut self, label: &str) {
self.streaming_label = label.to_string();
}
/// Advance the spinner animation to the next frame.
pub fn tick_streaming(&mut self) {
if self.streaming {
self.streaming_frame = (self.streaming_frame + 1) % STREAMING_FRAMES.len();
}
}
/// Handle a mouse click on the input bar to position the cursor.
///
/// Computes where the user clicked relative to the prompt and text
/// content, then moves the cursor to that position.
pub fn click_to_cursor(&mut self, click_row: u16, click_col: u16, area: Rect) {
if self.confirming || self.questioning {
return;
}
let prompt = format!("[{}] ", self.mode_label);
let prompt_width = prompt.width() as u16;
let available = area.width.saturating_sub(prompt_width).max(1);
let first_input_row = area.y + 1;
let rel_row = click_row.saturating_sub(first_input_row) as usize;
let rows = input_rows(&self.content, prompt_width, area.x, available);
let Some(row) = rows.get(rel_row) else {
self.cursor = self.content.len();
return;
};
let mut col = row.col as usize;
for (idx, ch) in row.text.char_indices() {
let w = ch.width().unwrap_or(1).max(1) as usize;
if col + w > click_col as usize {
self.cursor = row.byte_offset + idx;
return;
}
col += w;
}
self.cursor = row.byte_offset + row.text.len();
}
/// Attempt tab completion for slash commands.
///
/// If the input starts with `/`, cycle through matching command names
/// (or subcommand arguments). Returns `true` if a completion was applied,
/// `false` if no completions matched.
///
/// Tab cycling works by remembering the original prefix the user typed
/// before the first Tab. Subsequent Tabs cycle through all commands
/// that start with that prefix.
fn tab_complete(&mut self) -> bool {
if !self.content.starts_with('/') {
return false;
}
// Determine if we're completing a subcommand or a top-level command
if let Some(space_pos) = self.content.find(' ') {
// Subcommand completion: "/command sub<tab>"
let cmd = &self.content[..space_pos].to_lowercase();
let current_arg = self.content[space_pos + 1..].trim_start().to_lowercase();
let subs = self
.subcommands
.get(cmd)
.map(|s| s.as_slice())
.unwrap_or(&[]);
if subs.is_empty() {
return false;
}
// On first Tab (or if the prefix changed), start a new cycle
if self.tab_cycle_index.is_none()
|| self.tab_cycle_prefix != current_arg
|| !self.tab_cycle_subcommand
{
self.tab_cycle_prefix = current_arg.clone();
self.tab_cycle_index = Some(0);
self.tab_cycle_subcommand = true;
}
let matches: Vec<&String> = subs
.iter()
.filter(|s| s.starts_with(&self.tab_cycle_prefix))
.collect();
if matches.is_empty() {
self.tab_cycle_index = None;
return false;
}
let idx = self.tab_cycle_index.unwrap() % matches.len();
let completion = matches[idx];
// Replace the subcommand argument
self.content = format!("{} {}", cmd, completion);
self.cursor = self.content.len();
self.tab_cycle_index = Some(idx + 1);
true
} else {
// Top-level command completion: "/mod<tab>"
let current_input = self.content.to_lowercase();
// On first Tab (or if cycling context was for subcommands), start fresh
if self.tab_cycle_index.is_none() || self.tab_cycle_subcommand {
self.tab_cycle_prefix = current_input.clone();
self.tab_cycle_index = Some(0);
self.tab_cycle_subcommand = false;
} else {
// Continuing a cycle: the current content was set by the previous Tab,
// so the prefix we're matching against is still tab_cycle_prefix.
// The current content is a completed command name — don't update prefix.
}
let matches: Vec<&String> = self
.command_names
.iter()
.filter(|name| name.starts_with(&self.tab_cycle_prefix))
.collect();
if matches.is_empty() {
self.tab_cycle_index = None;
return false;
}
let idx = self.tab_cycle_index.unwrap() % matches.len();
let completion = matches[idx];
self.content = completion.to_string();
self.cursor = self.content.len();
self.tab_cycle_index = Some(idx + 1);
true
}
}
/// Reset tab-completion cycling state (e.g., when a non-Tab key is pressed).
fn reset_tab_cycle(&mut self) {
self.tab_cycle_index = None;
self.tab_cycle_prefix.clear();
self.tab_cycle_subcommand = false;
}
}
impl Widget for InputBarWidget {
fn render(&mut self, area: Rect, screen: &mut Screen) {
if area.is_empty() || area.height < 2 {
return;
}
let row = area.y;
// Draw top border
screen.hline(
row,
area.x,
area.x + area.width - 1,
'─',
Color::Ansi(240),
Color::Default,
);
// Draw prompt and input on the next rows
let input_row = row + 1;
if self.streaming {
// ── Streaming mode: show spinner + label, block input ──
let frame = STREAMING_FRAMES.get(self.streaming_frame).unwrap_or(&"⠋");
let label = format!("{} {}…", frame, self.streaming_label);
let mut col = area.x;
screen.write_str(
input_row,
col,
&label,
Color::ORANGE,
styles::INPUT_BAR_BG,
Style::dim(),
);
col += label.width() as u16;
// Fill the rest with background
for c in col..area.x + area.width {
if let Some(cell) = screen.get_mut(input_row, c) {
cell.bg = styles::INPUT_BAR_BG;
}
}
// Fill any additional rows with background
for r in (input_row + 1)..area.y + area.height {
for c in area.x..area.x + area.width {
if let Some(cell) = screen.get_mut(r, c) {
cell.bg = styles::INPUT_BAR_BG;
}
}
}
} else if self.confirming {
// In confirmation mode, show a yellow prompt asking for y/n/a
let confirm_prompt = "[y/n/a]? ";
let mut col = area.x;
screen.write_str(
input_row,
col,
confirm_prompt,
Color::YELLOW,
styles::INPUT_BAR_BG,
Style::bold(),
);
col += confirm_prompt.len() as u16;
// Draw blinking cursor indicator
if self.focused && col < area.x + area.width {
if let Some(cell) = screen.get_mut(input_row, col) {
cell.char = '█';
cell.wide = false;
cell.fg = Color::YELLOW;
cell.style = Style::blink();
}
}
// Fill the rest with background
for c in col + 1..area.x + area.width {
if let Some(cell) = screen.get_mut(input_row, c) {
cell.bg = styles::INPUT_BAR_BG;
}
}
} else if self.questioning {
// In question mode, show a cyan prompt asking for answer
let question_prompt = format!("[1-{} or type]: ", self.question_answer_count);
let mut col = area.x;
screen.write_str(
input_row,
col,
&question_prompt,
Color::CYAN,
styles::INPUT_BAR_BG,
Style::bold(),
);
col += question_prompt.len() as u16;
// Draw input content
let available_width = area.width.saturating_sub(col - area.x);
let (display_text, display_offset) = if self.content.width() > available_width as usize
{
// Content is wider than available — show the tail, snapping to a
// char boundary so multi-byte UTF-8 doesn't panic.
let target_bytes = self.content.len().saturating_sub(available_width as usize);
let start = self
.content
.char_indices()
.find(|(i, _)| *i >= target_bytes)
.map(|(i, _)| i)
.unwrap_or(target_bytes);
(&self.content[start..], start)
} else {
(self.content.as_str(), 0)
};
screen.write_str(
input_row,
col,
display_text,
Color::WHITE,
styles::INPUT_BAR_BG,
Style::default(),
);
// Draw cursor
if self.focused {
let adjusted_cursor = self
.cursor
.saturating_sub(display_offset)
.min(display_text.len());
let before_cursor = &display_text[..adjusted_cursor];
let cursor_col = col + before_cursor.width() as u16;
if cursor_col < area.x + area.width {
if let Some(cell) = screen.get_mut(input_row, cursor_col) {
cell.style.underline = true;
}
}
}
} else {
let prompt = format!("[{}] ", self.mode_label);
// Draw mode label
let mut col = area.x;
screen.write_str(
input_row,
col,
&prompt,
self.mode_color,
styles::INPUT_BAR_BG,
Style::bold(),
);
col += prompt.width() as u16;
let available_width = area.width.saturating_sub(col - area.x);
// Render wrapped content over the available rows.
render_wrapped_input(
&self.content,
self.cursor,
self.focused,
screen,
input_row,
area.y + area.height - 1,
area.x,
col,
available_width,
);
}
}
fn handle_event(&mut self, event: &Event) -> Action {
// In streaming mode, block all input except Ctrl+C and Ctrl+D
if self.streaming {
if let Event::Key(key) = event {
match key {
KeyEvent {
key: Key::Char('c'),
modifiers,
} if modifiers.ctrl => {
return Action::Interrupt;
}
KeyEvent {
key: Key::Char('d'),
modifiers,
} if modifiers.ctrl => {
return Action::Quit;
}
_ => return Action::None,
}
}
return Action::None;
}
// Handle paste events (bracketed paste mode)
if let Event::Paste(text) = event {
if !self.confirming && !self.questioning {
self.content.insert_str(self.cursor, text);
self.cursor += text.len();
self.reset_tab_cycle();
}
return Action::None;
}
let Event::Key(key) = event else {
return Action::None;
};
// In confirmation mode, only accept y/n/a responses
if self.confirming {
match key {
KeyEvent {
key: Key::Char('y'),
modifiers,
} if !modifiers.ctrl && !modifiers.alt => {
self.confirming = false;
Action::ConfirmYes
}
KeyEvent {
key: Key::Char('n'),
modifiers,
} if !modifiers.ctrl && !modifiers.alt => {
self.confirming = false;
Action::ConfirmNo
}
KeyEvent {
key: Key::Char('a'),
modifiers,
} if !modifiers.ctrl && !modifiers.alt => {
self.confirming = false;
Action::ConfirmAll
}
KeyEvent {
key: Key::Escape, ..
} => {
self.confirming = false;
Action::ConfirmNo
}
_ => Action::None,
}
} else if self.questioning {
// In question mode, accept typing and Enter to submit
match key {
KeyEvent {
key: Key::Enter,
modifiers,
} if !modifiers.shift => {
let text = self.take_input();
self.questioning = false;
if text.trim().is_empty() {
// Empty input — skip the question
Action::AnswerQuestion("Skipped (no answer provided)".to_string())
} else {
// Check if the user typed a number matching an option
let trimmed = text.trim();
if let Ok(num) = trimmed.parse::<usize>() {
if num >= 1 && num <= self.question_answer_count {
// Number input — will be resolved by the app
Action::AnswerQuestion(trimmed.to_string())
} else {
// Out of range number — treat as free-form input
Action::AnswerQuestion(trimmed.to_string())
}
} else {
// Free-form text answer
Action::AnswerQuestion(trimmed.to_string())
}
}
}
KeyEvent {
key: Key::Escape, ..
} => {
self.questioning = false;
Action::AnswerQuestion("Skipped (no answer provided)".to_string())
}
KeyEvent {
key: Key::Char(c),
modifiers,
} if !modifiers.ctrl && !modifiers.alt => {
self.content.insert(self.cursor, *c);
self.cursor += c.len_utf8();
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Backspace,
..
} => {
if self.cursor > 0 {
let prev_char = self.content[..self.cursor].chars().next_back();
if let Some(ch) = prev_char {
self.cursor -= ch.len_utf8();
self.content.remove(self.cursor);
}
}
self.reset_tab_cycle();
Action::None
}
_ => Action::None,
}
} else {
self.handle_normal_key(key)
}
}
fn focused(&self) -> bool {
self.focused
}
fn set_focus(&mut self, focused: bool) {
self.focused = focused;
}
}
/// Render the normal input text wrapped into the available area.
/// `first_col` is where the first line starts (after the prompt); subsequent
/// lines start at `area_x`.
fn render_wrapped_input(
content: &str,
cursor: usize,
focused: bool,
screen: &mut Screen,
start_row: u16,
max_row: u16,
area_x: u16,
first_col: u16,
available_width: u16,
) {
let prompt_width = first_col.saturating_sub(area_x);
let rows = input_rows(content, prompt_width, area_x, available_width);
if rows.is_empty() {
// Empty content: draw the cursor at the prompt end on the first row,
// then fill the rest with background. We must start clearing at
// first_col (after the prompt) on the first row so we don't
// overwrite the prompt label that was already drawn.
if focused {
if let Some(cell) = screen.get_mut(start_row, first_col) {
cell.style.underline = true;
cell.bg = styles::INPUT_BAR_BG;
}
}
// Fill from first_col on the first row (preserving prompt area),
// then from area_x on subsequent rows.
let prompt_end = first_col + prompt_width.min(available_width);
let content_width = available_width.saturating_sub(prompt_width.min(available_width));
for c in prompt_end..prompt_end + content_width {
if let Some(cell) = screen.get_mut(start_row, c) {
cell.char = ' ';
cell.wide = false;
cell.fg = Color::Default;
cell.bg = styles::INPUT_BAR_BG;
cell.style = Style::default();
}
}
for r in (start_row + 1)..=max_row {
for c in area_x..area_x + available_width {
if let Some(cell) = screen.get_mut(r, c) {
cell.char = ' ';
cell.wide = false;
cell.fg = Color::Default;
cell.bg = styles::INPUT_BAR_BG;
cell.style = Style::default();
}
}
}
return;
}
for (i, row) in rows.iter().enumerate() {
let screen_row = start_row + i as u16;
if screen_row > max_row {
break;
}
// Show only the tail of the row if it doesn't fit.
let display_text = if row.text.width() > available_width as usize {
truncate_str_width(row.text, available_width as usize)
} else {
row.text
};
screen.write_str(
screen_row,
row.col,
display_text,
Color::WHITE,
styles::INPUT_BAR_BG,
Style::default(),
);
// Cursor on the active row.
if focused && cursor >= row.byte_offset && cursor <= row.byte_offset + row.text.len() {
let before_cursor_len = cursor.saturating_sub(row.byte_offset).min(row.text.len());
let before_cursor = &row.text[..before_cursor_len];
let cursor_col = row.col + before_cursor.width() as u16;
if cursor_col < area_x + available_width {
if let Some(cell) = screen.get_mut(screen_row, cursor_col) {
cell.style.underline = true;
if cell.char == ' ' {
cell.fg = Color::WHITE;
}
}
}
}
}
// Fill remaining lines with background so stale content is cleared.
let last_rendered_row = start_row + rows.len() as u16;
for r in last_rendered_row..=max_row {
for c in area_x..area_x + available_width {
if let Some(cell) = screen.get_mut(r, c) {
cell.char = ' ';
cell.wide = false;
cell.fg = Color::Default;
cell.bg = styles::INPUT_BAR_BG;
cell.style = Style::default();
}
}
}
}
impl InputBarWidget {
/// Handle a key event in normal (non-confirmation) mode.
fn handle_normal_key(&mut self, key: &KeyEvent) -> Action {
match key {
KeyEvent {
key: Key::Enter,
modifiers,
} => {
if modifiers.shift {
// Shift+Enter: insert newline
self.content.insert(self.cursor, '\n');
self.cursor += 1;
self.reset_tab_cycle();
Action::None
} else {
// Enter: submit the message
let text = self.take_input();
self.reset_tab_cycle();
if text.trim().is_empty() {
Action::None
} else {
Action::SendMessage(text)
}
}
}
KeyEvent {
key: Key::Backspace,
..
} => {
if self.cursor > 0 {
// Handle deleting across newlines
let prev_char = self.content[..self.cursor].chars().next_back();
if let Some(ch) = prev_char {
self.cursor -= ch.len_utf8();
self.content.remove(self.cursor);
}
}
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Delete, ..
} => {
if self.cursor < self.content.len() {
// Find the next character boundary
let next_char = self.content[self.cursor..].chars().next();
if let Some(ch) = next_char {
let end = self.cursor + ch.len_utf8();
self.content.replace_range(self.cursor..end, "");
}
}
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Left,
modifiers,
} => {
if modifiers.ctrl {
self.cursor = word_start_backward(&self.content, self.cursor);
} else if self.cursor > 0 {
if let Some((idx, _ch)) = self.content[..self.cursor].char_indices().next_back()
{
self.cursor = idx;
}
}
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Right,
modifiers,
} => {
if modifiers.ctrl {
self.cursor = word_end_forward(&self.content, self.cursor);
} else if self.cursor < self.content.len() {
if let Some((idx, ch)) = self.content[self.cursor..].char_indices().next() {
self.cursor = idx + ch.len_utf8();
}
}
self.reset_tab_cycle();
Action::None
}
KeyEvent { key: Key::Home, .. } => {
// Move to start of current line
let line_start = self.content[..self.cursor]
.rfind('\n')
.map(|p| p + 1)
.unwrap_or(0);
self.cursor = line_start;
self.reset_tab_cycle();
Action::None
}
KeyEvent { key: Key::End, .. } => {
// Move to end of current line
let line_end = self.content[self.cursor..]
.find('\n')
.map(|p| self.cursor + p)
.unwrap_or(self.content.len());
self.cursor = line_end;
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Up,
modifiers,
} if !modifiers.alt && !modifiers.ctrl => {
// History navigation
if !self.history.is_empty() {
let idx = self.history_index.unwrap_or(self.history.len());
if idx > 0 {
let new_idx = idx - 1;
self.history_index = Some(new_idx);
self.content = self.history[new_idx].clone();
self.cursor = self.content.len();
}
}
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Down,
modifiers,
} if !modifiers.alt && !modifiers.ctrl => {
// History navigation
if let Some(idx) = self.history_index {
if idx + 1 < self.history.len() {
self.history_index = Some(idx + 1);
self.content = self.history[idx + 1].clone();
} else {
self.history_index = None;
self.content.clear();
}
self.cursor = self.content.len();
}
self.reset_tab_cycle();
Action::None
}
KeyEvent {
key: Key::Tab,
modifiers,
} if !modifiers.shift => {
// Tab: command completion if input starts with '/', otherwise cycle focus
if self.is_command_input() {
self.tab_complete();
Action::None
} else {
// Not a command — let the app cycle focus
Action::CycleFocusForward
}
}
KeyEvent {
key: Key::BackTab, ..
} => {
// Shift+Tab: always cycle focus backward
Action::CycleFocusBackward
}
KeyEvent {
key: Key::Char(c),
modifiers,
} => {
if modifiers.ctrl {
// Handle Ctrl+key shortcuts
match c {
'c' => Action::Quit,
'd' => Action::Quit,
'a' => {
// Ctrl+A: move cursor to start of line
let line_start = self.content[..self.cursor]
.rfind('\n')
.map(|p| p + 1)
.unwrap_or(0);
self.cursor = line_start;
self.reset_tab_cycle();
Action::None
}
'e' => {
// Ctrl+E: move cursor to end of line
let line_end = self.content[self.cursor..]
.find('\n')
.map(|p| self.cursor + p)
.unwrap_or(self.content.len());
self.cursor = line_end;
self.reset_tab_cycle();
Action::None
}
'u' => {
// Ctrl+U: clear from cursor to beginning of line
let line_start = self.content[..self.cursor]
.rfind('\n')
.map(|p| p + 1)
.unwrap_or(0);
let killed = self.content[line_start..self.cursor].to_string();
if !killed.is_empty() {
self.kill_ring = killed;
}
self.content.replace_range(line_start..self.cursor, "");
self.cursor = line_start;
self.reset_tab_cycle();
Action::None
}
'k' => {
// Ctrl+K: clear from cursor to end of line
let line_end = self.content[self.cursor..]
.find('\n')
.map(|p| self.cursor + p)
.unwrap_or(self.content.len());
let killed = self.content[self.cursor..line_end].to_string();
if !killed.is_empty() {
self.kill_ring = killed;
}
self.content.replace_range(self.cursor..line_end, "");
self.reset_tab_cycle();
Action::None
}
'w' => {
// Ctrl+W: delete word backward
if self.cursor > 0 {
let word_start = word_start_backward(&self.content, self.cursor);
let killed = self.content[word_start..self.cursor].to_string();
if !killed.is_empty() {
self.kill_ring = killed;
}
self.content.replace_range(word_start..self.cursor, "");
self.cursor = word_start;
}
self.reset_tab_cycle();
Action::None
}
'y' => {
// Ctrl+Y: yank (paste) from kill ring
if !self.kill_ring.is_empty() {
self.content.insert_str(self.cursor, &self.kill_ring);
self.cursor += self.kill_ring.len();
}
self.reset_tab_cycle();
Action::None
}
_ => Action::None,
}
} else if modifiers.alt {
// Handle Alt+key shortcuts
match c {
'b' => {
// Alt+B: move cursor back one word
self.cursor = word_start_backward(&self.content, self.cursor);
self.reset_tab_cycle();
Action::None
}
'f' => {
// Alt+F: move cursor forward one word
self.cursor = word_end_forward(&self.content, self.cursor);
self.reset_tab_cycle();
Action::None
}
'\x08' | '\x7f' => {
// Alt+Backspace: delete word backward (same as Ctrl+W)
if self.cursor > 0 {
let word_start = word_start_backward(&self.content, self.cursor);
let killed = self.content[word_start..self.cursor].to_string();
if !killed.is_empty() {
self.kill_ring = killed;
}
self.content.replace_range(word_start..self.cursor, "");
self.cursor = word_start;
}
self.reset_tab_cycle();
Action::None
}
_ => Action::None,
}
} else {
self.content.insert(self.cursor, *c);
self.cursor += c.len_utf8();
self.reset_tab_cycle();
Action::None
}
}
KeyEvent {
key: Key::Escape, ..
} => {
if self.content.is_empty() {
Action::Quit
} else {
// Clear input on Escape
self.content.clear();
self.cursor = 0;
self.reset_tab_cycle();
Action::None
}
}
_ => Action::None,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tui::event::Modifiers;
/// Standard command names used in tests.
fn test_command_names() -> Vec<String> {
vec![
"/add",
"/agent",
"/apikey",
"/audit",
"/autoaccept",
"/casual",
"/clear",
"/command",
"/compact",
"/context",
"/contextlimit",
"/drop",
"/dropall",
"/exit",
"/files",
"/help",
"/init",
"/mode",
"/model",
"/plan",
"/project-settings",
"/quit",
"/refresh",
"/rename",
"/retries",
"/research",
"/session",
"/sessions",
"/settings",
"/showthink",
"/skill",
"/skills",
"/think",
"/timeout",
"/unload",
"/use",
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
/// Standard subcommand completions used in tests.
fn test_subcommands() -> HashMap<String, Vec<String>> {
let mut subs = HashMap::new();
subs.insert(
"/command".to_string(),
vec![
"add".into(),
"deny".into(),
"help".into(),
"list".into(),
"rm".into(),
"reset".into(),
"resetdeny".into(),
"undeny".into(),
],
);
subs.insert("/session".to_string(), vec!["delete".into()]);
subs.insert(
"/mode".to_string(),
vec![
"agent".into(),
"casual".into(),
"planning".into(),
"research".into(),
],
);
subs.insert("/settings".to_string(), vec!["all".into()]);
subs.insert("/autoaccept".to_string(), vec!["off".into(), "on".into()]);
subs.insert("/apikey".to_string(), vec!["clear".into()]);
subs.insert("/showthink".to_string(), vec!["off".into(), "on".into()]);
subs.insert(
"/think".to_string(),
vec!["high".into(), "low".into(), "medium".into(), "off".into()],
);
subs
}
/// Create an InputBarWidget with test command data for tab-completion tests.
fn bar_with_commands(mode_label: &str, model_name: &str) -> InputBarWidget {
InputBarWidget::with_commands(
mode_label,
model_name,
test_command_names(),
test_subcommands(),
)
}
#[test]
fn test_input_bar_new() {
let bar = InputBarWidget::new("agent", "llama3.1:8b");
assert!(bar.content.is_empty());
assert_eq!(bar.cursor, 0);
assert!(bar.focused);
}
#[test]
fn test_input_bar_take_input() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let text = bar.take_input();
assert_eq!(text, "hello");
assert!(bar.content.is_empty());
assert_eq!(bar.cursor, 0);
assert_eq!(bar.history.len(), 1);
}
#[test]
fn test_input_bar_type_chars() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
let event = Event::Key(KeyEvent {
key: Key::Char('h'),
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "h");
assert_eq!(bar.cursor, 1);
let event = Event::Key(KeyEvent {
key: Key::Char('i'),
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "hi");
assert_eq!(bar.cursor, 2);
}
#[test]
fn test_input_bar_backspace() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Backspace,
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "hell");
assert_eq!(bar.cursor, 4);
}
#[test]
fn test_input_bar_enter_submits() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Enter,
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::SendMessage(ref s) if s == "hello"));
assert!(bar.content.is_empty());
}
#[test]
fn test_input_bar_shift_enter_newline() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Enter,
modifiers: Modifiers::shift(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::None));
assert_eq!(bar.content, "hello\n");
}
#[test]
fn test_input_bar_escape_clears() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Escape,
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::None));
assert!(bar.content.is_empty());
}
#[test]
fn test_tab_complete_command() {
let mut bar = bar_with_commands("agent", "llama3.1:8b");
bar.content = "/mod".to_string();
bar.cursor = 4;
let event = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "/mode");
assert_eq!(bar.cursor, 5);
}
#[test]
fn test_tab_complete_cycle() {
let mut bar = bar_with_commands("agent", "llama3.1:8b");
bar.content = "/co".to_string();
bar.cursor = 3;
let event = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
// First Tab — completes to first match
bar.handle_event(&event);
let first = bar.content.clone();
assert!(first.starts_with("/co"));
// Second Tab — cycles to next match
bar.handle_event(&event);
let second = bar.content.clone();
assert!(second.starts_with("/co"));
assert_ne!(first, second);
// Third Tab — cycles to next match
bar.handle_event(&event);
let third = bar.content.clone();
assert!(third.starts_with("/co"));
// Should cycle through /command, /compact, /context
assert_ne!(second, third);
}
#[test]
fn test_tab_complete_resets_on_typing() {
let mut bar = bar_with_commands("agent", "llama3.1:8b");
bar.content = "/mod".to_string();
bar.cursor = 4;
let tab = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
bar.handle_event(&tab);
assert_eq!(bar.content, "/mode");
// Type a character — should reset tab cycle state
let char_event = Event::Key(KeyEvent {
key: Key::Char(' '),
modifiers: Modifiers::new(),
});
bar.handle_event(&char_event);
assert_eq!(bar.content, "/mode ");
// Tab again — should start a new completion cycle for subcommands
bar.handle_event(&tab);
// "/mode " with subcommand completion for /mode
assert!(bar.content.starts_with("/mode "));
}
#[test]
fn test_tab_complete_subcommand() {
let mut bar = bar_with_commands("agent", "llama3.1:8b");
bar.content = "/command a".to_string();
bar.cursor = 10;
let event = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "/command add");
}
#[test]
fn test_tab_non_command_cycles_focus() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::CycleFocusForward));
// Content should be unchanged
assert_eq!(bar.content, "hello");
}
#[test]
fn test_shift_tab_cycles_focus_backward() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.content = "hello".to_string();
let event = Event::Key(KeyEvent {
key: Key::BackTab,
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::CycleFocusBackward));
}
#[test]
fn test_tab_complete_empty_prefix() {
let mut bar = bar_with_commands("agent", "llama3.1:8b");
bar.content = "/".to_string();
bar.cursor = 1;
let event = Event::Key(KeyEvent {
key: Key::Tab,
modifiers: Modifiers::new(),
});
bar.handle_event(&event);
// Should complete to the first command alphabetically
assert!(bar.content.starts_with('/'));
assert!(bar.content.len() > 1);
}
#[test]
fn test_is_command_input() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
assert!(!bar.is_command_input());
bar.content = "/help".to_string();
assert!(bar.is_command_input());
bar.content = "hello".to_string();
assert!(!bar.is_command_input());
}
#[test]
fn test_confirmation_mode_set() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
assert!(!bar.is_confirming());
bar.set_confirming(true);
assert!(bar.is_confirming());
assert!(bar.content.is_empty());
bar.set_confirming(false);
assert!(!bar.is_confirming());
}
#[test]
fn test_confirmation_y_approves() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Char('y'),
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::ConfirmYes));
assert!(!bar.is_confirming());
}
#[test]
fn test_confirmation_n_denies() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Char('n'),
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::ConfirmNo));
assert!(!bar.is_confirming());
}
#[test]
fn test_confirmation_a_approves_all() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Char('a'),
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::ConfirmAll));
assert!(!bar.is_confirming());
}
#[test]
fn test_confirmation_escape_denies() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Escape,
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::ConfirmNo));
assert!(!bar.is_confirming());
}
#[test]
fn test_confirmation_ignores_other_keys() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Char('x'),
modifiers: Modifiers::new(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::None));
assert!(bar.is_confirming()); // Still in confirmation mode
}
#[test]
fn test_confirmation_ctrl_y_ignored() {
let mut bar = InputBarWidget::new("agent", "llama3.1:8b");
bar.set_confirming(true);
let event = Event::Key(KeyEvent {
key: Key::Char('y'),
modifiers: Modifiers::ctrl(),
});
let action = bar.handle_event(&event);
assert!(matches!(action, Action::None));
assert!(bar.is_confirming()); // Ctrl+y should not confirm
}
// ── Emacs-style editing shortcut tests ─────────────────────────────
#[test]
fn test_ctrl_u_clears_before_cursor() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Char('u'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.content, " world");
assert_eq!(bar.cursor, 0);
}
#[test]
fn test_ctrl_k_clears_after_cursor() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Char('k'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "hello");
assert_eq!(bar.cursor, 5);
}
#[test]
fn test_ctrl_w_deletes_word_backward() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 11;
let event = Event::Key(KeyEvent {
key: Key::Char('w'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "hello ");
}
#[test]
fn test_ctrl_a_move_to_line_start() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 5;
let event = Event::Key(KeyEvent {
key: Key::Char('a'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.cursor, 0);
}
#[test]
fn test_ctrl_e_move_to_line_end() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 0;
let event = Event::Key(KeyEvent {
key: Key::Char('e'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.cursor, 11);
}
#[test]
fn test_ctrl_y_yanks_kill_ring() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 11;
// Kill "world" with Ctrl+W
let kill_event = Event::Key(KeyEvent {
key: Key::Char('w'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&kill_event);
assert_eq!(bar.content, "hello ");
assert_eq!(bar.kill_ring, "world");
// Yank it back
let yank_event = Event::Key(KeyEvent {
key: Key::Char('y'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&yank_event);
assert_eq!(bar.content, "hello world");
}
#[test]
fn test_ctrl_k_yank_roundtrip() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 5;
// Ctrl+K kills " world"
let event = Event::Key(KeyEvent {
key: Key::Char('k'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.content, "hello");
assert_eq!(bar.kill_ring, " world");
// Ctrl+Y yanks it back
let yank_event = Event::Key(KeyEvent {
key: Key::Char('y'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&yank_event);
assert_eq!(bar.content, "hello world");
}
#[test]
fn test_ctrl_u_yank_roundtrip() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world".to_string();
bar.cursor = 5;
// Ctrl+U kills "hello"
let event = Event::Key(KeyEvent {
key: Key::Char('u'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&event);
assert_eq!(bar.content, " world");
assert_eq!(bar.kill_ring, "hello");
// Ctrl+Y yanks it back
let yank_event = Event::Key(KeyEvent {
key: Key::Char('y'),
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&yank_event);
assert_eq!(bar.content, "hello world");
}
#[test]
fn test_ctrl_left_right_word_movement() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world test".to_string();
bar.cursor = 0;
// Ctrl+Right: jump forward by word (word + trailing whitespace)
let right_event = Event::Key(KeyEvent {
key: Key::Right,
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&right_event);
assert_eq!(bar.cursor, 6); // after "hello " (0 + 5 + 1 = 6)
bar.handle_event(&right_event);
assert_eq!(bar.cursor, 12); // after "world " (6 + 5 + 1 = 12)
// Ctrl+Left: jump back by word
let left_event = Event::Key(KeyEvent {
key: Key::Left,
modifiers: Modifiers::ctrl(),
});
bar.handle_event(&left_event);
assert_eq!(bar.cursor, 6); // before "world "
bar.handle_event(&left_event);
assert_eq!(bar.cursor, 0); // before "hello "
}
#[test]
fn test_alt_b_f_word_movement() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello world test".to_string();
bar.cursor = 16; // end
// Alt+B: move back by word
let alt_b = Event::Key(KeyEvent {
key: Key::Char('b'),
modifiers: Modifiers::alt(),
});
bar.handle_event(&alt_b);
assert_eq!(bar.cursor, 12); // before "test"
bar.handle_event(&alt_b);
assert_eq!(bar.cursor, 6); // before "world"
// Alt+F: move forward by word (skips word + trailing whitespace)
let alt_f = Event::Key(KeyEvent {
key: Key::Char('f'),
modifiers: Modifiers::alt(),
});
bar.handle_event(&alt_f);
assert_eq!(bar.cursor, 12); // after "world " (6 + 5 + 1 = 12)
bar.handle_event(&alt_f);
assert_eq!(bar.cursor, 16); // after "test" (12 + 4 = 16)
}
#[test]
fn test_bracketed_paste() {
let mut bar = InputBarWidget::new("agent", "test");
bar.content = "hello".to_string();
bar.cursor = 5;
let event = Event::Paste(" world from paste".to_string());
bar.handle_event(&event);
assert_eq!(bar.content, "hello world from paste");
assert_eq!(bar.cursor, 22);
}
#[test]
fn test_bracketed_paste_ignored_in_confirmation_mode() {
let mut bar = InputBarWidget::new("agent", "test");
bar.set_confirming(true);
let event = Event::Paste("pasted text".to_string());
bar.handle_event(&event);
// In confirmation mode, paste should be ignored
assert!(bar.content.is_empty());
}
#[test]
fn test_bracketed_paste_ignored_in_question_mode() {
let mut bar = InputBarWidget::new("agent", "test");
bar.set_questioning(true, 3);
// Actually, question mode does allow typing. Let's just test it doesn't crash.
let event = Event::Paste("test".to_string());
bar.handle_event(&event);
// Paste is ignored in question mode per our implementation
}
#[test]
fn test_question_mode_render_multibyte_no_panic() {
// Regression test: non-ASCII content in questioning mode should not
// panic when the display is truncated to fit the available width.
// The old code used content.len().saturating_sub(available_width) as a
// byte offset, which could land mid-character and panic.
let mut screen = Screen::new(30, 5);
let mut bar = InputBarWidget::new("agent", "test");
bar.set_questioning(true, 3);
// Fill with CJK characters (3 bytes each, display width 2)
bar.content = "你好世界测试".to_string(); // 6 chars, 18 bytes, width 12
bar.cursor = bar.content.len();
let area = Rect::new(0, 0, 30, 5);
bar.render(area, &mut screen);
// Should not panic — that's the test
}
#[test]
fn test_question_mode_render_cursor_position_with_truncation() {
// When content is truncated in question mode, the cursor should be
// positioned correctly relative to the displayed (truncated) text.
let mut screen = Screen::new(20, 5);
let mut bar = InputBarWidget::new("agent", "test");
bar.set_questioning(true, 3);
// Content wider than available width so it gets truncated
bar.content = "abcdefghij".to_string(); // 10 chars, width 10
bar.cursor = 8; // cursor at 'i'
let area = Rect::new(0, 0, 20, 5);
bar.render(area, &mut screen);
// Should not panic and cursor should be visible
}
}