dirge-agent 0.7.6

Minimalistic coding agent written in Rust, optimized for memory footprint and performance
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
use crate::ui::input::InputEditor;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

fn press(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::empty())
}

fn ctrl(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::CONTROL)
}

fn meta(code: KeyCode) -> KeyEvent {
    KeyEvent::new(code, KeyModifiers::ALT)
}

fn shift_enter() -> KeyEvent {
    KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT)
}

fn meta_enter() -> KeyEvent {
    KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT)
}

fn type_str(editor: &mut InputEditor, s: &str) {
    for c in s.chars() {
        editor.handle_key(press(KeyCode::Char(c)));
    }
}

fn len_bytes(s: &str) -> usize {
    s.len()
}

// ── existing tests ──────────────────────────────────────────

#[test]
fn typing_multibyte_chars_does_not_panic() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "");
    assert_eq!(editor.buffer.as_str(), "");
    assert_eq!(editor.cursor, editor.buffer.len());
}

#[test]
fn typing_mixed_ascii_and_multibyte() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hei på deg så fin dag æøå");
    assert_eq!(editor.buffer.as_str(), "hei på deg så fin dag æøå");
    assert_eq!(editor.cursor, editor.buffer.len());
}

#[test]
fn backspace_after_multibyte_does_not_panic() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "å");
    editor.handle_key(press(KeyCode::Backspace));
    assert_eq!(editor.buffer.as_str(), "");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn left_arrow_steps_one_char_not_one_byte() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "aåb");
    assert_eq!(editor.cursor, 4);
    editor.handle_key(press(KeyCode::Left));
    assert_eq!(editor.cursor, 3);
    editor.handle_key(press(KeyCode::Left));
    assert_eq!(editor.cursor, 1);
}

#[test]
fn right_arrow_steps_one_char_not_one_byte() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "aåb");
    editor.cursor = 0;
    editor.handle_key(press(KeyCode::Right));
    assert_eq!(editor.cursor, 1);
    editor.handle_key(press(KeyCode::Right));
    assert_eq!(editor.cursor, 3);
}

#[test]
fn enter_returns_buffer_and_resets() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hei på");
    let out = editor.handle_key(press(KeyCode::Enter)).unwrap();
    assert_eq!(out.as_str(), "hei på");
    assert_eq!(editor.cursor, 0);
    assert_eq!(editor.buffer.as_str(), "");
}

// ── Ctrl+A / Ctrl+E ─────────────────────────────────────────

#[test]
fn ctrl_a_moves_to_start_of_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    assert_eq!(editor.cursor, len_bytes("hello world"));
    editor.handle_key(ctrl(KeyCode::Char('a')));
    assert_eq!(editor.cursor, 0);
    assert_eq!(editor.buffer.as_str(), "hello world");
}

#[test]
fn ctrl_e_moves_to_end_of_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('e')));
    assert_eq!(editor.cursor, len_bytes("hello world"));
    assert_eq!(editor.buffer.as_str(), "hello world");
}

// ── Ctrl+B / Ctrl+F ─────────────────────────────────────────

#[test]
fn ctrl_b_moves_left_one_char() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "abc");
    assert_eq!(editor.cursor, 3);
    editor.handle_key(ctrl(KeyCode::Char('b')));
    assert_eq!(editor.cursor, 2);
    editor.handle_key(ctrl(KeyCode::Char('b')));
    assert_eq!(editor.cursor, 1);
}

#[test]
fn ctrl_b_at_start_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "abc");
    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('b')));
    assert_eq!(editor.cursor, 0);
}

// ── Option+Left / Option+Right (word skip) ──────────────────

#[test]
fn option_left_skips_to_prev_word_start() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world foo");
    let len = len_bytes("hello world foo");
    assert_eq!(editor.cursor, len);
    editor.handle_key(meta(KeyCode::Left));
    assert_eq!(editor.cursor, len_bytes("hello world ")); // start of "foo"
    editor.handle_key(meta(KeyCode::Left));
    assert_eq!(editor.cursor, len_bytes("hello ")); // start of "world"
    editor.handle_key(meta(KeyCode::Left));
    assert_eq!(editor.cursor, 0); // start of "hello"
}

#[test]
fn option_left_at_start_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "abc");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Left));
    assert_eq!(editor.cursor, 0);
}

#[test]
fn option_left_from_middle_of_word_goes_to_its_start() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello wo"); // middle of "world"
    editor.handle_key(meta(KeyCode::Left));
    assert_eq!(editor.cursor, len_bytes("hello ")); // start of "world"
}

#[test]
fn option_right_skips_to_next_word_start() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world foo");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, len_bytes("hello ")); // start of "world"
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, len_bytes("hello world ")); // start of "foo"
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, len_bytes("hello world foo")); // end of line
}

#[test]
fn option_right_at_end_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "abc");
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, 3);
}

