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
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
//! Input handling — keyboard events, history, and approval interception.
use super::events::{AppMode, ToolApprovalResponse, TuiEvent};
use super::*;
use anyhow::Result;
use tokio::sync::mpsc;
use uuid::Uuid;
/// Detect whether a character is likely part of a mouse tracking CSI sequence
/// that crossterm failed to parse (e.g. `[<35;116;77M` arriving as individual
/// chars after ESC was consumed as KeyCode::Esc).
///
/// Strategy: scan the recent tail for the start of either:
///
/// - SGR mouse mode (1006): `\x1b[<Cb;Cx;Cy[Mm]` — visible as `[<…M/m`
/// - URXVT mouse mode (1015): `\x1b[Cb;Cx;Cy M` — visible as `[N;…M`
///
/// crossterm enables both modes (`EnableMouseCapture` emits `?1015h ?1006h`)
/// and some terminals fall back to URXVT for motion events. If the tail
/// matches either prefix and the current char fits the continuation pattern
/// (digits, `;`, `M`, `m`) we treat it as garbage.
pub(crate) fn is_mouse_sequence_fragment(c: char, buf: &str, cursor: usize) -> bool {
// Only bother checking chars that actually appear in mouse sequences
if !matches!(c, '[' | '<' | '>' | 'M' | 'm' | ';') && !c.is_ascii_digit() {
return false;
}
let mut tail_start = cursor.saturating_sub(30);
// Snap to a char boundary — cursor.saturating_sub(30) can land inside
// a multi-byte character (e.g. 🦀 is 4 bytes).
while tail_start > 0 && !buf.is_char_boundary(tail_start) {
tail_start -= 1;
}
let tail = &buf[tail_start..cursor];
// SGR mode (1006): `[<` anywhere in the tail starts the sequence.
// Everything after it (digits, ;, M/m) is garbage until a non-matching char.
if let Some(csi_pos) = tail.rfind("[<") {
let after_csi = &tail[csi_pos + 2..];
if after_csi
.chars()
.all(|ch| ch.is_ascii_digit() || matches!(ch, ';' | 'M' | 'm'))
{
return true;
}
}
// URXVT mode (1015): the rightmost `[` in the tail is followed only by
// digits/`;` — that's the cb;cx;cy stretch of `\x1b[Cb;Cx;Cy M`. Skip
// when the bracket is followed by `<` since that's already handled above.
// Requires at least one digit between `[` and the cursor so we don't
// false-fire on a bare `[` that the user just typed.
if let Some(bracket_pos) = tail.rfind('[') {
let after_bracket = &tail[bracket_pos + 1..];
if !after_bracket.starts_with('<')
&& !after_bracket.is_empty()
&& after_bracket
.chars()
.all(|ch| ch.is_ascii_digit() || ch == ';')
&& matches!(c, '0'..='9' | ';' | 'M' | 'm')
{
return true;
}
}
// `[` at the end of tail = CSI just started; the next char picks the
// mode (`<` for SGR, digit for URXVT, letter for other CSI) or
// continues a sequence whose intermediate bytes were already
// suppressed (which leaves `;` or `M`/`m` showing up here too).
// Any of those after a stray `[` is garbage.
if tail.ends_with('[') && matches!(c, '<' | 'A'..='Z' | 'a'..='z' | '0'..='9' | ';') {
return true;
}
// Tail ends with `[<` partially built — suppress digits/; that follow
if tail.ends_with("[<")
|| tail.ends_with(|ch: char| ch.is_ascii_digit() || ch == ';') && tail.contains("[<")
{
return matches!(c, '0'..='9' | ';' | 'M' | 'm');
}
false
}
/// Find the byte offset in `text` where the cumulative display width reaches `target_col`.
fn byte_offset_at_display_col(text: &str, target_col: usize) -> usize {
let mut width = 0usize;
for (idx, ch) in text.char_indices() {
if width >= target_col {
return idx;
}
width += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
}
text.len()
}
impl App {
/// Remove mouse tracking / CSI escape fragments from `input_buffer`.
///
/// When tmux pane-switches while mouse capture is active, raw mouse
/// sequences get split across reads and crossterm delivers them as
/// individual `Key(Char(...))` events. Both formats leak this way:
///
/// - SGR mode (1006): `\x1b[<35;116;77M` → `[`, `<`, digits, `;`, `M`
/// - URXVT mode (1015): `\x1b[35;116;77M` → `[`, digits, `;`, `M`
///
/// On `FocusGained` we scrub anything that looks like these fragments
/// so the user doesn't see garbage.
pub fn clear_escape_garbage(&mut self) {
if self.input_buffer.is_empty() {
return;
}
// Fast path: detect dominance by either of the leak signatures.
// The SGR set (`\x1b`, `[`, `<`, `M`, `m`, `^`) was the original
// trigger; URXVT motion bursts produce mostly digits and `;` so
// a separate "lots of `[NN;` clusters" check catches them too.
let dominated_by_garbage = {
let total = self.input_buffer.len();
let sgr_chars = self
.input_buffer
.chars()
.filter(|c| matches!(c, '\x1b' | '[' | '<' | 'M' | 'm' | '^'))
.count();
let urxvt_chars = self
.input_buffer
.chars()
.filter(|c| c.is_ascii_digit() || matches!(c, ';' | '[' | 'M' | 'm'))
.count();
// 30% threshold for SGR (small alphabet, harder to false-fire),
// 80% for URXVT (digits + `;` + `[` cover so much of normal
// typing that we need to be confident before scrubbing).
total > 5 && (sgr_chars * 100 / total > 30 || urxvt_chars * 100 / total > 80)
};
if !dominated_by_garbage {
return;
}
// Strip escape sequences via the same helper used for paste events
let cleaned = Self::strip_terminal_escapes(&self.input_buffer);
// Also remove leftover mouse-sequence fragment chars that arrived as
// individual key events. Digits and `;` are added when the buffer
// is dominated by URXVT-style fragments — otherwise we'd nuke any
// legit text the user mixed in (e.g. "5; ").
let strip_urxvt_chars = {
let total = cleaned.chars().count().max(1);
let urxvt_run = cleaned
.chars()
.filter(|c| c.is_ascii_digit() || matches!(c, ';' | '[' | 'M' | 'm'))
.count();
urxvt_run * 100 / total > 80
};
let cleaned: String = cleaned
.chars()
.filter(|c| {
if matches!(c, '[' | '<' | '>' | 'M' | 'm' | '^') {
return false;
}
if strip_urxvt_chars && (c.is_ascii_digit() || *c == ';') {
return false;
}
true
})
.collect();
if cleaned.trim().is_empty() {
tracing::debug!(
"Cleared {} bytes of escape garbage from input buffer",
self.input_buffer.len()
);
self.input_buffer.clear();
self.cursor_position = 0;
} else {
self.input_buffer = cleaned;
self.cursor_position = self.input_buffer.len().min(self.cursor_position);
}
}
/// Returns (line_start_byte, column_bytes) for the cursor's current logical line.
/// `line_start_byte` is the byte offset where the current line begins (after `\n`).
/// `column_bytes` is how many bytes into the line the cursor is.
fn cursor_line_position(&self) -> (usize, usize) {
let line_start = self.input_buffer[..self.cursor_position]
.rfind('\n')
.map(|i| i + 1)
.unwrap_or(0);
let col = self.cursor_position - line_start;
(line_start, col)
}
/// Get the effective text width per visual line in the input box.
/// Accounts for borders (2) and prefix/padding (2).
fn input_visual_line_width() -> usize {
let term_width = crossterm::terminal::size()
.map(|(w, _)| w as usize)
.unwrap_or(80);
// input_content_width = term_width - 2 (borders)
// text area = input_content_width - 2 (prefix "❯ " or padding " ")
term_width.saturating_sub(4).max(10)
}
/// Read-only predicate: is there anywhere for the cursor to move up to?
/// True whenever the cursor isn't already at the very start of the
/// buffer — this covers visual rows, logical lines, and "move to 0"
/// when we're already on the first line but mid-line.
fn can_cursor_move_up(&self) -> bool {
self.cursor_position > 0
}
/// Read-only predicate: is there anywhere for the cursor to move down to?
/// True whenever the cursor isn't already at the very end of the buffer.
fn can_cursor_move_down(&self) -> bool {
self.cursor_position < self.input_buffer.len()
}
/// Move cursor up one visual line within a logical line, accounting for soft wrapping.
/// Returns true if the cursor moved, false if already on the first visual line.
fn cursor_visual_up(&mut self) -> bool {
use unicode_width::UnicodeWidthStr;
let (line_start, _col_bytes) = self.cursor_line_position();
let text_before = &self.input_buffer[line_start..self.cursor_position];
let display_col = text_before.width();
let vw = Self::input_visual_line_width();
let visual_row = display_col / vw;
if visual_row == 0 {
// Already on first visual line of this logical line
return false;
}
// Target: same display column but one visual row up
let target_display_col = (visual_row - 1) * vw + (display_col % vw);
// Find byte offset at that display column within this logical line
let line_text = &self.input_buffer[line_start..];
let line_end = line_text.find('\n').unwrap_or(line_text.len());
let line_text = &line_text[..line_end];
self.cursor_position =
line_start + byte_offset_at_display_col(line_text, target_display_col);
true
}
/// Move cursor down one visual line within a logical line, accounting for soft wrapping.
/// Returns true if the cursor moved, false if already on the last visual line.
fn cursor_visual_down(&mut self) -> bool {
use unicode_width::UnicodeWidthStr;
let (line_start, _col_bytes) = self.cursor_line_position();
let text_before = &self.input_buffer[line_start..self.cursor_position];
let display_col = text_before.width();
let vw = Self::input_visual_line_width();
// Get full logical line
let line_text = &self.input_buffer[line_start..];
let line_end = line_text.find('\n').unwrap_or(line_text.len());
let line_text = &line_text[..line_end];
let total_width = line_text.width();
let visual_row = display_col / vw;
let max_visual_row = if total_width == 0 {
0
} else {
(total_width.saturating_sub(1)) / vw
};
if visual_row >= max_visual_row {
// Already on last visual line of this logical line
return false;
}
// Target: same display column but one visual row down
let target_display_col = ((visual_row + 1) * vw + (display_col % vw)).min(total_width);
self.cursor_position =
line_start + byte_offset_at_display_col(line_text, target_display_col);
true
}
/// Map terminal row to message index using the render-time line mapping
fn row_to_msg_idx(&self, row: u16) -> Option<usize> {
let row_in_chat = row.saturating_sub(self.chat_area_y + 1) as usize;
let line_idx = self.chat_render_scroll + row_in_chat;
self.chat_line_to_msg.get(line_idx).copied().flatten()
}
/// Left-click: select/highlight a message
pub(crate) fn handle_click_select(&mut self, row: u16) {
// A fresh click clears any in-flight drag selection and message highlight.
self.drag_anchor = None;
self.drag_current = None;
let msg_idx = self.row_to_msg_idx(row);
// Toggle: click same message deselects, click different selects
if self.selected_message_idx == msg_idx {
self.selected_message_idx = None;
} else {
self.selected_message_idx = msg_idx;
}
}
/// Left-button drag — update the live drag selection.
/// The anchor is the click position (captured on the first drag event
/// because crossterm does not deliver drags until the pointer moves).
pub(crate) fn handle_mouse_drag(&mut self, col: u16, row: u16) {
if self.drag_anchor.is_none() {
self.drag_anchor = Some((col, row));
// While drag-selecting we suppress the message highlight so the
// two visual cues don't fight.
self.selected_message_idx = None;
}
self.drag_current = Some((col, row));
}
/// Left-button released — finalize selection, extract text, copy, notify.
pub(crate) fn handle_mouse_up(&mut self, col: u16, row: u16) {
// If this was a plain click (no drag motion), treat it as a click-select.
let Some(anchor) = self.drag_anchor.take() else {
self.drag_current = None;
self.handle_click_select(row);
return;
};
let end = (col, row);
self.drag_current = None;
let text = self.extract_drag_selection(anchor, end);
if text.trim().is_empty() {
return;
}
if Self::copy_to_clipboard(&text) {
self.notification = Some("Copied to clipboard".to_string());
self.notification_shown_at = Some(std::time::Instant::now());
}
}
/// Turn a pair of terminal-screen coordinates into the plain-text that was
/// drawn between them. Strips leading chat padding and code-block gutter
/// (e.g. `" 1 │ "`) so the copied text matches what the user visually sees.
fn extract_drag_selection(&self, a: (u16, u16), b: (u16, u16)) -> String {
// Normalize so (start) precedes (end) in reading order.
let (start, end) = if (a.1, a.0) <= (b.1, b.0) {
(a, b)
} else {
(b, a)
};
let chat_left = self.chat_area_x;
let chat_top = self.chat_area_y;
let chat_height = self.chat_area_height as usize;
if chat_height == 0 {
return String::new();
}
// Screen row → logical line index in `chat_rendered_lines`.
// Render uses `Padding::new(1,1,1,0)` on the inner block, so the first
// line of text is drawn at `chat_top + 1`.
let top_pad = 1u16;
let row_to_line = |row: u16| -> Option<usize> {
let row_in_chat = row.checked_sub(chat_top + top_pad)? as usize;
if row_in_chat >= chat_height.saturating_sub(top_pad as usize) {
return None;
}
Some(self.chat_render_scroll + row_in_chat)
};
// Content starts one cell in (Padding left = 1).
let content_left = chat_left + 1;
let col_in_line = |col: u16| -> usize { col.saturating_sub(content_left) as usize };
let start_line = row_to_line(start.1);
let end_line = row_to_line(end.1);
let (Some(start_line), Some(end_line)) = (start_line, end_line) else {
return String::new();
};
let strip_gutter = |s: &str| -> String {
// Trim leading spaces first.
let trimmed = s.trim_start();
// Code-block lines look like " 1 │ fn main()" → after trim_start:
// "1 │ fn main()". Strip the "<digits> │ " prefix if present.
if let Some(rest) = trimmed.strip_prefix(|c: char| c.is_ascii_digit()) {
let rest = rest.trim_start_matches(|c: char| c.is_ascii_digit());
if let Some(after_bar) = rest.strip_prefix(" │ ") {
return after_bar.to_string();
}
if let Some(after_bar) = rest.strip_prefix("│ ") {
return after_bar.to_string();
}
}
trimmed.to_string()
};
// Helper to slice a line by display-column range (char-based is fine
// for monospaced ASCII; for multi-byte we fall back to char indices).
let slice_line = |line: &str, from: usize, to: usize| -> String {
let chars: Vec<char> = line.chars().collect();
let from = from.min(chars.len());
let to = to.min(chars.len());
if from >= to {
return String::new();
}
chars[from..to].iter().collect()
};
let mut out = String::new();
if start_line == end_line {
let Some(line) = self.chat_rendered_lines.get(start_line) else {
return String::new();
};
let from = col_in_line(start.0);
let to = col_in_line(end.0).max(from);
let piece = slice_line(line, from, to + 1);
out.push_str(&strip_gutter(&piece));
} else {
for (i, line_idx) in (start_line..=end_line).enumerate() {
let Some(line) = self.chat_rendered_lines.get(line_idx) else {
continue;
};
let piece = if i == 0 {
// First line: from start.col to EOL
let from = col_in_line(start.0);
slice_line(line, from, line.chars().count())
} else if line_idx == end_line {
// Last line: from 0 to end.col (inclusive)
let to = col_in_line(end.0) + 1;
slice_line(line, 0, to)
} else {
line.clone()
};
let cleaned = strip_gutter(&piece);
// Skip purely-whitespace lines to match opencode's "no empty lines" UX.
if !cleaned.trim().is_empty() {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&cleaned);
}
}
}
out
}
/// Right-click: copy the clicked (or selected) message to clipboard
pub(crate) fn handle_right_click_copy(&mut self, row: u16) {
// Use clicked message, or fall back to already-selected message
let msg_idx = self.row_to_msg_idx(row).or(self.selected_message_idx);
let Some(idx) = msg_idx else { return };
let content = match self.messages.get(idx) {
Some(msg) if !msg.content.trim().is_empty() => msg.content.clone(),
_ => return,
};
if Self::copy_to_clipboard(&content) {
self.notification = Some("Copied to clipboard".to_string());
self.notification_shown_at = Some(std::time::Instant::now());
self.selected_message_idx = None;
}
}
/// Handle mouse drag in the input area — track text selection.
pub(crate) fn handle_input_mouse_drag(&mut self, col: u16, row: u16) {
if self.input_area_height == 0 {
return;
}
// Check if mouse is within input area
if row < self.input_area_y || row >= self.input_area_y + self.input_area_height {
return;
}
if !self.input_drag_selecting {
self.input_drag_selecting = true;
self.input_drag_anchor = Some((col, row));
// Clear any chat drag selection
self.drag_anchor = None;
self.drag_current = None;
}
self.input_drag_current = Some((col, row));
}
/// Handle mouse up in the input area — finalize selection and copy.
/// Returns true if text was copied.
pub(crate) fn handle_input_mouse_up(&mut self, col: u16, row: u16) -> bool {
if !self.input_drag_selecting {
return false;
}
self.input_drag_selecting = false;
let Some(anchor) = self.input_drag_anchor.take() else {
self.input_drag_current = None;
return false;
};
self.input_drag_current = None;
let text = self.extract_input_drag_selection(anchor, (col, row));
if text.trim().is_empty() {
return false;
}
Self::copy_to_clipboard(&text)
}
/// Extract text from input buffer based on drag selection coordinates.
fn extract_input_drag_selection(&self, a: (u16, u16), b: (u16, u16)) -> String {
let (start, end) = if (a.1, a.0) <= (b.1, b.0) {
(a, b)
} else {
(b, a)
};
let input_top = self.input_area_y;
let input_left = self.input_area_x;
let content_left = input_left + 2;
let input_width = self.input_area_width.saturating_sub(2) as usize;
if input_width == 0 || self.input_buffer.is_empty() {
return String::new();
}
// Build visual rows: each is (global_byte_start, global_byte_end)
let buf = &self.input_buffer;
let blen = buf.len();
let mut visual_rows: Vec<(usize, usize)> = Vec::new();
let mut ls = 0usize;
while ls <= blen {
let le = buf[ls..].find('\n').map(|i| ls + i).unwrap_or(blen);
let line = &buf[ls..le];
let lw = unicode_width::UnicodeWidthStr::width(line);
let rows = if lw == 0 { 1 } else { lw.div_ceil(input_width) };
for vr in 0..rows {
let chunk_start_display = vr * input_width;
let chunk_end_display = chunk_start_display + input_width;
let mut disp_w = 0;
let mut char_start = 0;
let mut char_end = line.len();
for (idx, ch) in line.char_indices() {
let cw = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if vr == 0 && disp_w + cw > chunk_end_display {
char_end = idx;
break;
}
if vr > 0 {
if disp_w < chunk_start_display {
char_start = idx;
}
if disp_w + cw > chunk_end_display {
char_end = idx;
break;
}
}
disp_w += cw;
}
visual_rows.push((ls + char_start, ls + char_end));
}
if le == blen {
break;
}
ls = le + 1;
}
// Map visual row + column to byte offset
let map_to_byte = |vr: usize, col: u16| -> usize {
if vr >= visual_rows.len() {
return blen;
}
let (rs, re) = visual_rows[vr];
let chunk = &buf[rs..re];
let target_disp = col.saturating_sub(content_left) as usize;
let mut w = 0;
for (idx, ch) in chunk.char_indices() {
if w >= target_disp {
return rs + idx;
}
w += unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
}
re
};
let start_visual = start.1.saturating_sub(input_top + 1) as usize;
let end_visual = end.1.saturating_sub(input_top + 1) as usize;
let from = map_to_byte(start_visual, start.0);
let to = map_to_byte(end_visual, end.0);
buf[from.min(to)..from.max(to)].to_string()
}
/// Copy text to system clipboard
fn copy_to_clipboard(text: &str) -> bool {
use std::io::Write;
use std::process::{Command, Stdio};
// Try pbcopy (macOS)
if let Ok(mut child) = Command::new("pbcopy")
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
if let Some(ref mut stdin) = child.stdin {
let _ = stdin.write_all(text.as_bytes());
}
return child.wait().is_ok_and(|s| s.success());
}
// Try xclip (Linux)
if let Ok(mut child) = Command::new("xclip")
.args(["-selection", "clipboard"])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
if let Some(ref mut stdin) = child.stdin {
let _ = stdin.write_all(text.as_bytes());
}
return child.wait().is_ok_and(|s| s.success());
}
// Try xsel (Linux fallback)
if let Ok(mut child) = Command::new("xsel")
.args(["--clipboard", "--input"])
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()
{
if let Some(ref mut stdin) = child.stdin {
let _ = stdin.write_all(text.as_bytes());
}
return child.wait().is_ok_and(|s| s.success());
}
false
}
/// Delete the word before the cursor (for Ctrl+Backspace and Alt+Backspace)
pub(crate) fn delete_last_word(&mut self) {
if self.cursor_position == 0 {
return;
}
let before = &self.input_buffer[..self.cursor_position];
// Skip trailing whitespace
let trimmed = before.trim_end();
// Find the last whitespace boundary in the trimmed portion.
// Use ceil_char_boundary to handle multi-byte whitespace safely.
let word_start = trimmed
.rfind(char::is_whitespace)
.map(|pos| trimmed.ceil_char_boundary(pos + 1))
.unwrap_or(0);
// Remove from word_start to cursor_position
self.input_buffer.drain(word_start..self.cursor_position);
self.cursor_position = word_start;
}
/// History file path: ~/.opencrabs/history.txt
fn history_path() -> Option<std::path::PathBuf> {
Some(crate::config::opencrabs_home().join("history.txt"))
}
/// Load input history from disk (one entry per line, most recent last)
pub(crate) fn load_history() -> Vec<String> {
let Some(path) = Self::history_path() else {
return Vec::new();
};
match std::fs::read_to_string(&path) {
Ok(content) => content
.lines()
.filter(|l| !l.is_empty())
.map(|l| l.to_string())
.collect(),
Err(_) => Vec::new(),
}
}
/// Append a single entry to the history file (and trim to 500 entries)
fn save_history_entry(&self, entry: &str) {
let Some(path) = Self::history_path() else {
return;
};
// Ensure directory exists
if let Some(parent) = path.parent() {
let _ = std::fs::create_dir_all(parent);
}
// Cap at 500 entries: keep last 499 + new entry
let max_entries = 500;
if self.input_history.len() > max_entries {
// Rewrite the whole file with only the last max_entries
let start = self.input_history.len().saturating_sub(max_entries);
let trimmed: Vec<&str> = self.input_history[start..]
.iter()
.map(|s| s.as_str())
.collect();
let _ = std::fs::write(&path, trimmed.join("\n") + "\n");
} else {
// Just append
use std::io::Write;
if let Ok(mut f) = std::fs::OpenOptions::new()
.create(true)
.append(true)
.open(&path)
{
let _ = writeln!(f, "{}", entry);
}
}
}
pub fn has_pending_approval(&self) -> bool {
self.messages.iter().rev().any(|msg| {
msg.approval
.as_ref()
.is_some_and(|a| a.state == ApprovalState::Pending)
})
}
pub(crate) fn has_pending_approve_menu(&self) -> bool {
self.messages.iter().rev().any(|msg| {
msg.approve_menu
.as_ref()
.is_some_and(|m| m.state == ApproveMenuState::Pending)
})
}
/// Handle keys in chat mode
pub(crate) async fn handle_chat_key(
&mut self,
event: crossterm::event::KeyEvent,
) -> Result<()> {
use super::events::keys;
use crossterm::event::{KeyCode, KeyModifiers};
// Intercept keys when /approve menu is pending
if self.has_pending_approve_menu() {
if keys::is_up(&event) {
if let Some(menu) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approve_menu.as_mut())
.filter(|m| m.state == ApproveMenuState::Pending)
{
menu.selected_option = menu.selected_option.saturating_sub(1);
}
return Ok(());
} else if keys::is_down(&event) {
if let Some(menu) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approve_menu.as_mut())
.filter(|m| m.state == ApproveMenuState::Pending)
{
menu.selected_option = (menu.selected_option + 1).min(2);
}
return Ok(());
} else if keys::is_enter(&event) || keys::is_submit(&event) {
let selected = self
.messages
.iter()
.rev()
.find_map(|m| m.approve_menu.as_ref())
.filter(|m| m.state == ApproveMenuState::Pending)
.map(|m| m.selected_option)
.unwrap_or(0);
// Apply policy
match selected {
0 => {
// Reset to approve-only
self.approval_auto_session = false;
self.approval_auto_always = false;
}
1 => {
// Allow all for this session
self.approval_auto_session = true;
self.approval_auto_always = false;
}
_ => {
// Yolo mode
self.approval_auto_session = false;
self.approval_auto_always = true;
}
}
let label = match selected {
0 => "Approve-only (always ask)",
1 => "Allow all for this session",
_ => "Yolo mode (execute without approval)",
};
// Mark menu as resolved
if let Some(menu) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approve_menu.as_mut())
.filter(|m| m.state == ApproveMenuState::Pending)
{
menu.state = ApproveMenuState::Selected(selected);
}
// Persist to config.toml
let policy_str = match selected {
0 => "ask",
1 => "auto-session",
_ => "auto-always",
};
if let Err(e) =
crate::config::Config::write_key("agent", "approval_policy", policy_str)
{
tracing::warn!("Failed to persist approval policy: {}", e);
}
// Rebuild the agent service so tool_loop.auto_approve_tools
// matches the new policy — otherwise the compaction/continuation
// system prompt keeps injecting "AUTO-APPROVE OFF" even after
// the user switches to yolo mode.
if let Err(e) = self.rebuild_agent_service().await {
tracing::warn!("Failed to rebuild agent service after /approve: {}", e);
}
self.push_system_message(format!("Approval policy set to: {}", label));
return Ok(());
} else if keys::is_cancel(&event) {
// Cancel — dismiss menu without changing policy
if let Some(menu) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approve_menu.as_mut())
.filter(|m| m.state == ApproveMenuState::Pending)
{
menu.state = ApproveMenuState::Selected(99); // sentinel for cancelled
}
self.push_system_message("Approval policy unchanged.".to_string());
return Ok(());
}
return Ok(());
}
// Intercept keys when an inline approval is pending
// Options: Yes(0), Always(1), No(2)
if self.has_pending_approval() {
if keys::is_left(&event) || keys::is_up(&event) {
// Navigate options left
if let Some(approval) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approval.as_mut())
.filter(|a| a.state == ApprovalState::Pending)
{
approval.selected_option = approval.selected_option.saturating_sub(1);
}
return Ok(());
} else if keys::is_right(&event) || keys::is_down(&event) {
// Navigate options right
if let Some(approval) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approval.as_mut())
.filter(|a| a.state == ApprovalState::Pending)
{
approval.selected_option = (approval.selected_option + 1).min(2);
}
return Ok(());
} else if keys::is_enter(&event) || keys::is_submit(&event) {
// Confirm: Yes(0)=approve once, Always(1)=approve always, No(2)=deny
let approval_data: Option<(
Uuid,
usize,
mpsc::UnboundedSender<ToolApprovalResponse>,
)> = self
.messages
.iter()
.rev()
.find_map(|m| m.approval.as_ref())
.filter(|a| a.state == ApprovalState::Pending)
.map(|a| (a.request_id, a.selected_option, a.response_tx.clone()));
if let Some((request_id, selected, response_tx)) = approval_data {
if selected == 2 {
// "No" — deny
let response = ToolApprovalResponse {
request_id,
approved: false,
reason: Some("User denied permission".to_string()),
};
if let Err(e) = response_tx.send(response.clone()) {
tracing::error!(
"Failed to send denial response back to agent: {:?}",
e
);
}
let _ = self
.event_sender()
.send(TuiEvent::ToolApprovalResponse(response));
} else {
// "Yes" (0) or "Always" (1)
let option = if selected == 1 {
ApprovalOption::AllowAlways
} else {
ApprovalOption::AllowOnce
};
if matches!(option, ApprovalOption::AllowAlways) {
self.approval_auto_session = true;
crate::utils::persist_auto_session_policy();
self.push_system_message(
"Auto-approve enabled for this session. Use /approve to reset."
.to_string(),
);
}
let response = ToolApprovalResponse {
request_id,
approved: true,
reason: None,
};
if let Err(e) = response_tx.send(response.clone()) {
tracing::error!(
"Failed to send approval response back to agent: {:?}",
e
);
}
let _ = self
.event_sender()
.send(TuiEvent::ToolApprovalResponse(response));
}
// Remove resolved approval messages to prevent channel accumulation
self.messages.retain(|m| {
m.approval
.as_ref()
.is_none_or(|a| a.request_id != request_id)
});
}
return Ok(());
} else if keys::is_deny(&event) || keys::is_cancel(&event) {
// D/Esc shortcut — deny directly
let approval_data: Option<(Uuid, mpsc::UnboundedSender<ToolApprovalResponse>)> =
self.messages
.iter()
.rev()
.find_map(|m| m.approval.as_ref())
.filter(|a| a.state == ApprovalState::Pending)
.map(|a| (a.request_id, a.response_tx.clone()));
if let Some((request_id, response_tx)) = approval_data {
let response = ToolApprovalResponse {
request_id,
approved: false,
reason: Some("User denied permission".to_string()),
};
if let Err(e) = response_tx.send(response.clone()) {
tracing::error!("Failed to send denial response back to agent: {:?}", e);
}
let _ = self
.event_sender()
.send(TuiEvent::ToolApprovalResponse(response));
// Remove resolved approval message
self.messages.retain(|m| {
m.approval
.as_ref()
.is_none_or(|a| a.request_id != request_id)
});
}
return Ok(());
} else if keys::is_view_details(&event) {
// V key — toggle details
if let Some(approval) = self
.messages
.iter_mut()
.rev()
.find_map(|m| m.approval.as_mut())
.filter(|a| a.state == ApprovalState::Pending)
{
approval.show_details = !approval.show_details;
}
return Ok(());
} else if event.code == KeyCode::Char('o') && event.modifiers == KeyModifiers::CONTROL {
// Allow Ctrl+O during approval so user can collapse tool groups to see the approval
let target = if let Some(ref group) = self.active_tool_group {
!group.expanded
} else if let Some(msg) =
self.messages.iter().rev().find(|m| m.tool_group.is_some())
{
!msg.tool_group.as_ref().expect("checked").expanded
} else {
true
};
if let Some(ref mut group) = self.active_tool_group {
group.expanded = target;
}
for msg in self.messages.iter_mut() {
if let Some(ref mut group) = msg.tool_group {
group.expanded = target;
}
}
return Ok(());
}
// Other keys ignored while approval pending
return Ok(());
}
// When slash suggestions are active, intercept navigation keys
if self.slash_suggestions_active {
if keys::is_up(&event) {
self.slash_selected_index = self.slash_selected_index.saturating_sub(1);
return Ok(());
} else if keys::is_down(&event) {
if !self.slash_filtered.is_empty() {
self.slash_selected_index =
(self.slash_selected_index + 1).min(self.slash_filtered.len() - 1);
}
return Ok(());
} else if keys::is_enter(&event) || keys::is_submit(&event) {
// Select the highlighted command and execute it
if let Some(&cmd_idx) = self.slash_filtered.get(self.slash_selected_index) {
let cmd_name = self.slash_command_name(cmd_idx).unwrap_or("").to_string();
self.input_buffer.clear();
self.cursor_position = 0;
self.slash_suggestions_active = false;
self.handle_slash_command(&cmd_name).await;
}
return Ok(());
} else if keys::is_cancel(&event) {
// Dismiss dropdown but keep input
self.slash_suggestions_active = false;
return Ok(());
}
// Other keys fall through to normal handling
}
// When emoji picker is active, intercept navigation keys
if self.emoji_picker_active {
if keys::is_up(&event) {
self.emoji_selected_index = self.emoji_selected_index.saturating_sub(1);
return Ok(());
} else if keys::is_down(&event) {
if !self.emoji_filtered.is_empty() {
self.emoji_selected_index =
(self.emoji_selected_index + 1).min(self.emoji_filtered.len() - 1);
}
return Ok(());
} else if event.code == KeyCode::Tab
|| keys::is_enter(&event)
|| keys::is_submit(&event)
{
self.accept_emoji();
return Ok(());
} else if keys::is_cancel(&event) {
self.dismiss_emoji_picker();
return Ok(());
}
// Other keys fall through to normal handling (typing more chars refines the filter)
}
// Any key other than Escape resets escape confirmation
if !keys::is_cancel(&event) {
self.escape_pending_at = None;
}
// --- Attachment focus navigation ---
// When an attachment is focused, Up/Down navigate between attachments,
// Backspace/Delete removes the focused one, any other key returns to input.
if self.focused_attachment.is_some() {
if keys::is_up(&event) {
// Move to previous attachment (or stay at first)
if let Some(idx) = self.focused_attachment
&& idx > 0
{
self.focused_attachment = Some(idx - 1);
}
return Ok(());
} else if keys::is_down(&event) {
// Move to next attachment, or return to input if at last
if let Some(idx) = self.focused_attachment {
if idx + 1 < self.attachments.len() {
self.focused_attachment = Some(idx + 1);
} else {
self.focused_attachment = None; // back to input
}
}
return Ok(());
} else if event.code == KeyCode::Backspace || event.code == KeyCode::Delete {
// Remove the focused attachment
if let Some(idx) = self.focused_attachment
&& idx < self.attachments.len()
{
self.attachments.remove(idx);
// Adjust focus: stay on same index if more remain, else move back
if self.attachments.is_empty() {
self.focused_attachment = None;
} else if idx >= self.attachments.len() {
self.focused_attachment = Some(self.attachments.len() - 1);
}
}
return Ok(());
} else if keys::is_cancel(&event) {
// Escape returns to input without removing
self.focused_attachment = None;
return Ok(());
} else {
// Any other key returns to input
self.focused_attachment = None;
// Fall through to handle the key normally
}
}
if keys::is_newline(&event) {
// Alt+Enter or Shift+Enter = insert newline for multi-line input
self.input_buffer.insert(self.cursor_position, '\n');
self.cursor_position += 1;
} else if keys::is_submit(&event)
&& (!self.input_buffer.trim().is_empty() || !self.attachments.is_empty())
{
// Check for slash commands before sending to LLM
let content = self.input_buffer.clone();
if self.handle_slash_command(content.trim()).await {
self.input_buffer.clear();
self.cursor_position = 0;
self.slash_suggestions_active = false;
self.dismiss_emoji_picker();
return Ok(());
}
// Bang operator: `!cmd args` runs a shell command directly in the
// current working directory and pushes stdout/stderr as a system
// message — no LLM, no tool approval. Mirrors Claude Code's `!`.
if let Some(shell_cmd) = content.trim().strip_prefix('!') {
let shell_cmd = shell_cmd.trim().to_string();
if !shell_cmd.is_empty() {
self.push_system_message(format!("$ {}", shell_cmd));
let cwd = self.working_directory.clone();
let sender = self.event_sender();
// Capture the session id at submit time so the output
// lands in the same session that fired the command —
// even if the user Tabs to another pane while sh runs.
let origin_session = self
.current_session
.as_ref()
.map(|s| s.id)
.unwrap_or_else(uuid::Uuid::nil);
tokio::spawn(async move {
let output = tokio::process::Command::new("sh")
.arg("-c")
.arg(&shell_cmd)
.current_dir(&cwd)
.output()
.await;
let msg = match output {
Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout);
let stderr = String::from_utf8_lossy(&out.stderr);
let mut combined = String::new();
if !stdout.is_empty() {
combined.push_str(stdout.trim_end());
}
if !stderr.is_empty() {
if !combined.is_empty() {
combined.push('\n');
}
combined.push_str(stderr.trim_end());
}
if combined.is_empty() {
if out.status.success() {
"(no output)".to_string()
} else {
format!("(no output, exit {})", out.status)
}
} else if !out.status.success() {
format!("{}\n(exit {})", combined, out.status)
} else {
combined
}
}
Err(e) => format!("Failed to run command: {}", e),
};
let _ = sender.send(TuiEvent::SystemMessage {
session_id: origin_session,
text: msg,
});
});
}
self.input_buffer.clear();
self.cursor_position = 0;
self.slash_suggestions_active = false;
self.dismiss_emoji_picker();
return Ok(());
}
// Also scan typed input for image paths at submit time
let (clean_text, typed_attachments) = Self::extract_image_paths(&content);
let mut all_attachments = std::mem::take(&mut self.attachments);
all_attachments.extend(typed_attachments);
let final_content =
if !all_attachments.is_empty() && clean_text.trim() != content.trim() {
clean_text
} else {
content.clone()
};
// Enter = send message
// Save to input history (dedup consecutive) and persist to disk
let trimmed = content.trim().to_string();
if self.input_history.last() != Some(&trimmed) {
self.input_history.push(trimmed.clone());
self.save_history_entry(&trimmed);
}
self.input_history_index = None;
self.input_history_stash.clear();
self.input_buffer.clear();
self.cursor_position = 0;
self.attachments.clear();
self.focused_attachment = None;
self.slash_suggestions_active = false;
self.dismiss_emoji_picker();
// Build message content with attachment markers for the agent.
// Format: `<<IMG:/path>>` for images, `<<VID:/path>>` for videos —
// handles spaces in paths. The marker tells the agent which tool
// to call (`analyze_image` vs `analyze_video`).
let send_content = if all_attachments.is_empty() {
final_content
} else {
let mut msg = final_content.clone();
for att in &all_attachments {
let prefix = if att.is_video { "VID" } else { "IMG" };
msg.push_str(&format!(" <<{}:{}>>", prefix, att.path));
}
msg
};
self.send_message(send_content).await?;
} else if keys::is_cancel(&event) {
// When processing, double-Escape aborts the operation
if self.is_processing {
if let Some(pending_at) = self.escape_pending_at {
if pending_at.elapsed() < std::time::Duration::from_secs(3) {
// Second Escape within 3 seconds — abort
// PERSIST visible streaming content to DB BEFORE killing the task.
// This prevents data loss: everything shown on screen survives cancel.
if let Some(ref session) = self.current_session {
self.persist_streaming_state(session.id).await;
}
// Cancel the active cancel token (cooperative)
if let Some(token) = &self.cancel_token {
token.cancel();
}
// Hard-abort the agent task as a backstop
if let Some(handle) = self.task_abort_handle.take() {
handle.abort();
}
// Also cancel any stashed session token (e.g. from session switch)
if let Some(ref session) = self.current_session {
if let Some(stashed) = self.session_cancel_tokens.remove(&session.id) {
stashed.cancel();
}
self.processing_sessions.remove(&session.id);
}
self.is_processing = false;
self.processing_started_at = None;
// Flush any in-flight tool group into the message list
// BEFORE touching streaming state. Per-tool DB persistence
// already wrote them to the message row, but the TUI's
// DisplayMessage for the group only exists as
// `active_tool_group` until the next flush point. Without
// this, the user watches tools execute, hits Escape-twice,
// and the whole group vanishes from view — only
// reappearing on session reload from DB. Commit it to
// `self.messages` so the history stays stable across cancel.
if let Some(group) = self.active_tool_group.take()
&& !group.calls.is_empty()
{
let count = group.calls.len();
self.messages.push(DisplayMessage {
id: Uuid::new_v4(),
role: "tool_group".to_string(),
content: format!(
"{} tool call{}",
count,
if count == 1 { "" } else { "s" }
),
timestamp: chrono::Utc::now(),
token_count: None,
cost: None,
approval: None,
approve_menu: None,
details: None,
expanded: false,
tool_group: Some(group),
});
}
// Promote any in-progress streaming text + reasoning to
// a permanent assistant DisplayMessage BEFORE clearing
// them. Without this the user sees streaming content
// during the turn, hits Escape-twice, and the whole
// response vanishes from the in-memory history — the
// DB still has it (persist_streaming_state above wrote
// it) but rendering pulls from `self.messages`, so the
// chat appears to reset to just the user's message
// until restart. Push now so the render matches what
// the user actually saw on screen.
let stash_text = self.streaming_response.take();
let stash_reasoning = self.streaming_reasoning.take();
let has_visible_text = stash_text
.as_deref()
.map(|s| !s.trim().is_empty())
.unwrap_or(false);
let has_visible_reasoning = stash_reasoning
.as_deref()
.map(|s| !s.trim().is_empty())
.unwrap_or(false);
if has_visible_text || has_visible_reasoning {
let content = stash_text
.as_deref()
.map(crate::utils::sanitize::strip_llm_artifacts)
.unwrap_or_default();
self.messages.push(DisplayMessage {
id: Uuid::new_v4(),
role: "assistant".to_string(),
content,
timestamp: chrono::Utc::now(),
token_count: None,
cost: None,
approval: None,
approve_menu: None,
details: stash_reasoning,
expanded: false,
tool_group: None,
});
}
self.streaming_render_cache = None;
self.cancel_token = None;
self.escape_pending_at = None;
self.streaming_output_tokens = 0;
self.intermediate_text_received = false;
// Drop any queued user message — otherwise it would
// survive the cancel and get injected into the NEXT
// unrelated turn, appearing as a duplicate in chat.
if let Some(sid) = self.current_session.as_ref().map(|s| s.id)
&& let Ok(mut q) = self.queued_messages.lock()
{
q.remove(&sid);
}
// Deny any pending approvals so agent callbacks don't hang
for msg in &mut self.messages {
if let Some(ref mut approval) = msg.approval
&& approval.state == ApprovalState::Pending
{
let _ = approval.response_tx.send(ToolApprovalResponse {
request_id: approval.request_id,
approved: false,
reason: Some("Operation cancelled".to_string()),
});
approval.state =
ApprovalState::Denied("Operation cancelled".to_string());
}
}
} else if event.code == KeyCode::Char('a')
&& event.modifiers == KeyModifiers::CONTROL
{
// Ctrl+A — beginning of current line (readline)
let line_start = self.input_buffer[..self.cursor_position]
.rfind('\n')
.map(|i| i + 1)
.unwrap_or(0);
self.cursor_position = line_start;
} else if event.code == KeyCode::Char('e')
&& event.modifiers == KeyModifiers::CONTROL
{
// Ctrl+E — end of current line (readline)
let line_end = self.input_buffer[self.cursor_position..]
.find('\n')
.map(|i| self.cursor_position + i)
.unwrap_or(self.input_buffer.len());
self.cursor_position = line_end;
} else if event.code == KeyCode::Char('p')
&& event.modifiers == KeyModifiers::CONTROL
&& !self.slash_suggestions_active
{
// Ctrl+P — previous command (history up, readline)
if self.input_history_index.is_none() {
// Entering history — stash current input
if !self.input_buffer.is_empty() {
self.input_history_stash = self.input_buffer.clone();
}
if !self.input_history.is_empty() {
let idx = self.input_history.len() - 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
}
} else if let Some(idx) = self.input_history_index
&& idx > 0
{
let idx = idx - 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
}
} else if event.code == KeyCode::Char('n')
&& event.modifiers == KeyModifiers::CONTROL
&& !self.slash_suggestions_active
{
// Ctrl+N — next command (history down, readline)
if let Some(idx) = self.input_history_index {
if idx + 1 < self.input_history.len() {
let idx = idx + 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
} else {
// Past newest — restore stashed input
self.input_history_index = None;
self.input_buffer = std::mem::take(&mut self.input_history_stash);
self.cursor_position = self.input_buffer.len();
}
}
// Reload session from DB so tool calls appear inline
// (matching the persisted order from expand_message) instead
// of being stacked at the bottom from in-memory finalization.
if let Some(ref session) = self.current_session {
let session_id = session.id;
self.load_session(session_id).await?;
}
self.push_system_message("Operation cancelled.".to_string());
} else {
self.escape_pending_at = Some(std::time::Instant::now());
self.error_message = Some("Press Esc again to abort".to_string());
self.error_message_shown_at = Some(std::time::Instant::now());
}
} else {
self.escape_pending_at = Some(std::time::Instant::now());
self.error_message = Some("Press Esc again to abort".to_string());
self.error_message_shown_at = Some(std::time::Instant::now());
}
} else if !self.auto_scroll {
// User is scrolled up — scroll to bottom first
self.scroll_offset = 0;
self.auto_scroll = true;
self.error_message = None;
self.error_message_shown_at = None;
self.escape_pending_at = None;
} else if self.input_buffer.is_empty() {
// Nothing to clear, just dismiss error
self.error_message = None;
self.error_message_shown_at = None;
self.escape_pending_at = None;
} else if let Some(pending_at) = self.escape_pending_at {
if pending_at.elapsed() < std::time::Duration::from_secs(3) {
// Second Escape within 3 seconds — stash input then clear
// Arrow Up will recover the stashed text
if !self.input_buffer.is_empty() {
self.input_history_stash = self.input_buffer.clone();
}
self.input_buffer.clear();
self.cursor_position = 0;
self.attachments.clear();
self.focused_attachment = None;
self.error_message = None;
self.error_message_shown_at = None;
self.escape_pending_at = None;
self.slash_suggestions_active = false;
self.dismiss_emoji_picker();
} else {
// Expired — treat as first Escape again
self.escape_pending_at = Some(std::time::Instant::now());
self.error_message = Some("Press Esc again to clear input".to_string());
self.error_message_shown_at = Some(std::time::Instant::now());
}
} else {
// First Escape — show confirmation hint
self.escape_pending_at = Some(std::time::Instant::now());
self.error_message = Some("Press Esc again to clear input".to_string());
self.error_message_shown_at = Some(std::time::Instant::now());
}
} else if event.code == KeyCode::Char('o') && event.modifiers == KeyModifiers::CONTROL {
// Ctrl+O — toggle expand/collapse on ALL tool groups and reasoning details
let target = if let Some(ref group) = self.active_tool_group {
!group.expanded
} else if let Some(msg) = self.messages.iter().rev().find(|m| m.tool_group.is_some()) {
!msg.tool_group
.as_ref()
.expect("tool_group checked is_some above")
.expanded
} else {
true
};
if let Some(ref mut group) = self.active_tool_group {
group.expanded = target;
}
for msg in self.messages.iter_mut() {
if let Some(ref mut group) = msg.tool_group {
group.expanded = target;
}
// Also toggle expanded on messages with reasoning details
if msg.details.is_some() {
msg.expanded = target;
}
}
} else if keys::is_page_up(&event) {
let before = self.scroll_offset;
self.scroll_offset = self.scroll_offset.saturating_add(10);
self.auto_scroll = false;
tracing::debug!(
"[SCROLL] PageUp: {} -> {} (auto_scroll=false)",
before,
self.scroll_offset
);
// Load more history when paging up if hidden messages exist
if self.hidden_older_messages > 0 && self.display_token_count < 300_000 {
let _ = self.load_more_history().await;
}
} else if keys::is_page_down(&event) {
let before = self.scroll_offset;
self.scroll_offset = self.scroll_offset.saturating_sub(10);
tracing::debug!("[SCROLL] PageDown: {} -> {}", before, self.scroll_offset);
if self.scroll_offset == 0 {
self.auto_scroll = true;
}
} else if event.code == KeyCode::Backspace && event.modifiers.contains(KeyModifiers::ALT) {
// Alt+Backspace — delete last word
self.delete_last_word();
} else if keys::is_up(&event)
&& !self.slash_suggestions_active
&& !self.input_buffer.is_empty()
&& self.can_cursor_move_up()
{
// Arrow Up — navigate lines within the buffer. Runs regardless
// of whether we're inside a history browse, so a recalled
// multiline entry is navigable. Only falls through to history
// when the cursor is already at the top and can't move further.
if !self.cursor_visual_up() {
// Already on first visual line of this logical line
let line_start = self.cursor_line_position().0;
if line_start == 0 {
// First logical line — move to start
self.cursor_position = 0;
} else {
// Move to previous logical line, try to land on its last visual row
// at the same column offset
use unicode_width::UnicodeWidthStr;
let prev_line_end = line_start - 1;
let prev_line_start = self.input_buffer[..prev_line_end]
.rfind('\n')
.map(|i| i + 1)
.unwrap_or(0);
let prev_line = &self.input_buffer[prev_line_start..prev_line_end];
let prev_total_width = prev_line.width();
let vw = Self::input_visual_line_width();
let last_row = if prev_total_width == 0 {
0
} else {
(prev_total_width.saturating_sub(1)) / vw
};
let current_col = self.input_buffer[line_start..self.cursor_position].width();
let target_col = last_row * vw
+ (current_col % vw).min(prev_total_width.saturating_sub(last_row * vw));
self.cursor_position =
prev_line_start + byte_offset_at_display_col(prev_line, target_col);
}
}
} else if keys::is_down(&event)
&& !self.slash_suggestions_active
&& !self.input_buffer.is_empty()
&& self.can_cursor_move_down()
{
// Arrow Down — navigate lines within the buffer. Runs regardless
// of whether we're inside a history browse, so a recalled
// multiline entry is navigable. Only falls through to history
// when the cursor is already at the bottom.
if !self.cursor_visual_down() {
// Already on last visual line of this logical line
let line_start = self.cursor_line_position().0;
let line_end = self.input_buffer[line_start..]
.find('\n')
.map(|i| line_start + i)
.unwrap_or(self.input_buffer.len());
if line_end == self.input_buffer.len() {
// Last logical line — move to end
self.cursor_position = self.input_buffer.len();
} else {
// Move to next logical line, first visual row, same column offset
use unicode_width::UnicodeWidthStr;
let next_line_start = line_end + 1;
let next_line_end = self.input_buffer[next_line_start..]
.find('\n')
.map(|i| next_line_start + i)
.unwrap_or(self.input_buffer.len());
let next_line = &self.input_buffer[next_line_start..next_line_end];
let current_col = self.input_buffer[line_start..self.cursor_position].width();
let vw = Self::input_visual_line_width();
let target_col = (current_col % vw).min(next_line.width());
self.cursor_position =
next_line_start + byte_offset_at_display_col(next_line, target_col);
}
}
} else if keys::is_up(&event)
&& !self.slash_suggestions_active
&& !self.attachments.is_empty()
&& self.cursor_position == 0
&& self.input_history_index.is_none()
{
// Arrow Up at start of input with attachments — focus last attachment.
// User can then Up/Down to navigate, Backspace/Delete to remove.
self.focused_attachment = Some(self.attachments.len() - 1);
} else if keys::is_up(&event)
&& !self.slash_suggestions_active
&& {
let sid = self.current_session.as_ref().map(|s| s.id);
sid.is_some()
&& self
.queued_messages
.lock()
.map(|q| q.contains_key(&sid.unwrap()))
.unwrap_or(false)
}
&& self.input_history_index.is_none()
{
// Arrow Up while a message is queued — dequeue it for editing.
// Moves it into the input_buffer for editing, removing from the
// per-session queue map.
if let Some(sid) = self.current_session.as_ref().map(|s| s.id)
&& let Ok(mut q) = self.queued_messages.lock()
&& let Some(msgs) = q.remove(&sid)
{
drop(q); // release lock before touching self.input_buffer
self.input_buffer = msgs.join("\n");
self.cursor_position = self.input_buffer.len();
}
} else if keys::is_up(&event)
&& !self.slash_suggestions_active
&& self.input_buffer.is_empty()
&& !self.input_history_stash.is_empty()
&& self.input_history_index.is_none()
{
// Arrow Up on empty input — restore stashed text first (cleared via Esc)
self.input_buffer = std::mem::take(&mut self.input_history_stash);
self.cursor_position = self.input_buffer.len();
} else if keys::is_up(&event)
&& !self.slash_suggestions_active
&& !self.input_history.is_empty()
&& (self.input_buffer.is_empty() || self.input_history_index.is_some())
{
// Arrow Up — browse input history (older). Only when the buffer
// is empty (nothing to lose) or we're already inside history.
match self.input_history_index {
None => {
// Entering history — stash current input
self.input_history_stash = self.input_buffer.clone();
let idx = self.input_history.len() - 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
}
Some(idx) if idx > 0 => {
let idx = idx - 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
}
_ => {} // already at oldest
}
} else if keys::is_down(&event)
&& !self.slash_suggestions_active
&& self.input_history_index.is_some()
{
// Arrow Down — browse input history (newer)
let idx = self.input_history_index.expect("checked is_some");
if idx + 1 < self.input_history.len() {
let idx = idx + 1;
self.input_history_index = Some(idx);
self.input_buffer = self.input_history[idx].clone();
self.cursor_position = self.input_buffer.len();
} else {
// Past newest — restore stashed input
self.input_history_index = None;
self.input_buffer = std::mem::take(&mut self.input_history_stash);
self.cursor_position = self.input_buffer.len();
}
} else {
// Regular character input
match event.code {
KeyCode::Char('@') => {
self.open_file_picker().await?;
}
KeyCode::Char(c)
if !event.modifiers.contains(KeyModifiers::CONTROL)
|| event.modifiers.contains(KeyModifiers::ALT) =>
{
// Reject chars that are fragments of mouse tracking CSI
// sequences leaked through tmux pane switches. Pattern:
// ESC [ < Ps ; Ps ; Ps M — the ESC is eaten by crossterm
// as KeyCode::Esc, leaving [, <, digits, ;, M as chars.
if is_mouse_sequence_fragment(c, &self.input_buffer, self.cursor_position) {
// silently drop — not real user input
} else {
self.input_buffer.insert(self.cursor_position, c);
self.cursor_position += c.len_utf8();
}
}
KeyCode::Backspace if event.modifiers.is_empty() && self.cursor_position > 0 => {
// Find the previous char boundary
let prev = self.input_buffer[..self.cursor_position]
.char_indices()
.last()
.map(|(i, _)| i)
.unwrap_or(0);
self.input_buffer.remove(prev);
self.cursor_position = prev;
}
KeyCode::Delete
if event.modifiers.is_empty()
&& self.cursor_position < self.input_buffer.len() =>
{
self.input_buffer.remove(self.cursor_position);
}
KeyCode::Left
if event.modifiers.is_empty()
// Move cursor left one character
&& self.cursor_position > 0 =>
{
let prev = self.input_buffer[..self.cursor_position]
.char_indices()
.last()
.map(|(i, _)| i)
.unwrap_or(0);
self.cursor_position = prev;
}
KeyCode::Right
if event.modifiers.is_empty()
// Move cursor right one character
&& self.cursor_position < self.input_buffer.len() =>
{
let next = self.input_buffer[self.cursor_position..]
.char_indices()
.nth(1)
.map(|(i, _)| self.cursor_position + i)
.unwrap_or(self.input_buffer.len());
self.cursor_position = next;
}
KeyCode::Home => {
// Jump to start of current line (not absolute start)
let line_start = self.input_buffer[..self.cursor_position]
.rfind('\n')
.map(|i| i + 1)
.unwrap_or(0);
self.cursor_position = line_start;
}
KeyCode::End => {
// Jump to end of current line (not absolute end)
let line_end = self.input_buffer[self.cursor_position..]
.find('\n')
.map(|i| self.cursor_position + i)
.unwrap_or(self.input_buffer.len());
self.cursor_position = line_end;
}
KeyCode::Enter => {
// Fallback — if Enter didn't match is_submit (e.g., empty input)
// do nothing
}
_ => {}
}
}
// Update slash autocomplete after any keystroke that modifies input
self.update_slash_suggestions();
// Update emoji picker after any keystroke that modifies input
if !self.slash_suggestions_active {
self.update_emoji_picker();
}
Ok(())
}
/// Handle keys in sessions mode
pub(crate) async fn handle_sessions_key(
&mut self,
event: crossterm::event::KeyEvent,
) -> Result<()> {
use super::events::keys;
use crossterm::event::KeyCode;
// Rename mode: typing the new name
if self.session_renaming {
match event.code {
KeyCode::Enter => {
// Save the new name
if let Some(session) = self.sessions.get(self.selected_session_index) {
let new_title = if self.session_rename_buffer.trim().is_empty() {
None
} else {
Some(self.session_rename_buffer.trim().to_string())
};
let session_id = session.id;
self.session_service
.update_session_title(session_id, new_title)
.await?;
// Update current session if it's the one being renamed
if let Some(ref mut current) = self.current_session
&& current.id == session_id
{
current.title = if self.session_rename_buffer.trim().is_empty() {
None
} else {
Some(self.session_rename_buffer.trim().to_string())
};
}
self.load_sessions().await?;
}
self.session_renaming = false;
self.session_rename_buffer.clear();
}
KeyCode::Esc => {
self.session_renaming = false;
self.session_rename_buffer.clear();
}
KeyCode::Backspace => {
self.session_rename_buffer.pop();
}
KeyCode::Char(c) => {
self.session_rename_buffer.push(c);
}
_ => {}
}
return Ok(());
}
// Normal sessions mode
if keys::is_cancel(&event) {
self.switch_mode(AppMode::Chat).await?;
} else if keys::is_up(&event) {
self.selected_session_index = self.selected_session_index.saturating_sub(1);
} else if keys::is_down(&event) {
self.selected_session_index =
(self.selected_session_index + 1).min(self.sessions.len().saturating_sub(1));
} else if keys::is_enter(&event) {
if let Some(session) = self.sessions.get(self.selected_session_index) {
let session_id = session.id;
// If this session is already in another pane, switch focus there
let existing_pane = self.pane_manager.panes.iter().find(|p| {
p.session_id == Some(session_id) && p.id != self.pane_manager.focused
});
if let Some(pane) = existing_pane {
let target_id = pane.id;
self.pane_manager.focused = target_id;
}
self.load_session(session_id).await?;
self.switch_mode(AppMode::Chat).await?;
}
} else if event.code == KeyCode::Char('r') || event.code == KeyCode::Char('R') {
// Start renaming the selected session
if let Some(session) = self.sessions.get(self.selected_session_index) {
self.session_renaming = true;
self.session_rename_buffer = session.title.clone().unwrap_or_default();
}
} else if event.code == KeyCode::Char('n') || event.code == KeyCode::Char('N') {
// Create a new session and switch to it
self.create_new_session().await?;
self.switch_mode(AppMode::Chat).await?;
} else if event.code == KeyCode::Char('|') {
// Split horizontal (left | right)
// Ensure current session is pinned to the original pane before splitting
if let Some(ref session) = self.current_session {
let sid = session.id;
if let Some(pane) = self.pane_manager.focused_pane_mut() {
pane.session_id = Some(sid);
}
}
self.pane_manager
.split(crate::tui::pane::SplitDirection::Horizontal);
self.pane_manager.save_layout();
// Stay on sessions screen — user picks which session goes in the new pane.
// When they press Enter, load_session assigns it to the focused (new) pane.
} else if event.code == KeyCode::Char('_') {
// Split vertical (top / bottom)
if let Some(ref session) = self.current_session {
let sid = session.id;
if let Some(pane) = self.pane_manager.focused_pane_mut() {
pane.session_id = Some(sid);
}
}
self.pane_manager
.split(crate::tui::pane::SplitDirection::Vertical);
self.pane_manager.save_layout();
// Stay on sessions screen — user picks which session goes in the new pane.
} else if event.code == KeyCode::Char('d') || event.code == KeyCode::Char('D') {
// Delete the selected session
if let Some(session) = self.sessions.get(self.selected_session_index) {
let session_id = session.id;
let is_current = self
.current_session
.as_ref()
.map(|s| s.id == session_id)
.unwrap_or(false);
self.session_service.delete_session(session_id).await?;
// Clean up all cached state for this session
self.pane_message_cache.remove(&session_id);
if let Ok(mut q) = self.queued_messages.lock() {
q.remove(&session_id);
}
self.session_cancel_tokens.remove(&session_id);
self.processing_sessions.remove(&session_id);
if is_current {
self.current_session = None;
self.messages.clear();
self.render_cache.clear();
*self.shared_session_id.lock().await = None;
}
self.load_sessions().await?;
// Adjust index if it's now out of bounds
if self.selected_session_index >= self.sessions.len() {
self.selected_session_index = self.sessions.len().saturating_sub(1);
}
}
}
Ok(())
}
}