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

//! Multi-panel events grid with BSP layout, tab focus cycling, pinning, and
//! layout cycling.
//!
//! The grid is a container for multiple [`PanelState`] instances arranged by
//! the BSP layout engine from [`super::layout`]. It manages panel lifecycle
//! (open/close), `Tab` focus cycling in reading order, `Space` pinning,
//! `w` layout cycling, and `Esc` to clear all pins.

use std::collections::HashSet;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;

use super::icons::IconSet;
use super::layout::{Composition, closest_composition, compute_layout, curated_layouts};
use super::panel::{PanelState, render_panel};
use super::theme::Theme;

/// The pin ratio used for pinned panels (pinned panels get 2x space).
const PIN_RATIO: f64 = 2.0;

/// The Events grid containing multiple panels in a BSP layout.
pub struct EventsGrid<'a> {
    /// Open panels, in reading order.
    pub panels: Vec<PanelState<'a>>,
    /// Semantic color theme (borrowed, same lifetime as panels).
    pub theme: &'a Theme,
    /// Resolved icon set (borrowed, same lifetime as panels).
    pub icons: &'a IconSet,
    /// Current BSP composition (panels-per-row).
    pub composition: Composition,
    /// Index of the focused panel (receives keyboard input), if any.
    pub focused: Option<usize>,
    /// Index into `curated_layouts()` for the current panel count.
    /// Used by `w` to cycle.
    pub layout_cycle_index: usize,
}

impl<'a> EventsGrid<'a> {
    /// Create an empty grid with no panels and no focus.
    #[must_use]
    pub const fn new(theme: &'a Theme, icons: &'a IconSet) -> Self {
        Self {
            panels: Vec::new(),
            theme,
            icons,
            composition: Composition(vec![]),
            focused: None,
            layout_cycle_index: 0,
        }
    }

    /// Open a panel for the given session.
    ///
    /// If a panel for this session already exists, returns its index without
    /// creating a duplicate. Otherwise creates a new panel, updates the
    /// composition, and auto-focuses if this is the only panel.
    pub fn open_panel(&mut self, session_id: String) -> usize {
        if let Some(idx) = self.panel_for_session(&session_id) {
            return idx;
        }

        let panel = PanelState::new(session_id, self.theme, self.icons);
        self.panels.push(panel);

        let new_count = self.panels.len();
        self.composition = closest_composition(&self.composition, new_count);
        self.sync_cycle_index();

        if new_count == 1 {
            self.focused = Some(0);
        }

        new_count - 1
    }

    /// Close the panel at the given index.
    ///
    /// Updates the composition for the new panel count and adjusts focus:
    /// - If closing the focused panel: move to the next panel in reading
    ///   order, or the previous if none, or `None` if empty.
    /// - If closing a panel before the focused one: decrement the focus index.
    pub fn close_panel(&mut self, index: usize) {
        if index >= self.panels.len() {
            return;
        }

        self.panels.remove(index);

        let new_count = self.panels.len();
        self.composition = closest_composition(&self.composition, new_count);
        self.sync_cycle_index();

        if new_count == 0 {
            self.focused = None;
            return;
        }

        if let Some(focused) = self.focused {
            if index == focused {
                // Closing the focused panel — move to next (same index if
                // it's still valid, otherwise clamp to last).
                self.focused = Some(index.min(new_count - 1));
            } else if index < focused {
                // Closing before focused — decrement.
                self.focused = Some(focused - 1);
            }
        }
    }

    /// Advance focus to the next panel in reading order (Tab).
    ///
    /// Wraps around to 0 after the last panel. No-op if no panels.
    pub const fn focus_next(&mut self) {
        if self.panels.is_empty() {
            return;
        }
        self.focused = Some(match self.focused {
            Some(idx) => (idx + 1) % self.panels.len(),
            None => 0,
        });
    }

    /// Move focus to the previous panel in reading order (Shift+Tab).
    ///
    /// Wraps to the last panel from 0. No-op if no panels.
    pub const fn focus_prev(&mut self) {
        if self.panels.is_empty() {
            return;
        }
        let len = self.panels.len();
        self.focused = Some(match self.focused {
            Some(0) | None => len - 1,
            Some(idx) => idx - 1,
        });
    }