#[test]
fn option_right_skips_punctuation() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "foo.bar_baz");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Right));
    // skip "foo" (word) then skip "." (punct) → land at "bar_baz" start
    assert_eq!(editor.cursor, len_bytes("foo."));
    assert_eq!(&editor.buffer[editor.cursor..], "bar_baz");
}

#[test]
fn option_right_multibyte_words() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hå bør");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, len_bytes("")); // after "hå ", start of "bør"
    editor.handle_key(meta(KeyCode::Right));
    assert_eq!(editor.cursor, len_bytes("hå bør")); // end
}

// ── Meta+B / Meta+F (Emacs-style word skip) ─────────────────

#[test]
fn meta_b_skips_to_prev_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    assert_eq!(editor.cursor, len_bytes("hello world"));
    editor.handle_key(meta(KeyCode::Char('b')));
    assert_eq!(editor.cursor, len_bytes("hello ")); // start of "world"
    editor.handle_key(meta(KeyCode::Char('b')));
    assert_eq!(editor.cursor, 0); // start of "hello"
}

#[test]
fn meta_f_skips_to_next_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Char('f')));
    assert_eq!(editor.cursor, len_bytes("hello ")); // start of "world"
    editor.handle_key(meta(KeyCode::Char('f')));
    assert_eq!(editor.cursor, len_bytes("hello world")); // end
}

// ── Ctrl+K (kill to line end) ────────────────────────────────

#[test]
fn ctrl_k_kills_to_end_of_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('k')));
    assert_eq!(editor.buffer.as_str(), "hello ");
    assert_eq!(editor.cursor, len_bytes("hello "));
}

#[test]
fn ctrl_k_at_end_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl(KeyCode::Char('k')));
    assert_eq!(editor.buffer.as_str(), "hello");
    assert_eq!(editor.cursor, 5);
}

#[test]
fn consecutive_ctrl_k_accumulates_in_kill_ring() {
    let mut editor = InputEditor::new();

    // first kill
    type_str(&mut editor, "one two three");
    editor.cursor = len_bytes("one ");
    editor.handle_key(ctrl(KeyCode::Char('k'))); // kills "two three"
    assert_eq!(editor.buffer.as_str(), "one ");

    // consecutive kill (no non-kill action in between)
    editor.handle_key(ctrl(KeyCode::Char('k'))); // kills "" (nothing after cursor)
    // ring[0] should be "two three" (empty string appended = no change)

    // yank should return "two three"
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "one two three");
}

#[test]
fn non_kill_action_resets_kill_accumulation() {
    let mut editor = InputEditor::new();

    // first kill
    type_str(&mut editor, "one two three");
    editor.cursor = len_bytes("one ");
    editor.handle_key(ctrl(KeyCode::Char('k'))); // kill "two three"

    // type something (breaks kill accumulation)
    type_str(&mut editor, "X");
    assert_eq!(editor.buffer.as_str(), "one X");

    // Ctrl+K at end does nothing (cursor at end, nothing to kill)
    // The kill ring still has "two three" from earlier.
    // Kill accumulation was reset, but the ring entry persists.
    editor.handle_key(ctrl(KeyCode::Char('k')));

    // yank returns the previous kill (ring entries persist across typing)
    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "two threeone X");
}

// ── Ctrl+U (kill to line start) ─────────────────────────────

#[test]
fn ctrl_u_kills_to_start_of_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('u')));
    assert_eq!(editor.buffer.as_str(), "world");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn ctrl_u_at_start_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('u')));
    assert_eq!(editor.buffer.as_str(), "hello");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn ctrl_u_kills_entire_line_when_at_end() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl(KeyCode::Char('u')));
    assert_eq!(editor.buffer.as_str(), "");
    assert_eq!(editor.cursor, 0);
}

// ── Ctrl+W (kill word before) ────────────────────────────────

#[test]
fn ctrl_w_kills_previous_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.handle_key(ctrl(KeyCode::Char('w')));
    assert_eq!(editor.buffer.as_str(), "hello ");
    assert_eq!(editor.cursor, len_bytes("hello "));
}

#[test]
fn ctrl_w_in_middle_of_word_kills_partial_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    // cursor at middle of "world": after 'r' (byte 9)
    editor.cursor = len_bytes("hello wor");
    editor.handle_key(ctrl(KeyCode::Char('w')));
    // prev_word_boundary goes to start of "world" → kills "wor"
    assert_eq!(editor.buffer.as_str(), "hello ld");
    assert_eq!(editor.cursor, len_bytes("hello "));
}

#[test]
fn ctrl_w_at_start_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('w')));
    assert_eq!(editor.buffer.as_str(), "hello");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn ctrl_w_kills_word_with_punctuation() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "foo.bar baz");
    editor.handle_key(ctrl(KeyCode::Char('w')));
    assert_eq!(editor.buffer.as_str(), "foo.bar ");
    assert_eq!(editor.cursor, len_bytes("foo.bar "));
}

