omni-dev 0.43.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
//! The pane stack (issue #1585 §4, Phase 4b): groups of terminal tabs, the
//! tab strip over each, and the focus/lifecycle rules that decide which tab
//! a key, a PTY event or a resize belongs to.
//!
//! [`super::layout`] owns the geometry (weights, splitters, drags);
//! this owns the *tabs*. The two are separate so the maths stays testable
//! with no PTY in sight, and this file's rules stay testable with scripted
//! children rather than a real terminal.
//!
//! A tab remembers the worktree it was opened in, which is what feeds the
//! tree's `here` cue without registering with the daemon
//! ([ADR-0072](../../../../docs/adrs/adr-0072.md) §1).

use std::collections::HashSet;
use std::path::{Path, PathBuf};

use alacritty_terminal::event::Event as TermEvent;
use anyhow::Result;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Paragraph};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr as _;

use super::layout::{self, MIN_GROUP_HEIGHT};
use super::terminal::{GridSize, TabEffect, TabId, TabKind, TerminalTab};

/// One vertical slice of the terminal side: a tab strip and the active
/// tab's grid under it.
pub struct PaneGroup {
    pub tabs: Vec<TerminalTab>,
    /// Index into `tabs`; always valid while `tabs` is non-empty.
    pub active: usize,
}

impl PaneGroup {
    fn new(tab: TerminalTab) -> Self {
        Self {
            tabs: vec![tab],
            active: 0,
        }
    }

    pub fn active_tab(&self) -> Option<&TerminalTab> {
        self.tabs.get(self.active)
    }

    pub fn active_tab_mut(&mut self) -> Option<&mut TerminalTab> {
        self.tabs.get_mut(self.active)
    }

    /// Clamps `active` back into range after a removal.
    fn clamp_active(&mut self) {
        if self.active >= self.tabs.len() {
            self.active = self.tabs.len().saturating_sub(1);
        }
    }
}

/// Where a tab lives.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TabAddr {
    pub group: usize,
    pub tab: usize,
}

/// The stack of groups, their relative weights, and which group has focus.
///
/// Empty (no groups) is the normal starting state: the tree pane then takes
/// the full width, exactly as in Phases 1–3.
#[derive(Default)]
pub struct PaneLayout {
    pub groups: Vec<PaneGroup>,
    /// One weight per group, top to bottom — see [`layout::split_groups`].
    pub weights: Vec<u16>,
    pub focused: usize,
    next_id: TabId,
}

impl PaneLayout {
    pub fn is_empty(&self) -> bool {
        self.groups.is_empty()
    }

    pub fn group_count(&self) -> usize {
        self.groups.len()
    }

    /// The next tab id, unique for this process's lifetime — ids are never
    /// reused, so a PTY event from a closed tab can always be told apart
    /// from one for a live tab that took its slot.
    fn take_id(&mut self) -> TabId {
        self.next_id += 1;
        self.next_id
    }

    fn focused_group(&self) -> Option<&PaneGroup> {
        self.groups.get(self.focused)
    }

    /// The focused group's active tab — the one a key or a copy acts on.
    pub fn active_tab(&self) -> Option<&TerminalTab> {
        self.focused_group()?.active_tab()
    }

    /// Group `index`'s active tab — how a mouse event, which names the
    /// group it landed in, reaches a tab without changing focus first.
    pub fn group_tab(&self, index: usize) -> Option<&TerminalTab> {
        self.groups.get(index)?.active_tab()
    }

    /// Every tab, in stack order.
    pub fn tabs(&self) -> impl Iterator<Item = &TerminalTab> {
        self.groups.iter().flat_map(|g| g.tabs.iter())
    }

    /// Whether any tab still has a live child — what `q` asks about.
    pub fn any_alive(&self) -> bool {
        self.tabs().any(TerminalTab::is_alive)
    }

    /// Finds a tab by id.
    pub fn find(&self, id: TabId) -> Option<TabAddr> {
        self.groups.iter().enumerate().find_map(|(group, g)| {
            g.tabs
                .iter()
                .position(|t| t.id() == id)
                .map(|tab| TabAddr { group, tab })
        })
    }

    pub fn tab_mut(&mut self, addr: TabAddr) -> Option<&mut TerminalTab> {
        self.groups.get_mut(addr.group)?.tabs.get_mut(addr.tab)
    }