    /// Set focus to a specific panel by index.
    ///
    /// No-op if the index is out of bounds.
    pub const fn focus_panel(&mut self, index: usize) {
        if index < self.panels.len() {
            self.focused = Some(index);
        }
    }

    /// Toggle pinning on the focused panel (Space).
    ///
    /// No-op if no panel is focused.
    pub fn toggle_pin(&mut self) {
        if let Some(idx) = self.focused
            && let Some(panel) = self.panels.get_mut(idx)
        {
            panel.pinned = !panel.pinned;
        }
    }

    /// Clear all pins (Esc).
    pub fn clear_pins(&mut self) {
        for panel in &mut self.panels {
            panel.pinned = false;
        }
    }

    /// Sync `layout_cycle_index` to the position of the current composition
    /// in the curated list. Falls back to 0 if no match is found.
    fn sync_cycle_index(&mut self) {
        let layouts = curated_layouts(self.panels.len());
        self.layout_cycle_index = layouts
            .iter()
            .position(|c| *c == self.composition)
            .unwrap_or(0);
    }

    /// Cycle to the next curated layout for the current panel count (w).
    ///
    /// No-op if there are no panels or only one layout available.
    pub fn cycle_layout(&mut self) {
        let layouts = curated_layouts(self.panels.len());
        if layouts.is_empty() {
            return;
        }
        self.layout_cycle_index = (self.layout_cycle_index + 1) % layouts.len();
        self.composition = layouts[self.layout_cycle_index].clone();
    }

    /// Get a reference to the focused panel, if any.
    #[must_use]
    pub fn focused_panel(&self) -> Option<&PanelState<'a>> {
        self.focused.and_then(|idx| self.panels.get(idx))
    }

    /// Get a mutable reference to the focused panel, if any.
    pub fn focused_panel_mut(&mut self) -> Option<&mut PanelState<'a>> {
        self.focused.and_then(|idx| self.panels.get_mut(idx))
    }

    /// Collect indices of all pinned panels.
    ///
    /// Passed to [`compute_layout`] for pin-driven sizing.
    #[must_use]
    pub fn pinned_indices(&self) -> HashSet<usize> {
        self.panels
            .iter()
            .enumerate()
            .filter(|(_, p)| p.pinned)
            .map(|(i, _)| i)
            .collect()
    }

    /// Find the panel index for a given session ID, if open.
    #[must_use]
    pub fn panel_for_session(&self, session_id: &str) -> Option<usize> {
        self.panels.iter().position(|p| p.session_id == session_id)
    }
}

/// Render the full events grid into the given buffer area.
///
/// Computes the BSP layout from the grid's composition and pinned set, then
/// renders each panel into its assigned rect. The focused panel receives a
/// highlighted border.
pub fn render_grid(grid: &EventsGrid<'_>, area: Rect, buf: &mut Buffer) {
    if grid.panels.is_empty() {
        return;
    }

    let pinned = grid.pinned_indices();
    let layout = compute_layout(area, &grid.composition, &pinned, PIN_RATIO);

    for panel_rect in &layout.panels {
        if panel_rect.index >= grid.panels.len() {
            continue;
        }
        let is_focused = grid.focused == Some(panel_rect.index);
        render_panel(
            &grid.panels[panel_rect.index],
            panel_rect.rect,
            buf,
            is_focused,
        );
    }
}

