bohay 0.8.2

Next-Gen Agents multiplexer
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
//! Rendering. compute (resize PTYs) then a pure draw pass: chrome (sidebar,
//! tab bar, status) plus the tiled panes. See docs/06-ui-rendering.md.

pub mod theme;

use std::path::Path;

use ratatui::buffer::Buffer;
use ratatui::layout::{Alignment, Constraint, Layout, Position, Rect};
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph, Widget};
use ratatui::Frame;

use crate::app::{App, DockKind, Mode, Side};
use crate::ids::PaneId;
use crate::ui::theme::{State, Theme};

/// A draw surface mirroring the slice of `ratatui::Frame` the UI actually uses, but
/// over a `Buffer` we own. The server renders straight into its frame buffer through
/// this and runs a single `diff_buffer`, skipping `Terminal`'s redundant internal
/// reset+diff+flush (~28% of the per-frame cost — see `bench_render_hotpath`). The
/// `--local` path and tests keep calling `render(&mut Frame, …)`, which wraps the
/// terminal's own buffer in one of these.
pub struct RenderTarget<'a> {
    buf: &'a mut Buffer,
    area: Rect,
    cursor: Option<(u16, u16)>,
}

impl<'a> RenderTarget<'a> {
    /// Wrap a buffer we own (the server's frame buffer) as a draw surface.
    pub fn new(buf: &'a mut Buffer, area: Rect) -> Self {
        RenderTarget {
            buf,
            area,
            cursor: None,
        }
    }
    pub fn area(&self) -> Rect {
        self.area
    }
    pub fn buffer_mut(&mut self) -> &mut Buffer {
        self.buf
    }
    pub fn render_widget<W: Widget>(&mut self, widget: W, area: Rect) {
        widget.render(area, self.buf);
    }
    pub fn set_cursor_position<P: Into<Position>>(&mut self, position: P) {
        let p = position.into();
        self.cursor = Some((p.x, p.y));
    }
}

mod board;
mod borders;
mod cmdinfo;
mod git;
mod help;
mod menu;
mod panes;
mod picker;
mod settings;
mod sidebar;
mod status;
mod tabbar;

/// Frame-based entry (used by `--local` and tests): wrap the terminal's buffer in a
/// `RenderTarget`, render, then copy the resulting cursor back onto the frame.
pub fn render(f: &mut Frame, app: &mut App) {
    let area = f.area();
    let cursor = {
        let mut target = RenderTarget {
            buf: f.buffer_mut(),
            area,
            cursor: None,
        };
        render_into(&mut target, app);
        target.cursor
    };
    if let Some(p) = cursor {
        f.set_cursor_position(p);
    }
}

