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
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2026 Mark Wells <contact@markwells.dev>

//! Top-level draw function composing all TUI widgets.
//!
//! Brings together sessions tree, events grid, scrollbars, overflow counts,
//! hints bar, filter bar, and selection highlights into a single frame.

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Style};

use super::app::{App, FocusedPane, InputMode};
use super::degradation::{
    DegradationConfig, compute_degradation, is_below_minimum, render_below_minimum,
};
use super::filter::render_filter_bar;
use super::hints::render_hints;
use super::layout::compute_layout;
use super::panel::render_panel;
use super::scrollbar::{ScrollMetrics, compute_overflow, render_overflow_counts, render_scrollbar};
use super::selection::render_selection_highlight;
use super::tree::render_tree;

/// Pin ratio for pinned panels (same as grid module).
const PIN_RATIO: f64 = 2.0;

/// Draw the full TUI frame.
///
/// Computes degradation for the current terminal size, then renders:
/// 1. Sessions tree (if visible).
/// 2. Events grid with BSP layout.
/// 3. Scrollbars for each panel.
/// 4. Overflow count indicators.
/// 5. Selection highlights (visual mode).
/// 6. Hints bar or filter bar at the bottom row.
#[allow(
    clippy::cast_possible_truncation,
    clippy::too_many_lines,
    reason = "terminal coordinates are bounded; draw function coordinates many widgets"
)]
pub fn draw(frame: &mut Frame, app: &mut App<'_>) {
    let area = frame.area();

    // Below-minimum check.
    if is_below_minimum(area.width, area.height) {
        render_below_minimum(area, frame.buffer_mut());
        return;
    }

    // Compute degradation.
    let config = DegradationConfig {
        sessions_width_ratio: app.sessions_width_ratio,
        ..DegradationConfig::default()
    };
    let degrade = compute_degradation(area.width, area.height, app.grid.panels.len(), &config);

    // Degradation can hide sessions, but not force-show them (user `s` toggle wins).
    if !degrade.sessions_visible {
        app.sessions_visible = false;
    }

    // Split into sessions area + grid area.
    let sessions_width = if app.sessions_visible && app.grid.panels.is_empty() {
        area.width
    } else if app.sessions_visible {
        degrade.sessions_width
    } else {
        0
    };

    let grid_width = area.width.saturating_sub(sessions_width);

    // Reserve 1 row at the bottom for hints/filter bar.
    let content_height = area.height.saturating_sub(1);

    let tree_area = Rect::new(area.x, area.y, sessions_width, content_height);
    let grid_area = Rect::new(area.x + sessions_width, area.y, grid_width, content_height);
    let hints_area = Rect::new(area.x, area.y + content_height, area.width, 1);

    app.tree_area = tree_area;
    app.grid_area = grid_area;

    // Render sessions tree.
    if app.sessions_visible && tree_area.width > 0 && tree_area.height > 0 {
        // Content area: inside top border (1 row) and right border (1 col).
        let tree_content_height = tree_area.height.saturating_sub(1) as usize;
        app.tree.viewport_height = tree_content_height;

        render_tree(
            &app.tree,
            tree_area,
            frame.buffer_mut(),
            app.theme,
            app.icons,
            app.focus == FocusedPane::Sessions,
        );

        // Render scrollbar and overflow counts for the sessions tree.
        let visible_count = app.tree.visible_items().len();
        if visible_count > tree_content_height && tree_area.width > 0 {
            let track_area = Rect::new(
                tree_area.x + tree_area.width.saturating_sub(1),
                tree_area.y + 1,
                1,
                tree_area.height.saturating_sub(1),
            );
            let metrics = ScrollMetrics {
                content_length: visible_count,
                viewport_length: tree_content_height,
                position: app.tree.scroll_offset,
            };
            render_scrollbar(
                &metrics,
                track_area,
                frame.buffer_mut(),
                Color::White,
                Color::DarkGray,
            );

            let content_area = Rect::new(
                tree_area.x,
                tree_area.y + 1,
                tree_area.width.saturating_sub(1),
                tree_area.height.saturating_sub(1),
            );
            let counts = compute_overflow(&metrics);
            render_overflow_counts(
                &counts,
                content_area,
                frame.buffer_mut(),
                Style::default().fg(Color::DarkGray),
            );
        }

        // Render visual selection highlight on the sessions tree.
        if let Some(ref sel) = app.tree.visual_selection {
            // Content area: inside the top border (1 row).
            let content_area = Rect::new(
                tree_area.x,
                tree_area.y + 1,
                tree_area.width,
                tree_area.height.saturating_sub(1),
            );
            render_selection_highlight(
                sel,
                app.tree.scroll_offset,
                frame.buffer_mut(),
                content_area,
                app.theme.selection,
            );
        }
    }

    // Compute grid layout.
    if !app.grid.panels.is_empty() && grid_area.width > 0 && grid_area.height > 0 {
        let pinned = app.grid.pinned_indices();
        let layout = compute_layout(grid_area, &app.grid.composition, &pinned, PIN_RATIO);

        // Render each panel.
        for panel_rect in &layout.panels {
            if panel_rect.index >= app.grid.panels.len() {
                continue;
            }
            // Record real viewport height so snap_viewport uses it between frames.
            app.grid.panels[panel_rect.index].viewport_height =
                panel_rect.rect.height.saturating_sub(1) as usize;
            let is_focused =
                app.focus == FocusedPane::Events && app.grid.focused == Some(panel_rect.index);
            render_panel(
                &app.grid.panels[panel_rect.index],
                panel_rect.rect,
                frame.buffer_mut(),
                is_focused,
            );

            // Render scrollbar for this panel.
            let panel = &app.grid.panels[panel_rect.index];
            let flat_len = panel.flat_lines().len();
            let inner_height = panel_rect.rect.height.saturating_sub(1) as usize; // title row
            if flat_len > inner_height && panel_rect.rect.width > 0 {
                let track_area = Rect::new(
                    panel_rect.rect.x + panel_rect.rect.width.saturating_sub(1),
                    panel_rect.rect.y + 1,
                    1,
                    panel_rect.rect.height.saturating_sub(1),
                );
                let metrics = ScrollMetrics {
                    content_length: flat_len,
                    viewport_length: inner_height,
                    position: panel.scroll_offset,
                };
                render_scrollbar(
                    &metrics,
                    track_area,
                    frame.buffer_mut(),
                    Color::White,
                    Color::DarkGray,
                );

                // Render overflow counts.
                let content_area = Rect::new(
                    panel_rect.rect.x + 1,
                    panel_rect.rect.y + 1,
                    panel_rect.rect.width.saturating_sub(2),
                    panel_rect.rect.height.saturating_sub(1),
                );
                let counts = compute_overflow(&metrics);
                render_overflow_counts(
                    &counts,
                    content_area,
                    frame.buffer_mut(),
                    Style::default().fg(Color::DarkGray),
                );
            }

            // Render visual selection highlight.
            if let Some(ref sel) = panel.visual_selection {
                let content_area = Rect::new(
                    panel_rect.rect.x + 1,
                    panel_rect.rect.y + 1,
                    panel_rect.rect.width.saturating_sub(2),
                    panel_rect.rect.height.saturating_sub(1),
                );
                render_selection_highlight(
                    sel,
                    panel.scroll_offset,
                    frame.buffer_mut(),
                    content_area,
                    app.theme.selection,
                );
            }
        }

        app.grid_layout = Some(layout);
    } else {
        app.grid_layout = None;
    }

    // Render bottom bar: filter bar or hints.
    if hints_area.height > 0 {
        let filter_active = app.input_mode == InputMode::FilterInput;
        let filter_locked = app.filter.as_ref().is_some_and(|f| f.locked.is_some());
        let focused_on_bottom = app.focus == FocusedPane::Events;

        if filter_active {
            if let Some(ref filter) = app.filter {
                render_filter_bar(filter, hints_area, frame.buffer_mut(), app.theme);
            }
        } else {
            render_hints(
                hints_area,
                frame.buffer_mut(),
                app.theme,
                false,
                filter_locked,
                focused_on_bottom,
            );
        }
    }
}