// ── Option/Meta+Backspace (delete word before) ──────────────

#[test]
fn meta_backspace_deletes_previous_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.handle_key(meta(KeyCode::Backspace));
    assert_eq!(editor.buffer.as_str(), "hello ");
    assert_eq!(editor.cursor, len_bytes("hello "));
}

// ── Option/Meta+D (delete word after) ───────────────────────

#[test]
fn meta_d_deletes_next_word() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world foo");
    editor.cursor = 0;
    editor.handle_key(meta(KeyCode::Char('d')));
    assert_eq!(editor.buffer.as_str(), "world foo");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn meta_d_in_middle_of_word_deletes_to_word_end() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = 1; // after 'h'
    editor.handle_key(meta(KeyCode::Char('d')));
    assert_eq!(editor.buffer.as_str(), "hworld");
    assert_eq!(editor.cursor, 1);
}

#[test]
fn meta_d_at_end_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(meta(KeyCode::Char('d')));
    assert_eq!(editor.buffer.as_str(), "hello");
    assert_eq!(editor.cursor, 5);
}

// ── Ctrl+Y (yank) ───────────────────────────────────────────

#[test]
fn ctrl_y_yanks_most_recent_kill() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('k'))); // kill "world"
    assert_eq!(editor.buffer.as_str(), "hello ");

    editor.cursor = 0;
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "worldhello ");
    assert_eq!(editor.cursor, len_bytes("world"));
}

#[test]
fn ctrl_y_yanks_ctrl_w_kill() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.handle_key(ctrl(KeyCode::Char('w'))); // kill "world"
    assert_eq!(editor.buffer.as_str(), "hello ");

    editor.handle_key(ctrl(KeyCode::Char('y'))); // yank back
    assert_eq!(editor.buffer.as_str(), "hello world");
}

#[test]
fn ctrl_y_yanks_ctrl_u_kill() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('u'))); // kill "hello "
    assert_eq!(editor.buffer.as_str(), "world");

    editor.cursor = len_bytes("world");
    editor.handle_key(ctrl(KeyCode::Char('y'))); // yank "hello "
    assert_eq!(editor.buffer.as_str(), "worldhello ");
}

#[test]
fn ctrl_y_does_nothing_with_empty_kill_ring() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "hello");
    assert_eq!(editor.cursor, 5);
}

// ── Meta+Y (yank-pop / cycle kill ring) ─────────────────────

#[test]
fn meta_y_cycles_kill_ring_after_yank() {
    let mut editor = InputEditor::new();

    // first kill: "world"
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('k')));
    assert_eq!(editor.buffer.as_str(), "hello ");

    // type to break kill accumulation
    type_str(&mut editor, "foo bar");
    // now buffer is "hello foo bar"
    editor.cursor = len_bytes("hello foo ");
    editor.handle_key(ctrl(KeyCode::Char('k'))); // kill "bar"
    assert_eq!(editor.buffer.as_str(), "hello foo ");

    // yank — most recent kill
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "hello foo bar");

    // meta+y → cycle to "world" (previous entry)
    editor.handle_key(meta(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "hello foo world");
}

#[test]
fn meta_y_does_nothing_without_prior_yank() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.cursor = len_bytes("hello ");
    editor.handle_key(ctrl(KeyCode::Char('k')));

    editor.handle_key(meta(KeyCode::Char('y')));
    // no prior yank, should do nothing
    assert_eq!(editor.buffer.as_str(), "hello ");
}

// ── Ctrl+N / Ctrl+P (history) ────────────────────────────────

#[test]
fn ctrl_p_navigates_history_up() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second");
    editor.handle_key(press(KeyCode::Enter));

    assert!(editor.buffer.is_empty());
    editor.handle_key(ctrl(KeyCode::Char('p')));
    assert_eq!(editor.buffer.as_str(), "second");
    editor.handle_key(ctrl(KeyCode::Char('p')));
    assert_eq!(editor.buffer.as_str(), "first");
}

#[test]
fn ctrl_n_navigates_history_down() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('p')));
    editor.handle_key(ctrl(KeyCode::Char('p')));
    assert_eq!(editor.buffer.as_str(), "first");

    editor.handle_key(ctrl(KeyCode::Char('n')));
    assert_eq!(editor.buffer.as_str(), "second");
}

#[test]
fn ctrl_n_at_bottom_clears_buffer() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('n')));
    assert!(editor.buffer.is_empty());
    assert_eq!(editor.cursor, 0);
}

// ── Kill ring max size ───────────────────────────────────────

