lemurclaw-tui 0.0.1

Terminal UI for the lemurclaw AI coding agent
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
//! The chat composer history module owns shell-style recall and incremental search traversal.
//!
//! It combines persistent cross-session entries with local in-session entries into one offset
//! space. Normal navigation fetches persistent entries individually through
//! [`ChatComposerHistory::on_entry_response`]. Reverse search switches to bounded,
//! query-independent batches through [`ChatComposerHistory::on_batch_response`] after probing the
//! newest entry. Batch responses populate the shared cache even when the active search has moved
//! on, but only the awaited cursor resumes a search; stale log IDs are ignored, and batch read
//! failures follow a bounded retry path. Local entries are already available with full draft
//! metadata.
//!
//! Ctrl+R search is modeled separately from normal Up/Down navigation because it has different
//! guarantees: query edits restart from the newest match, repeated Older/Newer keys move through
//! unique matching text, pending persistent fetches continue the same scan after the response
//! arrives, and boundary hits must not advance hidden cursor state. Search deduplication is scoped
//! to a single active search session and uses exact prompt text; it does not mutate stored history
//! or change normal history browsing.
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::PathBuf;

use crate::tui_internal::app_event::AppEvent;
use crate::tui_internal::app_event_sender::AppEventSender;
use crate::tui_internal::bottom_pane::MentionBinding;
use crate::tui_internal::mention_codec::decode_history_mentions_with_at_mentions;
use crate::message_history::HistoryBatchCursor;
use lemurclaw_core::protocol::ThreadId;
use lemurclaw_core::protocol::user_input::TextElement;

#[path = "chat_composer_history/search_batch.rs"]
mod search_batch;
#[cfg(test)]
#[path = "chat_composer_history/search_batch_tests.rs"]
mod search_batch_tests;

const MAX_BATCH_READ_RETRIES: u8 = 2;

/// A composer history entry that can rehydrate draft state.
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct HistoryEntry {
    /// Raw text stored in history (may include placeholder strings).
    pub(crate) text: String,
    /// Text element ranges for placeholders inside `text`.
    pub(crate) text_elements: Vec<TextElement>,
    /// Local image paths captured alongside `text_elements`.
    pub(crate) local_image_paths: Vec<PathBuf>,
    /// Remote image URLs restored with this draft.
    pub(crate) remote_image_urls: Vec<String>,
    /// Mention bindings for tool/app/skill references inside `text`.
    pub(crate) mention_bindings: Vec<MentionBinding>,
    /// Placeholder-to-payload pairs used to restore large paste content.
    pub(crate) pending_pastes: Vec<(String, String)>,
}

impl HistoryEntry {
    /// Creates a text-only history entry and decodes persisted mention bindings.
    ///
    /// Persistent history does not store attachment payloads or text-element metadata, so this
    /// constructor intentionally leaves those fields empty. Local in-session submissions should be
    /// recorded with the full `HistoryEntry` value built by the composer; using `new` for a local
    /// image or paste submission would make recall lose placeholder ownership.
    pub(crate) fn new(text: String) -> Self {
        Self::new_with_at_mentions(text, /*at_mentions_enabled*/ true)
    }

    pub(crate) fn new_with_at_mentions(text: String, at_mentions_enabled: bool) -> Self {
        let decoded = decode_history_mentions_with_at_mentions(&text, at_mentions_enabled);
        Self {
            text: decoded.text,
            text_elements: Vec::new(),
            local_image_paths: Vec::new(),
            remote_image_urls: Vec::new(),
            mention_bindings: decoded
                .mentions
                .into_iter()
                .map(|mention| MentionBinding {
                    sigil: mention.sigil,
                    mention: mention.mention,
                    path: mention.path,
                })
                .collect(),
            pending_pastes: Vec::new(),
        }
    }

    #[cfg(test)]
    pub(crate) fn with_pending(
        text: String,
        text_elements: Vec<TextElement>,
        local_image_paths: Vec<PathBuf>,
        pending_pastes: Vec<(String, String)>,
    ) -> Self {
        Self {
            text,
            text_elements,
            local_image_paths,
            remote_image_urls: Vec::new(),
            mention_bindings: Vec::new(),
            pending_pastes,
        }
    }

    #[cfg(test)]
    pub(crate) fn with_pending_and_remote(
        text: String,
        text_elements: Vec<TextElement>,
        local_image_paths: Vec<PathBuf>,
        pending_pastes: Vec<(String, String)>,
        remote_image_urls: Vec<String>,
    ) -> Self {
        Self {
            text,
            text_elements,
            local_image_paths,
            remote_image_urls,
            mention_bindings: Vec::new(),
            pending_pastes,
        }
    }
}

/// State machine that manages shell-style history navigation (Up/Down) inside
/// the chat composer. This struct is intentionally decoupled from the
/// rendering widget so the logic remains isolated and easier to test.
pub(crate) struct ChatComposerHistory {
    /// Thread that owns persistent lookup responses for this metadata snapshot.
    thread_id: Option<ThreadId>,
    /// Identifier of the persistent history log used for stale lookup rejection.
    persistent_log_id: Option<u64>,
    /// Number of entries already present in the persistent cross-session
    /// history file when the session started.
    persistent_entry_count: usize,

    /// Messages submitted by the user *during this UI session* (newest at END).
    /// Local entries retain full draft state (text elements, image paths, pending pastes, remote image URLs).
    local_history: Vec<HistoryEntry>,
    /// Local entries seeded from resumed transcript replay.
    replay_seeded_history: Vec<HistoryEntry>,