    /// The first tab opened in `worktree`, if any — so `enter` on a row
    /// that already has a tab focuses it instead of opening a second.
    pub fn find_in_worktree(&self, worktree: &Path, kind: TabKind) -> Option<TabAddr> {
        self.groups.iter().enumerate().find_map(|(group, g)| {
            g.tabs
                .iter()
                .position(|t| t.opened_in == worktree && t.kind == kind && t.is_alive())
                .map(|tab| TabAddr { group, tab })
        })
    }

    /// Focuses `addr`, making it its group's active tab.
    pub fn focus(&mut self, addr: TabAddr) {
        if let Some(group) = self.groups.get_mut(addr.group) {
            if addr.tab < group.tabs.len() {
                group.active = addr.tab;
                self.focused = addr.group;
            }
        }
    }

    /// Opens a tab in the focused group (or the first group when there is
    /// none yet), and focuses it. `spawn` builds the tab from the id this
    /// allocates — injected so tests can script the child.
    pub fn open_tab(
        &mut self,
        spawn: impl FnOnce(TabId) -> Result<TerminalTab>,
    ) -> Result<TabAddr> {
        let id = self.take_id();
        let tab = spawn(id)?;
        if self.groups.is_empty() {
            self.groups.push(PaneGroup::new(tab));
            self.weights = layout::even_weights(1);
            self.focused = 0;
            return Ok(TabAddr { group: 0, tab: 0 });
        }
        let group = self.focused.min(self.groups.len() - 1);
        self.groups[group].tabs.push(tab);
        let tab = self.groups[group].tabs.len() - 1;
        self.groups[group].active = tab;
        self.focused = group;
        Ok(TabAddr { group, tab })
    }

    /// Opens a tab in a **new group** below the focused one — `alt-s`.
    pub fn split(&mut self, spawn: impl FnOnce(TabId) -> Result<TerminalTab>) -> Result<TabAddr> {
        if self.groups.is_empty() {
            return self.open_tab(spawn);
        }
        let id = self.take_id();
        let tab = spawn(id)?;
        let at = (self.focused + 1).min(self.groups.len());
        self.groups.insert(at, PaneGroup::new(tab));
        self.weights.insert(at, average_weight(&self.weights));
        self.focused = at;
        Ok(TabAddr { group: at, tab: 0 })
    }

    /// Closes the tab at `addr`, shutting its child down. Returns the
    /// worktree it was opened in, so the caller can update the `here` cue.
    /// An emptied group is removed, and its weight with it.
    pub fn close_tab(&mut self, addr: TabAddr) -> Option<PathBuf> {
        let group = self.groups.get_mut(addr.group)?;
        if addr.tab >= group.tabs.len() {
            return None;
        }
        let mut tab = group.tabs.remove(addr.tab);
        tab.shutdown();
        group.clamp_active();
        if group.tabs.is_empty() {
            self.groups.remove(addr.group);
            if addr.group < self.weights.len() {
                self.weights.remove(addr.group);
            }
            if self.focused >= self.groups.len() {
                self.focused = self.groups.len().saturating_sub(1);
            }
        } else {
            self.focused = addr.group;
        }
        Some(tab.opened_in)
    }

    /// Closes the focused group's active tab.
    pub fn close_active(&mut self) -> Option<PathBuf> {
        let addr = TabAddr {
            group: self.focused,
            tab: self.focused_group()?.active,
        };
        self.close_tab(addr)
    }

    /// The set of worktrees that still have a tab open — the `here` cue's
    /// truth after any close, since one worktree may have several tabs.
    pub fn open_worktrees(&self) -> HashSet<PathBuf> {
        self.tabs().map(|t| t.opened_in.clone()).collect()
    }

    /// Cycles the focused group's active tab by `delta` (`alt-[` / `alt-]`),
    /// wrapping.
    pub fn cycle_tab(&mut self, delta: isize) {
        let Some(group) = self.groups.get_mut(self.focused) else {
            return;
        };
        let len = group.tabs.len();
        if len == 0 {
            return;
        }
        let len_i = isize::try_from(len).unwrap_or(isize::MAX);
        let current = isize::try_from(group.active).unwrap_or(0);
        group.active = usize::try_from((current + delta).rem_euclid(len_i)).unwrap_or(0);
    }