#[test]
fn kill_ring_capped_at_10_entries() {
    let mut editor = InputEditor::new();
    // Create 12 distinct kill entries by breaking accumulation between kills.
    // Submit each word to history (Enter resets kill accumulation), then
    // navigate back and kill it. This gives 12 separate ring entries.
    for i in 0..12 {
        type_str(&mut editor, &format!("word{}", i));
        editor.handle_key(press(KeyCode::Enter)); // pushes to history, clears buffer
        // Navigate back to the word, position cursor, and kill
        editor.handle_key(ctrl(KeyCode::Char('p'))); // load "wordN" from history
        editor.cursor = 0;
        editor.handle_key(ctrl(KeyCode::Char('k'))); // kill entire buffer → ring entry
        assert!(editor.buffer.is_empty());
    }
    // Yank the most recent kill (word11, since limit is 10, word0 and word1 were evicted)
    editor.handle_key(ctrl(KeyCode::Char('y')));
    assert_eq!(editor.buffer.as_str(), "word11");
}

// ── Option+arrow during picker ──────────────────────────────

#[test]
fn option_left_with_picker_active_handled_by_picker() {
    let mut editor = InputEditor::new();
    editor.cursor = 0;
    editor.handle_key(press(KeyCode::Char('@')));
    assert!(editor.picker.as_ref().is_some_and(|p| p.active));

    let result = editor.handle_key(meta(KeyCode::Left));
    assert!(result.is_none());
}

// ── Multi-line input ────────────────────────────────────────

#[test]
fn shift_enter_inserts_newline() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "world");
    assert_eq!(editor.buffer.as_str(), "hello\nworld");
}

#[test]
fn meta_enter_inserts_newline() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(meta_enter());
    type_str(&mut editor, "world");
    assert_eq!(editor.buffer.as_str(), "hello\nworld");
}

#[test]
fn plain_enter_submits_multiline_text() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "line1");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "line2");
    let submitted = editor.handle_key(press(KeyCode::Enter)).unwrap();
    assert_eq!(submitted.as_str(), "line1\nline2");
    assert!(editor.buffer.is_empty());
}

#[test]
fn multiline_history_saves_and_restores() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "second");
    editor.handle_key(press(KeyCode::Enter)); // submit

    // Navigate up in history
    editor.handle_key(press(KeyCode::Up));
    assert_eq!(editor.buffer.as_str(), "first\nsecond");
}

#[test]
fn multiline_cursor_up_moves_to_previous_logical_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "line1");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "line2");
    // cursor is at end: after "line2"
    let end_pos = editor.cursor;
    editor.handle_key(press(KeyCode::Up));
    // cursor should now be on line1
    assert!(editor.cursor < end_pos);
    // verify it's on line1
    let line1_end = "line1".len();
    assert!(editor.cursor <= line1_end);
}

#[test]
fn multiline_cursor_down_moves_to_next_logical_line() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "line1");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "line2");
    // Move to start of line1
    editor.cursor = 0;
    editor.handle_key(press(KeyCode::Down));
    // cursor should now be on line2
    let line1_len = "line1\n".len();
    assert!(editor.cursor >= line1_len);
}

#[test]
fn multiline_up_at_top_goes_to_history() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "prev");
    editor.handle_key(press(KeyCode::Enter)); // submit to history

    type_str(&mut editor, "line1");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "line2");
    editor.cursor = 0; // at top of multi-line buffer

    // Up at top should go to history
    editor.handle_key(press(KeyCode::Up));
    assert_eq!(editor.buffer.as_str(), "prev");
}

#[test]
fn multiline_down_at_bottom_goes_to_history() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "prev");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "next");
    editor.handle_key(press(KeyCode::Enter));

    // Load "next" from history
    editor.handle_key(press(KeyCode::Up));
    assert_eq!(editor.buffer.as_str(), "next");

    // Down from bottom of single line should clear
    editor.handle_key(press(KeyCode::Down));
    assert!(editor.buffer.is_empty());
}

#[test]
fn enter_with_picker_active_does_not_submit() {
    let mut editor = InputEditor::new();
    editor.cursor = 0;
    editor.handle_key(press(KeyCode::Char('@')));
    assert!(editor.picker.as_ref().is_some_and(|p| p.active));

    let result = editor.handle_key(press(KeyCode::Enter));
    assert!(result.is_none());
    assert!(editor.picker.as_ref().is_some_and(|p| p.active));
}

#[test]
fn meta_enter_with_picker_active_inserts_newline() {
    let mut editor = InputEditor::new();
    editor.cursor = 0;
    editor.handle_key(press(KeyCode::Char('@')));
    // Even with picker active, Meta+Enter should insert newline
    // (the handle_picker_key returns false for Meta+Enter, so it falls through)
    let result = editor.handle_key(meta_enter());
    assert!(result.is_none());
}

// ── Paste collapse ──────────────────────────────────────────

#[test]
fn short_paste_inserts_raw() {
    // Single-line paste — should go in as plain text, no placeholder.
    let mut editor = InputEditor::new();
    editor.handle_paste("hello world");
    assert_eq!(editor.buffer.as_str(), "hello world");
    assert_eq!(editor.cursor, "hello world".len());
}

#[test]
fn three_line_paste_still_raw() {
    // Threshold is 4 lines — three lines should not collapse.
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc");
    assert_eq!(editor.buffer.as_str(), "a\nb\nc");
}

