catenary-mcp 1.6.1

A high-performance multiplexing bridge between MCP (Model Context Protocol) and LSP (Language Server Protocol). Enables LLMs to access IDE-grade code intelligence across multiple languages simultaneously with smart routing and UTF-8 accuracy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>

//! Filter system with history navigation and autocomplete for event panels.
//!
//! Supports local filters (single panel via `f`) and global filters (all
//! panels via `F`). Provides live-as-you-type filtering, filter history
//! with `Up`/`Down` navigation, and `Tab`-cycled autocomplete from history.

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;

use super::format::format_message_plain;
use super::theme::Theme;
use crate::session::SessionMessage;

/// Maximum number of autocomplete suggestions shown.
const MAX_SUGGESTIONS: usize = 5;

// ── Types ────────────────────────────────────────────────────────────────

/// Scope of a filter: local to one panel or global across all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FilterScope {
    /// Applies to a single panel (by index).
    Local(usize),
    /// Applies to all Events panels simultaneously.
    Global,
}

/// State for filter input and active filtering.
pub struct FilterState {
    /// Current text being typed.
    pub input: String,
    /// Locked (active) filter string, set on Enter.
    pub locked: Option<String>,
    /// Filter scope.
    pub scope: FilterScope,
    /// History of locked filter strings (most recent last).
    pub history: Vec<String>,
    /// Current position in history navigation (`None` = not navigating).
    pub history_cursor: Option<usize>,
    /// Current autocomplete suggestion index (`None` = no suggestion).
    pub suggestion_index: Option<usize>,
    /// Text saved before history navigation (to restore on cancel).
    pub saved_input: Option<String>,
}

// ── FilterState ──────────────────────────────────────────────────────────

impl FilterState {
    /// Create a new filter state with the given scope.
    ///
    /// Starts with empty input, no locked filter, and empty history.
    #[must_use]
    pub const fn new(scope: FilterScope) -> Self {
        Self {
            input: String::new(),
            locked: None,
            scope,
            history: Vec::new(),
            history_cursor: None,
            suggestion_index: None,
            saved_input: None,
        }
    }

    /// Append a character to the input.
    ///
    /// Resets suggestion and history cursor (typing cancels navigation).
    pub fn push_char(&mut self, c: char) {
        self.input.push(c);
        self.suggestion_index = None;
        self.history_cursor = None;
        self.saved_input = None;
    }

    /// Remove the last character from the input (backspace).
    ///
    /// Resets suggestion state.
    pub fn pop_char(&mut self) {
        self.input.pop();
        self.suggestion_index = None;
    }

    /// Lock the current filter (Enter).
    ///
    /// If a suggestion is active, materializes it into input first.
    /// Sets `locked` to the input (or `None` if empty). Adds to history
    /// with deduplication.
    pub fn submit(&mut self) {
        // Materialize active suggestion.
        if let Some(idx) = self.suggestion_index {
            let matches = self.matching_entries_owned();
            if let Some(suggestion) = matches.get(idx) {
                self.input.clone_from(suggestion);
            }
        }

        if self.input.is_empty() {
            self.locked = None;
        } else {
            self.locked = Some(self.input.clone());
            // Deduplicate: remove existing identical entry before appending.
            self.history.retain(|h| h != &self.input);
            self.history.push(self.input.clone());
        }

        self.input.clear();
        self.suggestion_index = None;
        self.history_cursor = None;
        self.saved_input = None;
    }

    /// Cancel filter input without locking (Esc while typing).
    pub fn cancel(&mut self) {
        self.input.clear();
        self.suggestion_index = None;
        self.history_cursor = None;
        self.saved_input = None;
    }

    /// Clear the locked filter (Esc with locked filter, not in input mode).
    pub fn clear_locked(&mut self) {
        self.locked = None;
    }