    /// Persistent offsets fetched on demand, with `None` for malformed batch rows.
    fetched_history: HashMap<usize, Option<HistoryEntry>>,

    /// Current cursor within the combined (persistent + local) history. `None`
    /// indicates the user is *not* currently browsing history.
    history_cursor: Option<isize>,
    pending_navigation_direction: Option<HistorySearchDirection>,

    /// The text that was last inserted into the composer as a result of
    /// history navigation. Used to decide if further Up/Down presses should be
    /// treated as navigation versus normal cursor movement, together with the
    /// "cursor at line boundary" check in [`Self::should_handle_navigation`].
    last_history_text: Option<String>,

    /// Active incremental history search, if Ctrl+R search mode is open.
    search: Option<HistorySearchState>,
    /// Whether persistent history restore should rehydrate `@` tool mentions.
    at_mention_restore_enabled: bool,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum HistorySearchDirection {
    /// Traverse toward older history offsets.
    Older,
    /// Traverse toward newer history offsets.
    Newer,
}

/// Result of a single incremental history search step.
///
/// `Pending` means a persistent entry lookup has been requested and the caller should keep the
/// visible search session open until [`ChatComposerHistory::on_entry_response`] supplies the next
/// result. `AtBoundary` means the current selected match is still valid but the requested direction
/// has no further unique match; callers should avoid treating it like a query miss. `Unavailable`
/// ends a failed lookup without claiming the query has no matching history.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum HistorySearchResult {
    Found(HistoryEntry),
    Pending,
    AtBoundary,
    NotFound,
    Unavailable,
}

/// Result of integrating an asynchronous persistent history response.
///
/// A response can satisfy normal Up/Down navigation, resume a pending Ctrl+R search scan, or be
/// ignored if it belongs to a stale log or an offset the composer no longer needs.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum HistoryEntryResponse {
    Found(HistoryEntry),
    Search(HistorySearchResult),
    Ignored,
}

/// State for one active Ctrl+R search query.
///
/// The state keeps two cursors: `selected_offset` is the raw combined-history offset used to
/// continue scanning, while `selected_match_index` points into `unique_matches` so already
/// discovered unique results can be revisited without rescanning duplicate offsets. `seen_texts`
/// intentionally keys on exact prompt text because the UI previews and accepts text, not the
/// storage identity of each historical record. `next_older_cursor` retains the query-independent
/// batch boundary so a match does not force the next Older search back onto the prefix-scan path.
#[derive(Clone, Debug)]
struct HistorySearchState {
    query: String,
    query_lower: String,
    selected_offset: Option<usize>,
    unique_matches: Vec<UniqueHistoryMatch>,
    selected_match_index: Option<usize>,
    seen_texts: HashSet<String>,
    awaiting: Option<PendingHistorySearch>,
    next_older_cursor: Option<HistoryBatchCursor>,
    exhausted_older: bool,
    exhausted_newer: bool,
}

/// A unique search match cached with enough draft state to be selected again.
///
/// The vector of these matches is kept in newest-to-oldest offset order. Storing the entry beside
/// the offset avoids depending on later cache lookups when the user moves Newer/Older among matches
/// that have already been discovered.
#[derive(Clone, Debug)]
struct UniqueHistoryMatch {
    offset: usize,
    entry: HistoryEntry,
}

/// Persistent-history lookup currently blocking an incremental search scan.
///
/// The pending request records the boundary behavior that was active when the fetch was issued so
/// the response can either return a unique match or continue scanning as if no async gap had
/// occurred. Single-entry requests retain their direction; batch requests are older-only by
/// construction.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum PendingHistorySearch {
    Entry {
        offset: usize,
        direction: HistorySearchDirection,
        boundary_if_exhausted: bool,
    },
    Batch {
        cursor: HistoryBatchCursor,
        boundary_if_exhausted: bool,
        read_failures: u8,
    },
}

impl ChatComposerHistory {
    /// Creates an empty history state machine with no persistent metadata.
    ///
    /// The caller must provide session metadata before cross-session history can be fetched, but
    /// local in-session entries can still be recorded and traversed. Keeping construction cheap and
    /// metadata-free lets the composer reset and reuse this helper across session lifecycles.
    pub fn new() -> Self {
        Self {
            thread_id: None,
            persistent_log_id: None,
            persistent_entry_count: 0,
            local_history: Vec::new(),
            replay_seeded_history: Vec::new(),
            fetched_history: HashMap::new(),
            history_cursor: None,
            pending_navigation_direction: None,
            last_history_text: None,
            search: None,
            at_mention_restore_enabled: false,
        }
    }

    pub fn set_at_mention_restore_enabled(&mut self, enabled: bool) {
        if self.at_mention_restore_enabled == enabled {
            return;
        }
        self.at_mention_restore_enabled = enabled;
        self.fetched_history.clear();
        self.history_cursor = None;
        self.last_history_text = None;
        self.search = None;
    }

    /// Updates persistent history metadata when a new session is configured.
    ///
    /// This clears fetched entries, local entries, navigation cursors, and active search state
    /// because offsets only make sense within one history log snapshot. Reusing old offsets after a
    /// log-id change would allow a stale async response to hydrate the wrong prompt.
    pub fn set_metadata(&mut self, thread_id: ThreadId, log_id: u64, entry_count: usize) {
        self.thread_id = Some(thread_id);
        self.persistent_log_id = Some(log_id);
        self.persistent_entry_count = entry_count;
        self.fetched_history.clear();
        self.local_history.clear();
        self.replay_seeded_history.clear();
        self.history_cursor = None;
        self.pending_navigation_direction = None;
        self.last_history_text = None;
        self.search = None;
    }