    /// Selects the focused group's `index`-th tab (`alt-1`…`alt-9`).
    pub fn select_tab(&mut self, index: usize) -> bool {
        match self.groups.get_mut(self.focused) {
            Some(group) if index < group.tabs.len() => {
                group.active = index;
                true
            }
            _ => false,
        }
    }

    /// Moves focus between groups by `delta`, clamped.
    pub fn cycle_group(&mut self, delta: isize) {
        if self.groups.is_empty() {
            return;
        }
        let max = isize::try_from(self.groups.len() - 1).unwrap_or(0);
        let current = isize::try_from(self.focused).unwrap_or(0);
        self.focused = usize::try_from((current + delta).clamp(0, max)).unwrap_or(0);
    }

    /// Moves the active tab into the adjacent group (`alt-⇧↑` / `alt-⇧↓`),
    /// creating no groups and removing one that empties. Returns whether
    /// anything moved.
    pub fn move_tab_to_group(&mut self, delta: isize) -> bool {
        if self.groups.len() < 2 {
            return false;
        }
        let from = self.focused;
        let Ok(target) = usize::try_from(isize::try_from(from).unwrap_or(0) + delta) else {
            return false;
        };
        if target >= self.groups.len() {
            return false;
        }
        let Some(group) = self.groups.get_mut(from) else {
            return false;
        };
        if group.tabs.is_empty() {
            return false;
        }
        let tab = group.tabs.remove(group.active);
        group.clamp_active();
        let emptied = group.tabs.is_empty();
        // Removing the source group shifts every later index down by one.
        let target = if emptied && target > from {
            target - 1
        } else {
            target
        };
        if emptied {
            self.groups.remove(from);
            if from < self.weights.len() {
                self.weights.remove(from);
            }
        }
        let Some(dest) = self.groups.get_mut(target) else {
            return false; // unreachable: the target existed a moment ago
        };
        dest.tabs.push(tab);
        dest.active = dest.tabs.len() - 1;
        self.focused = target;
        true
    }

    /// Resets the stack to equal weights — `alt-0`.
    pub fn reset_weights(&mut self) {
        self.weights = layout::even_weights(self.groups.len());
    }

    /// Routes one emulator event to the tab it belongs to. Returns `None`
    /// when no live tab has that id (an event from a tab already closed).
    pub fn handle_event(&mut self, id: TabId, event: TermEvent) -> Option<TabEffect> {
        let addr = self.find(id)?;
        Some(self.tab_mut(addr)?.handle_event(event))
    }

    /// Lays the stack out in `area` and resizes every visible group's
    /// active tab to the grid it will be drawn into. Returns one
    /// [`GroupRects`] per rendered group.
    pub fn arrange(&mut self, area: Rect) -> Vec<GroupRects> {
        let rects = layout::split_groups(area, &self.weights);
        let mut out = Vec::with_capacity(rects.len());
        for (index, rect) in rects.into_iter().enumerate() {
            let strip = Rect::new(rect.x, rect.y, rect.width, 1);
            let body = Rect::new(
                rect.x,
                rect.y + 1,
                rect.width,
                rect.height.saturating_sub(1),
            );
            let grid = Block::default().borders(Borders::ALL).inner(body);
            if let Some(tab) = self
                .groups
                .get_mut(index)
                .and_then(PaneGroup::active_tab_mut)
            {
                tab.resize(GridSize {
                    cols: grid.width,
                    lines: grid.height,
                });
            }
            let tab_spans = self
                .groups
                .get(index)
                .map(|g| strip_cells(g, strip).iter().map(|c| c.span).collect())
                .unwrap_or_default();
            out.push(GroupRects {
                strip,
                body,
                grid,
                index,
                tab_spans,
            });
        }
        out
    }

    /// Draws every group: its tab strip, then its active tab.
    pub fn draw(&self, frame: &mut Frame<'_>, rects: &[GroupRects], focused_pane: bool) {
        for group_rects in rects {
            let Some(group) = self.groups.get(group_rects.index) else {
                continue;
            };
            let is_focused = focused_pane && group_rects.index == self.focused;
            draw_tab_strip(frame, group_rects.strip, group, is_focused);
            if let Some(tab) = group.active_tab() {
                tab.draw(frame, group_rects.body, is_focused);
            }
        }
    }
}