#[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::config::IconConfig;
    use crate::session::SessionMessage;

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

    fn test_icons() -> IconSet {
        IconSet::from_config(IconConfig::default())
    }

    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()),
        }
    }

    /// 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
    }

    #[test]
    fn test_grid_open_panel() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        let idx = grid.open_panel("session-1".to_string());
        assert_eq!(idx, 0);
        assert_eq!(grid.panels.len(), 1);
        assert_eq!(grid.focused, Some(0));
        assert_eq!(grid.composition.total(), 1);
    }

    #[test]
    fn test_grid_open_duplicate() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("abc".to_string());
        let idx = grid.open_panel("abc".to_string());
        assert_eq!(idx, 0);
        assert_eq!(grid.panels.len(), 1);
    }

    #[test]
    fn test_grid_open_multiple() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());
        assert_eq!(grid.panels.len(), 3);
        assert_eq!(grid.composition.total(), 3);
    }

    #[test]
    fn test_grid_close_panel() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.close_panel(1);
        assert_eq!(grid.panels.len(), 2);
        assert_eq!(grid.panels[0].session_id, "s1");
        assert_eq!(grid.panels[1].session_id, "s3");
    }

    #[test]
    fn test_grid_close_focused_moves_focus() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.focus_panel(1);
        assert_eq!(grid.focused, Some(1));

        grid.close_panel(1);
        // Focus should move to the next panel (now index 1, was s3).
        assert_eq!(grid.focused, Some(1));
        assert_eq!(grid.panels[1].session_id, "s3");
    }

    #[test]
    fn test_grid_close_before_focused() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.focus_panel(2);
        assert_eq!(grid.focused, Some(2));

        grid.close_panel(0);
        assert_eq!(grid.focused, Some(1));
        assert_eq!(grid.panels[1].session_id, "s3");
    }

    #[test]
    fn test_grid_close_last_panel() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.close_panel(0);

        assert!(grid.panels.is_empty());
        assert_eq!(grid.focused, None);
    }

    #[test]
    fn test_grid_focus_next() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.focus_panel(0);
        grid.focus_next();
        assert_eq!(grid.focused, Some(1));

        grid.focus_next();
        assert_eq!(grid.focused, Some(2));

        // Wrap around.
        grid.focus_next();
        assert_eq!(grid.focused, Some(0));
    }

    #[test]
    fn test_grid_focus_prev() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.focus_panel(0);
        // Wrap to last.
        grid.focus_prev();
        assert_eq!(grid.focused, Some(2));
    }

    #[test]
    fn test_grid_toggle_pin() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());

        grid.focus_panel(0);
        grid.toggle_pin();
        assert!(grid.panels[0].pinned);
        assert!(!grid.panels[1].pinned);
    }

    #[test]
    fn test_grid_clear_pins() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());

        grid.focus_panel(0);
        grid.toggle_pin();
        grid.focus_panel(1);
        grid.toggle_pin();
        assert!(grid.panels[0].pinned);
        assert!(grid.panels[1].pinned);

        grid.clear_pins();
        assert!(!grid.panels[0].pinned);
        assert!(!grid.panels[1].pinned);
    }

    #[test]
    fn test_grid_cycle_layout() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        let initial = grid.composition.clone();
        // cycle_index is synced to the curated list, so the first w press
        // always advances to a different composition.
        grid.cycle_layout();
        assert_ne!(
            grid.composition, initial,
            "first cycle should change composition"
        );
    }

    #[test]
    fn test_grid_render_two_panels() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("panel-a".to_string());
        grid.open_panel("panel-b".to_string());

        // Load some messages into each panel.
        grid.panels[0].load_messages(vec![make_message("hover")]);
        grid.panels[1].load_messages(vec![make_message("definition")]);

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

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

        assert!(content.contains("panel-a"), "expected panel-a session id");
        assert!(content.contains("panel-b"), "expected panel-b session id");
        assert!(
            content.contains("hover"),
            "expected hover method in panel-a"
        );
        assert!(
            content.contains("definition"),
            "expected definition method in panel-b"
        );
    }

    #[test]
    fn test_grid_pinned_indices() {
        let theme = test_theme();
        let icons = test_icons();
        let mut grid = EventsGrid::new(&theme, &icons);

        grid.open_panel("s1".to_string());
        grid.open_panel("s2".to_string());
        grid.open_panel("s3".to_string());

        grid.focus_panel(0);
        grid.toggle_pin();
        grid.focus_panel(2);
        grid.toggle_pin();

        let pinned = grid.pinned_indices();
        assert!(pinned.contains(&0));
        assert!(!pinned.contains(&1));
        assert!(pinned.contains(&2));
        assert_eq!(pinned.len(), 2);
    }
}