#[test]
fn four_line_paste_collapses_to_placeholder() {
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd");
    // Buffer holds a marker block; render_line should show "[4 lines pasted]".
    assert!(editor.buffer.contains('\u{0001}'));
    let raw_line = editor.buffer.as_str();
    let (display, _) = editor.render_line(raw_line, editor.cursor);
    assert_eq!(display, "[4 lines pasted]");
    // Expanded text is the original paste.
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\nd");
}

#[test]
fn submit_expands_placeholders() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "before ");
    editor.handle_paste("L1\nL2\nL3\nL4");
    type_str(&mut editor, " after");
    let submitted = editor.handle_key(press(KeyCode::Enter)).unwrap();
    assert_eq!(submitted.as_str(), "before L1\nL2\nL3\nL4 after");
    // Buffer and pastes both cleared after submit.
    assert!(editor.buffer.is_empty());
}

#[test]
fn left_right_skip_placeholder_as_unit() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "x");
    editor.handle_paste("a\nb\nc\nd");
    type_str(&mut editor, "y");
    // Buffer now: "x" + marker + "y"
    let end = editor.cursor;
    // One Left should jump from after 'y' to between marker close and 'y'.
    editor.handle_key(press(KeyCode::Left));
    assert!(editor.cursor < end);
    // Next Left should skip the entire marker block, landing just after 'x'.
    let after_first = editor.cursor;
    editor.handle_key(press(KeyCode::Left));
    assert_eq!(editor.cursor, 1); // just after 'x'
    assert!(editor.cursor < after_first);
}

#[test]
fn backspace_deletes_whole_placeholder() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "a");
    editor.handle_paste("L1\nL2\nL3\nL4");
    type_str(&mut editor, "b");
    let len_with_marker = editor.buffer.len();
    // Move left past 'b', so cursor sits just after the marker.
    editor.handle_key(press(KeyCode::Left));
    // Backspace removes the whole marker block in one go.
    editor.handle_key(press(KeyCode::Backspace));
    assert!(editor.buffer.len() < len_with_marker);
    assert_eq!(editor.buffer.as_str(), "ab");
}

#[test]
fn second_paste_of_same_content_expands_inline() {
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd");
    // After first paste: buffer holds a marker; expanded length matches input.
    assert!(editor.buffer.contains('\u{0001}'));
    // Second paste of identical content expands the existing placeholder.
    editor.handle_paste("a\nb\nc\nd");
    assert_eq!(editor.buffer.as_str(), "a\nb\nc\nd");
    assert!(!editor.buffer.contains('\u{0001}'));
}

#[test]
fn second_paste_of_different_content_creates_new_placeholder() {
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd");
    editor.handle_paste("X\nY\nZ\nW");
    // Two distinct placeholder markers in the buffer.
    let marker_count = editor.buffer.matches('\u{0001}').count();
    assert_eq!(marker_count, 4); // two open + two close
    // Expanded contains both bodies in order.
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\ndX\nY\nZ\nW");
}

#[test]
fn paste_mark_chars_stripped_from_input() {
    // A malicious paste containing PASTE_MARK shouldn't break the parser.
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\n\u{0001}\nc\nd");
    // PASTE_MARK chars are stripped before storage; line count after strip is 5
    // (still >= 4) so it should collapse.
    assert_eq!(editor.expanded().as_str(), "a\nb\n\nc\nd");
}

#[test]
fn ctrl_w_does_not_split_paste_marker() {
    // Regression: word-skip-back from position past a paste marker used
    // prev_word_boundary directly, which treats \x01 as punctuation and
    // would happily land mid-marker — corrupting it.
    let mut editor = InputEditor::new();
    type_str(&mut editor, "before ");
    editor.handle_paste("L1\nL2\nL3\nL4");
    type_str(&mut editor, " after");
    // Cursor at end of buffer. Ctrl+W should kill "after"; the marker stays.
    editor.handle_key(ctrl(KeyCode::Char('w')));
    // Buffer should still contain the paste marker intact.
    let mark_count = editor.buffer.matches('\u{0001}').count();
    assert_eq!(mark_count, 2, "marker bytes corrupted by Ctrl+W");
    assert_eq!(editor.expanded().as_str(), "before L1\nL2\nL3\nL4 ");
}

#[test]
fn meta_b_skips_past_paste_marker() {
    // Meta+B from after the marker should land before the marker, not inside.
    let mut editor = InputEditor::new();
    editor.handle_paste("L1\nL2\nL3\nL4");
    type_str(&mut editor, " trailing");
    // Meta+B once: lands at the start of "trailing".
    editor.handle_key(meta(KeyCode::Char('b')));
    // Meta+B again: should jump past the entire marker block.
    let before = editor.cursor;
    editor.handle_key(meta(KeyCode::Char('b')));
    // Now cursor should be at byte 0 (before the marker).
    assert_eq!(editor.cursor, 0);
    assert!(editor.cursor < before);
    // Marker still intact.
    assert_eq!(editor.buffer.matches('\u{0001}').count(), 2);
}