/// Dispatch a keyboard event in Normal mode.
///
/// Returns `true` if the event was consumed.
#[allow(clippy::too_many_lines, reason = "match arms for each keybinding")]
pub fn handle_key_normal(app: &mut App<'_>, key: crossterm::event::KeyEvent) -> bool {
    use crossterm::event::{KeyCode, KeyModifiers};

    match key.code {
        KeyCode::Char('q') => {
            app.quit = true;
            true
        }
        KeyCode::Tab => {
            match app.focus {
                FocusedPane::Sessions => {
                    if !app.grid.panels.is_empty() {
                        app.focus = FocusedPane::Events;
                        // Focus first panel when entering Events from Sessions.
                        app.grid.focus_panel(0);
                    }
                }
                FocusedPane::Events => {
                    // Cycle through panels. When wrapping past the last panel,
                    // jump to Sessions (if visible) instead.
                    let at_last = app
                        .grid
                        .focused
                        .is_some_and(|f| f + 1 >= app.grid.panels.len());
                    if at_last && app.sessions_visible {
                        app.focus = FocusedPane::Sessions;
                    } else {
                        app.grid.focus_next();
                    }
                }
            }
            true
        }
        KeyCode::BackTab => {
            // Shift+Tab: reverse direction of Tab.
            match app.focus {
                FocusedPane::Sessions => {
                    if !app.grid.panels.is_empty() {
                        app.focus = FocusedPane::Events;
                        // Focus last panel when entering Events from Sessions in reverse.
                        app.grid.focus_panel(app.grid.panels.len() - 1);
                    }
                }
                FocusedPane::Events => {
                    let at_first = app.grid.focused.is_some_and(|f| f == 0);
                    if at_first && app.sessions_visible {
                        app.focus = FocusedPane::Sessions;
                    } else {
                        app.grid.focus_prev();
                    }
                }
            }
            true
        }
        KeyCode::Char('f') if app.focus == FocusedPane::Events => {
            // Enter filter input mode.
            let scope = app
                .grid
                .focused
                .map_or(super::filter::FilterScope::Global, |idx| {
                    super::filter::FilterScope::Local(idx)
                });
            app.filter = Some(super::filter::FilterState::new(scope));
            app.input_mode = InputMode::FilterInput;
            true
        }
        KeyCode::Char('F') if app.focus == FocusedPane::Events => {
            // Enter global filter input mode.
            app.filter = Some(super::filter::FilterState::new(
                super::filter::FilterScope::Global,
            ));
            app.input_mode = InputMode::FilterInput;
            true
        }
        KeyCode::Char('v') => {
            app.input_mode = InputMode::Visual;
            match app.focus {
                FocusedPane::Sessions => {
                    app.tree.visual_selection =
                        Some(super::selection::VisualSelection::new(app.tree.cursor));
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.visual_selection =
                            Some(super::selection::VisualSelection::new(panel.cursor));
                    }
                }
            }
            true
        }
        KeyCode::Char('j') | KeyCode::Down => {
            match app.focus {
                FocusedPane::Sessions => app.tree.navigate(1),
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.navigate(1);
                    }
                }
            }
            true
        }
        KeyCode::Char('k') | KeyCode::Up => {
            match app.focus {
                FocusedPane::Sessions => app.tree.navigate(-1),
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.navigate(-1);
                    }
                }
            }
            true
        }
        KeyCode::Enter => {
            if app.focus == FocusedPane::Sessions {
                if let Some(session_id) = app.tree.toggle_at_cursor() {
                    let idx = app.grid.open_panel(session_id.clone());
                    app.grid.focus_panel(idx);
                    app.focus = FocusedPane::Events;
                    // Load messages for the panel.
                    if let Ok(messages) = app.data.monitor_messages(&session_id)
                        && let Some(panel) = app.grid.panels.get_mut(idx)
                    {
                        panel.load_messages(messages);
                        panel.update_language_servers();
                    }
                    // Create a tail if one doesn't already exist.
                    if !app.tails.contains_key(&session_id)
                        && let Ok(tail) = app.data.create_message_tail(&session_id)
                    {
                        app.tails.insert(session_id, tail);
                    }
                }
            } else if app.focus == FocusedPane::Events
                && let Some(panel) = app.grid.focused_panel_mut()
            {
                panel.toggle_expansion();
            }
            true
        }
        KeyCode::Char('h') | KeyCode::Left => {
            match app.focus {
                FocusedPane::Sessions => app.tree.collapse_at_cursor(),
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.scroll_horizontal(-1);
                    }
                }
            }
            true
        }
        KeyCode::Char('l') | KeyCode::Right => {
            match app.focus {
                FocusedPane::Sessions => app.tree.expand_at_cursor(),
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.scroll_horizontal(1);
                    }
                }
            }
            true
        }
        KeyCode::Char('x') if app.focus == FocusedPane::Events => {
            // Close focused panel and remove its tail.
            if let Some(idx) = app.grid.focused {
                let session_id = app.grid.panels.get(idx).map(|p| p.session_id.clone());
                app.grid.close_panel(idx);
                if let Some(id) = session_id {
                    app.tails.remove(&id);
                }
                if app.grid.panels.is_empty() {
                    app.focus = FocusedPane::Sessions;
                }
            }
            true
        }
        KeyCode::Char('w') if app.focus == FocusedPane::Events => {
            app.grid.cycle_layout();
            true
        }
        KeyCode::Char('p') if app.focus == FocusedPane::Events => {
            app.grid.toggle_pin();
            true
        }
        KeyCode::Char(' ') => {
            match app.focus {
                FocusedPane::Sessions => {
                    app.tree.toggle_at_cursor();
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.toggle_expansion();
                    }
                }
            }
            true
        }
        KeyCode::Char('g') if app.focus == FocusedPane::Events => {
            if let Some(panel) = app.grid.focused_panel_mut() {
                panel.scroll_to_top();
            }
            true
        }
        KeyCode::Char('G') if app.focus == FocusedPane::Events => {
            if let Some(panel) = app.grid.focused_panel_mut() {
                panel.scroll_to_bottom();
            }
            true
        }
        KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            if app.focus == FocusedPane::Events
                && let Some(panel) = app.grid.focused_panel_mut()
            {
                panel.page_up(20);
            }
            true
        }
        KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
            if app.focus == FocusedPane::Events
                && let Some(panel) = app.grid.focused_panel_mut()
            {
                panel.page_down(20);
            }
            true
        }
        KeyCode::Char('s') => {
            app.sessions_visible = !app.sessions_visible;
            if !app.sessions_visible
                && app.focus == FocusedPane::Sessions
                && !app.grid.panels.is_empty()
            {
                app.focus = FocusedPane::Events;
            }
            true
        }
        KeyCode::Char('?') => {
            // If Sessions is hidden, show it first, then toggle cheatsheet.
            if !app.sessions_visible {
                app.sessions_visible = true;
            }
            app.tree.show_cheatsheet = !app.tree.show_cheatsheet;
            true
        }
        KeyCode::Esc => {
            // Clear pins, clear locked filter, clear panel filters.
            app.grid.clear_pins();
            if let Some(ref mut filter) = app.filter {
                filter.clear_locked();
                app.filter = None;
            }
            for panel in &mut app.grid.panels {
                panel.filter_pattern = None;
            }
            true
        }
        _ => false,
    }
}