    /// Navigate filter history (`Up` = delta -1, `Down` = delta +1).
    ///
    /// On first navigation, saves the current input. Moving past the newest
    /// entry restores the saved input. Clamps at boundaries (no wrap).
    #[allow(
        clippy::cast_possible_wrap,
        clippy::cast_sign_loss,
        reason = "history indices never overflow isize"
    )]
    pub fn navigate_history(&mut self, delta: isize) {
        if self.history.is_empty() {
            return;
        }

        // Save input on first navigation.
        if self.history_cursor.is_none() {
            self.saved_input = Some(self.input.clone());
        }

        let len = self.history.len() as isize;

        let new_pos = self
            .history_cursor
            .map_or_else(|| len + delta, |pos| pos as isize + delta);

        if new_pos >= len {
            // Past newest — restore saved input.
            self.history_cursor = None;
            if let Some(saved) = self.saved_input.take() {
                self.input = saved;
            }
        } else if new_pos < 0 {
            // At oldest — clamp.
            self.history_cursor = Some(0);
            self.input = self.history[0].clone();
        } else {
            let idx = new_pos as usize;
            self.history_cursor = Some(idx);
            self.input = self.history[idx].clone();
        }

        self.suggestion_index = None;
    }

    /// Cycle autocomplete suggestions (`Tab` = delta -1, `Shift+Tab` = delta +1).
    ///
    /// Tab enters the suggestion list at the most recent match (index 0)
    /// and advances through older entries. `Shift+Tab` reverses.
    ///
    /// Both directions wrap: Tab past the oldest entry returns to null
    /// (raw input), Shift+Tab past the most recent also returns to null.
    /// The cycle is: null → 0 (most recent) → 1 → ... → null.
    pub fn cycle_suggestion(&mut self, delta: isize) {
        let matches = self.matching_entries_owned();
        if matches.is_empty() {
            self.suggestion_index = None;
            return;
        }

        let count = matches.len();
        // Tab (delta -1): null → 0 → 1 → ... → count-1 → null
        // Shift+Tab (delta +1): null → count-1 → ... → 1 → 0 → null
        match (self.suggestion_index, delta.signum()) {
            (None, -1) => self.suggestion_index = Some(0),
            (None, 1) => self.suggestion_index = Some(count - 1),
            (Some(idx), -1) if idx + 1 >= count => self.suggestion_index = None,
            (Some(idx), -1) => self.suggestion_index = Some(idx + 1),
            (Some(0), 1) => self.suggestion_index = None,
            (Some(idx), 1) => self.suggestion_index = Some(idx - 1),
            _ => {}
        }
    }

    /// Return history entries matching the current input.
    ///
    /// Entries that start with the input are preferred, followed by entries
    /// that contain the input. Deduplicated, most recent first, max 5.
    #[must_use]
    pub fn matching_entries(&self) -> Vec<&str> {
        if self.input.is_empty() {
            return self
                .history
                .iter()
                .rev()
                .map(String::as_str)
                .take(MAX_SUGGESTIONS)
                .collect();
        }

        let lower_input = self.input.to_lowercase();
        let mut seen = std::collections::HashSet::new();
        let mut result: Vec<&str> = Vec::new();

        // Most recent first — iterate in reverse.
        for entry in self.history.iter().rev() {
            let lower_entry = entry.to_lowercase();
            if lower_entry.contains(&lower_input) && seen.insert(entry.as_str()) {
                result.push(entry.as_str());
                if result.len() >= MAX_SUGGESTIONS {
                    break;
                }
            }
        }

        result
    }

    /// The text to use for filtering.
    ///
    /// If a suggestion is active, returns the full suggestion text.
    /// Otherwise returns the typed input.
    #[must_use]
    pub fn effective_input(&self) -> &str {
        if let Some(idx) = self.suggestion_index {
            let matches = self.matching_entries();
            if let Some(entry) = matches.get(idx) {
                return entry;
            }
        }
        &self.input
    }

    /// Ghost text suffix beyond what the user has typed.
    ///
    /// Returns `Some(suffix)` if a suggestion is active and extends
    /// beyond the typed input. `None` if no suggestion.
    #[must_use]
    pub fn virtual_text(&self) -> Option<&str> {
        let idx = self.suggestion_index?;
        let matches = self.matching_entries();
        let entry = matches.get(idx)?;
        if entry.len() > self.input.len() && entry.starts_with(&self.input) {
            Some(&entry[self.input.len()..])
        } else {
            // Suggestion doesn't extend input (contains-match, not prefix-match).
            None
        }
    }

    /// Internal helper: owned version of `matching_entries()` for use in
    /// methods that need to avoid borrowing `&self` conflicts.
    fn matching_entries_owned(&self) -> Vec<String> {
        self.matching_entries()
            .into_iter()
            .map(String::from)
            .collect()
    }
}

// ── Filtering ────────────────────────────────────────────────────────────

/// Return indices of messages matching the pattern.
///
/// Performs a case-insensitive substring match on the plain-text
/// representation of each message (via [`format_message_plain`]).
#[must_use]
pub fn filter_messages(messages: &[SessionMessage], pattern: &str) -> Vec<usize> {
    let lower_pattern = pattern.to_lowercase();
    messages
        .iter()
        .enumerate()
        .filter(|(_, msg)| {
            format_message_plain(msg)
                .to_lowercase()
                .contains(&lower_pattern)
        })
        .map(|(i, _)| i)
        .collect()
}