    /// Records a current-session submission so it can be recalled with full draft metadata.
    ///
    /// Empty submissions are ignored, adjacent duplicates are collapsed, and active navigation or
    /// search state is reset because a new newest entry changes the combined history offset space.
    pub fn record_local_submission(&mut self, entry: HistoryEntry) {
        self.record_local_submission_inner(entry);
    }

    pub fn record_replayed_submission(&mut self, entry: HistoryEntry) {
        if self.record_local_submission_inner(entry.clone()) {
            self.replay_seeded_history.push(entry);
        }
    }

    fn record_local_submission_inner(&mut self, entry: HistoryEntry) -> bool {
        if entry.text.is_empty()
            && entry.text_elements.is_empty()
            && entry.local_image_paths.is_empty()
            && entry.remote_image_urls.is_empty()
            && entry.mention_bindings.is_empty()
            && entry.pending_pastes.is_empty()
        {
            return false;
        }
        self.history_cursor = None;
        self.pending_navigation_direction = None;
        self.last_history_text = None;
        self.search = None;

        // Avoid inserting a duplicate if identical to the previous entry.
        if self.local_history.last().is_some_and(|prev| prev == &entry) {
            return false;
        }

        self.local_history.push(entry);
        true
    }

    /// Resets normal history navigation so the next Up key resumes from the newest entry.
    ///
    /// This also clears any active incremental search, since normal browsing and Ctrl+R search
    /// maintain different cursor semantics. Failing to clear search here would let an old query
    /// influence later Up/Down recall.
    pub fn reset_navigation(&mut self) {
        self.history_cursor = None;
        self.pending_navigation_direction = None;
        self.last_history_text = None;
        self.search = None;
    }

    /// Clears only the active incremental search state.
    ///
    /// The normal Up/Down navigation cursor and cached persistent entries are left intact. Composer
    /// search mode calls this when it accepts a match or returns to an empty query so the next
    /// search starts with a fresh unique-result cache.
    pub fn reset_search(&mut self) {
        self.search = None;
    }

    /// Returns whether Up/Down should navigate history for the current textarea state.
    ///
    /// Empty text always enables history traversal. For non-empty text, this requires both:
    ///
    /// - the current text exactly matching the last recalled history entry, and
    /// - the cursor being at a line boundary (start or end).
    ///
    /// This boundary gate keeps multiline cursor movement usable while preserving shell-like
    /// history recall. If callers moved the cursor into the middle of a recalled entry and still
    /// forced navigation, users would lose normal vertical movement within the draft.
    pub fn should_handle_navigation(&self, text: &str, cursor: usize) -> bool {
        if self.persistent_entry_count == 0 && self.local_history.is_empty() {
            return false;
        }

        if text.is_empty() {
            return true;
        }

        // Textarea is not empty – only navigate when text matches the last
        // recalled history entry and the cursor is at a line boundary. This
        // keeps shell-like Up/Down recall working while still allowing normal
        // multiline cursor movement from interior positions.
        if cursor != 0 && cursor != text.len() {
            return false;
        }

        matches!(&self.last_history_text, Some(prev) if prev == text)
    }

    /// Handles Up by moving toward older entries in the combined history space.
    ///
    /// Local entries can be returned immediately, while missing persistent entries emit a
    /// `LookupMessageHistoryEntry` and return `None` until the response arrives. Calling this while
    /// Ctrl+R search is active intentionally exits search traversal.
    pub fn navigate_up(&mut self, app_event_tx: &AppEventSender) -> Option<HistoryEntry> {
        self.search = None;
        let total_entries = self.persistent_entry_count + self.local_history.len();
        if total_entries == 0 {
            return None;
        }

        let next_idx = match self.history_cursor {
            None => (total_entries as isize) - 1,
            Some(0) => return None, // already at oldest
            Some(idx) => idx - 1,
        };

        self.history_cursor = Some(next_idx);
        self.populate_history_at_index(
            next_idx as usize,
            HistorySearchDirection::Older,
            app_event_tx,
        )
    }

    /// Handles Down by moving toward newer entries or clearing the composer past the newest entry.
    ///
    /// Returning an empty `HistoryEntry` means the user moved past the newest known entry and the
    /// caller should clear the composer draft. As with Up, invoking this during Ctrl+R search clears
    /// search state and resumes normal shell-style browsing.
    pub fn navigate_down(&mut self, app_event_tx: &AppEventSender) -> Option<HistoryEntry> {
        self.search = None;
        let total_entries = self.persistent_entry_count + self.local_history.len();
        if total_entries == 0 {
            return None;
        }

        let next_idx_opt = match self.history_cursor {
            None => return None, // not browsing
            Some(idx) if (idx as usize) + 1 >= total_entries => None,
            Some(idx) => Some(idx + 1),
        };

        match next_idx_opt {
            Some(idx) => {
                self.history_cursor = Some(idx);
                self.populate_history_at_index(
                    idx as usize,
                    HistorySearchDirection::Newer,
                    app_event_tx,
                )
            }
            None => {
                // Past newest – clear and exit browsing mode.
                self.history_cursor = None;
                self.pending_navigation_direction = None;
                self.last_history_text = None;
                Some(HistoryEntry::new(String::new()))
            }
        }
    }