#[test]
fn paste_during_picker_is_ignored() {
    // When the picker is active, paste should not insert marker bytes into
    // the buffer (the picker doesn't know about them, would render badly).
    let mut editor = InputEditor::new();
    editor.handle_key(press(KeyCode::Char('@')));
    let buffer_before = editor.buffer.to_string();
    editor.handle_paste("a\nb\nc\nd");
    assert_eq!(editor.buffer.as_str(), buffer_before);
}

fn ctrl_j() -> KeyEvent {
    KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL)
}

#[test]
fn ctrl_j_inserts_newline_as_fallback() {
    // Terminals that don't deliver Shift+Enter as a distinct event always
    // deliver Ctrl+J. It must insert a newline, never submit.
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl_j());
    type_str(&mut editor, "world");
    assert_eq!(editor.buffer.as_str(), "hello\nworld");
}

#[test]
fn ctrl_j_during_picker_is_noop() {
    let mut editor = InputEditor::new();
    editor.handle_key(press(KeyCode::Char('@')));
    let buf_before = editor.buffer.to_string();
    let result = editor.handle_key(ctrl_j());
    assert!(result.is_none());
    assert_eq!(editor.buffer.as_str(), buf_before);
}

#[test]
fn at_picker_triggers_after_multibyte_char() {
    // Regression: `at_word_start` used to do
    //   self.buffer.as_bytes().get(self.cursor - 1) == Some(&b' ')
    // which inspects a UTF-8 continuation byte when the prior char is
    // multibyte (e.g. `é` is 0xC3 0xA9). The continuation byte never
    // equals `b' '`, so the picker silently failed to open. Must
    // accept "start of word" via the actual prior `char`, not a raw
    // byte. After typing "é @" the picker should be active because
    // `@` follows whitespace; after typing "é@" (no gap) it should
    // NOT activate (still mid-word). Both cases used to be wrong.
    let mut editor = InputEditor::new();
    type_str(&mut editor, "é ");
    editor.handle_key(press(KeyCode::Char('@')));
    assert!(
        editor.picker.as_ref().is_some_and(|p| p.active),
        "picker should activate when `@` follows a space, even when the previous word ends in a multibyte char"
    );
}

#[test]
fn at_picker_does_not_trigger_mid_word_after_multibyte() {
    // Symmetric guard: `@` directly after a non-whitespace multibyte
    // char (no separating space) is mid-word; the picker must stay
    // closed. A pure byte check could now flip-flop the wrong way
    // after the fix if we're sloppy — pin the inverse case too.
    let mut editor = InputEditor::new();
    type_str(&mut editor, "café@");
    assert!(
        editor.picker.is_none() || !editor.picker.as_ref().unwrap().active,
        "picker must stay closed when `@` lands mid-word after a multibyte char"
    );
}

#[test]
fn paste_with_crlf_line_endings_collapses() {
    // Regression: a paste from a clipboard/source that uses \r\n line
    // endings used to be treated as a single line because matches('\n')
    // only counts LF. The threshold check failed, the raw text (including
    // \r) got inserted, and the terminal rendered carriage returns as
    // overstrikes — garbling the input.
    let mut editor = InputEditor::new();
    editor.handle_paste("a\r\nb\r\nc\r\nd\r\ne");
    // After normalization the paste is 5 lines, >= 4, so collapses.
    assert!(editor.buffer.contains('\u{0001}'));
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\nd\ne");
}

#[test]
fn paste_with_cr_only_line_endings_collapses() {
    // Some sources (e.g., legacy macOS clipboards) deliver `\r` alone.
    // Same normalization should apply.
    let mut editor = InputEditor::new();
    editor.handle_paste("a\rb\rc\rd\re");
    assert!(editor.buffer.contains('\u{0001}'));
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\nd\ne");
}
#[test]
fn yank_after_submit_preserves_pasted_content() {
    // Regression: killing a marker into the kill ring, then submitting
    // (which cleared `pastes`), then yanking back, used to leave marker
    // bytes in the buffer referencing a now-empty pastes vec. `expanded()`
    // silently dropped them, so the agent received text *without* the
    // paste body the user thought they'd yanked back. We now expand
    // markers inline in kill-ring entries before clearing pastes, so the
    // kill ring carries raw text across the submit boundary.
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd\ne");
    editor.handle_key(ctrl(KeyCode::Char('u'))); // kill marker into ring
    editor.handle_key(press(KeyCode::Enter)); // submit empty (clears pastes)
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl(KeyCode::Char('y'))); // yank — text, not marker
    let submitted = editor.handle_key(press(KeyCode::Enter)).unwrap();
    assert!(
        submitted.contains("a\nb\nc\nd\ne"),
        "expected yank to restore paste body, got: {:?}",
        submitted
    );
}