// ── Rendering ────────────────────────────────────────────────────────────

/// Render the filter input bar into a 1-row area.
///
/// Layout: `<prefix><input>▏<virtual_text>      Esc cancel`
///
/// - Prefix is "Filter: " for local scope, "Global: " for global.
/// - Virtual text is rendered in dim style when a suggestion is active.
/// - "Esc cancel" is right-aligned.
#[allow(
    clippy::cast_possible_truncation,
    reason = "terminal coordinates are always small"
)]
pub fn render_filter_bar(state: &FilterState, area: Rect, buf: &mut Buffer, theme: &Theme) {
    if area.width < 10 || area.height < 1 {
        return;
    }

    let width = area.width as usize;
    let y = area.y;

    let prefix = match state.scope {
        FilterScope::Local(_) => "Filter: ",
        FilterScope::Global => "Global: ",
    };

    let hint = "Esc cancel";

    // Build the left side: prefix + input + cursor + virtual text.
    let mut spans: Vec<Span<'static>> = Vec::new();
    spans.push(Span::styled(prefix.to_string(), theme.accent));
    spans.push(Span::raw(state.input.clone()));
    spans.push(Span::styled("\u{258F}", theme.text)); // ▏ cursor

    if let Some(vtext) = state.virtual_text() {
        spans.push(Span::styled(vtext.to_string(), theme.muted));
    }

    let left_line = Line::from(spans);
    let left_width = UnicodeWidthStr::width(
        left_line
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect::<String>()
            .as_str(),
    );

    // Render left content.
    buf.set_line(area.x, y, &left_line, area.width);

    // Render right-aligned hint if there's room.
    let hint_width = UnicodeWidthStr::width(hint);
    let gap = 1; // minimum gap between content and hint
    if left_width + gap + hint_width <= width {
        let hint_x = area.x + area.width - hint_width as u16;
        let hint_line = Line::from(Span::styled(hint.to_string(), theme.muted));
        buf.set_line(hint_x, y, &hint_line, hint_width as u16);
    }
}

/// Render the autocomplete liftup above the filter bar.
///
/// Up to 5 matching entries. Most recent closest to the filter input
/// (at the bottom of the liftup). Selected entry has "▐" prefix.
#[allow(
    clippy::cast_possible_truncation,
    reason = "terminal coordinates are always small"
)]
pub fn render_filter_liftup(state: &FilterState, area: Rect, buf: &mut Buffer, theme: &Theme) {
    let matches = state.matching_entries();
    if matches.is_empty() || area.height < 1 {
        return;
    }

    let visible_count = matches.len().min(area.height as usize);

    // Entries are most-recent-first in the vec. We want most-recent at the
    // bottom of the liftup (closest to the filter bar), so we reverse
    // for rendering: bottom row = matches[0], row above = matches[1], etc.
    for (i, entry) in matches.iter().take(visible_count).enumerate() {
        // Row position: bottom-aligned within the area.
        let row = area.y + (visible_count - 1 - i) as u16;
        if row < area.y {
            break;
        }

        let is_selected = state.suggestion_index == Some(i);
        let prefix = if is_selected { "\u{2590} " } else { "  " }; //        let style = if is_selected { theme.text } else { theme.muted };

        let line = Line::from(vec![
            Span::styled(prefix.to_string(), style),
            Span::styled((*entry).to_string(), style),
        ]);
        buf.set_line(area.x, row, &line, area.width);
    }
}

// ── Tests ────────────────────────────────────────────────────────────────

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests use expect for readable assertions"
)]
mod tests {
    use super::*;
    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    use crate::session::SessionMessage;

    fn test_theme() -> Theme {
        Theme::new()
    }

    fn make_message(method: &str) -> SessionMessage {
        SessionMessage {
            id: 0,
            r#type: "mcp".to_string(),
            method: method.to_string(),
            server: "catenary".to_string(),
            client: "claude-code".to_string(),
            request_id: None,
            parent_id: None,
            timestamp: chrono::Utc::now(),
            payload: serde_json::json!({"params": {"name": method}}),
        }
    }

    /// Convert a ratatui buffer to a single string for assertion matching.
    fn buffer_to_string(buf: &Buffer) -> String {
        let mut s = String::new();
        for y in 0..buf.area.height {
            for x in 0..buf.area.width {
                let cell = &buf[(x, y)];
                s.push_str(cell.symbol());
            }
            s.push('\n');
        }
        s
    }

    // ── 1. Push and submit ──────────────────────────────────────────────