    /// Integrates a persistent history entry response into navigation or active search.
    ///
    /// Responses with a stale log id are ignored, matching responses update the persistent cache,
    /// and pending Ctrl+R searches resume their scan from the returned offset. The caller should
    /// route `HistoryEntryResponse::Search` back to the composer search session rather than normal
    /// history recall; otherwise an async search hit could be accepted without updating footer
    /// status or match highlighting.
    pub fn on_entry_response(
        &mut self,
        log_id: u64,
        offset: usize,
        entry: Option<String>,
        app_event_tx: &AppEventSender,
    ) -> HistoryEntryResponse {
        if self.persistent_log_id != Some(log_id) {
            return HistoryEntryResponse::Ignored;
        }

        let entry = entry.map(|entry| {
            HistoryEntry::new_with_at_mentions(entry, self.at_mention_restore_enabled)
        });
        if let Some(entry) = entry.clone() {
            self.fetched_history.insert(offset, Some(entry));
        }

        if self
            .search
            .as_ref()
            .and_then(|search| search.awaiting)
            .is_some_and(|pending| {
                matches!(pending, PendingHistorySearch::Entry { offset: awaited, .. } if awaited == offset)
            })
        {
            let pending = self
                .search
                .as_ref()
                .and_then(|search| search.awaiting)
                .unwrap_or(PendingHistorySearch::Entry {
                    offset,
                    direction: HistorySearchDirection::Older,
                    boundary_if_exhausted: false,
                });
            let PendingHistorySearch::Entry {
                direction,
                boundary_if_exhausted,
                ..
            } = pending
            else {
                return HistoryEntryResponse::Ignored;
            };
            if let Some(entry) = entry
                && self.search_matches(&entry)
                && self.search_result_is_unique(&entry)
            {
                return HistoryEntryResponse::Search(self.search_match(offset, entry));
            }
            let result = match direction {
                HistorySearchDirection::Older => self.advance_older_search_after_entry_miss(
                    offset,
                    boundary_if_exhausted,
                    app_event_tx,
                ),
                HistorySearchDirection::Newer => self.advance_search_after(
                    offset,
                    direction,
                    boundary_if_exhausted,
                    app_event_tx,
                ),
            };
            return HistoryEntryResponse::Search(result);
        }

        if self.history_cursor == Some(offset as isize) {
            let direction = self.pending_navigation_direction.take();
            let Some(entry) = entry else {
                return HistoryEntryResponse::Ignored;
            };
            if self.persistent_entry_duplicates_local(&entry)
                && let Some(direction) = direction
            {
                let Some(offset) = self.next_history_offset(offset, direction) else {
                    return HistoryEntryResponse::Ignored;
                };
                self.history_cursor = Some(offset as isize);
                return self
                    .populate_history_at_index(offset, direction, app_event_tx)
                    .map(HistoryEntryResponse::Found)
                    .unwrap_or(HistoryEntryResponse::Ignored);
            }
            self.last_history_text = Some(entry.text.clone());
            return HistoryEntryResponse::Found(entry);
        }

        HistoryEntryResponse::Ignored
    }

    /// Advance the active Ctrl+R search and return the next visible search state.
    ///
    /// Callers pass `restart` after opening search or editing the query; that clears the unique
    /// match cache and starts from the end of combined history. Repeated calls with the same query
    /// and `restart == false` move relative to the current unique match, preserving the selected
    /// entry at boundaries. Calling this while a previous persistent lookup is still pending will
    /// keep returning `Pending`; otherwise a stale response could race with a newer user action and
    /// replace the composer with an unexpected entry.
    pub fn search(
        &mut self,
        query: &str,
        direction: HistorySearchDirection,
        restart: bool,
        app_event_tx: &AppEventSender,
    ) -> HistorySearchResult {
        let total_entries = self.total_entries();
        if total_entries == 0 {
            self.search = Some(HistorySearchState::new(query));
            return HistorySearchResult::NotFound;
        }

        let query_changed = self
            .search
            .as_ref()
            .is_none_or(|search| search.query != query);
        if !query_changed
            && !restart
            && self
                .search
                .as_ref()
                .and_then(|search| search.awaiting)
                .is_some()
        {
            return HistorySearchResult::Pending;
        }

        if query_changed || restart || self.search.is_none() {
            self.search = Some(HistorySearchState::new(query));
        } else if let Some(search) = self.search.as_mut() {
            search.awaiting = None;
        }

        let boundary_if_exhausted = !restart
            && self
                .search
                .as_ref()
                .and_then(|search| search.selected_offset)
                .is_some();
        if !restart
            && !query_changed
            && let Some(result) = self.select_cached_unique_match(direction)
        {
            return result;
        }
        if boundary_if_exhausted
            && self
                .search
                .as_ref()
                .is_some_and(|search| search.is_exhausted(direction))
        {
            return HistorySearchResult::AtBoundary;
        }

        let start_offset =
            self.search_start_offset(total_entries, direction, query_changed || restart);
        let Some(start_offset) = start_offset else {
            return self.exhausted_search_result(direction, boundary_if_exhausted);
        };

        let result =
            self.advance_search_from(start_offset, direction, boundary_if_exhausted, app_event_tx);
        if matches!(result, HistorySearchResult::NotFound) {
            self.exhausted_search_result(direction, boundary_if_exhausted)
        } else {
            result
        }
    }

    // ---------------------------------------------------------------------
    // Internal helpers
    // ---------------------------------------------------------------------

    fn total_entries(&self) -> usize {
        self.persistent_entry_count + self.local_history.len()
    }

    fn search_start_offset(
        &self,
        total_entries: usize,
        direction: HistorySearchDirection,
        restart: bool,
    ) -> Option<usize> {
        let selected = self
            .search
            .as_ref()
            .and_then(|search| search.selected_offset);
        match direction {
            HistorySearchDirection::Older => {
                if restart {
                    total_entries.checked_sub(1)
                } else {
                    selected.and_then(|offset| offset.checked_sub(1))
                }
            }
            HistorySearchDirection::Newer => {
                if restart {
                    Some(0)
                } else {
                    selected
                        .and_then(|offset| offset.checked_add(1))
                        .filter(|offset| *offset < total_entries)
                }
            }
        }
    }