// ── Paste collapse — robustness ─────────────────────────────

#[test]
fn paste_at_start_of_buffer() {
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd");
    type_str(&mut editor, " trailing");
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\nd trailing");
}

#[test]
fn paste_in_middle_of_buffer() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "before-after");
    editor.cursor = "before-".len();
    editor.handle_paste("L1\nL2\nL3\nL4");
    assert_eq!(editor.expanded().as_str(), "before-L1\nL2\nL3\nL4after");
}

#[test]
fn two_distinct_pastes_keep_both_bodies() {
    let mut editor = InputEditor::new();
    editor.handle_paste("paste-1-a\nb\nc\nd");
    type_str(&mut editor, " mid ");
    editor.handle_paste("paste-2-w\nx\ny\nz");
    assert_eq!(
        editor.expanded().as_str(),
        "paste-1-a\nb\nc\nd mid paste-2-w\nx\ny\nz"
    );
    // Two complete marker blocks → 4 sentinel chars total.
    assert_eq!(editor.buffer.matches('\u{0001}').count(), 4);
}

#[test]
fn home_and_end_skip_past_markers() {
    let mut editor = InputEditor::new();
    editor.handle_paste("a\nb\nc\nd");
    type_str(&mut editor, "tail");
    editor.handle_key(press(KeyCode::End));
    assert_eq!(editor.cursor, editor.buffer.len());
    editor.handle_key(press(KeyCode::Home));
    assert_eq!(editor.cursor, 0);
    assert_eq!(editor.expanded().as_str(), "a\nb\nc\ndtail");
}

#[test]
fn marker_survives_multiline_up_down_nav() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "row1");
    editor.handle_key(shift_enter());
    editor.handle_paste("p1\np2\np3\np4");
    editor.handle_key(shift_enter());
    type_str(&mut editor, "row3");
    editor.handle_key(press(KeyCode::Up));
    editor.handle_key(press(KeyCode::Up));
    editor.handle_key(press(KeyCode::Down));
    editor.handle_key(press(KeyCode::Down));
    assert_eq!(editor.expanded().as_str(), "row1\np1\np2\np3\np4\nrow3");
}

#[test]
fn empty_paste_is_noop() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "existing");
    let buf_before = editor.buffer.to_string();
    let cur_before = editor.cursor;
    editor.handle_paste("");
    assert_eq!(editor.buffer.as_str(), buf_before);
    assert_eq!(editor.cursor, cur_before);
}

#[test]
fn paste_containing_only_paste_mark_chars_is_noop() {
    // PASTE_MARK chars get stripped first; if the paste was *only* those
    // chars, cleaned content is empty and we return early — no placeholder,
    // no empty marker block.
    let mut editor = InputEditor::new();
    editor.handle_paste("\u{0001}\u{0001}\u{0001}\u{0001}");
    assert_eq!(editor.buffer.as_str(), "");
    assert_eq!(editor.cursor, 0);
}

#[test]
fn delete_at_start_of_marker_removes_whole_block() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "before");
    editor.handle_paste("p1\np2\np3\np4");
    type_str(&mut editor, "after");
    editor.cursor = "before".len();
    editor.handle_key(press(KeyCode::Delete));
    assert_eq!(editor.expanded().as_str(), "beforeafter");
    assert!(!editor.buffer.contains('\u{0001}'));
}

#[test]
fn multibyte_chars_adjacent_to_marker() {
    // Marker bytes are ASCII, but surrounding text may be multibyte UTF-8.
    // Cursor motion and slicing must not split a multibyte char.
    let mut editor = InputEditor::new();
    type_str(&mut editor, "héllo "); // 'é' is 2 bytes
    editor.handle_paste("p1\np2\np3\np4");
    type_str(&mut editor, " wörld");
    while editor.cursor > 0 {
        editor.handle_key(press(KeyCode::Left));
    }
    assert_eq!(editor.cursor, 0);
    assert_eq!(editor.expanded().as_str(), "héllo p1\np2\np3\np4 wörld");
}

// ── Ctrl+F history search ───────────────────────────────────

#[test]
fn ctrl_r_enters_search_mode() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "draft");
    editor.handle_key(ctrl(KeyCode::Char('f')));

    assert!(editor.is_in_search());
    assert_eq!(editor.search_query(), "");
    assert_eq!(editor.search_match_text(), "second");
}

#[test]
fn ctrl_r_with_empty_history_is_noop() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello");
    editor.handle_key(ctrl(KeyCode::Char('f')));

    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "hello");
}

#[test]
fn search_typing_narrows_query_and_updates_match() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "different");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "different");

    editor.handle_key(press(KeyCode::Char('s')));
    assert!(editor.is_in_search());
    assert_eq!(editor.search_query(), "s");
    assert_eq!(editor.search_match_text(), "second");
}