/// Dispatch a keyboard event in `FilterInput` mode.
///
/// Returns `true` if the event was consumed.
pub fn handle_key_filter(app: &mut App<'_>, key: crossterm::event::KeyEvent) -> bool {
    use crossterm::event::KeyCode;

    let Some(ref mut filter) = app.filter else {
        app.input_mode = InputMode::Normal;
        return true;
    };

    match key.code {
        KeyCode::Esc => {
            filter.cancel();
            app.input_mode = InputMode::Normal;
            true
        }
        KeyCode::Enter => {
            filter.submit();
            let locked = filter.locked.clone();
            let scope = filter.scope.clone();
            apply_filter_to_panels(app, locked.as_ref(), &scope);
            app.input_mode = InputMode::Normal;
            true
        }
        KeyCode::Backspace => {
            filter.pop_char();
            true
        }
        KeyCode::Up => {
            filter.navigate_history(-1);
            true
        }
        KeyCode::Down => {
            filter.navigate_history(1);
            true
        }
        KeyCode::Tab => {
            filter.cycle_suggestion(-1);
            true
        }
        KeyCode::BackTab => {
            filter.cycle_suggestion(1);
            true
        }
        KeyCode::Char(c) => {
            filter.push_char(c);
            true
        }
        _ => false,
    }
}