/// The actual UI render, over a buffer we own (`RenderTarget`). The server calls
/// this directly with its frame buffer; `render` above adapts a `Frame` to it.
pub fn render_into(f: &mut RenderTarget, app: &mut App) {
    let t = app.theme.clone();
    // The active i18n catalog (Copy `&'static`), passed to draw fns that don't
    // get the whole `App` (picker, git tab) so all chrome is localized (docs/21).
    let cat = app.catalog;
    let area = f.area();
    f.render_widget(Block::new().style(Style::new().bg(t.mantle)), area);

    // An absurdly small window can't hold the chrome — say so instead of
    // drawing degraded fragments. (Every draw fn is underflow-safe regardless;
    // this is purely the friendlier message.)
    if area.width < 24 || area.height < 6 {
        if area.height > 0 {
            let msg = "◱ enlarge terminal";
            let y = area.y + area.height / 2;
            f.render_widget(
                Paragraph::new(Line::from(Span::styled(msg, Style::new().fg(t.overlay1)))),
                Rect::new(area.x, y, area.width, 1),
            );
        }
        return;
    }

    let [main, status] = Layout::vertical([Constraint::Min(0), Constraint::Length(1)]).areas(area);

    // Two sidebars flank the content (docs/29). Each is shown only if visible,
    // non-empty, and it (with the other) leaves the panes at least 24 columns —
    // the right yields space first, then the left. A width that would fall below
    // the minimum drops the sidebar entirely (matching the original behavior).
    let min = crate::app::SIDEBAR_WIDTH_MIN;
    let fit = |w: u16, budget: u16| -> u16 {
        let w = w.min(budget.saturating_sub(24));
        if w >= min {
            w
        } else {
            0
        }
    };
    let lw = if app.sidebars.left.shown() {
        fit(app.sidebars.left.width, main.width)
    } else {
        0
    };
    let rw = if app.sidebars.right.shown() {
        fit(app.sidebars.right.width, main.width.saturating_sub(lw))
    } else {
        0
    };
    let [left_area, content, right_area] = Layout::horizontal([
        Constraint::Length(lw),
        Constraint::Min(0),
        Constraint::Length(rw),
    ])
    .areas(main);
    let sidebar_left = (lw > 0).then_some(left_area);
    let sidebar_right = (rw > 0).then_some(right_area);

    let [tabbar, pane_area] =
        Layout::vertical([Constraint::Length(1), Constraint::Min(0)]).areas(content);

    app.last_pane_area = pane_area;

    let focus = app.layout().focus;
    let rects: Vec<(PaneId, Rect)> = if app.zoomed {
        vec![(focus, pane_area)]
    } else {
        app.layout()
            .panes(pane_area)
            .into_iter()
            .map(|p| (p.id, p.rect))
            .collect()
    };
    // Only frame panes when the tab is split; a lone pane needs no border.
    let bordered = rects.len() > 1;
    for (id, rect) in &rects {
        if let Some(content) = pane_content(*rect, bordered) {
            if let Some(p) = app.panes.get_mut(id) {
                p.resize(content.width, content.height);
            }
        }
    }

    // Clear every dock/sidebar hit-geometry up front, then let each drawn dock
    // set its own. A dock mounted nowhere (or a hidden sidebar) leaves its rects
    // zeroed, so nothing fires from under a widened pane area (docs/29).
    app.settings_icon_rect = None;
    app.sidebar_toggle_rect = None;
    app.right_sidebar_toggle_rect = None;
    app.workspaces_area = Rect::ZERO;
    app.agents_area = Rect::ZERO;
    app.agents_filter_rects.clear();
    app.workspace_branch_rects.clear();
    app.module_dock_rects.clear();
    let mut ws_rects = Vec::new();
    let mut agent_rects = Vec::new();
    let mut session_rects = Vec::new();
    let mut new_ws_rect = None;
    for (opt, side) in [(sidebar_left, Side::Left), (sidebar_right, Side::Right)] {
        if let Some(s) = opt {
            let (w, a, se, n) = sidebar::draw_sidebar(f, side, s, app, &t);
            ws_rects.extend(w);
            agent_rects.extend(a);
            session_rects.extend(se);
            new_ws_rect = new_ws_rect.or(n);
        }
    }
    let (tab_rects, tab_close_rects, tab_prev, tab_next) = tabbar::draw_tabbar(f, tabbar, app, &t);
    // Behind the panes, use the (dark) pane background.
    f.render_widget(Block::new().style(Style::new().bg(t.mantle)), pane_area);
    // The focused pane's ✕ close button, for mouse hit-testing.
    app.pane_close_rect = if bordered {
        rects
            .iter()
            .find(|(id, _)| *id == focus)
            .and_then(|(_, r)| pane_close_rect(*r, bordered))
    } else {
        None
    };
    // A git tab / orchestration board fills the pane area with a dashboard
    // instead of terminals.
    let mut git_section_rects = Vec::new();
    let mut title_rects: Vec<(PaneId, Rect)> = Vec::new();
    let cursor = if app.active_is_orch() {
        app.orch_area = pane_area;
        // Each task's live worker state (detection) rides along on its row.
        let live: Vec<Option<board::RowLive>> = app
            .orch
            .tasks
            .iter()
            .map(|task| {
                task.assignee
                    .map(crate::ids::PaneId)
                    .and_then(|pid| app.status.get(&pid))
                    .map(|st| board::RowLive {
                        agent: st.agent.clone(),
                        state: st.state,
                    })
            })
            .collect();
        app.orch_scroll = board::render(
            f,
            pane_area,
            &app.orch,
            &live,
            app.orch_scroll,
            app.orch_cursor,
            cat,
            &t,
        );
        None
    } else if let Some(g) = app.active_git_mut() {
        git_section_rects = git::render(f, pane_area, g, cat, &t);
        None
    } else {
        let cursor = panes::draw_panes(f, &rects, bordered, app, &t);
        // Draw all pane borders in one overlay pass (manual cell-by-cell), then
        // the dot+path+close titles ON each top border row.
        if bordered {
            borders::render_pane_borders(f, &rects, focus, app.hover_divider.as_ref(), &t);
            if app.config.layout.show_titles {
                title_rects = panes::draw_pane_titles(f, &rects, focus, app, &t);
            }
        }
        cursor
    };
    app.git_section_rects = git_section_rects;
    app.pane_title_rects = title_rects;
    // Per-pane content rects so mouse drags map to grid cells for text selection
    // (a git tab has no selectable terminal panes).
    app.pane_content_rects = if app.active_is_git() || app.active_is_orch() {
        Vec::new()
    } else {
        rects
            .iter()
            .filter_map(|(id, r)| pane_content(*r, bordered).map(|c| (*id, c)))
            .collect()
    };
    status::draw_status(f, status, app, &t);

    // The Settings modal draws last, on top of everything, and owns the cursor.
    let settings_hits = app
        .settings
        .is_some()
        .then(|| settings::draw_settings(f, area, app, &t));
    if let Some(h) = &settings_hits {
        app.settings_modal_rect = Some(h.modal);
        app.settings_close_rect = Some(h.close);
        app.settings_tab_rects = h.tabs.clone();
        app.settings_ctl_rects = h.ctls.clone();
        app.settings_arrow_rects = h.arrows.clone();
    } else {
        app.settings_modal_rect = None;
        app.settings_close_rect = None;
        app.settings_tab_rects.clear();
        app.settings_ctl_rects.clear();
        app.settings_arrow_rects.clear();
    }

    // The folder picker also draws last (over everything) when open.
    let picker_open = app.picker.is_some();
    let mut picker_rects = Vec::new();
    if let Some(p) = &app.picker {
        picker_rects = picker::draw_picker(f, area, p, cat, &t);
    }
    app.picker_rects = picker_rects;

    // The keyboard cheat-sheet overlay draws on top of everything.
    if app.help_open {
        help::draw_help(f, area, app, &t);
    }
    // The running-command overlay (click a pane title) draws above that.
    if let Some(c) = app.cmd_inspect.as_ref() {
        cmdinfo::draw(f, area, c, &t);
    }
    // Text-input modals: each returns the rects of its clickable ⏎/esc footer
    // hints (or `None` while an error occupies the line), stashed so the mouse
    // layer can act on them. Only one is ever open; clear first so a closed modal
    // leaves nothing behind.
    let hover = app.hover;
    app.modal_commit_rect = None;
    app.modal_cancel_rect = None;
    // The new-worktree branch prompt (docs/18 WT).
    if let Some(buf) = app.worktree_prompt.clone() {
        let err = app.worktree_error.clone();
        let (c, x) = picker::draw_worktree_prompt(f, area, &buf, err.as_deref(), hover, cat, &t);
        app.modal_commit_rect = c;
        app.modal_cancel_rect = x;
    }
    // The tab-rename modal (docs/28).
    if let Some(buf) = app.tab_rename.as_ref().map(|r| r.buffer.clone()) {
        let (c, x) = picker::draw_tab_rename(f, area, &buf, hover, cat, &t);
        app.modal_commit_rect = c;
        app.modal_cancel_rect = x;
    }
    // The workspace-rename modal, then the right-click context menu (on top).
    if let Some(buf) = app.ws_rename.as_ref().map(|r| r.buffer.clone()) {
        let (c, x) = picker::draw_ws_rename(f, area, &buf, hover, cat, &t);
        app.modal_commit_rect = c;
        app.modal_cancel_rect = x;
    }
    if app.pane_menu.is_some() {
        menu::draw_pane_menu(f, area, app, cat, &t);
    }
    if app.agent_menu.is_some() {
        menu::draw_agent_menu(f, area, app, cat, &t);
    }
    if app.ws_menu.is_some() {
        menu::draw_ws_menu(f, area, app, cat, &t);
    }
    // The board's new-task form (docs/22 ORCH-7).
    if let Some(form) = &app.orch_form {
        board::draw_form(f, area, form, cat, &t);
    }
    // The board's start-worker picker and task detail overlay.
    if let Some(start) = &app.orch_start {
        board::draw_start(f, area, start, cat, &t);
    }
    if let Some(id) = &app.orch_detail {
        let clamped = app
            .orch
            .tasks
            .iter()
            .find(|task| &task.id == id)
            .map(|task| board::draw_detail(f, area, task, app.orch_detail_scroll, cat, &t));
        if let Some(s) = clamped {
            app.orch_detail_scroll = s;
        }
    }
    // A transient toast (e.g. "Copied") flashes on top of everything.
    if let Some((text, _)) = &app.toast {
        draw_toast(f, area, text, &t);
    }

    let cursor = if settings_hits.is_some()
        || picker_open
        || app.help_open
        || app.worktree_prompt.is_some()
        || app.tab_rename.is_some()
        || app.ws_rename.is_some()
        || app.ws_menu.is_some()
        || app.pane_menu.is_some()
        || app.agent_menu.is_some()
        || app.orch_form.is_some()
        || app.orch_start.is_some()
        || app.orch_detail.is_some()
    {
        None
    } else {
        cursor
    };
    if let Some(p) = cursor {
        f.set_cursor_position(p);
    }
    app.last_cursor = cursor;
    app.pane_rects = rects;
    app.tab_rects = tab_rects;
    app.tab_close_rects = tab_close_rects;
    app.tab_prev_rect = tab_prev;
    app.tab_next_rect = tab_next;
    app.ws_rects = ws_rects;
    app.agent_rects = agent_rects;
    app.session_rects = session_rects;
    app.new_ws_rect = new_ws_rect;
}