    #[test]
    fn test_filter_push_and_submit() {
        let mut f = FilterState::new(FilterScope::Local(0));
        f.push_char('h');
        f.push_char('o');
        f.push_char('v');
        f.push_char('e');
        f.push_char('r');
        f.submit();
        assert_eq!(f.locked, Some("hover".to_string()));
        assert!(f.history.contains(&"hover".to_string()));
    }

    // ── 2. Cancel ───────────────────────────────────────────────────────

    #[test]
    fn test_filter_cancel() {
        let mut f = FilterState::new(FilterScope::Local(0));
        f.push_char('t');
        f.push_char('e');
        f.push_char('s');
        f.push_char('t');
        f.cancel();
        assert_eq!(f.locked, None);
        assert!(f.input.is_empty());
        assert!(f.history.is_empty());
    }

    // ── 3. Clear locked ─────────────────────────────────────────────────

    #[test]
    fn test_filter_clear_locked() {
        let mut f = FilterState::new(FilterScope::Local(0));
        for c in "hover".chars() {
            f.push_char(c);
        }
        f.submit();
        assert_eq!(f.locked, Some("hover".to_string()));

        f.clear_locked();
        assert_eq!(f.locked, None);
        assert!(f.history.contains(&"hover".to_string()));
    }

    // ── 4. History navigation ───────────────────────────────────────────

    #[test]
    fn test_filter_history_navigation() {
        let mut f = FilterState::new(FilterScope::Local(0));

        // Submit three entries.
        for s in &["aaa", "bbb", "ccc"] {
            for c in s.chars() {
                f.push_char(c);
            }
            f.submit();
        }

        // Start a new filter, navigate up.
        f.push_char('x');
        f.navigate_history(-1); // → ccc
        assert_eq!(f.input, "ccc");

        f.navigate_history(-1); // → bbb
        assert_eq!(f.input, "bbb");

        f.navigate_history(1); // → ccc
        assert_eq!(f.input, "ccc");

        f.navigate_history(1); // → back to original "x"
        assert_eq!(f.input, "x");
    }

    // ── 5. History dedup ────────────────────────────────────────────────

    #[test]
    fn test_filter_history_dedup() {
        let mut f = FilterState::new(FilterScope::Local(0));
        for _ in 0..2 {
            for c in "hover".chars() {
                f.push_char(c);
            }
            f.submit();
        }
        assert_eq!(
            f.history.iter().filter(|h| *h == "hover").count(),
            1,
            "history should contain only one 'hover' entry"
        );
    }

    // ── 6. Suggestion cycle ─────────────────────────────────────────────

    #[test]
    fn test_filter_suggestion_cycle() {
        let mut f = FilterState::new(FilterScope::Local(0));
        // Build history: ["hover ok", "hover error", "search"].
        for s in &["hover ok", "hover error", "search"] {
            for c in s.chars() {
                f.push_char(c);
            }
            f.submit();
        }

        // Type "hov".
        for c in "hov".chars() {
            f.push_char(c);
        }

        // Matches (most recent first): ["hover error", "hover ok"].
        let matches = f.matching_entries();
        assert_eq!(matches.len(), 2);
        assert_eq!(matches[0], "hover error");
        assert_eq!(matches[1], "hover ok");

        // Tab (delta -1): enters at most recent match (index 0).
        f.cycle_suggestion(-1);
        assert_eq!(f.effective_input(), "hover error");

        // Tab again: advances to older match (index 1).
        f.cycle_suggestion(-1);
        assert_eq!(f.effective_input(), "hover ok");

        // Tab again: wraps back to null (no suggestion).
        f.cycle_suggestion(-1);
        assert_eq!(f.suggestion_index, None);
        assert_eq!(f.effective_input(), "hov");
    }

    // ── 7. Virtual text ─────────────────────────────────────────────────

    #[test]
    fn test_filter_virtual_text() {
        let mut f = FilterState::new(FilterScope::Local(0));
        for c in "hover".chars() {
            f.push_char(c);
        }
        f.submit();

        // Type "ho".
        for c in "ho".chars() {
            f.push_char(c);
        }

        // Cycle to suggestion.
        f.cycle_suggestion(-1);
        assert_eq!(f.virtual_text(), Some("ver"));
    }

    // ── 8. Effective input ──────────────────────────────────────────────

    #[test]
    fn test_filter_effective_input() {
        let mut f = FilterState::new(FilterScope::Local(0));
        for c in "hover error".chars() {
            f.push_char(c);
        }
        f.submit();

        // No suggestion: returns typed input.
        for c in "hov".chars() {
            f.push_char(c);
        }
        assert_eq!(f.effective_input(), "hov");

        // With suggestion: returns full suggestion.
        f.cycle_suggestion(-1);
        assert_eq!(f.effective_input(), "hover error");
    }