#[test]
fn search_backspace_narrows_query() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "abc");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "abd");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('a')));
    editor.handle_key(press(KeyCode::Char('b')));
    editor.handle_key(press(KeyCode::Char('c')));
    assert_eq!(editor.search_match_text(), "abc");

    editor.handle_key(press(KeyCode::Backspace));
    assert_eq!(editor.search_query(), "ab");
    assert_eq!(editor.search_match_text(), "abd");
}

#[test]
fn search_backspace_on_empty_query_does_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "test");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Backspace));
    assert!(editor.is_in_search());
    assert_eq!(editor.search_query(), "");
    assert_eq!(editor.search_match_text(), "test");
}

#[test]
fn ctrl_r_again_cycles_to_older_match() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first foo");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second bar");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "third foo");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "third foo");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "first foo");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "third foo");
}

#[test]
fn search_enter_accepts_match() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "original");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "target match");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "draft text");
    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('t')));
    assert_eq!(editor.search_match_text(), "target match");

    editor.handle_key(press(KeyCode::Enter));
    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "target match");
}

#[test]
fn search_esc_cancels_and_restores_draft() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "old entry");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "draft text");
    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('o')));
    assert_eq!(editor.search_match_text(), "old entry");

    editor.handle_key(press(KeyCode::Esc));
    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "draft text");
}

#[test]
fn search_cancels_on_ctrl_c() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "history");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "draft");
    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(ctrl(KeyCode::Char('c')));

    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "draft");
}

#[test]
fn search_case_insensitive() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "Hello World");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('h')));
    assert_eq!(editor.search_match_text(), "Hello World");

    editor.handle_key(press(KeyCode::Char('e')));
    editor.handle_key(press(KeyCode::Char('l')));
    assert_eq!(editor.search_query(), "hel");
    assert_eq!(editor.search_match_text(), "Hello World");
}

#[test]
fn search_no_match_shows_nothing() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "hello world");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('x')));
    assert_eq!(editor.search_query(), "x");
    assert!(editor.is_in_search());
    assert_eq!(editor.search_match_text(), "");
}

#[test]
fn load_history_populates_for_ctrl_r() {
    let mut editor = InputEditor::new();
    editor.load_history_entry("first message");
    editor.load_history_entry("second message");
    editor.load_history_entry("third message");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert!(editor.is_in_search());
    assert_eq!(editor.search_match_text(), "third message");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "second message");

    editor.handle_key(press(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "first message");
}

#[test]
fn load_history_skips_dupes_and_empty() {
    let mut editor = InputEditor::new();
    editor.load_history_entry(""); // skipped: empty
    editor.load_history_entry("msg1");
    editor.load_history_entry("msg1"); // skipped: dupe
    editor.load_history_entry("msg2");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "msg2");

    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "msg1");

    editor.handle_key(press(KeyCode::Char('m')));
    editor.handle_key(press(KeyCode::Char('s')));
    editor.handle_key(press(KeyCode::Char('g')));
    editor.handle_key(press(KeyCode::Char('3')));
    assert_eq!(editor.search_match_text(), "");
}

#[test]
fn search_no_match_accept_restores_draft() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "history");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "my draft text");
    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('z'))); // no match for 'z'
    assert_eq!(editor.search_match_text(), "");

    editor.handle_key(press(KeyCode::Enter));
    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "my draft text");
}

#[test]
fn search_typing_after_cycle_narrows_from_position() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "first foo bar");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "second foo baz");
    editor.handle_key(press(KeyCode::Enter));
    type_str(&mut editor, "third foo qux");
    editor.handle_key(press(KeyCode::Enter));

    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('o')));
    editor.handle_key(press(KeyCode::Char('o')));
    // newest match for "foo": "third foo qux"
    assert_eq!(editor.search_match_text(), "third foo qux");

    // Cycle to older match
    editor.handle_key(ctrl(KeyCode::Char('f')));
    assert_eq!(editor.search_match_text(), "second foo baz");

    // Type more chars — should narrow from "second foo baz", not
    // teleport back to the newest "foo bar" match.
    editor.handle_key(press(KeyCode::Char(' ')));
    editor.handle_key(press(KeyCode::Char('b')));
    // Should find "second foo baz" (contains "foo b"), not "first foo bar"
    assert_eq!(editor.search_match_text(), "second foo baz");
}

#[test]
fn search_esc_from_input_editor_cancels() {
    let mut editor = InputEditor::new();
    type_str(&mut editor, "old");
    editor.handle_key(press(KeyCode::Enter));

    type_str(&mut editor, "draft text");
    editor.handle_key(ctrl(KeyCode::Char('f')));
    editor.handle_key(press(KeyCode::Char('o')));
    assert!(editor.is_in_search());

    // Esc should cancel search (tested via handle_search_key path)
    editor.handle_key(press(KeyCode::Esc));
    assert!(!editor.is_in_search());
    assert_eq!(editor.buffer.as_str(), "draft text");
}