    fn advance_search_after(
        &mut self,
        offset: usize,
        direction: HistorySearchDirection,
        boundary_if_exhausted: bool,
        app_event_tx: &AppEventSender,
    ) -> HistorySearchResult {
        let next_offset = match direction {
            HistorySearchDirection::Older => offset.checked_sub(1),
            HistorySearchDirection::Newer => offset
                .checked_add(1)
                .filter(|next| *next < self.total_entries()),
        };
        let Some(next_offset) = next_offset else {
            return self.exhausted_search_result(direction, boundary_if_exhausted);
        };
        let result =
            self.advance_search_from(next_offset, direction, boundary_if_exhausted, app_event_tx);
        if matches!(result, HistorySearchResult::NotFound) {
            self.exhausted_search_result(direction, boundary_if_exhausted)
        } else {
            result
        }
    }

    fn advance_search_from(
        &mut self,
        mut offset: usize,
        direction: HistorySearchDirection,
        boundary_if_exhausted: bool,
        app_event_tx: &AppEventSender,
    ) -> HistorySearchResult {
        let total_entries = self.total_entries();
        while offset < total_entries {
            if let Some(entry) = self.entry_at_cached_offset(offset) {
                if self.search_matches(&entry) && self.search_result_is_unique(&entry) {
                    return self.search_match(offset, entry);
                }
            } else if !self.fetched_history.contains_key(&offset)
                && offset < self.persistent_entry_count
            {
                if direction == HistorySearchDirection::Older
                    && let Some(cursor) = self
                        .search
                        .as_ref()
                        .and_then(|search| search.next_older_cursor)
                    && cursor.end_offset() == offset
                {
                    return self.request_older_search_batch(
                        cursor,
                        boundary_if_exhausted,
                        app_event_tx,
                    );
                }
                if let (Some(thread_id), Some(log_id)) = (self.thread_id, self.persistent_log_id) {
                    if let Some(search) = self.search.as_mut() {
                        search.awaiting = Some(PendingHistorySearch::Entry {
                            offset,
                            direction,
                            boundary_if_exhausted,
                        });
                    }
                    app_event_tx.send(AppEvent::LookupMessageHistoryEntry {
                        thread_id,
                        offset,
                        log_id,
                    });
                    return HistorySearchResult::Pending;
                }
            }

            let next_offset = match direction {
                HistorySearchDirection::Older => offset.checked_sub(1),
                HistorySearchDirection::Newer => {
                    offset.checked_add(1).filter(|next| *next < total_entries)
                }
            };
            let Some(next_offset) = next_offset else {
                return HistorySearchResult::NotFound;
            };
            offset = next_offset;
        }

        HistorySearchResult::NotFound
    }

    fn entry_at_cached_offset(&self, offset: usize) -> Option<HistoryEntry> {
        if offset >= self.persistent_entry_count {
            self.local_history
                .get(offset - self.persistent_entry_count)
                .cloned()
        } else {
            self.fetched_history.get(&offset).cloned().flatten()
        }
    }

    fn search_matches(&self, entry: &HistoryEntry) -> bool {
        let Some(search) = self.search.as_ref() else {
            return false;
        };
        search.query.is_empty() || entry.text.to_lowercase().contains(&search.query_lower)
    }

    fn search_result_is_unique(&self, entry: &HistoryEntry) -> bool {
        self.search
            .as_ref()
            .is_none_or(|search| !search.seen_texts.contains(entry.text.as_str()))
    }

    fn search_match(&mut self, offset: usize, entry: HistoryEntry) -> HistorySearchResult {
        self.history_cursor = Some(offset as isize);
        self.last_history_text = Some(entry.text.clone());
        if let Some(search) = self.search.as_mut() {
            search.selected_offset = Some(offset);
            search.record_match(offset, &entry);
            search.awaiting = None;
            search.exhausted_older = false;
            search.exhausted_newer = false;
        }
        HistorySearchResult::Found(entry)
    }

    fn select_cached_unique_match(
        &mut self,
        direction: HistorySearchDirection,
    ) -> Option<HistorySearchResult> {
        let next_index = {
            let search = self.search.as_ref()?;
            let selected_index = search.selected_match_index?;
            match direction {
                HistorySearchDirection::Older => {
                    let next_index = selected_index + 1;
                    (next_index < search.unique_matches.len()).then_some(next_index)?
                }
                HistorySearchDirection::Newer => selected_index.checked_sub(1)?,
            }
        };

        let history_match = self.search.as_ref()?.unique_matches[next_index].clone();
        self.history_cursor = Some(history_match.offset as isize);
        self.last_history_text = Some(history_match.entry.text.clone());
        if let Some(search) = self.search.as_mut() {
            search.select_match(next_index);
        }
        Some(HistorySearchResult::Found(history_match.entry))
    }

    fn exhausted_search_result(
        &mut self,
        direction: HistorySearchDirection,
        boundary_if_exhausted: bool,
    ) -> HistorySearchResult {
        if let Some(search) = self.search.as_mut() {
            search.awaiting = None;
            if boundary_if_exhausted {
                search.mark_exhausted(direction);
            }
        }

        if boundary_if_exhausted {
            HistorySearchResult::AtBoundary
        } else {
            HistorySearchResult::NotFound
        }
    }