// ── shared layout + state helpers (used across the ui submodules) ──

/// One cell inset on each side, for the border. Used to lay out the box.
fn pane_inner(rect: Rect, bordered: bool) -> Option<Rect> {
    if !bordered {
        if rect.width < 1 || rect.height < 1 {
            return None;
        }
        return Some(rect);
    }
    if rect.width < 4 || rect.height < 4 {
        return None;
    }
    Some(Rect::new(
        rect.x + 1,
        rect.y + 1,
        rect.width - 2,
        rect.height - 2,
    ))
}

/// Horizontal breathing room for a lone (border-less) pane, so its header and
/// terminal content line up with the tab bar's left edge (`area.x + 1`) instead
/// of touching the sidebar. Split panes get spacing from their borders instead.
pub(super) const LONE_PANE_HPAD: u16 = 1;

/// A footer hint line: each `(key, label)` rendered with the **key** in the
/// theme accent and the **label** in light text, separated by a dim `·`. Shared
/// by the modals (Settings / picker) and the git-tab footer. A pair with an
/// empty label is a bare key (e.g. `j/k`).
pub(super) fn hint_line(pairs: &[(&str, &str)], t: &Theme) -> Line<'static> {
    let mut spans = vec![Span::raw(" ")];
    for (i, (key, label)) in pairs.iter().enumerate() {
        if i > 0 {
            spans.push(Span::styled(" · ", Style::new().fg(t.overlay0)));
        }
        spans.push(Span::styled(
            key.to_string(),
            Style::new().fg(t.accent).bold(),
        ));
        if !label.is_empty() {
            spans.push(Span::styled(
                format!(" {label}"),
                Style::new().fg(t.subtext1),
            ));
        }
    }
    Line::from(spans)
}