/// Propagate a locked filter pattern to the relevant panels.
fn apply_filter_to_panels(
    app: &mut App<'_>,
    pattern: Option<&String>,
    scope: &super::filter::FilterScope,
) {
    let pat = pattern.cloned();
    match scope {
        super::filter::FilterScope::Local(idx) => {
            if let Some(panel) = app.grid.panels.get_mut(*idx) {
                panel.filter_pattern = pat;
                panel.cursor = 0;
                panel.scroll_offset = 0;
            }
        }
        super::filter::FilterScope::Global => {
            for panel in &mut app.grid.panels {
                panel.filter_pattern.clone_from(&pat);
                panel.cursor = 0;
                panel.scroll_offset = 0;
            }
        }
    }
}

/// Dispatch a keyboard event in Visual mode.
///
/// Returns `true` if the event was consumed.
pub fn handle_key_visual(app: &mut App<'_>, key: crossterm::event::KeyEvent) -> bool {
    use crossterm::event::KeyCode;

    match key.code {
        KeyCode::Esc | KeyCode::Char('v') => {
            // Cancel / toggle off visual selection.
            match app.focus {
                FocusedPane::Sessions => {
                    app.tree.visual_selection = None;
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.visual_selection = None;
                    }
                }
            }
            app.input_mode = InputMode::Normal;
            true
        }
        KeyCode::Char('y') => {
            // Yank selection.
            match app.focus {
                FocusedPane::Sessions => {
                    if let Some(ref sel) = app.tree.visual_selection {
                        let text = super::selection::yank_tree_text(&app.tree, sel);
                        let _ = super::selection::copy_to_clipboard(&text);
                    }
                    app.tree.visual_selection = None;
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel()
                        && let Some(ref sel) = panel.visual_selection
                    {
                        let text = super::selection::yank_text(panel, sel);
                        let _ = super::selection::copy_to_clipboard(&text);
                    }
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.visual_selection = None;
                    }
                }
            }
            app.input_mode = InputMode::Normal;
            true
        }
        KeyCode::Char('j') | KeyCode::Down => {
            match app.focus {
                FocusedPane::Sessions => {
                    app.tree.navigate(1);
                    if let Some(ref mut sel) = app.tree.visual_selection {
                        sel.extend(app.tree.cursor);
                    }
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.navigate(1);
                        if let Some(ref mut sel) = panel.visual_selection {
                            sel.extend(panel.cursor);
                        }
                    }
                }
            }
            true
        }
        KeyCode::Char('k') | KeyCode::Up => {
            match app.focus {
                FocusedPane::Sessions => {
                    app.tree.navigate(-1);
                    if let Some(ref mut sel) = app.tree.visual_selection {
                        sel.extend(app.tree.cursor);
                    }
                }
                FocusedPane::Events => {
                    if let Some(panel) = app.grid.focused_panel_mut() {
                        panel.navigate(-1);
                        if let Some(ref mut sel) = panel.visual_selection {
                            sel.extend(panel.cursor);
                        }
                    }
                }
            }
            true
        }
        _ => false,
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests use expect for readable assertions"
)]
mod tests {
    use std::collections::HashMap;