    fn populate_history_at_index(
        &mut self,
        global_idx: usize,
        direction: HistorySearchDirection,
        app_event_tx: &AppEventSender,
    ) -> Option<HistoryEntry> {
        let mut global_idx = global_idx;
        loop {
            if let Some(entry) = self.entry_at_cached_offset(global_idx) {
                if global_idx < self.persistent_entry_count
                    && self.persistent_entry_duplicates_local(&entry)
                {
                    let Some(next_idx) = self.next_history_offset(global_idx, direction) else {
                        self.pending_navigation_direction = None;
                        return None;
                    };
                    self.history_cursor = Some(next_idx as isize);
                    global_idx = next_idx;
                    continue;
                }
                self.pending_navigation_direction = None;
                self.last_history_text = Some(entry.text.clone());
                return Some(entry);
            }

            if global_idx >= self.persistent_entry_count {
                return None;
            }

            if let (Some(thread_id), Some(log_id)) = (self.thread_id, self.persistent_log_id) {
                self.pending_navigation_direction = Some(direction);
                app_event_tx.send(AppEvent::LookupMessageHistoryEntry {
                    thread_id,
                    offset: global_idx,
                    log_id,
                });
            }
            return None;
        }
    }

    fn next_history_offset(
        &self,
        offset: usize,
        direction: HistorySearchDirection,
    ) -> Option<usize> {
        match direction {
            HistorySearchDirection::Older => offset.checked_sub(1),
            HistorySearchDirection::Newer => offset
                .checked_add(1)
                .filter(|next| *next < self.total_entries()),
        }
    }

    fn persistent_entry_duplicates_local(&self, entry: &HistoryEntry) -> bool {
        self.replay_seeded_history.iter().any(|local_entry| {
            local_entry.text == entry.text && local_entry.mention_bindings == entry.mention_bindings
        })
    }
}

impl HistorySearchState {
    fn new(query: &str) -> Self {
        Self {
            query: query.to_string(),
            query_lower: query.to_lowercase(),
            selected_offset: None,
            unique_matches: Vec::new(),
            selected_match_index: None,
            seen_texts: HashSet::new(),
            awaiting: None,
            next_older_cursor: None,
            exhausted_older: false,
            exhausted_newer: false,
        }
    }

    fn is_exhausted(&self, direction: HistorySearchDirection) -> bool {
        match direction {
            HistorySearchDirection::Older => self.exhausted_older,
            HistorySearchDirection::Newer => self.exhausted_newer,
        }
    }

    fn mark_exhausted(&mut self, direction: HistorySearchDirection) {
        match direction {
            HistorySearchDirection::Older => self.exhausted_older = true,
            HistorySearchDirection::Newer => self.exhausted_newer = true,
        }
    }

    fn record_match(&mut self, offset: usize, entry: &HistoryEntry) {
        if let Some(index) = self
            .unique_matches
            .iter()
            .position(|history_match| history_match.offset == offset)
        {
            self.select_match(index);
            return;
        }

        self.seen_texts.insert(entry.text.clone());
        let insert_index = self
            .unique_matches
            .partition_point(|history_match| history_match.offset > offset);
        self.unique_matches.insert(
            insert_index,
            UniqueHistoryMatch {
                offset,
                entry: entry.clone(),
            },
        );
        self.select_match(insert_index);
    }

    fn select_match(&mut self, index: usize) {
        let Some(history_match) = self.unique_matches.get(index) else {
            return;
        };
        self.selected_offset = Some(history_match.offset);
        self.selected_match_index = Some(index);
        self.awaiting = None;
        self.exhausted_older = false;
        self.exhausted_newer = false;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tui_internal::app_event::AppEvent;
    use crate::tui_internal::app_event::HistoryBatchEntryResponse;
    use pretty_assertions::assert_eq;
    use tokio::sync::mpsc::unbounded_channel;

    fn test_thread_id() -> ThreadId {
        ThreadId::from_string("67e55044-10b1-426f-9247-bb680e5fe0c8")
            .expect("thread id should parse")
    }

    fn batch_entry(offset: usize, entry: &str) -> HistoryBatchEntryResponse {
        HistoryBatchEntryResponse {
            offset,
            entry: Some(entry.to_string()),
        }
    }

    #[test]
    fn duplicate_submissions_are_not_recorded() {
        let mut history = ChatComposerHistory::new();

        // Empty submissions are ignored.
        history.record_local_submission(HistoryEntry::new(String::new()));
        assert_eq!(history.local_history.len(), 0);

        // First entry is recorded.
        history.record_local_submission(HistoryEntry::new("hello".to_string()));
        assert_eq!(history.local_history.len(), 1);
        assert_eq!(
            history.local_history.last().unwrap(),
            &HistoryEntry::new("hello".to_string())
        );

        // Identical consecutive entry is skipped.
        history.record_local_submission(HistoryEntry::new("hello".to_string()));
        assert_eq!(history.local_history.len(), 1);

        // Different entry is recorded.
        history.record_local_submission(HistoryEntry::new("world".to_string()));
        assert_eq!(history.local_history.len(), 2);
        assert_eq!(
            history.local_history.last().unwrap(),
            &HistoryEntry::new("world".to_string())
        );
    }

    #[test]
    fn persistent_restore_gates_at_mentions() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);
        let mut history = ChatComposerHistory::new();
        history.set_metadata(test_thread_id(), /*log_id*/ 42, /*entry_count*/ 1);