/// Display width of `s` in terminal columns (CJK = 2 cells, etc.). Fixed-width
/// chrome must measure with this, not `chars().count()`, so translated/CJK labels
/// align (docs/21).
pub(super) fn display_width(s: &str) -> usize {
    use unicode_width::UnicodeWidthStr;
    s.width()
}

/// A small centered toast box near the bottom (e.g. "✓ Copied"). Drawn last, so
/// it floats over everything; the loop clears it after ~1.4s.
fn draw_toast(f: &mut RenderTarget, area: Rect, text: &str, t: &Theme) {
    use ratatui::widgets::{Borders, Clear};
    let w = (display_width(text) as u16 + 6).min(area.width);
    let h = 3u16;
    if w < 6 || area.height < h + 3 {
        return;
    }
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.bottom().saturating_sub(h + 2); // just above the status line
    let rect = Rect::new(x, y, w, h);
    f.render_widget(Clear, rect);
    let block = Block::new()
        .borders(Borders::ALL)
        .border_style(Style::new().fg(t.accent).bg(t.surface0))
        .style(Style::new().bg(t.surface0));
    let inner = block.inner(rect);
    f.render_widget(block, rect);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled("", Style::new().fg(t.green)),
            Span::styled(text.to_string(), Style::new().fg(t.text).bold()),
        ]))
        .alignment(Alignment::Center),
        inner,
    );
}