/// A group's three rects — its tab strip, the bordered body, and the grid
/// inside that border — plus where each tab sits on the strip.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GroupRects {
    pub strip: Rect,
    pub body: Rect,
    pub grid: Rect,
    pub index: usize,
    /// Each tab's `[start, end)` columns, from the same computation that
    /// renders them — so a click can never resolve to a different tab than
    /// the one under the pointer.
    pub tab_spans: Vec<(u16, u16)>,
}

/// One tab's strip cell: the text drawn and the columns it occupies.
struct StripCell {
    text: String,
    span: (u16, u16),
}

/// Lays the tab strip out for `group` within `area`, in display columns.
/// The single source of truth for both rendering and hit-testing.
fn strip_cells(group: &PaneGroup, area: Rect) -> Vec<StripCell> {
    let mut cells = Vec::with_capacity(group.tabs.len());
    let mut x = area.x;
    let end = area.x.saturating_add(area.width);
    for (index, tab) in group.tabs.iter().enumerate() {
        let text = format!(" {} {} ", index + 1, tab.strip_label());
        let width = u16::try_from(text.width()).unwrap_or(u16::MAX);
        if x >= end {
            break; // the strip is full; the rest are not drawn or clickable
        }
        let stop = x.saturating_add(width).min(end);
        cells.push(StripCell {
            text,
            span: (x, stop),
        });
        // One column of gap between tabs.
        x = stop.saturating_add(1);
    }
    cells
}

/// The mean of the current weights — what a newly split group starts at, so
/// a split neither dominates nor vanishes.
fn average_weight(weights: &[u16]) -> u16 {
    if weights.is_empty() {
        return 1;
    }
    let total: u32 = weights.iter().map(|w| u32::from(*w)).sum();
    u16::try_from(total / u32::try_from(weights.len()).unwrap_or(1))
        .unwrap_or(1)
        .max(1)
}