        assert!(history.navigate_up(&tx).is_none());
        let disabled = history.on_entry_response(
            /*log_id*/ 42,
            /*offset*/ 0,
            Some("[@sample](plugin://sample@test) and [$figma](app://figma)".to_string()),
            &tx,
        );
        assert_eq!(
            disabled,
            HistoryEntryResponse::Found(HistoryEntry {
                text: "$sample and $figma".to_string(),
                text_elements: Vec::new(),
                local_image_paths: Vec::new(),
                remote_image_urls: Vec::new(),
                mention_bindings: vec![
                    MentionBinding {
                        sigil: '$',
                        mention: "sample".to_string(),
                        path: "plugin://sample@test".to_string(),
                    },
                    MentionBinding {
                        sigil: '$',
                        mention: "figma".to_string(),
                        path: "app://figma".to_string(),
                    },
                ],
                pending_pastes: Vec::new(),
            })
        );

        history.set_at_mention_restore_enabled(/*enabled*/ true);
        assert!(history.navigate_up(&tx).is_none());
        let enabled = history.on_entry_response(
            /*log_id*/ 42,
            /*offset*/ 0,
            Some("[@sample](plugin://sample@test) and [$figma](app://figma)".to_string()),
            &tx,
        );
        assert_eq!(
            enabled,
            HistoryEntryResponse::Found(HistoryEntry {
                text: "@sample and $figma".to_string(),
                text_elements: Vec::new(),
                local_image_paths: Vec::new(),
                remote_image_urls: Vec::new(),
                mention_bindings: vec![
                    MentionBinding {
                        sigil: '@',
                        mention: "sample".to_string(),
                        path: "plugin://sample@test".to_string(),
                    },
                    MentionBinding {
                        sigil: '$',
                        mention: "figma".to_string(),
                        path: "app://figma".to_string(),
                    },
                ],
                pending_pastes: Vec::new(),
            })
        );
    }

    #[test]
    fn navigation_with_async_fetch() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        // Pretend there are 3 persistent entries.
        let thread_id = test_thread_id();
        history.set_metadata(thread_id, /*log_id*/ 1, /*entry_count*/ 3);
        history.record_local_submission(HistoryEntry::new("latest".to_string()));

        // First Up should recall current-session local history.
        assert!(history.should_handle_navigation("", /*cursor*/ 0));
        assert_eq!(
            Some(HistoryEntry::new("latest".to_string())),
            history.navigate_up(&tx)
        );

        // Next Up should request offset 2 and await async data.
        assert!(history.navigate_up(&tx).is_none()); // don't replace the text yet

        // Verify that a history lookup request was sent.
        let event = rx.try_recv().expect("expected AppEvent to be sent");
        let AppEvent::LookupMessageHistoryEntry {
            thread_id: response_thread_id,
            offset,
            log_id,
        } = event
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(response_thread_id, thread_id);
        assert_eq!(offset, 2);
        assert_eq!(log_id, 1);

        // Inject the async response.
        assert_eq!(
            HistoryEntryResponse::Found(HistoryEntry::new("latest".to_string())),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 2,
                Some("latest".into()),
                &tx
            )
        );

        // Next Up should move to offset 1.
        assert!(history.navigate_up(&tx).is_none()); // don't replace the text yet

        // Verify second lookup request for offset 1.
        let event2 = rx.try_recv().expect("expected second event");
        let AppEvent::LookupMessageHistoryEntry {
            thread_id: response_thread_id,
            offset,
            log_id,
        } = event2
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(response_thread_id, thread_id);
        assert_eq!(offset, 1);
        assert_eq!(log_id, 1);

        assert_eq!(
            HistoryEntryResponse::Found(HistoryEntry::new("older".to_string())),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 1,
                Some("older".into()),
                &tx
            )
        );
    }

    #[test]
    fn search_matches_local_history_and_stops_at_boundaries() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.record_local_submission(HistoryEntry::new("git status".to_string()));
        history.record_local_submission(HistoryEntry::new("cargo test -p codex-tui".to_string()));
        history.record_local_submission(HistoryEntry::new("git diff".to_string()));

        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git diff".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git status".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git diff".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Newer,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "git",
                HistorySearchDirection::Newer,
                /*restart*/ false,
                &tx
            )
        );
    }

    #[test]
    fn search_skips_duplicate_local_matches() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.record_local_submission(HistoryEntry::new("git status".to_string()));
        history.record_local_submission(HistoryEntry::new("cargo test -p codex-tui".to_string()));
        history.record_local_submission(HistoryEntry::new("git status".to_string()));
        history.record_local_submission(HistoryEntry::new("git diff".to_string()));

        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git diff".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git status".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git diff".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Newer,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("git status".to_string())),
            history.search(
                "git",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
    }

    #[test]
    fn repeated_boundary_search_does_not_refetch_persistent_history() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.set_metadata(test_thread_id(), /*log_id*/ 1, /*entry_count*/ 3);

        assert_eq!(
            HistorySearchResult::Pending,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        let _ = rx.try_recv().expect("expected latest lookup");
        assert_eq!(
            HistoryEntryResponse::Search(HistorySearchResult::Found(HistoryEntry::new(
                "needle latest".to_string()
            ))),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 2,
                Some("needle latest".into()),
                &tx,
            )
        );

        assert_eq!(
            HistorySearchResult::Pending,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        let _ = rx.try_recv().expect("expected next older lookup");
        assert_eq!(
            HistoryEntryResponse::Search(HistorySearchResult::Pending),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 1,
                Some("not a match".into()),
                &tx,
            )
        );
        let AppEvent::LookupMessageHistoryBatch { cursor, .. } =
            rx.try_recv().expect("expected oldest batch")
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(cursor.end_offset(), 0);
        assert_eq!(
            Some(HistorySearchResult::AtBoundary),
            history.on_batch_response(
                /*log_id*/ 1,
                cursor,
                vec![batch_entry(/*offset*/ 0, "also not a match")],
                /*next_older_cursor*/ None,
                &tx,
            )
        );
        assert!(rx.try_recv().is_err());

        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert!(rx.try_recv().is_err());
    }

    #[test]
    fn search_fetches_persistent_history_until_match() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        let thread_id = test_thread_id();
        history.set_metadata(thread_id, /*log_id*/ 1, /*entry_count*/ 3);

        assert_eq!(
            HistorySearchResult::Pending,
            history.search(
                "older",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        let AppEvent::LookupMessageHistoryEntry {
            thread_id: response_thread_id,
            offset,
            log_id,
        } = rx.try_recv().expect("expected latest lookup")
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(response_thread_id, thread_id);
        assert_eq!(offset, 2);
        assert_eq!(log_id, 1);

        assert_eq!(
            HistoryEntryResponse::Search(HistorySearchResult::Pending),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 2,
                Some("latest".into()),
                &tx
            )
        );
        let AppEvent::LookupMessageHistoryBatch {
            thread_id: response_thread_id,
            cursor,
            log_id,
        } = rx.try_recv().expect("expected next lookup")
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(response_thread_id, thread_id);
        assert_eq!(cursor.end_offset(), 1);
        assert_eq!(log_id, 1);

        assert_eq!(
            Some(HistorySearchResult::Found(HistoryEntry::new(
                "OLDER command".to_string()
            ))),
            history.on_batch_response(
                /*log_id*/ 1,
                cursor,
                vec![batch_entry(/*offset*/ 1, "OLDER command")],
                Some(HistoryBatchCursor::new(/*end_offset*/ 0)),
                &tx
            )
        );
    }

    #[test]
    fn search_skips_duplicate_persistent_matches() {
        let (tx, mut rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.set_metadata(test_thread_id(), /*log_id*/ 1, /*entry_count*/ 4);

        assert_eq!(
            HistorySearchResult::Pending,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        let _ = rx.try_recv().expect("expected latest lookup");
        assert_eq!(
            HistoryEntryResponse::Search(HistorySearchResult::Found(HistoryEntry::new(
                "needle same".to_string()
            ))),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 3,
                Some("needle same".into()),
                &tx,
            )
        );

        assert_eq!(
            HistorySearchResult::Pending,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        let _ = rx.try_recv().expect("expected duplicate lookup");
        assert_eq!(
            HistoryEntryResponse::Search(HistorySearchResult::Pending),
            history.on_entry_response(
                /*log_id*/ 1,
                /*offset*/ 2,
                Some("needle same".into()),
                &tx,
            )
        );
        let AppEvent::LookupMessageHistoryBatch { cursor, .. } =
            rx.try_recv().expect("expected next batch after duplicate")
        else {
            panic!("unexpected event variant");
        };
        assert_eq!(cursor.end_offset(), 1);
        assert_eq!(
            Some(HistorySearchResult::Found(HistoryEntry::new(
                "needle older".to_string()
            ))),
            history.on_batch_response(
                /*log_id*/ 1,
                cursor,
                vec![
                    batch_entry(/*offset*/ 1, "not a match"),
                    batch_entry(/*offset*/ 0, "needle older"),
                ],
                /*next_older_cursor*/ None,
                &tx,
            )
        );
        assert_eq!(
            HistorySearchResult::AtBoundary,
            history.search(
                "needle",
                HistorySearchDirection::Older,
                /*restart*/ false,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("needle same".to_string())),
            history.search(
                "needle",
                HistorySearchDirection::Newer,
                /*restart*/ false,
                &tx
            )
        );
    }

    #[test]
    fn search_is_case_insensitive_and_empty_query_finds_latest() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.record_local_submission(HistoryEntry::new("Build Release".to_string()));

        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("Build Release".to_string())),
            history.search(
                "release",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
        assert_eq!(
            HistorySearchResult::Found(HistoryEntry::new("Build Release".to_string())),
            history.search(
                "",
                HistorySearchDirection::Older,
                /*restart*/ true,
                &tx
            )
        );
    }

    #[test]
    fn reset_navigation_resets_cursor() {
        let (tx, _rx) = unbounded_channel::<AppEvent>();
        let tx = AppEventSender::new(tx);

        let mut history = ChatComposerHistory::new();
        history.set_metadata(test_thread_id(), /*log_id*/ 1, /*entry_count*/ 3);
        history
            .fetched_history
            .insert(1, Some(HistoryEntry::new("command2".to_string())));
        history
            .fetched_history
            .insert(2, Some(HistoryEntry::new("command3".to_string())));

        assert_eq!(
            Some(HistoryEntry::new("command3".to_string())),
            history.navigate_up(&tx)
        );
        assert_eq!(
            Some(HistoryEntry::new("command2".to_string())),
            history.navigate_up(&tx)
        );

        history.reset_navigation();
        assert!(history.history_cursor.is_none());
        assert!(history.last_history_text.is_none());

        assert_eq!(
            Some(HistoryEntry::new("command3".to_string())),
            history.navigate_up(&tx)
        );
    }

    #[test]
    fn should_handle_navigation_when_cursor_is_at_line_boundaries() {
        let mut history = ChatComposerHistory::new();
        history.record_local_submission(HistoryEntry::new("hello".to_string()));
        history.last_history_text = Some("hello".to_string());

        assert!(history.should_handle_navigation("hello", /*cursor*/ 0));
        assert!(history.should_handle_navigation("hello", "hello".len()));
        assert!(!history.should_handle_navigation("hello", /*cursor*/ 1));
        assert!(!history.should_handle_navigation("other", /*cursor*/ 0));
    }
}