/// The lone-pane horizontal pad, suppressed for panes too narrow to spare it.
pub(super) fn lone_pad(width: u16) -> u16 {
    if width > 2 * LONE_PANE_HPAD + 2 {
        LONE_PANE_HPAD
    } else {
        0
    }
}

/// The terminal content area: inside the box when bordered (the dot+path+close
/// live on the top border row as a title), else just below the header row with a
/// small horizontal pad so it aligns with the tab bar.
fn pane_content(rect: Rect, bordered: bool) -> Option<Rect> {
    if bordered {
        return pane_inner(rect, true);
    }
    let pad = lone_pad(rect.width);
    let c = Rect::new(
        rect.x + pad,
        rect.y + 1,
        rect.width.saturating_sub(2 * pad),
        rect.height.saturating_sub(1),
    );
    if c.width < 1 || c.height < 1 {
        return None;
    }
    Some(c)
}

/// Rect of the ✕ close button at the right of a pane's top-border title row.
fn pane_close_rect(area: Rect, bordered: bool) -> Option<Rect> {
    if !bordered || area.width < 9 {
        return None;
    }
    Some(Rect::new(area.x + area.width - 4, area.y, 3, 1))
}

fn pane_state(app: &App, id: PaneId) -> State {
    app.status
        .get(&id)
        .map(|s| s.state)
        .unwrap_or(State::Unknown)
}

/// Collapse `$HOME` to `~` and truncate from the left to fit `max` columns.
fn short_path(p: &Path, max: u16) -> String {
    let mut s = p.display().to_string();
    if let Some(home) = crate::platform::home_dir() {
        if let Some(rest) = s.strip_prefix(home.to_string_lossy().as_ref()) {
            s = format!("~{rest}");
        }
    }
    let max = max as usize;
    if s.chars().count() > max && max > 1 {
        let tail: String = s
            .chars()
            .rev()
            .take(max - 1)
            .collect::<Vec<_>>()
            .into_iter()
            .rev()
            .collect();
        format!("{tail}")
    } else {
        s
    }
}