/// One line of `[1 shell·repo] [2 claude·repo]`, the active tab reversed.
fn draw_tab_strip(frame: &mut Frame<'_>, area: Rect, group: &PaneGroup, focused: bool) {
    if area.height == 0 {
        return;
    }
    let mut spans = Vec::with_capacity(group.tabs.len() * 2);
    for (index, cell) in strip_cells(group, area).into_iter().enumerate() {
        let mut style = Style::default();
        if index == group.active {
            style = style.add_modifier(Modifier::REVERSED);
            if focused {
                style = style.fg(Color::Cyan);
            }
        } else {
            style = style.fg(Color::DarkGray);
        }
        spans.push(Span::styled(cell.text, style));
        spans.push(Span::raw(" "));
    }
    frame.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// The minimum terminal-side height that can host `count` groups — used to
/// refuse a split that would not fit rather than silently dropping a group.
pub fn min_height_for(count: usize) -> u16 {
    u16::try_from(count)
        .unwrap_or(u16::MAX)
        .saturating_mul(MIN_GROUP_HEIGHT)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[cfg_attr(not(unix), allow(unused_imports))]
    use tokio::sync::mpsc;

    #[cfg(unix)]
    fn spawner(
        script: &'static str,
        cwd: PathBuf,
        tx: mpsc::UnboundedSender<(TabId, TermEvent)>,
    ) -> impl FnOnce(TabId) -> Result<TerminalTab> {
        move |id| {
            let request = super::super::terminal::pty::SpawnRequest {
                tab: id,
                program: Some((
                    "/bin/sh".to_string(),
                    vec!["-c".to_string(), script.to_string()],
                )),
                cwd,
                size: GridSize { cols: 40, lines: 6 },
                extra_env: Vec::new(),
            };
            TerminalTab::from_request(TabKind::Shell, request, tx)
        }
    }

    #[cfg(unix)]
    fn layout_with(count: usize) -> (PaneLayout, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let (tx, _rx) = mpsc::unbounded_channel();
        let mut panes = PaneLayout::default();
        for _ in 0..count {
            panes
                .split(spawner("sleep 5", dir.path().to_path_buf(), tx.clone()))
                .unwrap();
        }
        (panes, dir)
    }

    #[test]
    fn an_empty_layout_has_no_groups_and_no_active_tab() {
        let panes = PaneLayout::default();
        assert!(panes.is_empty());
        assert_eq!(panes.group_count(), 0);
        assert!(panes.active_tab().is_none());
        assert!(!panes.any_alive());
        assert!(panes.find(1).is_none());
        assert!(panes.group_tab(0).is_none());
        assert!(panes.open_worktrees().is_empty());
    }

    #[test]
    fn average_weight_of_nothing_is_one() {
        assert_eq!(average_weight(&[]), 1);
        assert_eq!(average_weight(&[2, 4]), 3);
        assert_eq!(average_weight(&[0, 0]), 1, "never zero");
    }

    #[test]
    fn min_height_scales_with_the_group_count() {
        assert_eq!(min_height_for(1), MIN_GROUP_HEIGHT);
        assert_eq!(min_height_for(3), MIN_GROUP_HEIGHT * 3);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn opening_adds_to_the_focused_group_and_splitting_makes_a_new_one() {
        let (mut panes, dir) = layout_with(0);
        let (tx, _rx) = mpsc::unbounded_channel();
        let spawn = || spawner("sleep 5", dir.path().to_path_buf(), tx.clone());

        // The first open creates the one group.
        let first = panes.open_tab(spawn()).unwrap();
        assert_eq!(first, TabAddr { group: 0, tab: 0 });
        assert_eq!(panes.group_count(), 1);
        assert_eq!(panes.weights, vec![1]);
        assert!(panes.any_alive());

        // The second joins it as a tab.
        let second = panes.open_tab(spawn()).unwrap();
        assert_eq!(second, TabAddr { group: 0, tab: 1 });
        assert_eq!(panes.group_count(), 1);
        assert_eq!(panes.groups[0].tabs.len(), 2);
        assert_eq!(panes.groups[0].active, 1, "a new tab takes focus");

        // A split makes a second group below, and focuses it.
        let split = panes.split(spawn()).unwrap();
        assert_eq!(split, TabAddr { group: 1, tab: 0 });
        assert_eq!(panes.group_count(), 2);
        assert_eq!(panes.weights.len(), 2);
        assert_eq!(panes.focused, 1);

        // Ids are unique and never reused.
        let ids: Vec<TabId> = panes.tabs().map(TerminalTab::id).collect();
        let unique: HashSet<TabId> = ids.iter().copied().collect();
        assert_eq!(ids.len(), unique.len());
        for tab in panes.groups.iter_mut().flat_map(|g| g.tabs.iter_mut()) {
            tab.shutdown();
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn closing_removes_the_tab_then_its_group_and_reports_the_worktree() {
        let (mut panes, dir) = layout_with(2);
        let here = dir.path().to_path_buf();
        assert_eq!(panes.group_count(), 2);

        // One worktree, two tabs: closing one leaves the cue set.
        let closed = panes.close_active().unwrap();
        assert_eq!(closed, here);
        assert_eq!(panes.group_count(), 1, "the emptied group went with it");
        assert_eq!(panes.weights.len(), 1);
        assert_eq!(panes.focused, 0);
        assert!(panes.open_worktrees().contains(&here), "one tab remains");

        // Closing the last one empties the layout.
        assert_eq!(panes.close_active(), Some(here));
        assert!(panes.is_empty());
        assert!(panes.open_worktrees().is_empty());
        assert_eq!(panes.focused, 0);
        assert!(panes.close_active().is_none(), "nothing left to close");
        assert!(panes.close_tab(TabAddr { group: 9, tab: 9 }).is_none());
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn tabs_and_groups_cycle_select_and_move() {
        let (mut panes, dir) = layout_with(1);
        let (tx, _rx) = mpsc::unbounded_channel();
        let spawn = || spawner("sleep 5", dir.path().to_path_buf(), tx.clone());
        panes.open_tab(spawn()).unwrap();
        panes.open_tab(spawn()).unwrap(); // group 0 now has three tabs
        assert_eq!(panes.groups[0].tabs.len(), 3);

        // Cycling wraps in both directions.
        assert_eq!(panes.groups[0].active, 2);
        panes.cycle_tab(1);
        assert_eq!(panes.groups[0].active, 0, "wraps forward");
        panes.cycle_tab(-1);
        assert_eq!(panes.groups[0].active, 2, "wraps back");
        assert!(panes.select_tab(1));
        assert_eq!(panes.groups[0].active, 1);
        assert!(!panes.select_tab(9), "out of range selects nothing");
        assert_eq!(panes.groups[0].active, 1);

        // A second group: focus moves between them, clamped at the ends.
        panes.split(spawn()).unwrap();
        assert_eq!(panes.focused, 1);
        panes.cycle_group(-1);
        assert_eq!(panes.focused, 0);
        panes.cycle_group(-1);
        assert_eq!(panes.focused, 0, "clamped, not wrapped");
        panes.cycle_group(5);
        assert_eq!(panes.focused, 1);

        // Moving the only tab out of a group removes that group.
        assert!(panes.move_tab_to_group(-1));
        assert_eq!(panes.group_count(), 1);
        assert_eq!(panes.focused, 0);
        assert_eq!(panes.groups[0].tabs.len(), 4);
        assert!(
            !panes.move_tab_to_group(-1),
            "one group: nothing to move to"
        );

        panes.reset_weights();
        assert_eq!(panes.weights, vec![1]);
        for tab in panes.groups.iter_mut().flat_map(|g| g.tabs.iter_mut()) {
            tab.shutdown();
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn events_route_by_tab_id_and_unknown_ids_are_ignored() {
        let (mut panes, _dir) = layout_with(2);
        let ids: Vec<TabId> = panes.tabs().map(TerminalTab::id).collect();
        assert_eq!(
            panes.handle_event(ids[0], TermEvent::Title("t".to_string())),
            Some(TabEffect::Redraw)
        );
        assert_eq!(panes.groups[0].tabs[0].title.as_deref(), Some("t"));
        assert!(
            panes.groups[1].tabs[0].title.is_none(),
            "the other tab is untouched"
        );
        assert_eq!(panes.handle_event(9999, TermEvent::Wakeup), None);
        for tab in panes.groups.iter_mut().flat_map(|g| g.tabs.iter_mut()) {
            tab.shutdown();
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn arrange_sizes_every_group_and_draw_renders_the_strip() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let (mut panes, _dir) = layout_with(2);
        let area = Rect::new(0, 0, 50, 24);
        let rects = panes.arrange(area);
        assert_eq!(rects.len(), 2);
        assert_eq!(rects[0].strip.height, 1);
        assert_eq!(rects[1].body.y, rects[0].body.y + rects[0].body.height + 1);
        // Every group's grid is inside its body's border.
        for r in &rects {
            assert!(r.grid.width < r.body.width);
            assert_eq!(r.grid.y, r.body.y + 1);
        }

        let mut terminal = Terminal::new(TestBackend::new(50, 24)).unwrap();
        terminal
            .draw(|frame| {
                let rects = panes.arrange(frame.area());
                panes.draw(frame, &rects, true);
            })
            .unwrap();
        let text: String = terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect();
        assert!(text.contains("1 shell"), "the tab strip names the tab");

        // Too short for two groups: only what fits is arranged and drawn.
        let short = panes.arrange(Rect::new(0, 0, 50, 5));
        assert_eq!(short.len(), 1);
        for tab in panes.groups.iter_mut().flat_map(|g| g.tabs.iter_mut()) {
            tab.shutdown();
        }
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn find_in_worktree_matches_kind_and_liveness() {
        let (mut panes, dir) = layout_with(1);
        let here = dir.path().to_path_buf();
        assert_eq!(
            panes.find_in_worktree(&here, TabKind::Shell),
            Some(TabAddr { group: 0, tab: 0 })
        );
        assert!(panes.find_in_worktree(&here, TabKind::Claude).is_none());
        assert!(panes
            .find_in_worktree(Path::new("/nowhere"), TabKind::Shell)
            .is_none());

        // An exited tab is not a match — the row should open a fresh one.
        panes.groups[0].tabs[0].exit_status = Some(std::process::ExitStatus::default());
        assert!(panes.find_in_worktree(&here, TabKind::Shell).is_none());
        assert!(!panes.any_alive());

        // Focusing an address out of range is a no-op, not a panic.
        panes.focus(TabAddr { group: 9, tab: 9 });
        assert_eq!(panes.focused, 0);
        panes.focus(TabAddr { group: 0, tab: 0 });
        for tab in panes.groups.iter_mut().flat_map(|g| g.tabs.iter_mut()) {
            tab.shutdown();
        }
    }
}