    use ratatui::Terminal;
    use ratatui::backend::TestBackend;

    use crate::config::IconConfig;
    use crate::session::{SessionInfo, SessionMessage};
    use crate::tui::app::{App, FocusedPane, InputMode};
    use crate::tui::data::{MockDataSource, SessionRow};
    use crate::tui::icons::IconSet;
    use crate::tui::render::{draw, handle_key_normal};
    use crate::tui::theme::Theme;
    use crate::tui::tree::TreeItem;

    fn make_session(id: &str, workspace: &str, alive: bool) -> SessionRow {
        SessionRow {
            info: SessionInfo {
                id: id.to_string(),
                pid: 1234,
                workspace: workspace.to_string(),
                started_at: chrono::Utc::now(),
                client_name: Some("test-client".to_string()),
                client_version: None,
                client_session_id: None,
            },
            alive,
            languages: vec!["rust".to_string()],
        }
    }

    fn make_message(method: &str) -> SessionMessage {
        SessionMessage {
            id: 0,
            r#type: "lsp".to_string(),
            method: method.to_string(),
            server: "rust-analyzer".to_string(),
            client: "catenary".to_string(),
            request_id: None,
            parent_id: None,
            timestamp: chrono::Utc::now(),
            payload: serde_json::Value::Object(serde_json::Map::new()),
        }
    }

    fn make_mock_data(
        sessions: Vec<SessionRow>,
        messages_map: HashMap<String, Vec<SessionMessage>>,
    ) -> MockDataSource {
        MockDataSource {
            sessions,
            messages: messages_map,
            tail_messages: HashMap::new(),
        }
    }

    /// Convert a ratatui buffer to a single string for assertion matching.
    fn buffer_to_string(buf: &ratatui::buffer::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
    }