    // ── 9. Matching entries max 5 ───────────────────────────────────────

    #[test]
    fn test_filter_matching_entries_max_5() {
        let mut f = FilterState::new(FilterScope::Local(0));
        for i in 0..10 {
            let s = format!("test {i}");
            for c in s.chars() {
                f.push_char(c);
            }
            f.submit();
        }

        for c in "test".chars() {
            f.push_char(c);
        }
        let matches = f.matching_entries();
        assert!(
            matches.len() <= 5,
            "matching_entries should return at most 5, got {}",
            matches.len()
        );
    }

    // ── 10. filter_messages case insensitive ─────────────────────────────

    #[test]
    fn test_filter_messages_case_insensitive() {
        let messages = vec![make_message("Hover"), make_message("hover")];

        let result = filter_messages(&messages, "HOVER");
        // Both should match.
        assert_eq!(result.len(), 2);
        assert_eq!(result[0], 0);
        assert_eq!(result[1], 1);
    }

    // ── 11. filter_messages no match ──────────────────────────────────────

    #[test]
    fn test_filter_messages_no_match() {
        let messages = vec![make_message("tools/call"), make_message("initialize")];

        let result = filter_messages(&messages, "zzzzz");
        assert!(result.is_empty());
    }

    // ── 12. Render filter bar typing ────────────────────────────────────

    #[test]
    fn test_render_filter_bar_typing() {
        let theme = test_theme();
        let mut f = FilterState::new(FilterScope::Local(0));
        for c in "hov".chars() {
            f.push_char(c);
        }

        let backend = TestBackend::new(60, 1);
        let mut terminal = Terminal::new(backend).expect("terminal creation");
        terminal
            .draw(|frame| {
                let area = frame.area();
                render_filter_bar(&f, area, frame.buffer_mut(), &theme);
            })
            .expect("draw");

        let buf = terminal.backend().buffer().clone();
        let content = buffer_to_string(&buf);

        assert!(
            content.contains("Filter: hov"),
            "expected 'Filter: hov' in bar, got: {content}"
        );
        assert!(
            content.contains("Esc cancel"),
            "expected 'Esc cancel' hint, got: {content}"
        );
    }

    // ── 13. Render filter bar with suggestion ───────────────────────────

    #[test]
    fn test_render_filter_bar_with_suggestion() {
        let theme = test_theme();
        let mut f = FilterState::new(FilterScope::Local(0));
        for c in "hover error".chars() {
            f.push_char(c);
        }
        f.submit();

        // Type "hov" and cycle to suggestion.
        for c in "hov".chars() {
            f.push_char(c);
        }
        f.cycle_suggestion(-1);

        let backend = TestBackend::new(60, 1);
        let mut terminal = Terminal::new(backend).expect("terminal creation");
        terminal
            .draw(|frame| {
                let area = frame.area();
                render_filter_bar(&f, area, frame.buffer_mut(), &theme);
            })
            .expect("draw");

        let buf = terminal.backend().buffer().clone();
        let content = buffer_to_string(&buf);

        // Should show "hov" followed by "er error" (the virtual text).
        assert!(
            content.contains("hov"),
            "expected typed text 'hov', got: {content}"
        );
        assert!(
            content.contains("er error"),
            "expected virtual text 'er error', got: {content}"
        );
    }

    // ── 14. Render filter liftup ───────────────────────────────────────

    #[test]
    fn test_render_filter_liftup() {
        let theme = test_theme();
        let mut f = FilterState::new(FilterScope::Local(0));

        // Build history with 3 matching entries.
        for s in &["hover ok", "hover error", "hover timeout"] {
            for c in s.chars() {
                f.push_char(c);
            }
            f.submit();
        }

        for c in "hover".chars() {
            f.push_char(c);
        }

        let backend = TestBackend::new(40, 5);
        let mut terminal = Terminal::new(backend).expect("terminal creation");
        terminal
            .draw(|frame| {
                let area = frame.area();
                render_filter_liftup(&f, area, frame.buffer_mut(), &theme);
            })
            .expect("draw");

        let buf = terminal.backend().buffer().clone();
        let content = buffer_to_string(&buf);

        assert!(
            content.contains("hover ok"),
            "expected 'hover ok' in liftup, got: {content}"
        );
        assert!(
            content.contains("hover error"),
            "expected 'hover error' in liftup, got: {content}"
        );
        assert!(
            content.contains("hover timeout"),
            "expected 'hover timeout' in liftup, got: {content}"
        );
    }
}