    #[test]
    fn test_full_render_cycle() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());

        let sessions = vec![
            make_session("active01", "/ws/test", true),
            make_session("active02", "/ws/test", true),
        ];
        let mut messages_map = HashMap::new();
        messages_map.insert(
            "active01".to_string(),
            vec![
                make_message("initialize"),
                make_message("textDocument/hover"),
            ],
        );
        messages_map.insert(
            "active02".to_string(),
            vec![
                make_message("initialize"),
                make_message("workspace/symbol"),
                make_message("textDocument/definition"),
            ],
        );

        let data = Box::new(make_mock_data(sessions, messages_map));
        let mut app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        // Load events into the open panels.
        let panel_ids: Vec<String> = app
            .grid
            .panels
            .iter()
            .map(|p| p.session_id.clone())
            .collect();
        for id in &panel_ids {
            if let Ok(messages) = app.data.monitor_messages(id)
                && let Some(panel) = app.grid.panels.iter_mut().find(|p| p.session_id == *id)
            {
                panel.load_messages(messages);
            }
        }

        let backend = TestBackend::new(80, 24);
        let mut terminal = Terminal::new(backend).expect("terminal creation");
        terminal
            .draw(|f| {
                draw(f, &mut app);
            })
            .expect("draw");

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

        assert!(content.contains("Sessions"), "expected Sessions title");
        assert!(
            content.contains("active01") || content.contains("active0"),
            "expected session ID in tree"
        );
    }

    #[test]
    fn test_render_below_minimum() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());
        let data = Box::new(make_mock_data(vec![], HashMap::new()));
        let mut app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        let backend = TestBackend::new(3, 1);
        let mut terminal = Terminal::new(backend).expect("terminal creation");
        terminal
            .draw(|f| {
                draw(f, &mut app);
            })
            .expect("draw");

        let buf = terminal.backend().buffer().clone();
        for x in 0u16..3 {
            assert_eq!(
                buf[(x, 0u16)].symbol(),
                "\u{2573}",
                "cell ({x}, 0) should be \u{2573}"
            );
        }
    }

    #[test]
    fn test_keyboard_dispatch_quit() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());
        let data = Box::new(make_mock_data(vec![], HashMap::new()));
        let mut app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        let key = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char('q'),
            crossterm::event::KeyModifiers::NONE,
        );
        handle_key_normal(&mut app, key);
        assert!(app.quit, "q should set quit = true");
    }

    #[test]
    fn test_keyboard_dispatch_tab_focus() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());

        let sessions = vec![make_session("sess0001", "/ws/test", true)];
        let mut messages_map = HashMap::new();
        messages_map.insert("sess0001".to_string(), vec![make_message("initialize")]);
        let data = Box::new(make_mock_data(sessions, messages_map));
        let mut app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        assert_eq!(app.focus, FocusedPane::Sessions);

        let key = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Tab,
            crossterm::event::KeyModifiers::NONE,
        );
        handle_key_normal(&mut app, key);
        assert_eq!(
            app.focus,
            FocusedPane::Events,
            "Tab should move focus to Events"
        );
    }

    #[test]
    fn test_keyboard_dispatch_filter_mode() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());

        let sessions = vec![make_session("sess0001", "/ws/test", true)];
        let mut messages_map = HashMap::new();
        messages_map.insert("sess0001".to_string(), vec![make_message("initialize")]);
        let data = Box::new(make_mock_data(sessions, messages_map));
        let mut app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        // Move focus to Events.
        app.focus = FocusedPane::Events;

        let key = crossterm::event::KeyEvent::new(
            crossterm::event::KeyCode::Char('f'),
            crossterm::event::KeyModifiers::NONE,
        );
        handle_key_normal(&mut app, key);
        assert_eq!(
            app.input_mode,
            InputMode::FilterInput,
            "f should enter FilterInput mode"
        );
    }

    #[test]
    fn test_startup_auto_open_panels() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());

        let sessions = vec![
            make_session("active01", "/ws/test", true),
            make_session("active02", "/ws/test", true),
        ];
        let data = Box::new(make_mock_data(sessions, HashMap::new()));
        let app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        assert_eq!(
            app.grid.panels.len(),
            2,
            "should auto-open panels for 2 active sessions"
        );
    }

    #[test]
    fn test_startup_cursor_on_first_active() {
        let theme = Theme::new();
        let icons = IconSet::from_config(IconConfig::default());

        let sessions = vec![
            make_session("active01", "/ws/test", true),
            make_session("dead0001", "/ws/test", false),
        ];
        let data = Box::new(make_mock_data(sessions, HashMap::new()));
        let app = App::new(&theme, &icons, data, 0.4).expect("App creation");

        // The cursor should be on the first active session.
        // The tree is: workspace node (idx 0), active session (idx 1), dead session (idx 2).
        let items = app.tree.visible_items();
        if let Some(TreeItem::Session { row, .. }) = items.get(app.tree.cursor) {
            assert!(row.alive, "cursor should be on an active session");
            assert_eq!(row.info.id, "active01");
        }
        // Cursor may be on workspace — that's fine if it's index 0.
        // The important thing is auto-open worked.
    }
}