The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
hn 0.1.17: dialogs, repaint, pane drag, composer, side bar machines, Sign out (#1028)
lingrd7f2ffb8da90f
diff --git a/docs/plans/2026-10-07-003-confirm-dialog-button-row-plan.md b/docs/plans/2026-10-07-003-confirm-dialog-button-row-plan.mdnew file mode 100644index 000000000..ff0ced5a2--- /dev/null+++ b/docs/plans/2026-10-07-003-confirm-dialog-button-row-plan.md@@ -0,0 +1,222 @@+# One button row for every dialog — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** Every hn dialog that asks a question shows its answers as `[ Label ]` buttons on one row, drawn and driven by one shared component: ← → / Tab choose, Enter runs, Esc cancels, the dialog's letter keys still work, a click runs the button under it.++**Architecture:** A new module `tui/src/buttons.rs` owns the row: layout (right-aligned, two columns apart), drawing (theme styles from `settings::chrome()`), keys and clicks. Five dialogs that each draw their own buttons today move onto it. tmux's own `confirm-before` (`kill-pane #P? (y/n)` in the status line) stays as tmux has it — it is tmux behaviour, not an hn dialog.++**Tech Stack:** Rust (ratatui), Python native fixtures.++**Spec:** user 2026-10-07: "I want close tab on one row, pressing left/right" (screenshot of `Close Tab · zsh` with `Cancel (Escape)` / `Stop (s)` on two rows), then: "Some places don't use the same buttons, like Connect machine … can't they be the same as the dialog we'll build, with the `[ ]` style, and usable with the keyboard?"++## Today: five dialogs, four looks++| Dialog | Code | Buttons | ← → | Chosen button |+|---|---|---|---|---|+| Close Tab / Stop Harness | `session_close.rs:154-177` (a vertical `workspace_menu`) | `Cancel (Escape)` / `Stop (s)`, one per row | no | `menu-selected-style` row |+| Machines: Connect / Prevent new links | `devices.rs:1382-1394` (`prompt_actions`), keys `:870-892` (`answer_key`), clicks `:819-835` (`mouse`) | ` Yes ` ` Cancel ` (or ` Continue `/` Next `) + muted `y/n` | no | filled `selected` band |+| Files: Open dialog | `files/dialog.rs:424-431` (`buttons`), keys `:311-318` (`button_key`; Tab/Esc are taken earlier at `:276-281`) | `[ Cancel ] [ Open ]` | yes (Left/Right only) | bold + underline when it has focus; Open bold otherwise |+| Files: Delete confirm | `files.rs:1190-1205` (`confirm_layout`), keys `:810-820` (`confirm_key`), clicks `:853-855` | `[ Delete ] [ Cancel ]`, starts on Delete (Trash) or Cancel (Purge) | yes (also Tab, h, l) | `look.mode` |+| Editor: Save changes? | `files/editor.rs:536-549` (`ask_layout`), keys `:389-399` (`ask_key`) | `[ Save ] [ Don't save ] [ Cancel ]` | yes (Left/Right/Tab/BackTab) | `look.mode` |++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **Close Tab box colours:** a workspace menu that has a button row is filled with `chrome().base` (its border in `chrome().muted`), so the box and its buttons match; tmux `display-menu` and the vertical Pane/Tab/Harness menus keep `menu-style`.+2. **Narrow Machines panel (24 columns, `devices.rs:1808` test):** the keys hint is dropped first when it does not fit; the buttons must still fit. If `[ Cancel ] [ Yes ]` cannot fit at 24 columns, raise that test's minimum width by 2 and say so in the commit — never overlap or clip a button.+3. **Keys:** each dialog keeps Tab where it already means something else (the Open dialog's regions; Entry prompts keep letters for typing). ← → always move between buttons when the buttons have the keys.+4. **Delete defaults to Cancel** (risky action): accepted behaviour change; rewrite the old `files.rs` tests that pressed Enter on Delete to press Right (or `d`/the action key) first.++## Global Constraints++- **One look, no custom style:** `[ Label ]`; the chosen button in `chrome().selected` (bold on the lifted band — the command panel's chosen row); the others in `chrome().base`; a muted keys hint at the row's left (`s stop · esc cancel`). No fixed colours. `NO_COLOR`: the chosen button reversed (`chrome()` already does this).+- **One order:** the way out (Cancel / Don't save) first, the action last, right-aligned — `[ Cancel ] [ Stop ]`, `[ Don't save ] [ Cancel ] [ Save ]`, `[ Cancel ] [ Delete ]`, `[ Cancel ] [ Yes ]`.+- **One default:** a destructive action (Stop, Delete, Delete Permanently, Prevent new links) starts on Cancel; a safe one (Open, Save, Continue, Connect) starts on the action. The Close Tab tests require Cancel by default (`session_close.rs:417-429, 514`).+- **Same keys everywhere:** ← → Tab Shift-Tab (and h / l) move, wrapping; Enter runs the chosen; Esc, C-c, C-g cancel; each dialog keeps its letters (`s` stop, `y`/`n`, the files' `q`/`n`).+- Copy unchanged except `Cancel (Escape)` → `[ Cancel ]` and the order above. Follow `docs/naming-system.md`.+- tmux `display-menu`, `confirm-before` and the vertical Harness / Pane / Tab menus do not change.++## Target look++```+┌Close Tab · zsh──────────────────────────────────┐+ The terminal and its running commands will end.+ Stop? Saved history will remain.++ s stop · esc cancel [ Cancel ] [ Stop ]+└─────────────────────────────────────────────────┘+```++## Review Focus++- A dialog narrower than its buttons: the hint goes first, then the row is refused with the existing "Make the terminal larger" message (workspace menus) or clipped the way that dialog clips today — never overlapping buttons.+- A click between two buttons, or on the hint, runs nothing.+- Resize while a dialog is open keeps the chosen button.+- A failed stop shows only `[ Back ]`: one button, chosen, Enter runs it.+- The Machines dialog's password prompt (paste-protected, `tui/tests/workspace-controls.py:226-248`) keeps its input focus: while the input has the keys, typing, Backspace, Enter (continue) and Esc work as today and ← → move the caret in the input; Tab moves the keys to the buttons, then ← → move between the buttons and Enter runs one; Tab again, or typing a printable key, returns to the input. A pasted `y`/`n` is never a button letter (paste is never a yes).+- Enter on a chosen `[ Cancel ]` in an Entry prompt cancels (it does not submit the typed value).++---++### Task 1: The shared component `buttons.rs`++**Files:**+- Create: `tui/src/buttons.rs` (add `mod buttons;` to `tui/src/main.rs` beside `mod workspace_menu;` at `:44`)+- Test: `tui/src/buttons.rs` tests++The dialogs hand it keys of two types: devices/menus have a crossterm `KeyEvent`, the files UI has its own `crate::keys::Chord { code, mods }` (`config.rs:46`). So `Row::key` takes `(KeyCode, KeyModifiers)`; callers pass `k.code, k.mods` (a `KeyEvent` has `.code`/`.modifiers`, a `Chord` has `.code`/`.mods`).++**Interfaces:**+- Produces:+```rust+use crossterm::event::{KeyCode, KeyModifiers};+use ratatui::buffer::Buffer;+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Button { pub label: String, pub key: Option<char> } // key: the dialog's letter (s, y, d…)+#[derive(Clone, Debug)]+pub struct Row { pub buttons: Vec<Button>, pub chosen: usize, pub hint: String }+pub enum Answer { Chosen(usize), Cancel, Moved, Ignored }+impl Row {+ /// Total columns the row needs (hint + buttons), for a dialog's width.+ pub fn width(&self) -> u16;+ /// Each button's columns on a row whose right edge is [right]: (index, x, width).+ pub fn cells(&self, right: u16) -> Vec<(usize, u16, u16)>;+ /// Draws the hint at [left] and the buttons right-aligned to [right] on row [y].+ pub fn draw(&self, buf: &mut Buffer, left: u16, right: u16, y: u16, c: &crate::settings::Chrome);+ /// A key: ← → Tab BackTab h l move (wrapping; h / l only when no button owns that letter, and+ /// only without Ctrl/Alt); Enter → Chosen(chosen); Esc, Ctrl-C, Ctrl-G → Cancel;+ /// a button's letter (no Ctrl/Alt) → Chosen(that). Dialogs that use Tab for something else+ /// (the Open dialog) filter Tab/BackTab/Esc before calling.+ pub fn key(&mut self, code: KeyCode, mods: KeyModifiers) -> Answer;+ /// A click at (x, y) on a row drawn at [y_row] with right edge [right].+ pub fn click(&self, x: u16, y: u16, right: u16, y_row: u16) -> Option<usize>;+}+```++- [ ] **Step 1: Failing tests**++```rust+use super::*;+use ratatui::{layout::Rect, style::Modifier};++fn row() -> Row { Row { buttons: vec![Button { label: "Cancel".into(), key: None }, Button { label: "Stop".into(), key: Some('s') }], chosen: 0, hint: "s stop · esc cancel".into() } }++#[test]+fn buttons_sit_right_aligned_two_columns_apart() {+ let cells = row().cells(50);+ assert_eq!(cells, vec![(0, 50 - 8 - 2 - 10, 10), (1, 50 - 8, 8)]); // "[ Cancel ]" 10, "[ Stop ]" 8+}++#[test]+fn keys_move_wrap_choose_and_cancel() {+ let mut r = row();+ let k = |r: &mut Row, c| r.key(c, KeyModifiers::NONE);+ assert!(matches!(k(&mut r, KeyCode::Right), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(k(&mut r, KeyCode::Right), Answer::Moved)); assert_eq!(r.chosen, 0, "wraps");+ assert!(matches!(k(&mut r, KeyCode::BackTab), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(k(&mut r, KeyCode::Enter), Answer::Chosen(1)));+ assert!(matches!(k(&mut r, KeyCode::Char('s')), Answer::Chosen(1)));+ assert!(matches!(k(&mut r, KeyCode::Esc), Answer::Cancel));+ assert!(matches!(r.key(KeyCode::Char('c'), KeyModifiers::CONTROL), Answer::Cancel));+ assert!(matches!(k(&mut r, KeyCode::Char('x')), Answer::Ignored));+}++#[test]+fn the_chosen_button_is_the_panels_chosen_row() {+ if crate::theme::no_color() { return } // NO_COLOR: `selected` is REVERSED, with no bg to compare+ let c = crate::settings::chrome();+ let mut buf = Buffer::empty(Rect::new(0, 0, 50, 1));+ let mut r = row(); r.chosen = 1;+ r.draw(&mut buf, 0, 50, 0, &c);+ let (_, x, _) = r.cells(50)[1];+ assert_eq!(buf[(x, 0)].symbol(), "[");+ assert_eq!(buf[(x + 2, 0)].bg, c.selected.bg.unwrap());+ assert!(buf[(x + 2, 0)].modifier.contains(Modifier::BOLD));+ let (_, x0, _) = r.cells(50)[0];+ assert_ne!(buf[(x0 + 2, 0)].bg, c.selected.bg.unwrap());+ assert_eq!(buf[(0, 0)].fg, c.muted.fg.unwrap(), "the hint is muted");+}++#[test]+fn a_click_on_a_button_chooses_it_and_between_them_nothing() {+ let r = row(); let cells = r.cells(50);+ assert_eq!(r.click(cells[1].1 + 1, 3, 50, 3), Some(1));+ assert_eq!(r.click(cells[0].1 + cells[0].2, 3, 50, 3), None, "the gap");+ assert_eq!(r.click(cells[1].1 + 1, 2, 50, 3), None, "another row");+}+```+- [ ] **Step 2: Run** — `cd tui && cargo test --locked buttons::` → FAIL (module missing)+- [ ] **Step 3: Implement** — straightforward from the interface; `draw` fills each button's cells with its style (chosen: `c.selected`, others `c.base`, hint `c.muted`; paint via `buf.cell_mut((x, y))` as `settings::put` does), then writes `[ {label} ]`; the hint is drawn only when it fits left of the first button with 2 columns to spare. `cells(right)` saturates at 0 so a too-narrow `right` never underflows. An empty `hint` draws nothing (the Open dialog keeps its own text).+- [ ] **Step 4: Run** → PASS+- [ ] **Step 5: Commit** — `git add tui/src/buttons.rs tui/src/main.rs && git commit -m "hn: one button row for dialogs"`++### Task 2: Close Tab / Stop Harness on the button row++**Files:**+- Modify: `tui/src/modal.rs:134-153` (`Menu` gains `pub buttons: Option<crate::workspace_menu::Buttons>`). `Layout` (`workspace_menu.rs:10`) has private fields and `ui.rs` / `input.rs` only see `Menu`, so the row lives on `Menu`; `Layout` keeps its own copy for re-fitting. The only two `Menu { .. }` literals are `workspace_menu.rs:27` (`open`) and `input.rs:1976` (`prompt_menu`): add `buttons: None` to both.+- Modify: `tui/src/workspace_menu.rs`: `#[derive(Clone, Debug)] pub struct Buttons { pub row: crate::buttons::Row, pub actions: Vec<String> }` (`actions[i]` is the command button i runs; button 0 is the way out, so `actions[0]` is also what Esc runs). `Layout` gains `buttons: Option<Buttons>`. New `pub fn open_buttons(app, title, notes: Vec<MenuItem>, row: Row, actions: Vec<String>) -> bool` (like `open`, `choice: None`, items = notes only). `fit`: width also `max(row.width())` (before the `min(size.0 - 4)` clamp), height = wrapped notes + (1 blank + 1 row when buttons) + 2, the `size.1 < actions + 2` guard counts those two rows; when the row does not fit (`row.width() > width`) drop the hint first (`row.hint.clear()` on the copy in `Menu`), and if the buttons alone still do not fit return false (the existing "Make the terminal larger" path). `fit` copies `menu.buttons.row.chosen` back into the layout's row first so a resize keeps the chosen button.+- Modify: `tui/src/ui.rs:304-350` (`menu`): `h = m.items.len() as u16 + 2 + if m.buttons.is_some() { 2 } else { 0 }`; after the item loop draw the row with `Row::draw(buf, x0 + 2, x0 + 2 + m.width, y0 + 1 + items + 1, &crate::settings::chrome())` (`items = m.items.len()`; the blank row is already painted by the background fill).+- Modify: `tui/src/input.rs:1632` (`Modal::Menu(mut menu)` arm): before the existing `menu.items ... it.key == name` lookup, `if let Some(b) = menu.buttons.as_mut()`: `match b.row.key(key.code, key.modifiers)` — `Chosen(i)` runs `b.actions[i]` with `commands::execute_in(app, &cmd, menu.mouse.clone())` (as `menu_chosen` `:3533` ends), `Cancel` runs `b.actions[0]` (this replaces today's bare `return`, which left the close operation pending; `session_close::cancel` keeps a Stop in progress), `Moved` puts the menu back (`app.modal = Some(Modal::Menu(menu))`), `Ignored` falls through (so `q` and the vertical-menu keys stay harmless; notes are disabled items so nothing else is selectable).+- Modify: `tui/src/input.rs:3549-3574` (`menu_mouse`): the bounds test `m.y > py + count` must count the button rows (`count = items + 2` when `menu.buttons.is_some()`), else a click on the row closes the menu; when `m.y == py + 1 + items.len() + 1` use `Row::click(m.x, m.y, px + 2 + width, m.y)` — `Some(i)` (on a press / release as `chosen` is computed) runs `actions[i]`, `None` keeps the menu open; a click on a note row runs nothing.+- Modify: `tui/src/session_close.rs:150-152` (`showing`: `m.buttons.as_ref().is_some_and(|b| b.actions.iter().any(|a| *a == format!("close-harness -x {id}")))` — the cancel command is no longer a menu item, so the old test would never find the modal) and `:154-177` (`show`: keep the note building, drop the two `menu::item` lines and the `cancel` index; `menu::open_buttons(app, &title, items, Row { buttons: [Cancel|Back (None), Stop (Some('s')) when confirm], chosen: 0, hint: "s stop · esc cancel" when confirm else "" }, actions: [format!("close-harness -x {id}"), format!("close-harness -y {id}")])`; the hint is empty for `Back`).+- Test: `tui/src/session_close.rs` tests `:417-561` keep passing unchanged (Enter on default Cancel closes; `s` stops; Esc dismisses; `:560` `menu.items.iter().any(|i| i.label.contains("1 stopped"))` still holds because notes stay items). `tui/src/workspace_menu.rs` tests at `:99-130` use `open` and `wrap_notes` and are unchanged. New tests below.+- Fixtures: `tui/tests/workspace-controls.py:362` and `:607` `click_text('(s)')` → `click_text('[ Stop ]')`; `tui/tests/fresh-user.py:184,187` `'(s)' in self.screen()` → `'[ Stop ]' in self.screen()`. `shown('Cancel')` (`:599`) and `'Cancel' not in screen()` (`:603`) keep working: the hint reads `esc cancel` (lower case) so it never matches `Cancel`. `shell-first.py:553` only waits for the question text: unchanged.++- [ ] **Step 1: Failing tests**+ - In `session_close.rs` tests (helpers `app()`, `pane()`, `answer()`, `key()`, `modes()` already there):+```rust+#[tokio::test]+async fn right_then_enter_stops_and_the_buttons_are_one_row_model() {+ let mut app = app();+ pane(&mut app, 1);+ answer(&mut app, "inspect", json!({"activity":"working"}));+ let Some(Modal::Menu(m)) = &app.modal else { panic!("no confirmation") };+ let b = m.buttons.as_ref().expect("a button row");+ assert_eq!(b.row.buttons.iter().map(|x| x.label.as_str()).collect::<Vec<_>>(), ["Cancel", "Stop"]);+ assert_eq!(b.row.chosen, 0, "a destructive action starts on Cancel");+ key(&mut app, KeyCode::Right);+ key(&mut app, KeyCode::Enter);+ assert_eq!(modes(&app), ["inspect", "now"]);+}+```+ - In `ui.rs` `theme_render_tests` (`:2982`; its `app()` is 150x42 and `screen(&mut app)` returns the painted text): `crate::workspace_menu::open_buttons(&mut app, "Close Tab · zsh", vec![crate::workspace_menu::note("Stop? Saved history will remain.")], row, vec!["close-harness -x x".into(), "close-harness -y x".into()])` (row = Cancel, Stop); `let s = screen(&mut app)`; the line holding `[ Cancel ]` also holds `[ Stop ]`, with Cancel to its left; `crate::input::modal_key` Right then Enter closes the modal (the commands are ignored by `session_close` as no operation `x` exists).+ - In the `input.rs` tests module (`:3577`): open the same menu, call `menu_mouse` with a left press over `[ Stop ]` (x, y from `Row::cells` and the menu's `x`/`y`) → modal closed; a press in the 2-column gap between the buttons → modal still open and nothing run.+- [ ] **Step 2: Run** → FAIL (no `buttons` field)+- [ ] **Step 3: Implement** as in *Files*.+- [ ] **Step 4: Run** — `cd tui && cargo test --locked session_close:: workspace_menu:: buttons:: theme_render_tests` (then the full suite once at Task 5) → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: Close Tab and Stop Harness ask with [ Cancel ] [ Stop ] on one row"`++### Task 3: Machines prompts on the button row++**Files:**+- Modify: `tui/src/devices.rs:1382-1394` (`prompt_actions`): build a `Row` from `app.devices.ask`: `[ Cancel ] [ Yes ]` for `Ask::Confirm`, `[ Cancel ] [ Continue ]` / `[ Next ]` (`w < 19`) for `Ask::Entry`; hint `y yes · n no` for a confirm only (an Entry has no letters: typing goes to the input). Keep the existing `PromptActions { size, accept, cancel }` (`:149`) and fill `cancel` / `accept` from `Row::cells(x + w)` (button 0 / button 1), so `mouse` `:819-835` and the test helper `click_prompt` (`devices.rs:1747-1752`) keep working with their rects; the clicks only need `Row::click` if you drop the rects. The chosen button is state, not drawing: add `prompt_row: Cell<usize>` (chosen index) and `prompt_focus: Cell<bool>` (keys on the buttons) to `Devices` (`:151`, constructed at `:173`), reset by the two functions that set `app.devices.ask` (`entry` `:797`, `confirm` `:802`). Defaults: a confirm for `Act::ClearPassword | Unlink | Remove | Unpair` starts on Cancel (0), for `Act::Link | SetPassword | Rename | ArmPhone` on Yes (1); an Entry starts with `prompt_focus` false and chosen = the action. Keep the "needs room" guard (`w < needed` returns) with `needed = row.width()`.+- Modify: `tui/src/devices.rs:870-892` (`answer_key`): for `Ask::Confirm`, first `Row::key(key.code, key.modifiers)` on the row (letters `y` → Yes, `n` → Cancel; keep the existing `Y` / `N` arms and the "any other key keeps the prompt" arm): `Chosen(1)` → `run_act`, `Chosen(0)` / `Cancel` → `note(app, "Nothing changed")`, `Moved` → store the chosen index and keep the ask, `Ignored` → keep the ask. For `Ask::Entry`: Tab / BackTab toggle `prompt_focus`; while it is true, ← → Enter go through `Row::key` (`Chosen(1)` = `submit` as Enter does today, `Chosen(0)` / `Cancel` = `note(app, "Nothing changed")`); while false everything is as today (typing, Backspace, Ctrl-U, Enter submits, Esc cancels), and no letter is ever a button letter. Note `answer_key` takes the ask out (`.take()`) and puts it back at the end of each arm: put it back on the new paths too.+- Test: `tui/src/devices.rs` tests: `device_confirmation_buttons_survive_resize_and_hidden_targets_do_not_run` (`:1808`) asserts `visible.contains(" Yes ") && visible.contains(" Cancel ")` → `"[ Yes ]"` and `"[ Cancel ]"`; the smallest size in its loop `(24, 10)` must still show the row — `[ Cancel ] [ Yes ]` is 19 wide plus the panel's inset; if `w < 19` there, either raise the smallest size or assert the refusal (no row, `prompt_actions` is none) for that size only; do not weaken the other sizes. `mouse_link_requires_continue_then_explicit_yes_and_cancel_writes_nothing` (`:1773`) and `pasted_passwords_stay_masked...` (`:1788`) keep passing.+- Fixtures: `tui/tests/workspace-controls.py:248` `click_text(' Yes ')` → `click_text('[ Yes ]')`; `:257-258` `shown(' Cancel ')` / `shown(' Yes ')` → `shown('[ Cancel ]')` / `shown('[ Yes ]')`; `click_text('Continue')` (`:232, 235, 245, 247`) and `click_text('Cancel')` (`:239, 260`) still match inside the new labels.++- [ ] **Step 1: Failing test** — a Prevent-new-links prompt (`go_to(&mut app, "pw:clear"); press(&mut app, KeyCode::Enter)` as `:1821-1822`, helpers `press`, `screen`, `fake`, `has`, `clis` exist in the module): the row starts on Cancel; Left/Right move between the two buttons; Enter on Cancel closes without the request (`!has(&log, &clear)`); Right, Enter sends it (`clis(&log, "remote-password")` contains `clear` once); the drawn chosen button's cells have `chrome().selected`'s bg (read the buffer from the same `screen` helper's draw; skip the bg assert when `theme::no_color()`). A second test: in the password Entry prompt, Right does nothing to the typed value, Tab then Right/Enter on `[ Cancel ]` cancels without a request.+- [ ] **Step 2: Run** → FAIL (no ← →)+- [ ] **Step 3: Implement** as in *Files*.+- [ ] **Step 4: Run** — `cd tui && cargo test --locked devices::` and `python3 tests/workspace-controls.py` (from `tui/`, with the fixture's usual environment) → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: machines prompts use the dialog button row"`++### Task 4: Files and the editor on the button row++Buttons are always indexed in display order from now on (Cancel first, the action last). The three dialogs index their buttons by number today, so every `0` / `1` / `2` below changes with the order.++**Files:**+- Modify: `tui/src/files/dialog.rs`: `buttons()` (`:424-431`, returns `[(x, end, label); 2]`) is rebuilt on `Row::cells(self.size.0 - 2)` (Row `[Cancel, Open]`, `chosen: self.button`) and keeps its signature, so `click` and the test at `:797` (`let (ox, ..) = e.buttons()[1]`) work as they do. `button_key` (`:311-318`) becomes: build the row from `self.button`, `Row::key(k.code, k.mods)`, store `row.chosen` back to `self.button`; `Chosen(1)` → `self.open(self.target())`, `Chosen(0)` / `Cancel` → `DOut::Cancel`. Tab, BackTab, Esc, `/` and Ctrl-F are already consumed at `:276-281` before `button_key` is reached (Tab there moves focus between sidebar / columns / buttons), so they never reach `Row::key`. Drawing `:556-562`: the chosen button (`self.button`) is drawn with `chrome().selected` whether or not `focus == Focus::Buttons` (Open is the default action and is emphasised today even unfocused); the others `chrome().base`; `Row.hint` stays empty — the bottom row keeps its own `Enter open · Esc cancel · …` text drawn left of the first button at `:556-558`.+- Modify: `tui/src/files.rs`: `Confirm.focus` (`:181`, comment `:179`) now means 0 Cancel, 1 Delete / Delete Permanently. `confirm_layout` (`:1193-1209`) labels `["[ Cancel ]", "[ {yes} ]"]` (laid out left to right as today); draw `:1181-1187` `unwrap_or(0)` and uses `Row::draw`-equivalent cells; `confirm_key` (`:810-820`): the Left/Right/Tab/BackTab/h/l arm is replaced by `Row::key`, Enter → `if c.focus == 1 { self.confirmed() } else { self.confirm = None }`, and the extra cancel letters `q` and `n` (`:815`) stay as they are. `click_at` (`:853-855`): `if b == 1 { self.confirmed() } else { self.confirm = None }`. Defaults: `Act::Delete` (`:582`) `focus: 0` (Cancel — a change from today, where Trash starts on Delete), Purge (`:828`) `focus: 0` (was 1).+- Modify: `tui/src/files/editor.rs`: new order `[Don't save, Cancel, Save]`; `asking: Option<usize>` (`:87`) now holds 0 Don't save, 1 Cancel, 2 Save; the request at `:385` is `asking = Some(2)`; `ask_layout` (`:536-549`) `LABELS = ["[ Don't save ]", "[ Cancel ]", "[ Save ]"]`; `ask_key` (`:389-399`): `Row::key` (Left/BackTab/Right/Tab move as today, wrapping over 3); `Chosen(i)` → `self.answer(i)`; `Cancel` (Esc) → `asking = None`; `answer` (`:401-408`): `0 => EdOut::Close`, `1 => EdOut::None`, `2 =>` the save arm (`save()`: `Ok` → `Close`, `Err` → message). Click `:442-444` already calls `answer(b)` with the displayed index.+- Test: `files/dialog.rs` tests `:726-794` keep their text asserts (the Open dialog's order did not change); `files.rs` tests: `:2126-2134` — a Trash confirm now starts on Cancel, so the old `Delete, Right, Enter` (cancelled) becomes `Delete, Enter`, and the old `Delete, Enter` (deleted) becomes `Delete, Right, Enter`; `:2159-2170` (`what_cannot_go_to_the_trash_is_deleted_only_after_a_second_yes`): the first `Delete, Enter` becomes `Delete, Right, Enter`, `:2161` `Some((Doom::Purge(..), 1))` becomes `0`, `:2165-2168` `Delete, Enter, Left, Enter` becomes `Delete, Right, Enter, Right, Enter`; `editor.rs` `closing_with_changes_asks_first` (`:685-700`): `assert_eq!(e.asking, Some(0))` becomes `Some(2)`, the `Right, Right, Enter` = Cancel path still holds (2 -> 0 -> 1).++- [ ] **Step 1: Failing tests** — (a) Delete confirm: after `Delete`, `f.confirm` has `focus == 0` (Cancel), Right makes it 1, Enter deletes; (b) Editor: `closing_with_changes_asks_first` with the new `Some(2)` and Left (2 -> 1) = Cancel; (c) each dialog's chosen button has `chrome().selected`'s bg: draw into a `Buffer` (Editor: `e.draw(&mut buf, area, &Look::default())` as `editor.rs:716`; Open dialog: the `text(&mut d, 130, 34)` helper path; Delete confirm: the `files.rs` draw test helper) and read the cell at the chosen button's `[ x + 2 ]` from `ask_layout()` / `buttons()` / `confirm_layout(g)` (offset by the draw origin the dialog uses); skip the bg assert when `theme::no_color()`.+- [ ] **Step 2: Run** → FAIL+- [ ] **Step 3: Implement** — the files' `Look` is not used for buttons any more; `settings::chrome()` is. It reads `theme::pane_palette()` (the terminal's own colours, else the default palette), so it also works when Files runs in its own process (`files::standalone`, `files.rs:1517`) — there it follows the terminal's colours, not hn's chosen theme.+- [ ] **Step 4: Run** — `cd tui && cargo test --locked files::` → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: files and editor dialogs use the dialog button row"`++### Task 5: Gate and look++- [ ] `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui` (composer-machine on macOS bash 3.2: known, separate).+- [ ] Isolated hn, dark and light theme and `NO_COLOR=1`: capture Close Tab, a Machines prompt, the Open dialog, Delete and Save changes? — the five button rows look the same. Check in particular the Close Tab row: its non-chosen button uses `chrome().base` over a tmux `menu-style` box, so look for a visible band mismatch on the box background.diff --git a/docs/plans/2026-10-07-004-shell-composer-freeze-plan.md b/docs/plans/2026-10-07-004-shell-composer-freeze-plan.mdnew file mode 100644index 000000000..ea957f8da--- /dev/null+++ b/docs/plans/2026-10-07-004-shell-composer-freeze-plan.md@@ -0,0 +1,259 @@+# Shell composer: choosing with @ never freezes the shell — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** In a shell pane, Ctrl-N / `claude @…` → choose a computer, folder or model → the prompt comes back at once (or says why within a few seconds); the picker never sits still while it waits.++**Architecture:** The composer is a separate `hn --shell-picker` process started by the shell's line-editor widget (`tui/src/shell_integration.sh`), talking to the TUI over OSC 633 requests on the tty (`shell_context.rs`). Three waits block it today:+1. `_hn_request` (`shell_integration.sh:2-49`; the attempts at `:25-27`) retries a request **120 times with a 1 s read** — synchronously inside the ZLE/Readline widget (`_hn_picker_widget`, `:234-235`: `host-inline`, `model-inline`, `session-inline`; the same function also serves `ch`/`cm`/`hn sessions`, `:53-71`, and `_hn_choose`, `:196-198`). While it waits the shell accepts no keys: the user sees a frozen prompt for up to two minutes.+2. While that request is pending, the TUI refuses every other picker request (`shell_context.rs:454-455`: "close the current picker first") and only expires it after 100 s (`:850`). A `cancel` for the pending id is already handled (`:434-437` → `cancel` `:743` → `finish`, code 1, picker freed; tested at `:1308`).+3. The picker loop redraws only on a key or a reply (`shell_picker.rs:496-499` `dirty`), so its spinner stops while a remote folder scan runs (`Scan` in `shell_context/folders.rs`, notice `Searching folders…` at `:77`) — it looks hung. Worse, the inline picker never turns the spinner at all: `Screen::draw` (`shell_picker.rs:279-298`) passes `loading` to `inline_fzf` as `busy`, but `fzf_in_frame` only honours it for `PickerKind::Open` (`ui.rs:1486`, `reading = picker.busy.is_some() || Open && search_busy`) and the shell picker never sets `picker.busy`.+`exchange()` (Enter on `claude @x …`, via `--shell-compose-launch`) waits up to 180 s too (`shell_picker.rs:177-195`), but it is cancellable with Ctrl-C (`:181-185` sends `cancel`) and, today, draws nothing while it waits (`shell_composer.rs:517` is its only caller); keep it, and give it a visible wait (Task 3, step 3e).++The user's freeze ("gõ @ chọn gì đó là nó đơ") is choosing a computer: inside an agent draft (`codex @…`) the composer only edits the line (`edit` result, no request); the `-inline` requests come from Ctrl-P on a line that is not an agent command (`Draft::new` returns `None`, `shell_picker.rs` then prints `host\n<id>`), from `ch`/`cm`/`hn sessions`, and from the Ctrl-P sessions list. `host-inline` → the TUI switches the pane to that computer (`shell_context.rs:497` `switch_host`, defined at `:750`), the reply comes late or is lost after the stream reattaches, and the widget sits in the 120-try loop.++**Tech Stack:** POSIX sh (zsh/bash widgets), Rust, `tests/shell-integration.py` (real zsh/bash in private PTYs, fake picker and fake agents), `tests/composer-machine.py` (real zsh/bash in private PTYs with a fixture catalog).++**Spec:** user report 2026-10-07 + answer "Ô gõ trong shell (Ctrl-N)". Investigation: not reproduced as a hard hang locally (needs a second computer); the blocking loops above are confirmed by reading the code.++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **No 3 s cut-off.** Opening a shell on another computer legitimately takes up to 60 s (`agent_create`'s budget), so cancelling at 3 s would break `ch` to a slow machine. Instead, an `-inline` request: (a) prints a progress line on the terminal **at once** — `Opening a shell on <computer>… Ctrl-C to cancel` (model / session verbs: `Switching model…`, `Opening session…`); (b) waits at most **60 s** (`_hn_attempts=60` for `*-inline`); (c) Ctrl-C cancels it (the existing INT trap sends `cancel`) and returns the prompt with the line unchanged; (d) on running out, the one-line `<computer> did not answer. Your line is unchanged; try again.` Every "3 s" in Tasks 1, 2 and 4 means this rule instead; the `Gone` journey asserts: the progress line appears within 1 s, Ctrl-C gives the prompt back within 1 s with the line unchanged, and the next pick works. The TUI's pending `-inline` expiry becomes 65 s (not 5 s).+2. **The likeliest freeze is Enter after `@computer` (`exchange()`), which draws nothing for up to 180 s.** Step 3e (a visible wait: `Starting on <computer>… Ctrl-C to cancel` with a turning spinner) is required, not optional, and gets its own fixture check in Task 1 (`claude @Slow` + Enter: the text appears within 1 s).+3. **A failed list request** shows its message in the list and retries at most 3 times, 2 s apart, then stays open showing the error until Esc — never an endless retry loop.++## Global Constraints++- The shell stays usable and never looks dead: a request inside a line-editor widget says at once what it is waiting for, can always be cancelled with Ctrl-C, and gives up after 60 s with the line restored unchanged and a one-line message (see Controller ruling 1).+- The request id stays the same across retries (the TUI dedupes it, `shell_integration.sh:20-21` comment) — no action runs twice.+- zsh and bash 4/5 and macOS `/bin/bash` 3.2 all keep working (`composer-machine.py` runs zsh and `HN_COMPOSER_TEST_BASH`).+- No launch from the picker without Enter (the fixture's rule: "Starting an agent is a failure").++## Review Focus++- A reply that arrives after a Ctrl-C cancel or the 60 s limit must not change the line the user is now typing (the TUI must drop it: the request was cancelled).+- Ctrl-C while waiting returns the prompt and cancels the request (the `INT` trap already sends `cancel`).+- Choosing the same computer again right after a timed-out one works (no "close the current picker first").+- A computer that is offline: the picker says so in its status line, not a frozen spinner.+- The picker's spinner keeps turning with no key pressed while a folder scan runs.++---++### Task 1: Reproduce — a computer that never answers (widget) and one that answers late (picker)++The widget's `-inline` requests are not reachable from `composer-machine.py`: its fixture only accepts `list-compose` / `list-sessions` (`:90`, an agent draft edits the line and never sends `host-inline`), and a non-agent draft would send `list-host`, which the fixture rejects. So:+- the **never answers** journey goes into `tui/tests/shell-integration.py`, which already drives the real widget with a fake picker (`picker-choice` file) and answers `host-inline`/`model-inline`/`session-inline` itself through `s.reply(match)`; not replying is the `Gone` computer;+- the **answers late** journey (`Slow`) goes into `tui/tests/composer-machine.py`, whose fixture gets one new computer with a delayed folder reply.++**Files:**+- Modify: `tui/tests/shell-integration.py` (insert before the `(root/'picker-choice').unlink()` at `:138`, inside the `for shell … for custom …` loop, so it runs for zsh and bash, with and without custom aliases)+- Modify: `tui/tests/composer-machine.py` (`Shell.__init__` `:33-34`, `pump` `:70-121`, host rows `:97-98`, machine/path `:95,:100`, new journey at the end of `check` before `:219`)++- [ ] **Step 1: Gone — the widget gives the line back (shell-integration.py)**++Uses only the file's own helpers: `Shell.send`, `Shell.read_until(pattern, seconds)` (returns and clears the buffer), `Shell.result(marker)`, the `REQUEST` regex, `s.reply`.++```python+ # A computer that never answers: the widget gives the line back within+ # 3 s, cancels the request, says so, and the draft is untouched.+ (root/'picker-choice').write_text('host\nGone\n')+ s.send("printf 'GONE_%s\\n' LRIGHT")+ s.send('\x02'*5+'\x10')+ first=REQUEST.search(s.read_until(REQUEST))+ assert first[3]==b'host-inline' and base64.b64decode(first[4])==b'Gone'+ t0=time.monotonic()+ said=s.read_until(b'Gone did not answer',seconds=5)+ assert time.monotonic()-t0<4.5,'the shell waited too long'+ assert re.search(rb'633;hn;'+TOKEN.encode()+b';'+re.escape(first[2])+b';cancel;',said),'the request was not cancelled'+ if b'READY> ' not in said.split(b'Gone did not answer',1)[1]: s.read_until(b'READY> ')+ s.send('M\r')+ s.result(b'GONE_LMRIGHT') # the line is exactly what it was+ # Right after it, another choice is served (the TUI freed the picker).+ (root/'picker-choice').write_text('host\nlocal\n')+ s.send('\x10')+ match=REQUEST.search(s.read_until(REQUEST))+ assert match[3]==b'host-inline' and match[2]!=first[2]+ s.reply(match); s.read_until(b'READY> ')+```++- [ ] **Step 2: Slow — the fixture computer (composer-machine.py)**++(a) in `Shell.__init__` add `self.delayed = []`. (b) split the reply block at `:109-121` into a method and add a due-time flush at the top of `pump`:++```python+ def answer(self, request_id, catalog):+ path = self.root / '.harness/shell-requests' / TOKEN / request_id+ data = path.with_suffix('.json')+ try:+ if not path.exists():+ return # the user changed scope before this reply+ data.write_text(json.dumps(catalog))+ data.chmod(0o600)+ fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK)+ os.write(fd, ('HN:' + request_id + ':0:\n').encode())+ os.close(fd)+ except OSError:+ if path.exists():+ raise+```+and in `pump`, first lines:+```python+ for item in [d for d in self.delayed if d[0] <= time.monotonic()]:+ self.delayed.remove(item); self.answer(item[1], item[2])+```+(c) `:95` → `machine = 'remote-id' if host in ('Office','office','remote-id') else 'slow-id' if host in ('Slow','slow','slow-id') else 'local-id'`; `:98` add `dict(id='Slow', label='Slow', extra='slow-id')` to the host rows; `:100` → `path = {'remote-id': '~/office-project', 'slow-id': '~/slow-project'}.get(machine, '~/mac-project')`; replace the tail of `pump` (`:109-121`) with: `if machine == 'slow-id' and kind == 'folder': self.delayed.append((time.monotonic() + 8, request_id, catalog)); continue` then `self.answer(request_id, catalog)`. (The picker re-sends the same id every second; `self.answered` already dedupes it, so the delayed reply is queued once.)++(d) the journey, at the end of `check` before the `assert b'No such widget'` line:++```python+ # A computer whose folders take 8 s: the spinner keeps turning with no key pressed.+ s.load('codex '); n = s.count(); start = len(s.requests)+ s.host('Slow'); s.scope('folder', start, 'Slow')+ s.data = b''+ end = time.monotonic() + 2+ while time.monotonic() < end:+ s.pump()+ glyphs = set(re.findall('[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏]', s.data.decode('utf-8', 'ignore')))+ assert len(glyphs) >= 2, ('the spinner did not turn', glyphs, s.data[-500:])+ s.send('\x1b'); s.wait(lambda: s.count() == n + 1, 'cancel slow folders')+```+(`re` and `time` are already imported there.) Before the fix this fails: the inline picker never sets `picker.busy`, so no spinner glyph is drawn at all.++- [ ] **Step 3: Run to see them fail** (isolated HOME, fake picker/agents only; no real agent CLI is started — `PATH` in both fixtures is `bin` + system dirs)++Run: `cd tui && python3 -u tests/shell-integration.py` → FAIL at `Gone did not answer` (the loop runs 120 s; the file's 120 s `faulthandler` would end it).+Run: `cd tui && cargo build --release --locked && env HN_COMPOSER_TEST_BINARY=target/release/harness-tui python3 -u tests/composer-machine.py` → FAIL at `the spinner did not turn`.++- [ ] **Step 4: Commit the failing journeys on the branch** (only with the user's approval, as always) — `git commit -am "composer: fixture computers that answer late or never"`++### Task 2: Widget requests give up after 3 s++**Files:**+- Modify: `tui/src/shell_integration.sh:25-27` (attempts by verb), `:46-48` (the give-up path of `_hn_request`)+- Modify: `tui/src/shell_context.rs:850` (pending `-inline` requests expire after 5 s, not 100 s). No change for `cancel`: `output` already clears a pending request on `cancel` (`:434-437`), so a cancelled `-inline` request frees the picker and its late `switch_host` result is discarded (`:777-784` deletes the shell it created) — the Review Focus items "late reply" and "same computer again" rest on that, with the new test below.+- Test: `tui/src/shell_context.rs` tests (next to `:1308`), `tui/tests/shell-integration.py` (Task 1)++- [ ] **Step 1: Failing Rust test** (helpers that exist in this module: `app()`, `prepare`, `bind`, `request(token, verb, query) -> Vec<u8>`, `output`, `tick`; `Request` fields `token,id,verb,query,pane,at`)++```rust+ #[tokio::test]+ async fn an_inline_request_the_shell_gave_up_on_is_dropped_and_frees_the_picker() {+ let mut app=app();+ let token=prepare(&mut app,None,false);bind(&mut app,&token,"local","shell");+ let id=uuid::Uuid::new_v4().to_string();+ app.shell_context.pending=Some(Request{token:token.clone(),id:id.clone(),pane:1,verb:"host-inline".into(),query:"Gone".into(),at:Instant::now()-Duration::from_secs(6)});+ tick(&mut app);+ assert!(app.shell_context.pending.is_none(),"an -inline request expires after 5 s");+ assert_eq!(app.shell_context.replies.back().unwrap().code,1);+ // a later request is served, not refused with "close the current picker first"+ output(&mut app,1,&request(&token,"model-inline","default"));+ assert_eq!(app.shell_context.replies.back().unwrap().code,0);+ // a young -inline request is kept, and a cancel for it frees the picker at once+ app.shell_context.pending=Some(Request{token:token.clone(),id:id.clone(),pane:1,verb:"host-inline".into(),query:"Gone".into(),at:Instant::now()});+ tick(&mut app);assert!(app.shell_context.pending.is_some());+ output(&mut app,1,format!("\x1b]633;hn;{token};{id};cancel;\x07").as_bytes());+ assert!(app.shell_context.pending.is_none());+ output(&mut app,1,&request(&token,"model-inline","default"));+ assert_eq!(app.shell_context.replies.back().unwrap().code,0);+ }+```+- [ ] **Step 2: Run** — `cd tui && cargo test --locked an_inline_request_the_shell_gave_up` → FAIL (still pending after 6 s: the limit is 100 s)+- [ ] **Step 3: Implement**+ - `shell_integration.sh:25-27`: replace `_hn_attempts=120` + the `picker-ready` line with+ ```sh+ case "$1" in+ *-inline) _hn_attempts=3 ;; # called from a line-editor widget: never block it past 3 s+ picker-ready) _hn_attempts=5 ;;+ *) _hn_attempts=120 ;;+ esac+ ```+ and replace the final `printf … 'Harness did not answer …'; exit 1` (`:47-48`) with+ ```sh+ case "$1" in+ *-inline)+ printf '\033]633;hn;%s;%s;cancel;\007' "$_HN_CONTEXT" "$_hn_id" >&4+ case "$1" in host-inline) _hn_who=$(printf '%s' "${2-}" | tr -d '[:cntrl:]');; *) _hn_who='' ;; esac+ printf '%s did not answer. Your line is unchanged; try again.\n' "${_hn_who:-Harness}" >&2 ;;+ *) printf '%s\n' 'Harness did not answer. Your shell is still available; try again.' >&2 ;;+ esac+ exit 1+ ```+ (The cancel goes out before `exit`, the same bytes as the INT trap at `:16`; the query of `model-inline`/`session-inline` is an id or route token, so only `host-inline` names the computer.) POSIX sh only; `read -t 1` and `case` already work on bash 3.2.+ - `shell_context.rs:850`: `let limit = if r.verb == "compose-launch" { 180 } else if r.verb.ends_with("-inline") { 5 } else { 100 };` and use `Duration::from_secs(limit)` in the comparison.+- [ ] **Step 4: Run** — `cd tui && cargo test --locked` (the existing `inline_cancel_and_invalid_session_return_to_the_same_shell` `:1308` and `lost_picker_timeout_and_account_change…` `:1178` — a non-inline `host` request at 110 s — must still pass), then `python3 -u tests/shell-integration.py` (the Task 1 `Gone` journey now PASSES; the existing retry test `cm default` at `:197-203` still sees its retry at 1 s).+- [ ] **Step 5: Commit** (with approval) — `git commit -am "composer: a computer that does not answer gives the prompt back in 3 s"`++### Task 3: The picker keeps drawing while it waits++**Files:**+- Modify: `tui/src/shell_picker.rs:279-298` (`Screen::draw`: paint through one helper that sets `picker.busy` while loading — without it `inline_fzf` never spins, see Architecture 3), `:487-499` (the loop: redraw every 120 ms while loading), `:517-531` (a failed list request shows its message in the status line instead of ending the picker)+- Test: `tui/src/shell_picker.rs` tests (module starts at `:668`; the inline-render tests are at `:811-845`)++- [ ] **Step 1: Failing tests**++```rust+ #[test]+ fn frames_are_due_only_while_loading() {+ let t=Instant::now();+ assert!(frame_due(true,t,t+Duration::from_millis(150)));+ assert!(!frame_due(true,t,t+Duration::from_millis(50)));+ assert!(!frame_due(false,t,t+Duration::from_secs(5)),"an idle picker draws nothing");+ assert!(is_loading(false,"") && is_loading(true,"Searching folders…") && !is_loading(true,"Office is offline"));+ }+ #[test]+ fn a_loading_inline_picker_spins_and_a_loaded_one_does_not() {+ let area=Rect::new(0,0,60,12);+ for loading in [true,false,true] {+ let mut picker=Picker::new("","");configure(&mut picker,false);+ let mut buf=Buffer::empty(area);+ theme::begin_animation_frame(true);+ paint_inline(&mut buf,area,&mut picker,loading,vec![],false);+ assert_eq!(theme::needs_animation_frame(),loading);+ assert!(picker.busy.is_none(),"the busy mark is not left on the picker");+ }+ theme::fzf_reset();+ }+```+- [ ] **Step 2: Run** — `cd tui && cargo test --locked frame_due loading_inline` → FAIL (does not compile: the helpers do not exist)+- [ ] **Step 3: Implement**+ - a) helpers next to `clean` (`:176`):+ ```rust+ fn is_loading(items_loaded:bool,status:&str)->bool { !items_loaded || status.ends_with('…') }+ fn frame_due(loading:bool,last:Instant,now:Instant)->bool { loading && now.duration_since(last)>=Duration::from_millis(120) }+ fn paint_inline(next:&mut Buffer,area:Rect,picker:&mut Picker,loading:bool,lines:Vec<Line<'static>>,bottom:bool)->Position {+ let busy=std::mem::replace(&mut picker.busy,loading.then(||"loading".to_string()));+ let at=crate::ui::inline_fzf(next,area,picker,loading,lines,bottom);+ picker.busy=busy;at+ }+ ```+ - b) `Screen::draw` (`:286`): `let loading=is_loading(items.is_some(),&picker.status);` and `let cursor=paint_inline(&mut next,area,picker,loading,lines,bottom);` (replaces the `inline_fzf` call at `:290`; the `picker.empty` handling around it stays).+ - c) loop (`:487-499`): add `let mut last_draw=Instant::now();` beside `let mut dirty=true;` and make the draw block+ ```rust+ if dirty || frame_due(is_loading(items.is_some(),&picker.status),last_draw,Instant::now()) {+ theme::begin_animation_frame(true);+ screen.draw(&mut picker,items.as_ref(),last_id.as_deref())?;dirty=false;last_draw=Instant::now();+ }+ ```+ The poll at `:517` is already `event::poll(16 ms)`, so no timeout change is needed; `render_diff` sends only the changed spinner cell. Redrawing is restricted to a visible spinner (an in-flight request with rows already shown has nothing to animate).+ - d) failed request: today `r.poll(...)?` (`:518`) ends the picker with the error on stderr (which the widget swallows). Handle it in place:+ ```rust+ let polled=r.poll(&mut screen.out);+ match polled {+ Ok(Some(mut value)) => { /* the existing body unchanged */ },+ Ok(None) => {},+ Err(e) => { // "Office is offline", "Harness did not answer", …: say it in the list, retry in 2 s+ picker.status=e.to_string();+ if items.is_none() { items=Some(Items::default()); }+ request=None;due=Instant::now()+Duration::from_secs(2);dirty=true;+ }+ }+ ```+ A status that does not end in `…` with `items` set is drawn as the empty-list message (`Screen::draw` `:290-292`), not as a spinner.+ - e) `exchange()` visible wait (`:187-193`): write one line `Starting…` to its tty handle `out` right after `Request::new`, and erase it (`\r\x1b[2K`) when the loop returns or is interrupted; Ctrl-C still cancels. (No automated test: `exchange` needs a tty; covered by the by-hand check in Task 4.)+- [ ] **Step 4: Run** — `cd tui && cargo test --locked` (the picker tests at `:811-845` still pass), then `python3 -u tests/composer-machine.py` with `HN_COMPOSER_TEST_BINARY` — the `Slow` spinner journey PASSES.+- [ ] **Step 5: Commit** (with approval) — `git commit -am "composer: the picker shows it is working while a computer answers"`++### Task 4: Gate++- [ ] `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui` — all pass (`validate-tui-native.py:47` runs `tests/shell-integration.py`); `composer-machine` now passes its zsh part on macOS (its bash 3.2 part's existing "agent catalog" failure is the separate known issue — note it in the PR, do not hide it).+- [ ] By hand in an isolated hn with two fixture computers (not the user's live harnesses): Ctrl-P on `ls `, `@`, choose the unreachable one → prompt back and a message ≤ 3 s; open folders on a slow computer → spinner turns; Enter on `claude @Slow` shows `Starting…` until it answers.diff --git a/docs/plans/2026-10-07-005-flicker-and-stale-cells-plan.md b/docs/plans/2026-10-07-005-flicker-and-stale-cells-plan.mdnew file mode 100644index 000000000..fac6165f9--- /dev/null+++ b/docs/plans/2026-10-07-005-flicker-and-stale-cells-plan.md@@ -0,0 +1,346 @@+# Flicker and stale text in every terminal — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** hn never shows a blank flash when it repaints the whole screen, and text a terminal kept wrongly is written over shortly after the change that left it, not only after a scroll, focus or resize.++**Architecture:** Two separate causes.+1. **Flicker (hn's bug, confirmed in code).** A full repaint (`app.redraw_all`) calls `term.clear()` at `main.rs:597` *before* the frame is due; `TmuxBackend::clear_region(All)` (`term_out.rs:623-631`) writes `\e[2J` straight to the terminal outside a synchronized update (`?2026h … ?2026l` is only opened by the next frame, `term_out.rs:569`), and the frame may wait up to the frame budget (~6 ms). The terminal shows a blank screen in between. Captured bytes: `…\e[?2026l\e[2J\e[1;1H\e[?2026h…`. Triggers: every focus-in (`input.rs:45`), resize (`input.rs:42`), Ctrl-L in lists (`input.rs:2359`), `close_popup` (`app.rs:2369`), every `set`/`source-file` (`app.rs:2395`), `swap_tabs` (`app.rs:2526`), Settings (`app.rs:5530/5532`), sign-out (`app.rs:5681`), the clock (`input.rs:197`).+ Fix: a full repaint is a **soft** clear (rows erased and rewritten inside the frame's synchronized update, as #601 did for the wheel) unless the size changed; a hard clear, when needed, opens the synchronized update first and happens in the same pass as the draw.+2. **Stale text (Ghostty 1.3.1, the user's version).** hn's bytes are correct: an isolated replay with `HARNESS_TUI_VERIFY` found 0 differing cells and balanced `?2026` pairs (211/211). Ghostty has an open report of exactly this pattern — synchronized output plus small cursor-positioned updates with colour changes progressively corrupting the screen; a full rewrite or resize clears it ([ghostty discussion #12062](https://github.com/ghostty-org/ghostty/discussions/12062)). #592 (lingrd) already rewrites the screen after the wheel rests, on focus and on resize; it does not cover a modal closing or shrinking (command panel, New Harness list, Close Tab), the status/side bar changing, or bursts of pane output.+ Fix: generalise #592's settle repaint: any frame that removed an overlay, or wrote many cells one by one, schedules one soft full repaint ~250 ms after things go quiet.++**Tech Stack:** Rust (`term_out.rs` backend over crossterm/ratatui), `tests/repaint.py`.++**Spec:** user report 2026-10-07: "lâu lâu tôi thấy cái TUI bị chớp, cần bôi đen để clean nó là bình thường, trước đó version cũ tôi nhớ có fix rồi" — the earlier fix is #592/#601 (lingrd), still on main and unchanged.++## Every terminal, not only Ghostty++Every fix here is terminal-neutral: nothing reads the terminal's name, and each one only changes *how* hn writes the same picture.++| Terminal | Synchronized output (?2026) | What these fixes give it |+|---|---|---|+| Ghostty, iTerm2, WezTerm, kitty, foot, Warp, VS Code / Cursor terminal | yes | the clear and the redraw shown together (no blank flash); the settle rewrite clears anything kept wrongly |+| Terminal.app, Alacritty, xterm, an old outer tmux | no (the sequence is ignored) | the soft repaint never erases the whole screen, so no blank flash even without ?2026; the settle rewrite still clears kept cells |+| Over ssh / inside another tmux | as the outer terminal | same as above; bytes per frame do not grow (one rewrite per burst, none while idle) |++Task 4's fixture asserts the byte stream, which is the same for every terminal. Task 5 checks by hand on the terminals installed on the author's Mac (Ghostty, Terminal.app, Warp, Cursor's terminal) and with `HARNESS_TUI_SYNC=off` (a terminal without ?2026).++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **A list shrinking inside an open panel** must also owe the settle rewrite: `settle_due` compares the **area (Rect) of the overlay drawn in the previous frame with this frame's** (`Option<Rect>`, taken from what the frame drew: `picker.screen_area`, the menu box, the New Harness form/chooser rects), not a bool. Owed when the overlay is gone, or its rect shrank / moved. Test: a picker whose rows drop from 10 to 2 owes one settle rewrite.+2. **One cursor placement per frame (Task 3b) is accepted** even though it raises `plain_echo_keeps_the_printed_cursor_and_needs_few_bytes`' bound (`term_out.rs:730`) from 7 to 13 bytes: correct placement after an input method moved the cursor matters more than 6 bytes per frame.++## Global Constraints++- No terminal-specific branch: no `terminal_name()` / `TERM_PROGRAM` checks in these fixes.++- An idle hn writes nothing (`term_out.rs`: a frame that changes nothing is not written) — the settle repaint runs once per burst, never on a timer while idle.+- `HARNESS_TUI_SYNC=off` keeps working (no synchronized update at all).+- The soft clear must still erase empty rows (`term_out.rs:584-586`: "a row of a soft clear with nothing on it is still erased").+- No change to what is drawn — only how it is written.++## Review Focus++- A real size change must still hard-clear (the terminal reflowed its own cells; a soft rewrite of the old size would leave text outside the new rows).+- Two full repaints requested in one loop pass write one repaint, not two.+- The settle repaint must not fire while the user is dragging a selection in copy mode (it would not break it, but must not reset `copy_top` / selection state — it is a write-only operation; verify).+- Wide characters at the right edge after a soft repaint (the row is erased first with `\e[2K`).+- `HARNESS_TUI_SYNC=off`: the hard clear path writes `\e[2J` without `?2026h`.++---++## Facts the tasks rely on (checked against the code, 2026-10-07, origin/main 91fee170b)++- `ratatui` is 0.30.2 (`ratatui-core` 0.1.2). `Terminal::clear()` on a fullscreen viewport calls `backend.clear_region(ClearType::All)`, never `Backend::clear()`; it also calls `get_cursor_position()` (hn's backend answers `ORIGIN`, `term_out.rs:612`) and then `set_cursor_position(ORIGIN)`, which writes `\e[1;1H` whenever `cursor_at` is `None` (that is the `\e[2J\e[1;1H` in the captured bytes).+- `Terminal::draw` first calls `autoresize()`: if the backend's size differs from the last known area it calls `resize()`, which calls `clear_region(All)` (once, and a second time on a width shrink) and resets the back buffer. That clear happens *inside* `term.draw`, before `TmuxBackend::draw` runs, so it is also outside any `?2026h` today. Task 1's `begin_sync` in `clear_region` covers it. Because of it, a real size change needs no explicit `term.clear()` from `main.rs`.+- `ratatui::Terminal::new(TmuxBackend<Vec<u8>>)` is not usable in unit tests: `Terminal::new` asks the backend for its size, which goes to `crossterm::terminal::size()` (the real `/dev/tty`; it fails without a tty and returns the developer's window size in a terminal). Every existing `term_out.rs` test therefore drives the backend directly: `TmuxBackend::with_sync(&mut written)` (private, `term_out.rs:172`, available to the module's tests), `backend.draw(iter of (x, y, &Cell))`, `Backend::flush(&mut backend)` (the trait call; `flush()` alone is `Write::flush` and does not close `?2026`), `Backend::clear_region(&mut backend, ClearType::All)`, `backend.sync_ok = false`, then `drop(backend)` and read `written`. `Cell::default()` with `set_char`. A pane replay is `crate::pane::Pane::new(1, "m", "a", cols, rows)` + `pane.feed(&written)`. The tests below use only these.+- `main.rs` is a single loop; `need_draw` and `last_draw` are locals declared at `main.rs:503-506`; the draw block is `main.rs:599-628`. `redraw_all` is a field consumed (`mem::take`) in the pass that sees it, *before* the frame-budget check, so today a deferred frame loses its repaint request (it is not lost only because the clear already happened).++---++### Task 1: A hard clear inside the frame's synchronized update, in the same pass++**Files:**+- Modify: `tui/src/term_out.rs:622-632` (`clear`'s sibling `clear_region`, ~`:623-631`), frame writer line `:569`; `tui/src/main.rs:420` (startup clear) and the loop at `:595-599`+- Test: `tui/src/term_out.rs` tests (module `tests`, starts `:645`; next to `:664-691`)++**Interfaces:**+- Produces: `TmuxBackend::begin_sync(&mut self) -> io::Result<()>` (opens `?2026h` once, sets `syncing`) used by `clear_region` (both its hard and its soft branch) and by the frame writer at `:569`.+- Produces in `main.rs`: a local `repaint_due: bool` (declared next to `need_draw`) that carries a repaint request from the pass that sees it to the pass that draws.++- [ ] **Step 1: Failing tests** (in `term_out.rs`'s `mod tests`; no `ratatui::Terminal`, see Facts)++```rust+fn two_cells(backend: &mut TmuxBackend<&mut Vec<u8>>) {+ let (mut a, mut b) = (Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+}++#[test]+fn a_hard_clear_is_inside_the_frames_synchronized_update() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ // What `Terminal::clear` asks of the backend, then the frame that follows it.+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ let clear = s.find("\x1b[2J").expect("a hard clear");+ let open = s[..clear].rfind("\x1b[?2026h").expect("opened before the clear");+ assert!(s[..clear].rfind("\x1b[?2026l").map_or(true, |close| close < open), "no close between open and clear: {s:?}");+ assert!(s[clear..].contains("\x1b[?2026l"), "closed after the redraw: {s:?}");+ assert_eq!(s.matches("\x1b[?2026h").count(), s.matches("\x1b[?2026l").count(), "balanced: {s:?}");+ assert_eq!(s[clear..].matches("\x1b[?2026h").count(), 0, "the frame joins the clear's update, it does not open another: {s:?}");+}++#[test]+fn a_hard_clear_without_synchronized_output_writes_no_2026() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.sync_ok = false;+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(s.contains("\x1b[2J") && !s.contains("2026"), "{s:?}");+}+```+(Do not run these through `ratatui::Terminal`; its size query needs a real tty. The `main.rs` side, `repaint_due`, has no unit test of its own: Task 4's byte-stream journey covers it.)++- [ ] **Step 2: Run** — `cd tui && cargo test --locked a_hard_clear` → FAIL (`\e[2J` is written with no `?2026h` before it).+- [ ] **Step 3: Implement**++```rust+fn begin_sync(&mut self) -> io::Result<()> {+ if self.sync_ok && !self.syncing { self.inner.write_all(b"\x1b[?2026h")?; self.syncing = true }+ Ok(())+}+```+`clear_region(ClearType::All)` calls `self.begin_sync()?` first, before the soft/hard branch (so the soft path's `\e[1;1H` from `Terminal::clear`'s `set_cursor_position` is inside the update too; the draw that follows always has cells, so the update would have been opened anyway). The frame writer's `:569` line becomes `if cells.len() > 1 || !whole.is_empty() { self.begin_sync()? }`. The update is closed by `Backend::flush`, which `Terminal::draw` always calls, so every `clear_region` must be followed by a draw in the same pass (below). Two callers are not: `main.rs:420` (startup) must end `term.clear()?;` with `ratatui::backend::Backend::flush(term.backend_mut())?;` (full path: with `std::io::Write` in scope, `.flush()` would be `Write::flush`, which does not close `?2026`); the suspend path (`main.rs:582`) builds a fresh `Terminal` and does not clear, so it needs nothing.++In `main.rs`, the repaint request survives until the pass that draws, and the clear moves into the draw pass:++```rust+// beside `let mut need_draw = true;` (main.rs:505)+let mut repaint_due = false;+// ... in the loop, replacing main.rs:595-598:+let settle = app::scroll_settle_in(app.scrolled_at, Instant::now()) == Some(Duration::ZERO);+if settle { app.scrolled_at = None }+// Two requests in one pass (or a request that waited for the frame budget) are one repaint.+if std::mem::take(&mut app.redraw_all) || settle { repaint_due = true; need_draw = true }+if need_draw && last_draw.elapsed() >= frame_budget {+ let repaint = std::mem::take(&mut repaint_due);+ if repaint && !size_changed { // Task 2: size_changed is computed here+ term.backend_mut().soft_clear_next();+ term.clear()?;+ }+ ... the existing draw ...+}+```+A `redraw_all` that is set while `ui::draw` runs is picked up by the next pass, as today.+- [ ] **Step 4: Run** — `cargo test --locked term_out` → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: a full repaint's clear is in the same synchronized update as its frame"`++### Task 2: Full repaints are soft unless the size changed++**Files:**+- Modify: `tui/src/main.rs` (`let mut drawn_size = term.size()?;` after the startup `term.clear()` at `:420`; compute `size_changed` in the draw block; update `drawn_size` after `term.draw`), `tui/src/term_out.rs` (the pure decision fn)+- Unchanged: `tui/src/input.rs:42` (Resize keeps setting `redraw_all`)+- Test: `tui/src/term_out.rs` tests++**Decision fn** (`term_out.rs`, `pub fn repaint_is_soft(drawn: Size, now: Size) -> bool { drawn == now }`, `ratatui::layout::Size`).++- [ ] **Step 1: Failing tests**++```rust+#[test]+fn a_repaint_is_soft_unless_the_size_changed() {+ use ratatui::layout::Size;+ assert!(repaint_is_soft(Size::new(80, 24), Size::new(80, 24)));+ assert!(!repaint_is_soft(Size::new(80, 24), Size::new(100, 24)));+ assert!(!repaint_is_soft(Size::new(80, 24), Size::new(80, 20)));+}++#[test]+fn a_soft_clear_erases_each_row_once_inside_one_update_and_never_the_screen() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let mut cells = Vec::new();+ for y in 0..3u16 { let mut c = Cell::default(); c.set_char('x'); cells.push((0u16, y, c)) }+ backend.draw(cells.iter().map(|(x, y, c)| (*x, *y, c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ backend.draw(cells.iter().map(|(x, y, c)| (*x, *y, c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(!s.contains("\x1b[2J"), "{s:?}");+ // (the size query fails or answers for the developer's own window here, so: at least the three rows drawn)+ assert!(s.matches("\x1b[2K").count() >= 3, "{s:?}");+ assert_eq!(s.matches("\x1b[?2026h").count(), 2, "one update per frame: {s:?}");+ assert_eq!(s.matches("\x1b[?2026l").count(), 2, "{s:?}");+}+```+(The soft clear's existing test `a_soft_clear_writes_every_row_over_the_screen_without_erasing_it`, `:665`, already covers the replay on a stale cell; keep it unchanged. A size change cannot be faked through the backend: it comes from ratatui's `autoresize`, which Task 4's fixture covers by resizing the outer window.)+- [ ] **Step 2: Run** — `cargo test --locked repaint_is_soft` → FAIL (does not compile: no such fn)+- [ ] **Step 3: Implement** — in the draw block: `let size_changed = !term_out::repaint_is_soft(drawn_size, term.size()?);` before the `if repaint && !size_changed` of Task 1; after `term.draw(..)`: `drawn_size = term.size()?;` (ratatui already asks for the size on every draw, so this adds no new cost class). When `size_changed`, `main.rs` does *not* call `term.clear()`: `Terminal::draw`'s own `autoresize` hard-clears and resets the back buffer, and with Task 1's `begin_sync` that clear is inside the frame's update (an explicit second clear would only write a second `\e[2J`). `soft_clear_next()` must not be armed in that case (it would turn the autoresize clear soft and leave text outside the new rows).+- [ ] **Step 4: Run** — `cargo test --locked term_out && cargo check --locked` → PASS (the full `cargo test --locked` is Task 4's gate)+- [ ] **Step 5: Commit** — `git commit -am "hn: a repaint without a size change rewrites rows instead of erasing the screen"`++### Task 3: One settle repaint after any overlay closes or a burst of cell updates++**Files:**+- Modify: `tui/src/app.rs:100-106` (keep `SCROLL_SETTLE` and `scroll_settle_in`; add `SETTLE_CELLS: usize = 400` and `pub fn settle_due(..)` next to them; the field stays `scrolled_at` (`app.rs:497`), its meaning widened in its doc comment: "when the next settle repaint was last owed"), `tui/src/term_out.rs` (field `last_cells: usize`, set in `draw`; `pub fn last_cells(&self) -> usize`; the constructor `:172` gains `last_cells: 0`), `tui/src/main.rs:508-` (loop locals and the post-draw block)+- No rename: the plan's earlier `settle_in` / `settle_at` rename only touches `app.rs:104-105`, `:497`, `:1008`, `input.rs:36`, `main.rs:518,595-596` and the test `:6536-6547` for no behaviour; it is dropped to keep this task's footprint small.+- Test: `tui/src/app.rs` (`mod scroll_settle_tests`, `:6533`; the existing `the_screen_is_written_whole_once_the_wheel_has_rested` at `:6536` stays unchanged), `tui/src/term_out.rs` (`last_cells`)++**Design (fits the real loop):**+- `overlay_now = app.modal.is_some() || app.toast.is_some()` (`app.rs:472-473`) is read right after `term.draw`; `overlay_before` is a loop local holding the last frame's value (`let mut overlay_before = false;` beside `need_draw`).+- `last_cells()` is `cells.len()` of the frame, after the extras merge and before the `cells.is_empty() && !all` early return (`term_out.rs:552`); the early return leaves it 0 (set `self.last_cells = 0` before returning).+- A frame that was itself a repaint writes the whole screen cell by cell, which is over `SETTLE_CELLS`: it must count as 0, or every settle repaint would owe another one and an idle hn would repaint every 250 ms forever. The post-draw code therefore passes `0` for a frame whose `repaint` flag (Task 1) was set.+- A picker list that shrinks while the same modal stays open is *not* an "overlay gone" in this test (`Option<Modal>` is `Some` before and after); it is covered only when that frame wrote more than `SETTLE_CELLS` cells. (If the New Harness list must be covered even for a small shrink, `settle_due` would need the modal's rectangle area instead of a bool; that is a design choice for the owner, not made here.)++- [ ] **Step 1: Failing tests** (in `app.rs` `mod scroll_settle_tests`, which has `use super::*;`)++```rust+#[test]+fn a_closed_overlay_or_a_large_cell_by_cell_frame_owes_one_settle_repaint() {+ let t0 = Instant::now();+ assert_eq!(settle_due(false, true, 10, None, t0), Some(t0), "an overlay closed");+ assert_eq!(settle_due(true, true, 10, None, t0), None, "still open");+ assert_eq!(settle_due(false, false, SETTLE_CELLS + 1, None, t0), Some(t0), "many cells one by one");+ assert_eq!(settle_due(false, false, 3, None, t0), None, "a key echo");+ let earlier = t0 - Duration::from_millis(100);+ assert_eq!(settle_due(false, true, 10, Some(earlier), t0), Some(t0), "a new burst pushes it later");+ assert_eq!(settle_due(false, false, 3, Some(earlier), t0), Some(earlier), "a quiet frame leaves what is owed as it was");+}+```+`pub fn settle_due(overlay_now: bool, overlay_before: bool, cells: usize, owed_since: Option<Instant>, now: Instant) -> Option<Instant>`: `Some(now)` when `(overlay_before && !overlay_now) || cells > SETTLE_CELLS`, else `owed_since`.++`term_out.rs` test for `last_cells` (direct backend, as in Task 1): draw three cells → `backend.last_cells() == 3`; draw an unchanged frame (no cells) → `0`.+- [ ] **Step 2: Run** — `cargo test --locked settle_due` → FAIL (does not compile)+- [ ] **Step 3: Implement** — after `let done = term.draw(..)?;` (`main.rs:~607`) and `drawn_size = ..` (Task 2):++```rust+let overlay_now = app.modal.is_some() || app.toast.is_some();+let cells = if repaint { 0 } else { term.backend().last_cells() };+app.scrolled_at = app::settle_due(overlay_now, overlay_before, cells, app.scrolled_at, Instant::now());+overlay_before = overlay_now;+```+The existing settle branch (`scroll_settle_in(app.scrolled_at, ..) == Some(ZERO)` → `repaint_due`, Task 1) and the `wait.min(d)` at `main.rs:518` are unchanged: an owed settle already shortens the loop's wait, and `scrolled_at = None` is set when it fires, so a settle repaint runs once per burst and an idle hn owes nothing.+- [ ] **Step 4: Run** — `cargo test --locked settle && cargo test --locked term_out` → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: one quiet rewrite after an overlay closes or a large update, as after a scroll"`++### Task 3b: Never trust where the terminal's cursor was left between frames++**Why:** the writer keeps the cursor position across frames and skips the cursor move when it thinks the cursor is already there (`term_out.rs:575-582` and `set_cursor_position` `:614-621`; comment "an ordinary echoed key needs neither a CUP before it nor one after it"). Anything that moves the terminal's cursor outside hn — an input method composing text (the user types Vietnamese with an IME), a terminal's own overlay, a stray write — makes the next cells land in the wrong place until that area is rewritten, which is exactly what a mouse selection does. Terminal-neutral.++**Files:** Modify `tui/src/term_out.rs` (`Backend::draw`); Test: `tui/src/term_out.rs` tests.++- [ ] **Step 1: Failing test**++```rust+#[test]+fn each_frame_places_the_cursor_itself() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let (mut a, mut b, mut c) = (Cell::default(), Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b'); c.set_char('c');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // The next frame changes only the cell right after the cursor hn left (column 2).+ backend.draw(std::iter::once((2u16, 0u16, &c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(s.contains("\x1b[1;3H"), "the second frame moved the cursor first: {s:?}");+}+```+(Today the second frame has no `\e[1;3H`: `cursor_at` is already `(2, 0)`.)+- [ ] **Step 2: Run** — `cargo test --locked each_frame_places` → FAIL+- [ ] **Step 3: Implement** — in `Backend::draw`, immediately *after* the `if cells.is_empty() && !all { return Ok(()) }` early return (`term_out.rs:554`), set `self.cursor_at = None;`. Not at the top of `draw`: an idle frame must stay silent (ratatui calls `draw`, then `set_cursor_position`, every frame; clearing `cursor_at` before the early return would make every idle frame write a CUP — contradicting the Global Constraint "idle writes nothing"). One CUP per frame that writes cells, a few bytes; the skipping of CUPs *within* a frame stays.+- [ ] **Step 4: Run** — `cargo test --locked term_out` → the existing `plain_echo_keeps_the_printed_cursor_and_needs_few_bytes` (`term_out.rs:730`) now fails: it allows 7 bytes for one echoed key, and the echo's frame writes a 6-byte CUP of its own on top of the 6-byte one from `set_cursor_position(2, 1)` in the test. Update that test's expectation, not its intent: change `<= 7` to `<= 13` and its message to "one echoed key wrote {} bytes: its initial cursor, the frame's own CUP and the char" (keep its replay assertions). Search `term_out.rs` tests for other CUP-less assertions (`grep -n "echo" tui/src/term_out.rs`: only this one). Also re-run `cargo test --locked` once at Task 4's gate (the `pane`/`ui` tests replay frames).+- [ ] **Step 5: Commit** — `git commit -am "hn: each frame places the cursor itself, whatever moved it in between"`++### Task 3c: The shell picker's own renderer++**Files:** Modify `tui/src/term_out.rs:44` (`fn risky` becomes `pub(crate) fn risky`), `tui/src/shell_picker.rs:300-309` (`render_diff`); Test: `tui/src/shell_picker.rs` tests (next to `repainting_the_same_frame_does_not_erase_or_retransmit_the_list`, `:826`).++The picker writes through ratatui's plain `CrosstermBackend` (`render_diff`), not `TmuxBackend`, so the writer's risky-row rule does not apply to the inline composer. Rewrite a row whole when it holds a risky symbol, with the same `term_out::risky` rule, so the inline composer gets #592's protection too.++- [ ] **Step 1: Failing test**++```rust+#[test]+fn a_row_with_a_risky_symbol_is_erased_and_written_whole() {+ let area = Rect::new(0, 4, 20, 3);+ let mut first = Buffer::empty(area);+ first.set_string(0, 4, "plain", Style::default());+ first.set_string(0, 5, "go ⚡ now", Style::default());+ let mut next = first.clone();+ next.set_string(8, 5, "x", Style::default()); // a one-cell change on the risky row+ next.set_string(8, 4, "y", Style::default()); // and on a plain row+ let bytes = render_diff(Some(&first), &next, Position::new(0, 4)).unwrap();+ let s = String::from_utf8_lossy(&bytes);+ assert_eq!(s.matches("\x1b[2K").count(), 1, "only the risky row is erased: {s:?}");+ assert!(s.contains("\x1b[6;1H\x1b[2K"), "row 5 (screen row 6) is erased from its first column: {s:?}");+}+```+(`Style`, `Position`, `Buffer`, `Rect` are the imports the neighbouring tests use; add `use ratatui::style::Style;` in the test if the module lacks it. The existing test at `:826` asserts a plain navigation writes no `\e[2K`; it must keep passing: its rows hold no risky symbol.)+- [ ] **Step 2: Run** — `cargo test --locked a_row_with_a_risky_symbol` → FAIL+- [ ] **Step 3: Implement** — in `render_diff`: `let cells = previous.diff(next);` collect `risky_rows: BTreeSet<u16>` = the rows `y` of those cells for which any cell of `previous` or `next` in row `y` (x over `area.x..area.right()`) satisfies `term_out::risky(cell.symbol())`. Draw `cells` whose `y` is not in `risky_rows` as today. Then for each risky row write `\x1b[{y+1};1H\x1b[2K` and draw that row of `Buffer::empty(next.area).diff(next)` (the non-blank cells of the row; the erase already blanked the rest). The picker's rectangle starts at column 0 and spans the terminal width (`Rect::new(0, top, cols, height)`, `shell_picker.rs:264`), so `\e[2K` stays inside it. Everything stays between the `?2026h` and `?2026l` the function already writes.+- [ ] **Step 4: Run** — `cargo test --locked shell_picker` → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: the inline composer rewrites rows that hold risky symbols whole"`++### Task 4: The byte-stream fixture++**Files:**+- Modify: `tui/tests/repaint.py` (it already starts hn inside an outer tmux session `view` against `mock-daemon.mjs`, with helpers `outer()`, `hn()`, `wait()`, `screen()`; add a journey in the same file)++- [ ] **Step 1: Add the journey** — capture what hn writes with the outer tmux's `pipe-pane`, not `script`: after `started = True`, `outer('pipe-pane', '-t', 'view', f'cat >> {BASE}/raw.bin')` (the program's raw output, `?2026` included), and start hn with `HARNESS_TUI_VERIFY={BASE}/verify.log` added to `ENV`. Drive it with `outer('send-keys', ...)`: focus-in as `send-keys -H 1b 5b 49`, a resize with `outer('resize-window', '-t', 'view', '-x', '100', '-y', '30')` and back, Ctrl-L in a picker, command panel open/close, New Harness open/type/20×Backspace/close. Assert on `raw.bin`: `?2026h`/`?2026l` balanced and never nested; every `\x1b[2J` is between an open and its close; after the command panel closes, within 400 ms, one soft repaint (a `\x1b[2K` for every row) is written; `verify.log` has no line matching `=== .* [1-9][0-9]* cells differ` (a requested dump writes a `=== … 0 cells differ` header, which is fine). `scratchpad/stale.py` is outside the repo (the investigation's setup); the journey does not depend on it.+- [ ] **Step 2: Run** — `cd tui && python3 tests/repaint.py` (needs `cargo build --release --locked` first: it copies `tui/target/release/harness-tui`) → FAIL before Tasks 1-3 (`\x1b[2J` outside), PASS after.+- [ ] **Step 3: Full gate** — `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui`+- [ ] **Step 4: Commit** — `git commit -am "hn: repaint fixture checks synchronized clears and the settle rewrite"`++### Task 5: Check by hand on every terminal at hand++- [ ] With the build in an isolated hn (mock daemon, own sockets), in each of Ghostty, Terminal.app, Warp and Cursor's terminal, and once with `HARNESS_TUI_SYNC=off` in Ghostty: switch away and back (focus), resize, open and close the command panel, type and delete in New Harness, close a tab via Close Tab, scroll a pane. No blank flash; no text left after a panel closes (wait ½ s for the settle rewrite).+- [ ] Then the user's own hn, run for normal work with `HARNESS_TUI_VERIFY=/tmp/hn-verify.log`. If stale text still appears anywhere: a selection starting writes a dump (`main.rs:602-606`, `dump_now("a selection started")`); "0 cells differ" means the terminal drew correct bytes wrongly — shorten the settle delay or widen what triggers it (still terminal-neutral), and report it to that terminal's project with the captured bytes.++## Conflicts between the tasks++| Pair / task | Shared file or interface | Resolution |+|---|---|---|+| 1 and 2 | `main.rs` draw block, `clear_region` | 1 owns `repaint_due` and the soft/clear call; 2 only supplies `size_changed`. Land 1, then 2 (2's `if repaint && !size_changed` is written in 1's snippet). |+| 1 and 3 | `main.rs` settle lines, `scrolled_at` | 3 reads the `repaint` flag that 1 introduces (a repaint frame counts 0 cells); 3 depends on 1. |+| 1 and 3b | `term_out.rs` `draw`, `cursor_at` | independent code, same function: 3b's reset goes after the early return; 1's `begin_sync` is the `:569` line. Order free. |+| 2 and 3 | `main.rs` post-draw block | both add one statement after `term.draw`; 2: `drawn_size`, 3: `settle_due`. Order free. |+| 3b and the echo contract | test `plain_echo_keeps_the_printed_cursor_and_needs_few_bytes` | 3b makes it fail by design; Step 4 raises its byte bound (the extra CUP per cell-writing frame is the plan's stated cost: "one CUP per frame, a few bytes"). |+| 3c and 1-3b | `term_out.rs` | 3c only changes `fn risky` visibility. No conflict. |+| 4 | the whole stream | needs 1-3 built; asserts nothing 3b/3c-specific. |++| Task | Do its tests match its code? |+|---|---|+| 1 | yes: backend-level tests (no `ratatui::Terminal`); main.rs part covered by 4 |+| 2 | yes: pure-fn test plus a three-row soft clear; resize path covered by 4 |+| 3 | yes: `settle_due` and `last_cells` tests; loop wiring covered by 4 |+| 3b | yes after Step 4's change to the one echo test |+| 3c | yes |+| 4 | yes: uses the file's existing outer-tmux harness |++Global Constraints check: nothing reads a terminal's name; idle writes nothing (3b's reset is after the early return, repaint frames count 0 cells in 3, the settle fires once per burst); `HARNESS_TUI_SYNC=off` keeps `begin_sync` a no-op (second test in Task 1); soft clear still erases empty rows (untouched code, `term_out.rs:584-586`).++## Overlaps with other plans of 2026-10-07 (not edited here)++- 003 (confirm dialog): `ui.rs` (`menu`, `:304-350`) and a `mod` line in `main.rs`. This plan touches `main.rs`'s loop and not `ui.rs`; no code overlap.+- 004 (shell composer freeze): `shell_picker.rs` loop `:480-500` and `:612-627`; this plan's Task 3c edits `render_diff` `:300-309` and tests near `:826`. Same file, different regions; the tests region `:819-840` is shared (add, do not reorder).+- 006 (pane drag and drop): `ui.rs:231-232`, a `mod` line in `main.rs`, and it sets `app.redraw_all = true` on release (relies on this plan for stale-cell safety; with Task 1 that is a soft repaint, which is what it needs).+- 007 (composer dropdown): `shell_picker.rs` (`:653-662`) and `ui.rs` `inline_fzf`; `render_diff` draws what `inline_fzf` produces: 3c's risky-row rule applies to the new dropdown rows unchanged.+- 008: no overlap found.diff --git a/docs/plans/2026-10-07-006-pane-drag-and-drop-plan.md b/docs/plans/2026-10-07-006-pane-drag-and-drop-plan.mdnew file mode 100644index 000000000..f960c0680--- /dev/null+++ b/docs/plans/2026-10-07-006-pane-drag-and-drop-plan.md@@ -0,0 +1,460 @@+# Drag panes with the mouse — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** In hn, drag a pane by its title and drop it on another pane (swap it, or put it left / right / above / below that pane) or on a tab in the status bar or side bar (move it into that window).++**Architecture:** A new drag kind `Drag::Pane` in `mouse.rs` starts only from a pane's title (never the pane body, so text selection and programs' own mouse use are untouched). While it moves, a pure function `drop_target` turns the pointer into a `Drop` (swap / side / tab / nothing); the frame draws that drop's zone over the windows. On release the drop runs as the existing tmux commands (`swap-pane`, `join-pane`), so layouts, the desk and every other client follow through the paths they already use.++**Tech Stack:** Rust (ratatui), the tmux-compatible command layer (`commands.rs`), Python native fixtures.++**Spec:** user request 2026-10-07: "tôi muốn kéo thả pane qua lại được trong terminal luôn" (drag panes back and forth in the terminal). Investigation notes: there is no drag-and-drop code today; header hit boxes, `Drag`, `swap_panes`, `join_pane`, `break_pane` and desk publishing exist.++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **Build after plan 005 has merged**, so the `redraw_all` set on release is 005's soft repaint (no flash).+2. **Side-bar machine headings are not drop targets** in this version (only `Hit::Window` rows and status-bar tabs); a drop there does nothing.+3. **The line look:** dragging the pane's name moves the pane; dragging the rest of the title line resizes, as before. The two existing tests that pressed on the name to resize (`plain_pane_titles_keep_divider_drag_behavior`, `title_drag_journey`) press on the line part instead — that is the agreed change, not a regression.+4. Tests that assume status-bar tab ranges or an accent different from the background: the implementer asserts those preconditions explicitly at the start of the test (fail loudly, never skip).++## Global Constraints++- tmux's mouse bindings keep their meaning: `MouseDrag1Pane` (copy-mode selection / programs' mouse), `MouseDrag1Border resize-pane -M`, `MouseDown1Status select-window`. A user's own binding of `MouseDown1Pane/Border`, a modifier, the prefix, a key table, `tmux_look`, read-only and headless all turn the feature off, as they turn off the header controls today (`workspace_controls.rs:33, 132-148`).+- In the line look the title is the divider: dragging the divider line still resizes (`tests/workspace-controls.py` "plain title divider drags retain tmux resize behavior", `workspace_controls.rs:432`). A pane drag starts only from the title's **text** (the pane name), never from the line.+- A press and release without moving at least 2 cells is a click (selects the pane), as today.+- Every drop goes through `swap-pane` / `join-pane` so `layout_changed` → desk `tab.layout` + `pane.move` publish it (`app.rs:4893, 4914`).+- Colours from the theme (`theme::accent()`, `pane_palette()`), no fixed colours.++## Decisions (defaults; confirm with the user before Task 1)++| Question | Default |+|---|---|+| Where a drag starts | Pane title text (box / surface looks: the whole header row; line look: the name span only) |+| Drop on a pane | Outer 25% band on a side → put it on that side (`join-pane -h/-v [-b]`); the middle → swap (`swap-pane`) |+| Drop on a tab (status bar or side bar) | Move into that window beside its active pane (`join-pane -t :N`) |+| Drop on itself, nothing, or Escape | Nothing happens |+| A window with one pane dragged out | Its window closes, as `join-pane` does in tmux |+| Zoomed window | No drag starts while zoomed |+| Too small to split | The drop is refused with the command's message (`create pane failed: pane too small`), nothing moves |+| Undo | None (the same drag back undoes it); no confirmation |++## Review Focus++- A drag that starts on the header and ends inside the same pane's body must not run anything nor send input to the program.+- A drop while another client changes the layout (desk `pane.move` arriving mid-drag): the source or target may be gone — the drop re-checks both ids at release and does nothing if either is gone.+- Copy-mode drag selection inside a pane still selects text (start inside the body).+- A right-button drag or a drag with a modifier is never a pane drag.+- The overlay must be cleared after the drop (the frame after release has no zone; `redraw_all` once).++---++### Task 1: Drop targets (pure function)++**Files:**+- Create: `tui/src/pane_drag.rs` (module `pane_drag`; add `mod pane_drag;` in `tui/src/main.rs` after `mod pane_frame;` at :58)+- Modify: `tui/src/workspace_controls.rs:307` (`mod tests` → `pub(crate) mod tests`), `:344` (`fn app` → `pub(crate) fn app`), `:371` (`fn render` → `pub(crate) fn render`), so `pane_drag` tests reuse the real fixture instead of inventing one+- Test: `tui/src/pane_drag.rs` tests module++**Real pieces this uses** (all exist): `app.rects: Vec<(u64, Rect)>` (`app.rs:518`, screen coordinates of each pane of the current window); `app.bar.hits: Vec<(Rect, bar::Hit)>` and `bar::hit_at(app, x, y) -> Option<Hit>` (`bar.rs:473`; **side bar only**, it holds `Hit::Window(i)`); `app.status_ranges: Vec<(u16, draw::Range)>` with `RangeKind::Window(number)` for the status-bar tabs (`app.rs:586`; the screen row is `top + row`, `top = if app.status_top { 0 } else { app.size.1 - app.status_lines() }`, as `workspace_controls.rs:166` computes it for a right-click); `app.tab_by_num(n)` / `app.win_num(i)` (`app.rs:3740-3742`); `app.bar_side()`.++**Interfaces:**+- Produces:+```rust+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Side { Left, Right, Top, Bottom }+/// A tab is named by its id (`Tab.id`), not its index: a desk update mid-drag can renumber the tabs.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Drop { Swap(u64), Beside(u64, Side), Tab(String), Nothing }+/// [x, y] over the screen while pane [src] is dragged: what releasing there does.+pub fn drop_target(app: &App, src: u64, x: u16, y: u16) -> Drop+/// The cells that show [drop]: the zone of the target pane (a side half or the whole pane) or the tab's cells.+pub fn zone(app: &App, drop: &Drop) -> Option<ratatui::layout::Rect>+/// The cells of tab [i] in the side bar, else its status-bar range.+pub fn tab_cell(app: &App, i: usize) -> Option<ratatui::layout::Rect>+```++- [ ] **Step 0: Share the fixture.** In `tui/src/workspace_controls.rs` make `mod tests`, `fn app(width)` and `fn render(app)` `pub(crate)` (three one-word edits; `app(width)` builds two tabs `work-1` / `work-2`, each with one live pane, ids 1 and 2, `mouse = true`, 32 rows; to put both panes in one window, do what `plain_pane_titles_keep_divider_drag_behavior` does: `app.tabs.truncate(1)`, `root.split(1, 2, Dir::…)`, `fit_panes()`, `render`).++- [ ] **Step 1: Write the failing tests** (`tui/src/pane_drag.rs`, bottom of file)++```rust+#[cfg(test)]+mod tests {+ use super::*;+ use crate::layout::Dir;+ use crate::workspace_controls::tests::{app, render};++ /// Panes 1 | 2 side by side in one window (pane 2's own window is gone).+ fn two() -> App {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, Dir::Horizontal);+ app.fit_panes();+ render(&mut app);+ app+ }++ fn rect(app: &App, id: u64) -> ratatui::layout::Rect { app.rects.iter().find(|(i, _)| *i == id).unwrap().1 }++ #[tokio::test]+ async fn the_middle_swaps_the_outer_quarter_puts_beside_itself_is_nothing() {+ let app = two();+ let r2 = rect(&app, 2);+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.y + r2.height / 2), Drop::Swap(2));+ assert_eq!(drop_target(&app, 1, r2.x + 1, r2.y + r2.height / 2), Drop::Beside(2, Side::Left));+ assert_eq!(drop_target(&app, 1, r2.right() - 2, r2.y + r2.height / 2), Drop::Beside(2, Side::Right));+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.y + 1), Drop::Beside(2, Side::Top));+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.bottom() - 2), Drop::Beside(2, Side::Bottom));+ let r1 = rect(&app, 1);+ assert_eq!(drop_target(&app, 1, r1.x + 3, r1.y + 3), Drop::Nothing);+ }++ #[tokio::test]+ async fn a_tab_in_the_status_bar_is_a_target_and_the_current_tab_is_not() {+ let mut app = app(100); // window 1 holds pane 1, window 2 pane 2+ render(&mut app); // fills app.status_ranges+ assert!(app.status_lines() > 0 && app.bar_side().is_none(), "this test needs the status bar");+ let other = tab_cell(&app, 1).expect("the other tab has a range");+ assert_eq!(drop_target(&app, 1, other.x, other.y), Drop::Tab(app.tabs[1].id.clone()));+ let here = tab_cell(&app, 0).expect("this tab has a range");+ assert_eq!(drop_target(&app, 1, here.x, here.y), Drop::Nothing);+ assert_eq!(zone(&app, &Drop::Tab(app.tabs[1].id.clone())), Some(other));+ }++ #[tokio::test]+ async fn a_tab_in_the_side_bar_is_a_target() {+ let mut app = app(100);+ app.options.set("@hn-status-bar", Some("left"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes();+ render(&mut app);+ let other = tab_cell(&app, 1).expect("the side bar lists the other tab");+ assert_eq!(drop_target(&app, 1, other.x, other.y), Drop::Tab(app.tabs[1].id.clone()));+ }+}+```+(Use a pane-body rect only after `render`/`fit_panes`; `Rect::right()` / `bottom()` are exclusive edges, hence `- 2` for "one cell inside".)++- [ ] **Step 2: Run to verify they fail**++Run: `cd tui && cargo test --locked pane_drag`+Expected: FAIL (does not compile: `pane_drag` has no items).++- [ ] **Step 3: Implement**++```rust+use ratatui::layout::{Position, Rect};+use crate::{app::App, draw::RangeKind};++pub fn tab_cell(app: &App, i: usize) -> Option<Rect> {+ if app.bar_side().is_some() {+ return app.bar.hits.iter().find(|(_, h)| *h == crate::bar::Hit::Window(i)).map(|(r, _)| *r);+ }+ let number = app.win_num(i) as u64;+ let top = if app.status_top { 0 } else { app.size.1.saturating_sub(app.status_lines()) };+ app.status_ranges.iter().find(|(_, r)| matches!(r.kind, RangeKind::Window(n) if n == number))+ .map(|(row, r)| Rect::new(r.start, top + row, r.end.saturating_sub(r.start), 1))+}++fn tab_at(app: &App, x: u16, y: u16) -> Option<usize> {+ if app.bar_side().is_some() {+ return match crate::bar::hit_at(app, x, y) { Some(crate::bar::Hit::Window(i)) => Some(i), _ => None };+ }+ (0..app.tabs.len()).find(|i| tab_cell(app, *i).is_some_and(|r| r.contains(Position { x, y })))+}++pub fn drop_target(app: &App, src: u64, x: u16, y: u16) -> Drop {+ if let Some(i) = tab_at(app, x, y) {+ return if i == app.active { Drop::Nothing } else { Drop::Tab(app.tabs[i].id.clone()) };+ }+ let Some((id, r)) = app.rects.iter().find(|(_, r)| r.contains(Position { x, y })).copied() else { return Drop::Nothing };+ if id == src { return Drop::Nothing }+ let (bx, by) = ((r.width / 4).max(1), (r.height / 4).max(1));+ let (dl, dr, dt, db) = (x - r.x, r.right() - 1 - x, y - r.y, r.bottom() - 1 - y);+ // the nearest edge band wins (distance as a share of the band); outside every band, the middle swaps+ let near = [(dl, bx, Side::Left), (dr, bx, Side::Right), (dt, by, Side::Top), (db, by, Side::Bottom)]+ .into_iter().filter(|(d, b, _)| d < b).min_by_key(|(d, b, _)| *d as u32 * 1000 / *b as u32);+ match near { Some((_, _, side)) => Drop::Beside(id, side), None => Drop::Swap(id) }+}+```+`zone`: `Beside(id, Left)` the left half of the target's rect in `app.rects` (the half the moved pane will take), `Right` the right half, `Top` / `Bottom` likewise; `Swap(id)` the whole rect; `Tab(tab_id)` → `tab_cell(app, index_of(tab_id))`; `Nothing` / an id no longer present → `None`.++- [ ] **Step 4: Run to verify they pass** — `cd tui && cargo test --locked pane_drag` → PASS+- [ ] **Step 5: Commit** — `git add tui/src/pane_drag.rs tui/src/main.rs tui/src/workspace_controls.rs && git commit -m "hn: where a dragged pane would land"`++### Task 2: Starting, following and ending a pane drag++The pane drag lives in `workspace_controls`, not in `mouse.rs`'s `Drag` enum. Reason: a header press is already owned by `workspace_controls` (`begin_press` sets `controls.pressed`), and `input.rs:290` calls `finish_press` before anything else, which swallows every drag and release of that button. `mouse::drag_update` / `drag_release` (`mouse.rs:410, 418`) only run for tmux's own drags (`drag_flag`), so a `Drag::Pane` variant would never see an event; setting `mouse_state.drag` would also switch off `workspace_controls::mouse` (`:134`) and `bar::mouse` (`bar.rs:531`). `mouse.rs` is therefore not modified.++**Files:**+- Modify: `tui/src/workspace_controls.rs`: `State` (`:14-22`) gets `grips: RefCell<Vec<(Rect, u64)>>` (the cells a pane drag may start from) and `grab: Option<Grab>`; `begin_frame` (`:31`) also clears `grips`; `title` (`:47`) registers the remaining title rect as the pane's grip; new `pub fn name_span(app, pane, width)`; `finish_press` (`:122-130`); `mouse` Header press (`:151-158`)+- Modify: `tui/src/ui.rs:567` (`title_line`, line look): after the title is drawn, `workspace_controls::name_span(app, id, <number of leading drawn cells>)` narrows the grip to the name; `boxes` (`:585`, `:611`) keeps the whole title rect+- Modify: `tui/src/input.rs:21-31` (`handle`, the `CEvent::Key` arm): Escape cancels a live grab before `on_key`+- Modify: `tui/src/pane_drag.rs`: `follow` and a `release` stub+- Test: `tui/src/workspace_controls.rs` tests (next to `plain_pane_titles_keep_divider_drag_behavior` :432); the existing test is changed (below)++**Interfaces:**+- Consumes: `pane_drag::{drop_target, Drop}`.+- Produces:+```rust+// workspace_controls.rs+pub struct Grab { pub pane: u64, from: (u16, u16), /// true once the pointer moved 2 cells: a drag, no longer a click+ pub live: bool, pub drop: crate::pane_drag::Drop }+// State: pub grips: RefCell<Vec<(Rect, u64)>>, pub grab: Option<Grab>+// pane_drag.rs+pub fn follow(app: &mut App, x: u16, y: u16) // sets grab.live after 2 cells, then grab.drop = drop_target(..)+pub fn release(app: &mut App, src: u64, drop: Drop) // Task 4; here `{}`+pub fn cancel(app: &mut App) // grab = None, redraw+```+The frame draws `app.controls.grab` while `live`; there is no `app.pane_drag` field and `app.rs` is not modified.++**How a press becomes a grab.** `title()` already registers `Action::Header(pane)` over the whole title rect (kept: it still selects the pane and opens the menu on right-click). It also registers a grip over `rect` minus the 6 reserved control cells. In the boxed and surface looks that is the whole header row. In the line look `title_line` narrows it to the name: the leading run of cells `format_draw_over` drew (the same `cells.iter().position(|c| c.is_none())` that `boxes` uses at `ui.rs:615`), so the divider line to its right is not a grip. In `mouse()`, on `Down(Left)` over `Action::Header(pane)`: `over_resize_border` (`mouse.rs:141`) only wins when the press is **not** on a grip (today that branch calls `select_pane` and returns `false`, so tmux's `MouseDown1Border` / resize runs; keep that for the divider cells). On a grip (and not zoomed: `!app.tab().zoomed`) the press goes the normal header way (`begin_press`, `activate` selects the pane, `return true`) and also sets `app.controls.grab = Some(Grab { pane, from: (col, row), live: false, drop: Drop::Nothing })`.++- [ ] **Step 1: Failing tests** (in `workspace_controls.rs` `mod tests`; `app`, `render`, `hit` exist there; add these two small helpers)++```rust+ fn send(app: &mut App, kind: MouseEventKind, x: u16, y: u16) {+ crate::input::handle(app, Event::Mouse(MouseEvent { kind, column: x, row: y, modifiers: KeyModifiers::NONE }));+ }+ fn grip(app: &App, pane: u64) -> Rect {+ app.controls.grips.borrow().iter().find(|(_, p)| *p == pane).unwrap_or_else(|| panic!("no grip for {pane}")).0+ }+ fn live(app: &App) -> bool { app.controls.grab.as_ref().is_some_and(|g| g.live) }++ #[tokio::test]+ async fn a_header_drag_of_two_cells_becomes_a_pane_drag_and_a_short_one_stays_a_click() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 2, g.y); // 1 cell: still a click+ assert!(!live(&app));+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 4, g.y + 3); // 2 or more cells+ assert!(live(&app));+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ let (cx, cy) = (r2.x + r2.width / 2, r2.y + r2.height / 2);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), cx, cy);+ assert_eq!(app.controls.grab.as_ref().unwrap().drop, crate::pane_drag::Drop::Swap(2));+ send(&mut app, MouseEventKind::Up(MouseButton::Left), cx, cy);+ assert!(app.controls.grab.is_none() && app.controls.pressed.is_none());+ // a press and release that never moved 2 cells runs nothing+ let order = app.tabs[0].panes();+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Up(MouseButton::Left), g.x + 1, g.y);+ assert_eq!(app.tabs[0].panes(), order);+ }++ #[tokio::test]+ async fn the_line_looks_divider_still_resizes_and_only_the_name_drags_the_pane() {+ for name_drag in [false, true] {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Vertical);+ app.options.set("@hn-border", Some("line"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes(); render(&mut app);+ let title = hit(&app, Action::Header(2));+ let name = grip(&app, 2);+ assert!(name.width > 0 && name.right() < title.right() - 6, "the grip is the name, not the whole line");+ let before = app.tab().root.as_ref().unwrap().to_tmux();+ let x = if name_drag { name.x + 1 } else { name.right() + 1 };+ send(&mut app, MouseEventKind::Down(MouseButton::Left), x, title.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), x, title.y + 3);+ assert_eq!(live(&app), name_drag, "name_drag={name_drag}");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), x, title.y + 3);+ let after = app.tab().root.as_ref().unwrap().to_tmux();+ // the divider part resizes as before; the name part never resizes+ assert_eq!(after != before, !name_drag, "name_drag={name_drag}");+ }+ }++ #[tokio::test]+ async fn escape_during_a_pane_drag_cancels_it_and_the_release_runs_nothing() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let order = app.tabs[0].panes();+ let g = grip(&app, 1);+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 1, g.y + 3);+ assert!(live(&app));+ crate::input::handle(&mut app, Event::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Esc, KeyModifiers::NONE)));+ assert!(app.controls.grab.is_none());+ send(&mut app, MouseEventKind::Up(MouseButton::Left), r2.x + 5, r2.y + 5);+ assert_eq!(app.tabs[0].panes(), order);+ }+```+Also change the existing `plain_pane_titles_keep_divider_drag_behavior` (`workspace_controls.rs:432`) and `title_drag_journey` (`tui/tests/workspace-controls.py:392`): they press at `title.x + 3` / `x + 5`, which is on the name and would now start a pane drag. Press on the divider line instead: in the Rust test `let col = grip(&app, 2).right() + 1;` (before `if !controls { … }` the grips exist; clearing only `hits` for `controls=false` is unchanged) and use `col` in place of `title.x + 3`; in the Python journey pick the first `─` on the title row right of the name: `col = next(c for c in range(x + width('Beta task') + 2, x + int(value('#{pane_width}', beta)) - 7) if screen().splitlines()[top - 1][c] == '─')` and send `col + 1` in place of `x + 5` (the existing assertions are unchanged: the divider still resizes).++- [ ] **Step 2: Run** — `cd tui && cargo test --locked workspace_controls` → FAIL (`grips`, `grab` do not exist)+- [ ] **Step 3: Implement**+ - `State`: add `pub grips: RefCell<Vec<(Rect, u64)>>` and `pub grab: Option<Grab>`; `begin_frame` clears `grips` too.+ - `title()` (after `register(app, rect, Action::Header(pane))`): `app.controls.grips.borrow_mut().push((Rect::new(rect.x, rect.y, rect.width - reserve, 1), pane));`+ - `pub fn name_span(app: &App, pane: u64, width: u16)`: find the grip of `pane` and set its width to `width.min(old)`; remove it when `width == 0`. `ui.rs::title_line` calls it after building `cells` with `cells.iter().position(|c| c.is_none()).unwrap_or(cells.len())`.+ - `mouse()` Header press: `let on_grip = app.controls.grips.borrow().iter().any(|(r, p)| *p == pane && inside(r));` the `over_resize_border` early return becomes `if !on_grip && over_resize_border(..)`; after `begin_press`, `if on_grip && !app.tab().zoomed { app.controls.grab = Some(Grab { pane, from: (mouse.column, mouse.row), live: false, drop: Drop::Nothing }) }`.+ - `finish_press`:+```rust+ MouseEventKind::Up(up) if up == button => {+ app.controls.pressed = None;+ if let Some(g) = app.controls.grab.take() { if g.live { crate::pane_drag::release(app, g.pane, g.drop) } }+ true+ }+ MouseEventKind::Drag(drag) if drag == button => { crate::pane_drag::follow(app, mouse.column, mouse.row); true }+ MouseEventKind::Down(_) => { app.controls.pressed = None; app.controls.grab = None; false }+```+ - `pane_drag::follow`: read `grab` (`pane`, `from`, `live`); `live ||= |dx| + |dy| >= 2` from `from`; when live, `grab.drop = drop_target(app, pane, x, y)`. `cancel`: `app.controls.grab = None`.+ - `input.rs` `handle`, first line of the `CEvent::Key(key) if key.kind != KeyEventKind::Release` arm: `if key.code == KeyCode::Esc && app.controls.grab.is_some() { crate::pane_drag::cancel(app); return }` (the release that follows is still swallowed by `finish_press` because `controls.pressed` stays set).+- [ ] **Step 4: Run** — `cd tui && cargo test --locked` → PASS (including the edited `plain_pane_titles_keep_divider_drag_behavior`, `header_controls_preserve_custom_pane_mouse_bindings` :458, `right_click_opens_the_panes_menu_…` :586)+- [ ] **Step 5: Commit** — `git commit -am "hn: drag a pane by its title"`++### Task 3: Drawing the drop zone++**Files:**+- Modify: `tui/src/ui.rs:232` (right after the `DisplayPanes` overlay line, still before the modals: `crate::pane_drag::draw(buf, app);`)+- Modify: `tui/src/pane_drag.rs` (`pub fn draw(buf: &mut Buffer, app: &App)`)+- Test: `tui/src/pane_drag.rs` tests (buffer assertions through `render`)++- [ ] **Step 1: Failing test** (in `pane_drag.rs` `mod tests`, uses `two()`, `rect()`, `render` from Task 1)++```rust+ #[tokio::test]+ async fn the_zone_is_shaded_in_the_accent_with_a_hint_and_cleared_after() {+ let mut app = two();+ let r2 = rect(&app, 2);+ let tint = crate::theme::paint(crate::theme::accent());+ app.controls.grab = Some(crate::workspace_controls::Grab::live_for_test(1, Drop::Beside(2, Side::Left)));+ let buf = render(&mut app);+ let z = zone(&app, &Drop::Beside(2, Side::Left)).unwrap();+ assert_eq!(z.x, r2.x);+ assert!(z.width < r2.width && buf[(z.x, z.y + 1)].bg == tint, "the left half takes the accent");+ let row: String = (z.x..z.right()).map(|x| buf[(x, z.y + z.height / 2)].symbol()).collect();+ assert!(row.contains("left of Task 2"), "{row}");+ assert!(buf[(r2.right() - 1, r2.y + 1)].bg != tint, "outside the zone keeps its colour");+ app.controls.grab = None;+ let buf = render(&mut app);+ assert!(buf.content().iter().all(|c| c.bg != tint), "no zone once the drag is over");+ }+```+(`Grab::live_for_test(pane, drop)` is a `#[cfg(test)]` constructor next to `Grab` that fills the private `from`; the roster names panes `Task 1` / `Task 2` in `app()`. Hint texts: `left of <name>` / `right of` / `above` / `below`, `swap with <name>`, `to <tab name>` (`app.tabs[i].name`); a pane's name is `app.fleet.agent(&p.machine_id, &p.agent_id).map(|a| a.name.clone())`. If the theme's accent is not distinct from the pane background in the fixture, compare against a render without the grab instead.)+- [ ] **Step 2: Run** — `cargo test --locked pane_drag` → FAIL+- [ ] **Step 3: Implement** — `pub fn draw(buf, app)`: return unless `app.controls.grab` is `live`; take `zone(app, &grab.drop)`; for each cell of the zone `cell.set_bg(theme::paint(theme::accent())).set_fg(theme::paint(theme::pane_palette().background))` (symbols stay); write the hint centred on the zone's middle row, clipped to the zone width (`unicode_width` as `workspace_controls.rs` does). On release `pane_drag::release` sets `app.redraw_all = true` once (see Review Focus; plan 005 changes what `redraw_all` costs, so if 005 lands first a plain redraw request is enough, because the zone is part of the frame buffer and the diff removes it).+- [ ] **Step 4: Run** — `cargo test --locked pane_drag` → PASS+- [ ] **Step 5: Commit** — `git commit -am "hn: show where a dragged pane will land"`++### Task 4: The drop runs as tmux commands++**Files:**+- Modify: `tui/src/pane_drag.rs` (`release`)+- Test: `tui/src/pane_drag.rs` tests; `tui/tests/workspace-controls.py` (new `pane_drag_journey`). `tui/tests/layout-sync.py` is **not** extended: it has no mouse input path, and its existing `swap-pane` step (:287-291, `hn('swap-pane', '-s', source, '-t', target, '-d')` then `wait(... names() == desk_names() ...)`) already proves a swap publishes the pane order; the Rust test below proves the drop issues that same command and queues the layout.++How the commands target things (all exist): a pane is `crate::pane::tag(id)` (`%{id-1}`, `pane.rs:45`); a window is `:{number}` with `number = app.win_num(index)` (the form `bar.rs:481` uses for `select-window -t :{n}`; as a `join-pane -t` it resolves to that window's active pane through `commands::pane_target`, `commands.rs:279`). `swap-pane` takes `-s -t` (cmd.rs:115, `swap_panes` publishes via `layout_changed`, `app.rs:5333`); `join-pane` takes `-b -h -v -s -t` (cmd.rs:54; `App::join_pane` `app.rs:4455` refuses with `create pane failed: pane too small` before moving anything, and calls `layout_changed` for the window it left and the one it joined, `app.rs:4487-4488`). `layout_changed` (`app.rs:4893`) queues the tab's id in `app.desk_layouts` (a `HashSet<String>`, drained by `send_desk_layouts`, `app.rs:4914`) only when `app.session_desk` and `tab.on_desk` are set; the existing tests assert exactly that with `app.desk_layouts.contains("layout-test")` (`app.rs:7219`).++- [ ] **Step 1: Failing tests** (in `pane_drag.rs` `mod tests`)++```rust+ /// Panes 1 | 2 | 3 in one window, on the desk so that layout changes are queued.+ fn three() -> App {+ let mut app = app(120);+ app.tabs.truncate(1);+ let mut pane = crate::pane::Pane::new(3, "local", "a3", 120, 30);+ pane.phase = crate::pane::Phase::Live;+ app.panes.insert(3, pane);+ let root = app.tabs[0].root.as_mut().unwrap();+ root.split(1, 2, Dir::Horizontal);+ root.split(2, 3, Dir::Horizontal);+ app.session_desk = true;+ app.tabs[0].on_desk = true;+ app.fit_panes();+ app+ }++ #[tokio::test]+ async fn dropping_runs_swap_and_join_and_publishes_the_layout() {+ let mut app = three();+ release(&mut app, 1, Drop::Swap(3));+ assert_eq!(app.tabs[0].panes(), vec![3, 2, 1]);+ assert!(app.desk_layouts.contains(&app.tabs[0].id), "queued for the desk");+ app.desk_layouts.clear();+ release(&mut app, 3, Drop::Beside(1, Side::Bottom));+ assert_eq!(app.tabs[0].root.as_ref().unwrap().to_tmux().matches('[').count(), 1, "1 and 3 are stacked");+ assert!(app.desk_layouts.contains(&app.tabs[0].id));+ }++ #[tokio::test]+ async fn dropping_on_a_tab_moves_the_pane_into_that_window() {+ let mut app = app(100); // window 1: pane 1; window 2: pane 2+ let other = app.tabs[1].id.clone();+ release(&mut app, 1, Drop::Tab(other.clone()));+ let tab = app.tabs.iter().find(|t| t.id == other).unwrap();+ assert!(tab.panes().contains(&1) && tab.panes().contains(&2));+ assert_eq!(app.tabs.len(), 1, "a window left with no pane closes, as join-pane does");+ }++ #[tokio::test]+ async fn a_gone_source_or_target_does_nothing() {+ let mut app = three();+ let before = app.tabs[0].panes();+ release(&mut app, 99, Drop::Swap(2));+ release(&mut app, 1, Drop::Swap(99));+ release(&mut app, 1, Drop::Beside(99, Side::Left));+ release(&mut app, 1, Drop::Tab("no-such-window".into()));+ release(&mut app, 1, Drop::Swap(1));+ release(&mut app, 1, Drop::Nothing);+ assert_eq!(app.tabs[0].panes(), before);+ assert!(app.desk_layouts.is_empty());+ }+```+- [ ] **Step 2: Run** — `cargo test --locked pane_drag` → FAIL (the Task 2 stub does nothing)+- [ ] **Step 3: Implement**++```rust+pub fn release(app: &mut App, src: u64, drop: Drop) {+ let alive = |app: &App, id: u64| app.panes.contains_key(&id) && app.tabs.iter().any(|t| t.panes().contains(&id));+ if !alive(app, src) { return }+ let tag = crate::pane::tag;+ let command = match drop {+ Drop::Swap(dst) if dst != src && alive(app, dst) => format!("swap-pane -s {} -t {}", tag(src), tag(dst)),+ Drop::Beside(dst, side) if dst != src && alive(app, dst) => {+ let flags = match side { Side::Left => "-h -b", Side::Right => "-h", Side::Top => "-v -b", Side::Bottom => "-v" };+ format!("join-pane {flags} -s {} -t {}", tag(src), tag(dst))+ }+ Drop::Tab(id) => match app.tabs.iter().position(|t| t.id == id).filter(|i| *i != app.active) {+ Some(i) => format!("join-pane -s {} -t :{}", tag(src), app.win_num(i)),+ None => return,+ },+ _ => return,+ };+ crate::commands::execute(app, &command);+ app.redraw_all = true;+}+```+A refused drop (`create pane failed: pane too small`) is reported by the command itself (`app.error`); nothing moves.++Native journey (`tui/tests/workspace-controls.py`): add `pane_drag_journey(alpha, beta)` next to `title_drag_journey` (:392), called after it at :619 and under a new `--pane-drag` argument beside `--title-drag` (:459-462; `api({'action': 'terminal-mouse'})` first, as there). It sends raw SGR mouse bytes with the same `tmux('send-keys','-H', ...)` loop as `title_drag_journey` (a press `\x1b[<0;X;YM`, motion `\x1b[<32;X;YM`, release `\x1b[<0;X;Ym`; the existing `click()` at :142 shows the 1-based coordinates). Steps: `@hn-border box`; press on Alpha's title name (row `#{pane_top}` − 1 plus the box frame; read it from `screen()` as `painted_workspace` does), drag to the middle of Beta, release, then `wait` until `hn('list-panes', '-F', '#{pane_id}').splitlines()` is `[beta, alpha]`; `assert len(api()['inputs']) == before` (no program input); drag Alpha to Beta's bottom quarter and `wait` for `#{pane_top}` of the two panes to differ with equal `#{pane_left}`; drag a pane onto the other tab's name in the status bar (`click_text` shows how a tab's cell is located on screen) and check it is listed with `list-panes -t :N`. The Rust `workspace_controls.rs` / `pane_drag.rs` tests above are the primary evidence; this journey is the real-terminal check. Restore the layout at the end as `title_drag_journey` does.++- [ ] **Step 4: Run** — `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui` → all pass (the native runner starts `workspace-controls` once; `--pane-drag` runs only on demand: `cd tui && env HN_WORKSPACE_BINARY=<binary> HN_WORKSPACE_PORT=19930 python3 -u tests/workspace-controls.py --pane-drag`). Composer-machine: macOS bash 3.2, known.+- [ ] **Step 5: Commit** — `git commit -am "hn: dropping a pane swaps it, puts it beside another, or moves it to a tab"`++---++## Plan check (2026-10-07, against origin/main)++Conflicts between tasks, and whether each task's tests match its code:++| Pair / task | Shared file or interface | Status |+|---|---|---|+| Task 1 and Task 2 | `workspace_controls.rs`: Task 1 makes `tests`, `app`, `render` `pub(crate)`; Task 2 adds helpers and tests to the same module | No conflict (Task 1 first, one-word edits) |+| Task 1 and Task 4 | `Drop::Tab(String)`: Task 1 produces it, Task 4 resolves it by id | Same type in both; tests use ids |+| Task 2 and Task 3 | `Grab` (Task 2) is read by `pane_drag::draw` (Task 3); `Grab::live_for_test` is added in Task 2's struct | Task 3 depends on Task 2 |+| Task 2 and Task 4 | `pane_drag::release` is a stub in Task 2 and filled in Task 4; `finish_press` calls it on release | Order 2 then 4; tests of Task 2 assert the order only after Task 4 for the swap (the first test asserts `grab` cleared, not the swap) |+| Task 2 and Task 3 | both edit `ui.rs`: `title_line` (:567) and :232 | Different lines |+| Task 2 test and existing test | `plain_pane_titles_keep_divider_drag_behavior` and `title_drag_journey` pressed on the name | Both changed in Task 2 to press on the divider |+| Task 1 test | needs the status bar visible (`status_lines() > 0`, no side bar) | Asserted at the start of the test |+| Task 2 code and Global Constraints | line-look divider resizes; drag from the name only; Esc; 2-cell click rule | Match |+| Task 3 code and Global Constraints | theme colours only (`theme::accent()`, `pane_palette()`) | Match |+| Task 4 code and Global Constraints | every drop through `swap-pane` / `join-pane` | Match |++Cross-plan overlaps (not edited here): plan 005 changes the cost and meaning of `app.redraw_all` and edits `input.rs:36, 42` (this plan edits `input.rs:21-31` and sets `redraw_all` on release); plan 003 edits `ui.rs:304-350` and `input.rs:1632-1681, 3549-3574` (no shared lines); plan 007 edits `ui.rs:1460-1467, 2508-…` (no shared lines); plan 008 changes `bar::Hit` (`Hit::Machine(String, Option<usize>)`, new `Harness`/`More`) and `bar.rs:470-492`; this plan only uses `Hit::Window(i)` and `app.bar.hits`, which 008 keeps. Plan 004 touches none of these files.diff --git a/docs/plans/2026-10-07-007-composer-dropdown-plan.md b/docs/plans/2026-10-07-007-composer-dropdown-plan.mdnew file mode 100644index 000000000..043d7f158--- /dev/null+++ b/docs/plans/2026-10-07-007-composer-dropdown-plan.md@@ -0,0 +1,373 @@+# One list style for the composers: the command panel's — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** The shell composer (Ctrl-N / `claude @…`) and the New Harness form show their choices the way the command panel already does — a `›` query line, a muted rule with the count, rows drawn by the panel's own list, a keys line — directly under where you type, in the theme's colours, with a ghost line that says what `@ : % &` choose.++**Architecture:** No new style. The command panel (`settings::draw`, `settings.rs:422-593`) is the reference: `settings::chrome()` (theme-derived `base / muted / accent / selected`, `settings.rs:283-311`) and `settings::list_from` (rows, `settings.rs:596`: the chosen row is the row's text bold on the lifted `selected` band across the whole row, its `›` pointer in that same style; the other rows' detail is muted, the chosen row's detail is the same band without bold). Task 1 lifts the launcher's query line, count rule and keys line (`settings.rs:461-470`, `:486-488`, `:489-498`) into small `pub fn`s the panel itself then calls (no visual change). Tasks 2 and 4 draw the two composers with those functions and `list_from`. Task 3 gives the out-of-process shell picker the TUI's theme (the picker is a separate process and has no theme of its own: `settings::chrome()` there is the dark default until it is told) so `chrome()` there is the same theme.++**Tech Stack:** Rust (ratatui), the shell picker process (`hn --shell-picker`), Python fixtures.++**Spec:** user 2026-10-07: reference screenshot (input line, rule, list below with the chosen row bright and others muted, a footer); "cần có dòng placeholder để instruct @ # : là gì đó để họ gõ"; "cái cách select style của cái new harness nó ko giống trong cái command"; "UI màu đúng… đồng bộ theme"; answers: freeze in the shell composer; the dropdown for **the shell composer and the New Harness form**; "nó nên follow style và đồng bộ theme nhé bạn không custom, nhớ follow rules".++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **No preview while arrowing over fields:** a chooser drops down only when its field is entered (→, Enter, typing, a click); moving over fields with ↑ ↓ shows nothing extra. Accepted change — the dropdown sits where the old side preview could not.+2. **The user's own list options win:** when `@hn-lists fzf` is set or `FZF_DEFAULT_OPTS` sets `--layout` / `--border` / `--info` / `--color`, the shell composer keeps today's fzf drawing; otherwise (the default) it uses the command panel's pieces. The picker learns which from the TUI's reply (`look.lists`), and from `HN_LOOK` (below) for its first frame.+3. **First frame in the right theme:** the TUI exports `HN_LOOK` (the same JSON as the reply's `look`) into each shell it starts, so the picker's first frame uses it; every reply's `look` then keeps it current.+4. **Welcome page:** the dropdown sits under the chips row (the task box stays visible). Accepted.+5. **Task 4b also fixes → on Browse and Terminal** (today it sets `child_active` with no child — a trap): → there does what Enter does.+6. **Empty ghost:** `Search agents @ computer : project % model & agent` (the existing words, then the scopes), cut at whole scopes on narrow panes.+7. `Color::Reset` page fills stay: Reset is the terminal's own background, which is theme-following, not a fixed colour.+8. Task 4b's "opened" assertion: verify by running it; if `open_agent` cannot run in the bare test app, assert the same observable state the Enter test at `welcome.rs` asserts, by pressing → and comparing.+9. **Build after plan 004 has merged** (both edit `shell_picker.rs`'s loop and `shell_context.rs` replies).++## Global Constraints++- **No custom style.** Every colour and modifier comes from `settings::chrome()`; every row from `settings::list_from`. No `theme::fzf()` palette, no fixed `Color::*`, no new glyphs (the panel's `›` and `─` only).+- Copy follows `docs/naming-system.md` (Harness, computer, project, model) and the panel's sentence case.+- The shell composer's scopes stay `& agent`, `@ computer`, `: project`, `% model` (`shell_picker.rs:653-658`). `#` cannot be one in a shell: it starts a comment and the word parser refuses it (`shell_composer.rs:59`). The command panel keeps its own `> @ # : * ?`.+- `NO_COLOR` keeps working (`chrome()` already handles it, `settings.rs:284-287`).+- Behaviour unchanged: keys, what is chosen, what is launched. Only where and how the list is drawn.++## Target look (shell composer; the form's dropdown is the same block under its Task field)++```+READY> codex @Office :~/api+ › %gpt▌ @ computer : project % model & agent (ghost when empty)+ 2/9 ───────────────────────────────────────────────+ › gpt-6-astra OpenAI ← list_from: chosen row bold on the lifted band (pointer in the same style)+ gpt-6-astra-fast OpenAI ← detail muted+ ↑↓ move · enter choose · esc back ← keys line: keys bold, words muted+```++## Facts checked against the code (read before starting)++- `ui::inline_fzf` (`ui.rs:2508`) is the renderer of **every** shell picker process (`shell_picker.rs:290`, one call site): the composer (`source=="compose"`), the `ch` computer chooser, the model chooser, the `choose` picker and the sessions search. It hard-codes `PickerKind::ShellContext`; it has no notion of "composer". Its last parameter `bottom_up` is the **preview text's** anchoring (`preview_bottom` of the reply), not the list direction. So Task 2 needs a flag on the picker: `Picker.shell_panel: bool` (new `pub` field in `picker.rs`, default false; set by `compose_scope`, below). The sessions kind (blank Ctrl-P, with its preview split) and the other pickers keep the fzf frame.+- The shell picker never "opens upward": `Screen::new` reserves `dimensions()` rows by scrolling the terminal (`shell_picker.rs:210-250`). The composer panel is always top-down (query on top), like the panel's non-launcher menus (`settings::top_down`).+- The `part` kind (`shell_picker.rs:595`, `:502`, `:661`; `composition::list` `"part"`) is unreachable today: `composer_kind` (`:653`) only returns `agent|host|folder|model|sessions`. The ghost the user sees when the composer is empty is the placeholder of `sessions` ("Search sessions", blank Ctrl-P) or `agent` ("Search agents", blank Ctrl-N, `:661`). Leave `part` as it is.+- There are no `theme::set_pane_palette` / `theme::set_accent`. The theme the chrome reads is: `term_out::terminal_colours()` (a chosen theme's `THEME_COLOURS`, else the terminal's answer; setter `term_out::set_theme_colours(Option<(bg_hex, fg_hex)>)`, `term_out.rs:335`) and `term_out::accent_override()` (setter `term_out::set_accent_override(Option<String>)`, `:347`), both consulted by `theme::pane_palette()` (`theme.rs:489`) and `theme::accent()` (`theme.rs:403`). These are process-global; tests that set or read them hold `crate::term_out::colours_lock()`. `muted` is derived from the palette by `pane_palette_for` — it is not sent.+- `picker-ready` is the shell's own handshake (`shell_context.rs:457`), answered with empty text and no JSON; the picker process never sends it. The catalogs the picker draws from come back through `reply_data` (`shell_context.rs:375`), from `inline_list` (`:612`) and `composition::data` (`shell_context/composition.rs:47`), as `Items` (`shell_picker.rs:23`, `#[serde(default)]`).++---++### Task 1: The launcher's query line, count rule and keys line as functions++**Files:**+- Modify: `tui/src/settings.rs:461-470` (query), `:486-488` (count), `:489-498` (keys): extract; add `pub fn query_line`, `pub fn count_rule`, `pub fn keys_line`; `settings::draw` calls them+- Test: `tui/src/settings.rs` tests (`mod tests`, `:1019`; helpers there: `app((w,h))`, `text(&buf)`, `open(..)`)++**Interfaces:**+- Produces:+```rust+/// `› query` (or the ghost, muted, when empty) at [x, y], [w] wide. Returns the text cursor and the+/// columns the query or ghost took (the launcher puts its tabs after it). A ghost with ` `-separated+/// parts shows whole parts only (`@ computer : project`), one without is cut with `…` as the panel's was.+pub fn query_line(buf: &mut Buffer, picker: &Picker, x: u16, y: u16, w: u16, ghost: &str, c: &Chrome) -> (Position, u16)+/// `shown/total ───…` (and ` (marked)` when [marked] is Some, as the launcher's) in muted across [w].+pub fn count_rule(buf: &mut Buffer, shown: usize, total: usize, marked: Option<usize>, x: u16, y: u16, w: u16, c: &Chrome)+/// `key what · key what`, keys bold, words muted; stops at [w]. `&picker.hints[..]` fits ([(&'static str, &'static str)]).+pub fn keys_line(buf: &mut Buffer, keys: &[(&str, &str)], x: u16, y: u16, w: u16, c: &Chrome)+```+(`query_line` also does `picker.prompt_at.set((y, x + 2))` as `:466` does; the `on_tabs` filter on the cursor stays in `draw`. Today's panel draws the count as `{visible}/{rows} ({marked})`, so `count_rule` takes `marked`; the launcher passes `Some(picker.marked.len())`, the composers `None`.)++- [ ] **Step 1: Tests**. (a) A characterisation test that passes on today's code and must pass unchanged after the refactor (note `PickerKind::Commands` is not a launcher: the count and keys rows exist only for `modal::is_launcher` kinds, so use `Open`):+```rust+#[test]+fn the_launcher_draws_keys_count_and_query_in_three_rows() {+ let _l = crate::term_out::colours_lock();+ let app = app((100, 30));+ let body = Rect::new(0, 0, 100, 29);+ let kind = PickerKind::Open { filter: modal::Filter::All, machine: None, project: None };+ let mut p = Picker::new("harnesses", "");+ p.hints = vec![("↑↓", "move"), ("enter", "open")];+ p.set_rows(vec![Row::new("a", "alpha"), Row::new("b", "beta")]);+ let mut buf = Buffer::empty(body);+ let (cursor, _) = draw(&mut buf, &app, body, &kind, &mut p);+ let r = p.screen_area.get();+ let qy = r.bottom() - 2;+ let row = |y: u16| (r.x..r.right()).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>();+ assert!(row(qy).contains('›'), "{}", row(qy));+ assert!(row(qy - 1).trim_start().starts_with("2/2 (0) ─"), "{}", row(qy - 1));+ assert!(row(qy - 2).contains("↑↓ move · enter open"), "{}", row(qy - 2));+ assert_eq!(cursor, Some(Position::new(r.x + 2 + 2, qy)));+}+```+(`Row` is `crate::picker::Row`; add it to the test imports if `use super::*` does not bring it.) (b) The new function, which does not compile yet:+```rust+#[test]+fn the_query_line_is_the_panels() {+ let _l = crate::term_out::colours_lock();+ let c = chrome();+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 3));+ let mut p = Picker::new("", "");+ p.query = "gpt".into(); p.qcursor = 3;+ let (at, used) = query_line(&mut buf, &p, 0, 0, 40, "@ computer", &c);+ assert_eq!(buf[(0, 0)].symbol(), "›");+ assert_eq!(buf[(0, 0)].fg, c.accent.fg.unwrap());+ assert_eq!((buf[(2, 0)].symbol(), at, used), ("g", Position::new(5, 0), 3));+ p.query.clear(); p.qcursor = 0;+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 3));+ query_line(&mut buf, &p, 0, 0, 40, "@ computer", &c);+ assert_eq!(buf[(2, 0)].fg, c.muted.fg.unwrap(), "the ghost is muted");+ // whole scopes only, never a scope cut in half+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));+ query_line(&mut buf, &p, 0, 0, 20, "@ computer : project % model", &c);+ let line: String = (0..20).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(line.contains("@ computer") && !line.contains("proj") && !line.contains('…'), "{line}");+}+```+(`c.accent.fg.unwrap()` needs `NO_COLOR` unset, as the other colour tests here.)+- [ ] **Step 2: Run** — `cd tui && cargo test --locked the_launcher_draws_keys` → PASS (today's code); `cargo test --locked the_query_line_is_the_panels` → FAIL (does not compile: `query_line` not found)+- [ ] **Step 3: Implement** — move the code at `settings.rs:461-470` into `query_line` (the launcher passes `&format!("Search {}", …)` or `&picker.placeholder` as the ghost, as `:463` does), `:486-488` into `count_rule`, `:489-498` into `keys_line` (the launcher passes `&tab_keys[..]` or `&picker.hints[..]`); `settings::draw` calls them. Add `pub fn whole_parts(ghost: &str, w: u16) -> String` (the ` `-separated parts that fit whole, joined by ` `; the ghost without separators is returned as is) and use it in `query_line`. No other call-site changes. `tests/workspace-controls.py` / `keybinds.py` must not change.+- [ ] **Step 4: Run** — `cargo test --locked settings` → PASS (including the characterisation test)+- [ ] **Step 5: Commit** — `git commit -am "hn: the command panel's query, count and keys lines as shared pieces"`++### Task 2: The shell composer drawn with the panel's pieces++**Files:**+- Modify: `tui/src/picker.rs` (add `pub shell_panel: bool`, default false, next to `prefixed`/`scope_prefix`, `:129-131`; initialise in `Picker::new`, `:261-290`)+- Modify: `tui/src/shell_picker.rs:659-665` (`compose_scope`): `picker.shell_panel = kind != "sessions"`; the empty-query ghost: `"sessions"` => `Search sessions @ computer : project % model & agent`, `"agent"` => `Search agents @ computer : project % model & agent` (the existing text first, then the scopes, ` `-separated so a narrow pane shows whole parts only). `"part"` is left as it is (unreachable).+- Modify: `tui/src/ui.rs:2508` (`inline_fzf`): when `picker.shell_panel`, draw the panel instead of the fzf frame (a new private `fn inline_panel(buf, area, picker, busy) -> Position` called first): fill `area` with `chrome().base`; at `x = area.x + 1`, `w = area.width - 2`: row 0 `query_line(…, &picker.placeholder, &c)`; row 1 `count_rule(buf, picker.visible.len(), picker.total_rows.unwrap_or(rows that are not disabled), None, …)`; rows 2..height-1 `list_from(buf, picker, Rect::new(x, area.y + 2, w, area.height - 3), &c, true, false)` (empty list text: `picker.empty`, set by `Screen::draw` from the status; while `busy`, `picker.busy`'s spinner is the loading mark: put `theme::spinner`-style text from `picker.status` in the rule's place only if `picker.status` is non-empty — no new glyph); last row `keys_line(&[("↑↓","move"),("enter","choose"),("esc","back")], …)`. Too small (`area.height < 4 || area.width < 24`): only `› query` on row 0 (as the existing tiny fallback at `:2511-2519` keeps the query), cursor inside `area`. The panel is always top-down; the fzf `--layout`, `--border`, `--info` options do not apply to it (the user's `--height` still sizes the region through `dimensions()`).+- Modify: `tui/src/ui.rs:1461-1468` (inline ghost, used by the pickers that stay on the fzf frame — `ch`, models, sessions): after a ghost or placeholder is drawn, `shift = typed_w as i32 + 2` (two blanks before the inline count; both branches), fixing "Search agents14/14"+- Test: `tui/src/shell_picker.rs` tests (`mod tests`, near `:811`/`:825`), `tui/tests/shell-first.py` (NOT `composer-machine.py`: that test only talks to the OSC protocol and never reads the screen)++**shell-first.py updates:** `finder_text()` (`:161-164`) finds the box by `╭`…`╰`; `finder_ready()` (`:165`) wants `\d+/\d+` in it; `browsing()` (`:166-170`) looks for `'> '+query`; the closed-picker checks use `'╭' not in …` (`:382-426`, `:586-627`, `:692`), `'> &'` at `:334`. The composer no longer has a box and its prompt is `›`. Change `finder_text()` to return the lines from the first line holding `›` and an `n/m` rule row through the `esc back` keys line when there is no `╭` (the fzf-framed pickers — sessions, `cm` completion, `:664` box-height check — keep `╭`); change `browsing()` to look for `'› '+query` in that text; change the closed checks that follow a composer to `not finder_ready()` (a `'╭' not in` check would now pass while the composer is still open). Add the ghost assertions: with an empty Ctrl-N the screen shows `@ computer`, `: project`, `% model`, `& agent`.++- [ ] **Step 1: Failing test** (in `shell_picker.rs` `mod tests`; builds the picker the way `run` does, with a helper defined here):+```rust+fn composer_picker(labels: &[&str]) -> Picker {+ let mut p = Picker::new("", "");+ p.query = "%gpt".into(); p.qend();+ compose_scope(&mut p, "model");+ p.set_rows(labels.iter().map(|l| Row::new(*l, *l).detail(vec![ratatui::text::Span::raw("OpenAI")])).collect());+ p+}++#[test]+fn the_composer_is_drawn_like_the_command_panel() {+ let _l = crate::term_out::colours_lock();+ let c = crate::settings::chrome();+ let mut picker = composer_picker(&["gpt-6-astra", "gpt-6-astra-fast"]);+ assert!(picker.shell_panel);+ let area = Rect::new(0, 0, 60, 6);+ let mut buf = Buffer::empty(area);+ crate::ui::inline_fzf(&mut buf, area, &mut picker, false, vec![], false);+ let row = |y: u16| (0..60).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>();+ assert!(!row(0).contains('╭') && !row(0).contains('│'), "no border: {}", row(0));+ assert!(row(0).trim_start().starts_with("› %gpt"), "{}", row(0));+ assert!(row(1).starts_with(" 2/2 ─"), "{}", row(1));+ assert!(row(5).contains("↑↓ move") && row(5).contains("esc back"), "{}", row(5));+ let sel = (0..60).find(|x| buf[(*x, 2)].symbol() == "g").unwrap();+ assert_eq!(buf[(sel, 2)].bg, c.selected.bg.unwrap(), "the chosen row on the panel's lifted band");+ assert!(buf[(sel, 2)].modifier.contains(Modifier::BOLD));+ assert_ne!(buf[(sel, 3)].bg, c.selected.bg.unwrap());+}++#[test]+fn the_ghost_shows_whole_scopes_and_the_panel_survives_tiny_areas() {+ let _l = crate::term_out::colours_lock();+ let mut picker = Picker::new("", "");+ compose_scope(&mut picker, "agent");+ picker.set_rows(vec![Row::new("claude", "Claude Code")]);+ for w in [1, 8, 23, 24, 30, 60, 140] { for h in 1..12 {+ let area = Rect::new(0, 0, w, h);+ let mut buf = Buffer::empty(area);+ let at = crate::ui::inline_fzf(&mut buf, area, &mut picker, false, vec![], false);+ assert!(area.contains(at), "{w}x{h}: {at:?}");+ let first: String = (0..w).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(!first.contains("Search agents1"), "{w}x{h}: {first}");+ } }+}+```+(`Row`, `Rect`, `Buffer`, `Modifier` are in scope in this module through `use super::*` — add `use ratatui::style::Modifier;` if not.) The sessions-kind picker stays on the fzf frame; the existing `inline_renderer_survives_tiny_resizes_and_preserves_its_query` (`configure(&mut picker, true)`, `shell_panel` false) must keep passing.+- [ ] **Step 2: Run** — `cd tui && cargo test --locked the_composer_is_drawn_like` → FAIL (does not compile: `shell_panel`)+- [ ] **Step 3: Implement** as in *Files*. Remove the composer's use of `theme::fzf()` colours (`theme.rs` fzf palette stays for the fzf-framed lists).+- [ ] **Step 4: Run** — `cargo test --locked` + `cd tui && env HN_COMPOSER_TEST_BINARY=target/release/harness-tui python3 -u tests/composer-machine.py` (protocol only; must not change) + the `shell-first.py` journeys → PASS+- [ ] **Step 5: Commit** — `git commit -am "composer: the command panel's list, ghost and keys, no fzf box"`++### Task 3: The shell picker process uses the TUI's theme++**Files:**+- Modify: `tui/src/shell_context.rs:375` (`reply_data`): when `data` is a JSON object, set `data["look"] = {"background": "#rrggbb", "foreground": "#rrggbb", "accent": "<hex or empty>"}` before it is stored and sent — one place for `inline_list`, `composition::data` and the `{"unchanged":true}` replies (an `unchanged` reply must still carry it: a theme change does not change a catalog's revision). Values: background/foreground from `term_out::terminal_colours()` (a chosen theme, else the terminal's answer; omit `look` when it is None: the picker then keeps the same default the TUI uses before the terminal answers); accent from `term_out::accent_override()`, else `term_out::native_accent()` as `#rrggbb`, else `""`.+- Modify: `tui/src/shell_picker.rs:23` (`Items`: `pub look: Option<Look>`; new `#[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(default)] pub struct Look { pub background: String, pub foreground: String, pub accent: String }`) and the reply loop (`:512-520`): **before** the `if !value.unchanged` check, `if let Some(look) = &value.look { apply_look(look) }` where `apply_look` calls `term_out::set_theme_colours(Some((background, foreground)))` and `term_out::set_accent_override(Some(accent))` (None when empty) and marks `dirty = true` when either returned a change. `Request::poll` deserialises into `Items`, so `look` arrives with the rows.+- Test: `tui/src/shell_context.rs` tests (next to `inline_list_uses_shared_rows_and_does_not_open_a_modal`, `:1240`; helpers there: `app()`, `prepare`, `bind`, `request`, `output`), `tui/src/shell_picker.rs` tests++- [ ] **Step 1: Failing tests** — (a) in `shell_context.rs`:+```rust+#[tokio::test]+async fn catalog_replies_carry_the_tuis_theme() {+ let _l = crate::term_out::colours_lock();+ crate::term_out::set_theme_colours(Some(("#101010".into(), "#eeeeee".into())));+ crate::term_out::set_accent_override(Some("#ff0000".into()));+ let mut app = app();+ let token = prepare(&mut app, None, false); bind(&mut app, &token, "local", "shell");+ output(&mut app, 1, &request(&token, "list-host", r#"{"query":"","revision":""}"#));+ let data = app.shell_context.replies.back().unwrap().data.as_ref().unwrap();+ assert_eq!(data["look"]["accent"], "#ff0000");+ assert_eq!(data["look"]["background"], "#101010");+ let revision = data["revision"].as_str().unwrap().to_string();+ output(&mut app, 1, &request(&token, "list-host", &json!({"query":"","revision":revision}).to_string()));+ assert_eq!(app.shell_context.replies.back().unwrap().data.as_ref().unwrap()["look"]["accent"], "#ff0000", "an unchanged reply still says the theme");+ crate::term_out::set_theme_colours(None); crate::term_out::set_accent_override(None);+}+```+(b) in `shell_picker.rs`:+```rust+#[test]+fn a_replys_look_changes_the_pickers_chrome() {+ let _l = crate::term_out::colours_lock();+ apply_look(&Look { background: "#ffffff".into(), foreground: "#111111".into(), accent: "#ff0000".into() });+ assert_eq!(theme::accent(), Color::Rgb(255, 0, 0));+ assert_eq!(crate::term_out::terminal_colours(), Some(("#ffffff".into(), "#111111".into())));+ crate::term_out::set_theme_colours(None); crate::term_out::set_accent_override(None);+}+```+(`Color` from `ratatui::style::Color`; import in the test module if absent.)+- [ ] **Step 2: Run** — `cargo test --locked catalog_replies_carry` → FAIL+- [ ] **Step 3: Implement** — colours are `#rrggbb` (the accent override string is already one, or an indexed form `tmuxconf::colour` parses; send it as it is). Known limit: the very first frame, drawn before the first reply, is in the default palette; the next frame (one round trip later) is the theme's.+- [ ] **Step 4: Run** — `cargo test --locked shell` → PASS+- [ ] **Step 5: Commit** — `git commit -am "composer: the shell picker draws in the TUI's theme"`++### Task 4: The New Harness form's choosers drop down under their field, in the panel's style++**Files:**+- Modify: `tui/src/new_harness/view.rs`: remove the side panel (`:82-85` `side_w/side/child_w/child_h`, `:196-197` the side/overlay choice). The form is always drawn; when `form.child_active` and a child exists, `draw_child` is given a dropdown rect: `x = r.x + 1`, `width = form_w - 2`, `y` = the row under the focused field (`fy + height` of the focus row computed in the field loop `:120-190`; for `Field::Task` that is under the task text, `fy + task_h`), height = rows wanted (`4 + visible rows`, at most 12) clamped to `r.bottom() - 1 - y`. If fewer than 4 rows remain, fall back to the existing full-form overlay (`Rect::new(x, y0, form_w, form_h)`, the old `!side` path, form not drawn under it). A chooser that is open but not active (`reveal` on arrowing through fields) is **not drawn**: arrowing down through the fields must not drop a list over the next field (the footer's `form.hint()` already says Enter/→). `draw_child` (`:200-329`) is rewritten with `settings::query_line` + `count_rule` + `list_from(buf, &mut c.picker, Rect::new(x + 1, y + 2, w - 2, h - 3), &chrome, true, false)` + `keys_line(&[("↑↓","move"),("enter","choose"),("esc","back")])`; keep what it sets for the mouse (`form.child_area`, `c.picker.row_at` — `list_from` sets `row_at` and `list_area` itself; keep `page_rows`, the Project separator rows: a `Row` with a `group` gives `list_from`'s heading; `Choice::editing()` kinds — Path/Clone/NewFolder — draw only the query line, as now). Cursor: `query_line`'s position when `child_active`.+- Modify: `view.rs:77` (`Color::Reset` page fill) and `:162` (`theme::fzf().bg_plus` for the active Recent row) and `:189` (`theme::DANGER` errors): the active Recent row uses `chrome.selected` (as `welcome_view.rs:145` already does); the page fill and the error colour stay what they are unless they are fixed colours the constraint forbids — `theme::DANGER`/`theme::WARN` are the palette's semantic colours, not a style of their own: keep `DANGER`. Only `bg_plus` goes.+- Modify: `tui/src/new_harness/welcome_view.rs:186-194` (the chooser: same `draw_child` dropdown, anchored at `y = chips_y + 1` (the row under the settings chips), `x = rect.x`, `w = width.min(60)`, so the task box and the controls stay visible; same four-row fallback to the overlay at `controls_y`); `:136-145` Recent rows already use `chrome.selected`. The welcome page's `settings` chips (`:8-54`) keep their text.+- Modify: `tui/src/new_harness/task/editor.rs:185` (the empty Task's ghost): `What task should this agent work on?` becomes `What should it do? @ computer : project % model`, drawn as whole ` `-separated parts that fit `area.width` (the same rule as `query_line`; the helper `settings::whole_parts(ghost: &str, w: u16) -> String` that Task 1 adds for `query_line`). The old copy is asserted in `welcome.rs:285`, `workspace_controls.rs:534`, `ui.rs:691`, `tests/welcome.py:128`, `tests/welcome-composer.py:93,164`: update them to `What should it do?`.+- Modify: `tui/src/new_harness.rs:1453` (the Task arm `_ if form.blocked(Field::Task).is_none()`): before `task_editor.key`, for `KeyCode::Char('@'|':'|'%')` with no CONTROL/ALT, typed at a word start (the task is empty, or its char before the cursor is whitespace — read it from `form.draft.task` and `form.task_editor` cursor), and the target field exists in `form.fields()` (`%` needs `Field::Model`): `child(app, &mut form, Choice::Machine(None) | Choice::Project | Choice::Model, "")`, `form.child_active = true`, the character is not inserted; `form.focus` stays `Task`, so the dropdown opens under the Task text and Esc (`back()`, `:1366`) closes it with the text unchanged. Elsewhere in a word the character is typed as usual. `@` is the Machine chooser on both surfaces (`Field::Machine` exists only on the page, `fields()` `:162`; `Choice::Machine(None)` works without it), `:` the Project chooser, `%` the Model chooser.+- Modify: `tui/src/new_harness.rs:193-198` (`blocked(Task)`) and `:305-335` (`describe`): the message becomes `Not available for <agent>` (`self.draft.what.label`); `tui/src/new_harness/welcome_view.rs:101-107`: when `form.blocked(Field::Task)` is Some and the task is empty, draw that message (muted) in the task box instead of the editor — today the welcome page shows the editor and drops keys silently, the form page already shows the blocked text.+- Modify: `tui/src/new_harness.rs:439-447` (`open`, the reopen branch): when `!form.starting && form.attempt.is_none()` set `form.focus = Field::Task` (if `task::supported(engine)`, else leave) and `form.child = None; form.child_active = false;` so a reopened form is focused on Task.+- Test: `tui/src/new_harness.rs` tests (`mod tests` at `:1870`; helpers there: `app()`, `open(&mut app, None, Some(cwd))`, `child(..)`, `key(app, Box<Form>, KeyEvent)`, `draw(&mut buf, area, &mut form)`, `set_engine`), `tui/tests/new-harness.py` (it crops the side chooser: `form_bounds` `:54`, `form_screen` `:58`, `settle_ui` `:62`; `shows('Search agents and harnesses')` after only `Down`,`Tab` at `:208-210` expects the inactive preview — change to press `Right` first (`:211`); `:374` `'Search agents' not in screen()` stays)+- **Existing Rust tests that assert the side panel and must be rewritten** (they contradict the new layout): `compact_form_and_side_choosers_stay_anchored_at_every_terminal_size` (`new_harness.rs:2249-2318`: `child_area.y == form.area.y`, `child_area.x == form.area.right() + 2`, `width >= 32`) → `child_area` is inside `form.area` (or equals it in the fallback), never intersects `task_area` when focus is not Task, and `form.hits.len() == form.fields().len()` still holds whenever the dropdown is not the fallback; `the_form_stays_put_when_a_chooser_opens` (`:1915`) keeps passing as is (`form.area` is the same); `terminal_resize_before_its_input_event…` (`:2340`) unchanged.++- [ ] **Step 1: Failing tests** (in `new_harness.rs` `mod tests`; two small helpers defined here):+```rust+fn press(app: &mut App, code: KeyCode) {+ let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };+ key(app, form, KeyEvent::new(code, KeyModifiers::NONE));+}+fn form_of(app: &App) -> &Form {+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };+ form+}++#[tokio::test]+async fn a_chooser_drops_down_under_its_field_in_the_panels_style() {+ let _l = crate::term_out::colours_lock();+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ form.focus = Field::Project;+ child(&mut app, &mut form, Choice::Project, "");+ form.child_active = true;+ let body = Rect::new(0, 0, 120, 36);+ let mut buf = Buffer::empty(body);+ draw(&mut buf, body, &mut form);+ let at = form.hits.iter().find(|(_, f)| *f == Field::Project).unwrap().0;+ assert_eq!(form.child_area.y, at.y + 1, "right under the Project row");+ assert_eq!(form.child_area.intersection(form.area), form.child_area, "inside the form: no side panel");+ assert!(form.task_area.intersection(form.child_area).is_empty(), "never over the Task line");+ assert_eq!(buf[(form.child_area.x + 1, form.child_area.y)].symbol(), "›", "the query line first");+ let c = crate::settings::chrome();+ let (y, _) = form.child.as_ref().unwrap().picker.row_at[0];+ assert_eq!(buf[(form.child_area.x + 3, y)].bg, c.selected.bg.unwrap(), "the chosen row on the panel's band");+}++#[tokio::test]+async fn at_colon_percent_in_the_task_open_their_choosers() {+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ for ch in "fix the login ".chars() { press(&mut app, KeyCode::Char(ch)); }+ press(&mut app, KeyCode::Char('@'));+ let f = form_of(&app);+ assert_eq!(f.child.as_ref().map(|c| c.kind.clone()), Some(Choice::Machine(None)));+ assert!(f.child_active);+ assert_eq!(f.draft.task, "fix the login ", "the @ is not typed into the task");+ press(&mut app, KeyCode::Esc);+ let f = form_of(&app);+ assert!(f.child.is_none());+ assert_eq!((f.focus, f.draft.task.as_str()), (Field::Task, "fix the login "));+ press(&mut app, KeyCode::Char('%'));+ assert_eq!(form_of(&app).child.as_ref().map(|c| c.kind.clone()), Some(Choice::Model));+ press(&mut app, KeyCode::Esc);+ press(&mut app, KeyCode::Char(':'));+ assert_eq!(form_of(&app).child.as_ref().map(|c| c.kind.clone()), Some(Choice::Project));+ press(&mut app, KeyCode::Esc);+ for ch in "a@b".chars() { press(&mut app, KeyCode::Char(ch)); }+ assert!(form_of(&app).child.is_none());+ assert_eq!(form_of(&app).draft.task, "fix the login a@b", "inside a word it is a letter");+}+```+(The default agent of `app()` is `opencode`, which takes a task; `Choice` derives `Clone, PartialEq, Debug`.)+- [ ] **Step 2: Run** — `cd tui && cargo test --locked a_chooser_drops_down at_colon_percent` → FAIL+- [ ] **Step 3: Implement** as in *Files*.+- [ ] **Step 4: Run** — `cargo test --locked` + `tests/new-harness.py` + `tests/welcome-composer.py` + `tests/welcome.py` → PASS+- [ ] **Step 5: Commit** — `git commit -am "New Harness: choosers drop down under their field in the command panel's style; @ : % in the task"`++### Task 4b: ← → on a Recent row, as in the command panel++**Why:** on the New Harness page's Recent rows (`Field::Recent(i)`), → falls to `KeyCode::Right if form.focus != Field::Create` (`new_harness.rs:1528-1530`) → `activate(app, &mut form)` (`:1092`), whose `_` arm calls `reveal` (nothing for `Recent`) and then sets `form.child_active = true` with no child — the keyboard is stuck in an empty chooser until Esc. ← is only handled for `Worktree` (`:1531-1535`) and does nothing on Recent. Enter/Space open a row through `welcome::activate` (`:1432-1434`). The user chose: **→ opens it (as Enter), ← goes back to the Task field** — the command panel's way (→ into, ← back).++**Files:** Modify `tui/src/new_harness.rs:1432-1434` (the Enter/Space check also takes `KeyCode::Right` when the focus is `Recent(_)`: `matches!(key.code, Enter | Char(' ')) || key.code == KeyCode::Right && matches!(form.focus, Field::Recent(_))`, still before the `form.focus == Field::Task` block), and the else-branch `:1527-1536` (a new arm before the `Worktree` one: `KeyCode::Left if matches!(form.focus, Field::Recent(_) | Field::Browse | Field::Terminal) => { form.focus = Field::Task; reveal(app, &mut form); }`); Test: `tui/src/new_harness/welcome.rs` tests (`mod tests` at `:248`; helpers there: `app()`, `event(&mut app, code, mods)`, `ensure`, `take_active`, `store_form`, `prepare`; agents in the fleet become Recent rows as in the test at `:616`). → on Browse/Terminal (same empty-chooser trap) is left as it is: listed as an open question, not part of this task.++- [ ] **Step 1: Failing test**+```rust+#[tokio::test]+async fn right_opens_a_recent_row_and_left_goes_back_to_the_task() {+ let mut app = app();+ for i in 0..3 {+ let a = crate::fleet::agent_from("local", &json!({"id":format!("{i}"), "name":format!("Work {i}"), "engine":"codex"}), None);+ app.fleet.agents.insert(a.key(), a);+ }+ ensure(&mut app, None, None);+ let tab = app.tab().id.clone();+ let mut form = take_active(&mut app).unwrap();+ prepare(&app, &mut form);+ assert!(form.recent.len() >= 2);+ form.focus = Field::Recent(1);+ store_form(&mut app, form);+ event(&mut app, KeyCode::Left, KeyModifiers::NONE);+ assert_eq!(app.welcome.forms[&tab].focus, Field::Task);+ assert!(app.tab().home, "← opens nothing");+ app.welcome.forms.get_mut(&tab).unwrap().focus = Field::Recent(1);+ event(&mut app, KeyCode::Right, KeyModifiers::NONE);+ assert!(!app.tab().home, "→ opened the harness, as Enter on Recent(1) does");+}+```+(If `open_agent` needs a pane the test app lacks, compare with Enter on a second identical app instead: the effect of Right must equal the effect of `event(.., KeyCode::Enter, ..)`; verify by running both once.)+- [ ] **Step 2: Run** — `cd tui && cargo test --locked right_opens_a_recent_row` → FAIL+- [ ] **Step 3: Implement** as in *Files*. → on the Task field keeps moving the text cursor; → on other fields keeps opening their chooser.+- [ ] **Step 4: Run** — `cargo test --locked` + `tests/welcome.py` → PASS+- [ ] **Step 5: Commit** — `git commit -am "New Harness: → opens a recent harness, ← goes back to the task"`++### Task 5: Gate and look++- [ ] `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui`+- [ ] Isolated hn, dark and light theme, and `NO_COLOR=1`: screenshot the command panel, the shell composer and the New Harness dropdown side by side — same chosen-row band, same muted rule.++## Review Focus++- A light theme and a 256-colour terminal: the chosen row stays readable (`chrome()`'s `lifted` already handles both — verify the composer uses it, not fzf's 236).+- The theme changed while a shell picker is open or between pickers: the next reply carries the new colours (Task 3: every catalog reply says the theme, including `unchanged` ones). The first frame of a picker is in the default palette.+- A shell composer near the bottom of a pane: the region is reserved by scrolling (`Screen::new`), as today; the panel needs at least 4 rows (query, rule, one row, keys) and 24 columns, below that only the query line shows.+- Very narrow panes (< 24 columns): the ghost shows whole scopes only; the count is on its own row in the composer; on the pickers that stay on the fzf frame the count keeps two blanks after the ghost (today "Search agents14/14", `ui.rs:1461-1468`).+- The New Harness form with its dropdown open on a short terminal: the dropdown never covers the Task line being typed (it is drawn under the focused row; with fewer than 4 rows left the old full-form overlay is used, which covers the form while the chooser is active, as the narrow layout does today).++## Plan review (2026-10-07): conflicts between tasks++| Pair / task | File or interface | Verdict |+|---|---|---|+| 1 and 2 | `settings::query_line/count_rule/keys_line`; Task 2's `inline_panel` calls them | Task 1 first; signatures fixed here (`query_line` returns `(Position, u16)`, `count_rule` takes `marked`). |+| 1 and 4 | same functions; Task 4's `draw_child` calls them; `whole_parts` helper is added in Task 4 but `query_line` (Task 1) should use it | Add `whole_parts` in Task 1 (it is `query_line`'s ghost rule); Task 4 only calls it. |+| 2 and 3 | `shell_picker.rs` (`compose_scope`/loop vs `Items`/reply loop), `ui.rs` | Different regions; Task 3's `look` makes Task 2's `chrome()` the TUI's theme. Order 1, 2, 3 or 3 then 2; both before the Task 5 look. |+| 2 and 4 | `ui.rs` / `view.rs` | Disjoint files; both depend on Task 1 only. |+| 4 and 4b | `new_harness.rs` key paths (`:1432`, `:1453`, `:1527`) and `blocked`/`open` | Same function `key`, different arms; do 4 before 4b (4b's `Left` arm calls `reveal`, whose result Task 4 changes to "not drawn until active"). |+| Task 1 tests vs code | characterisation test + new-function test | Match (fixed: `Picker::new(title, placeholder)`, `Commands` is not a launcher). |+| Task 2 tests vs code | `shell_panel` flag, `inline_fzf` signature, count `" 2/2 ─"` | Match after fixes; `shell-first.py` (not `composer-machine.py`) is the screen-reading test. |+| Task 3 tests vs code | `reply_data`, `Items.look`, `term_out` setters | Match after fixes. |+| Task 4 tests vs code | `press`/`form_of` defined; side-panel test rewritten | Match after fixes. |+| Task 4b test vs code | welcome `app()/ensure/take_active/store_form/event` | Match; the "opened" assertion depends on `open_agent` in a bare test app (fallback given). |+| Global Constraints | "no `Color::*`": `view.rs:77` (`Color::Reset` page fill) and `welcome_view.rs` (`bg(Color::Reset)`) already exist | Left as is: they are the page's transparent surface, not a list style; only `theme::fzf().bg_plus` is removed. |+| Global Constraints | "behaviour unchanged" vs dropping the inactive chooser preview while arrowing, ignoring the fzf `--layout/--border/--info` and `@hn-lists fzf` in the composer, the new empty-form copy | Consequences of the requested look; listed for the owner to confirm. |diff --git a/docs/plans/2026-10-07-008-side-bar-machines-plan.md b/docs/plans/2026-10-07-008-side-bar-machines-plan.mdnew file mode 100644index 000000000..f990d4fdc--- /dev/null+++ b/docs/plans/2026-10-07-008-side-bar-machines-plan.md@@ -0,0 +1,316 @@+# Side bar: see and use every machine — Implementation Plan++> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.++**Goal:** In the side bar's `machines` list, each machine shows its harnesses (not only the windows open here), a harness opens with a click, and a machine row always does something: open a window, offer a small menu, connect, or say it is offline.++**Architecture:** Only the side bar (`bar.rs`), one small menu (`machine_menu.rs`) and two small public helpers in `devices.rs`. Everything it needs exists: the account's machines and each usable machine's roster are already in `app.fleet` (`merge_roster` in `relist`, `app.rs:1457-1482`); a harness opens as a window with `open-harness -s <machine>:<agent>` (`commands.rs:3650`; `find_harness`, `commands.rs:1330`, takes `machine-id:agent-id` or `machine-name:agent-id`; a harness already open here is gone to, not opened twice, `commands.rs:3679-3682`); a machine's harness list is the Open picker filtered to it (`devices.rs:1026-1034`, the `open` arm of `machine_action`, row "Open its harnesses" at `:1174`); linking is `Machines & devices` → `Connect…` (`devices::connect_to`, `devices.rs:438`, already `pub`: it opens the Connect view with the machine chosen and asks for its remote password; the row is `:1175`); New Harness opens preset to a machine with `new_harness::open(app, Some(machine), None)` (`new_harness.rs:410`; it refuses a machine that is not `usable()`). Menus are `workspace_menu` (the Pane / Tab menus' component; items run a command string through `commands::execute`, so the menu needs one small command, `machine-menu`). No yes/no step is added, so this plan does not depend on plan 003's button row.++**Tech Stack:** Rust (ratatui), Python native fixtures.++**Spec:** user 2026-10-07: "why can't I click to connect to the other machines?" … "I see it's online, but I can't click to control it or see the harnesses on the other machines." Agreed behaviour (item 7 of the 2026-10-07 list).++## Why nothing happens today++- `machine_entries` (`bar.rs:305-331`) lists under a machine only **windows of this hn** that have a pane on it. A machine with no such window has no rows under it, so its harnesses are invisible here.+- Its row's hit is `Hit::Machine(None)`, and a click on that does nothing (`bar.rs:490`: `Hit::Machine(None) | … => {}`). Same for a machine that needs a link or is offline.+- A right press on the bar does nothing for a machine: the bar's own `mouse` (`bar.rs:518`) takes only the left press and the wheel. Right presses reach the bar's code only through `workspace_controls::mouse` (`workspace_controls.rs:132`, called first from `input.rs:~314`), whose right-press branch (`:164-170`) already maps a bar `Hit::Window` to the Tab menu; a machine row is added there.++## Controller rulings (2026-10-07, after the plan check) — these OVERRIDE the task text below where they differ++1. **Other machine states:** `Connecting` → a click says `<name> is connecting…` and opens Machines & devices on it; `Error(msg)` → says `<name>: <msg>` and opens Machines & devices on it; `Unknown` → treated as offline. Right-click always opens the menu.+2. **Machine ids in menu commands are quoted** with the same quoting the command parser reads (`crate::commands` word splitting: wrap in single quotes, escape `'`), so an id or name with spaces works; add a test with an id containing a space.+3. **Tests:** set `app.mouse = true` where a press needs it; the scroll test chooses a bar height that really scrolls (assert the precondition first); if the new `machine-menu` command trips a command-list/help test, register it the way other internal commands are (hidden from the palette) rather than editing those tests' expectations.+4. **Build after plan 003 and plan 006** have merged (they share `workspace_menu.rs` / `workspace_controls.rs`).++## Global Constraints++- **No custom style:** rows use the side bar's existing marks and colours (`mark()` / `theme::state_mark`, `machine_spans`, the window rows' style); menus are `workspace_menu`.+- The current behaviour stays where it works: a machine with a window here still jumps to it on click; window and pane rows are unchanged.+- Read-only clients (`app.read_only()`) and `tmux_look` do not get the menu (the same opt-outs as the header controls, `workspace_controls.rs:33`, `enabled()`); clicks there keep today's behaviour.+- A harness already open in a window here is shown once — as that window's row, not again as a harness row.+- Copy per `docs/naming-system.md`: "harness", "computer"/"machine" as the side bar already says, "New Harness", "New Terminal".++## Target look (side bar, `machines` section)++Marks are the bar's own: a harness row's mark is `bar::mark(Some(state))` (spinner working, `?` needs you, `✓` done, `✗` failed; idle/paused/offline harnesses have no mark and the name sits close, as on the window rows); a machine's mark is `theme::machine_mark` (`✓` connected, `?` needs a link, `·` offline).++```+ machines+ ✓ Mac Auto+ ├─ 1:Harness TUI LMStudio 2 ← a window here (as today)+ └─ 3:pi:c+ ✓ grid-dev+ ├─ ? Run Ollama model on Mac ← its harnesses not open here: mark (if any) + name+ ├─ Start grid chat model+ ├─ Review the daemon logs+ └─ + 4 more ← opens "Open its harnesses" (the Open picker on grid-dev)+ ? linux-box ← needs a link: a click opens Connect…+ · MacBook-Air.local offline ← offline: a click says so+```++## Review Focus++- A machine with 40 harnesses must not push the other machines off the list: at most 3 harness rows per machine, then `+ N more`.+- A roster that arrives while the bar is scrolled: the scroll position stays on the same entry. `scroll_list` (`bar.rs:435`) keeps only an entry **index** (`app.bar.scroll`), and `follow` only moves it to the focused row, so Task 1 Step 3 adds the identity keeping.+- Clicking a harness that is already opening (a slow remote attach) twice opens one window, not two: verified, `open-harness -s` on a harness with a pane here selects that window (`commands.rs:3679-3682`), and once the first click has made the pane the row is drawn as a window row (`Hit::Window`) anyway. Task 1's test runs the command twice.+- A stopped harness (`status == "stopped"`) is not listed; `agent_rows` in the Open picker decides whether its list shows stopped ones.+- `This computer` and the local machine id show the same rows (no duplicate machine): the local-shells machine (`hn-local-shells`, `local::MACHINE`) holds only terminals, which are never listed, so no harness row can repeat.++---++### Task 1: Each machine's harnesses in the side bar++**Files:**+- Modify: `tui/src/bar.rs:40-56` (`Hit`: add `Harness(String, String)` — machine, agent; `More(String)` — machine), `:305-331` (`machine_entries`), `:435-442` (`scroll_list`), `:495-508` (`wheel`: add arms), `:480-492` (`click`: `Harness` → `crate::commands::execute(app, &format!("open-harness -s {m}:{a}"))`; `More(m)` → `crate::devices::open_machine_list(app, &m)`), `State` (`:60`: `top: [Option<Hit>; 2]`)+- Modify: `tui/src/devices.rs:1026-1034` (move the `open` arm's picker building into `pub(crate) fn open_machine_list(app: &mut App, machine: &str)`; the arm keeps `app.devices.sub = None;` and calls it)+- Test: `tui/src/bar.rs` tests (next to `the_bar_draws_the_machine_its_windows_with_their_panes_then_the_machines`, `:639`)++**Interfaces:**+- Produces: `Hit::Harness(String, String)`, `Hit::More(String)`; `pub(crate) fn devices::open_machine_list(app: &mut App, machine: &str)`.+- `Hit` stays `Clone` (it is not `Copy`); the new variants only add arms: `wheel` takes `Hit::Machines | Hit::Machine(..) | Hit::Harness(..) | Hit::More(_) | Hit::Fold => 1`, `click` takes the two new arms. Nothing outside `bar.rs` matches `Hit` exhaustively (`workspace_controls.rs:165` matches `Hit::Window(i)` with `_`).++- [ ] **Step 1: Failing tests** — the bar tests' real helper is `app(size, side)` (`bar.rs:560`: machines `local` "studio" Ready and `lab` Offline, four panes in two windows), with `screen(&mut app) -> (String, Buffer)`, `ev(kind, column, row)` and `mouse(app, &ev)`. Add these helpers to the `tests` module and the tests after them:++```rust+/// The bar app of `app((120, 50), "left")` plus the machine `grid` (named `grid-dev`, Ready) with+/// [n] harnesses that are open in no window here.+fn with_grid(n: usize) -> App {+ let mut app = app((120, 50), "left");+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "grid".into(), name: "grid-dev".into(), local: false, status: "online".into(), reach: crate::fleet::Reach::Ready });+ let rows: Vec<_> = (0..n).map(|i| json!({"id": format!("g{i}"), "name": format!("Grid task {i}"), "engine": "codex"})).collect();+ app.fleet.merge_roster("grid", &rows);+ app+}++/// Draw, then the first bar rect whose hit [want] accepts.+fn rect_of(app: &mut App, want: impl Fn(&Hit) -> bool) -> Rect {+ let _ = screen(app);+ app.bar.hits.iter().find(|(_, h)| want(h)).map(|(r, _)| *r).expect("that entry is drawn")+}++/// A left press on that entry (three columns in, on its first row).+fn click_on(app: &mut App, want: impl Fn(&Hit) -> bool) {+ let r = rect_of(app, want);+ assert!(mouse(app, &ev(MouseEventKind::Down(MouseButton::Left), r.x + 3, r.y)));+}++fn harness(m: &str, a: &str) -> Hit { Hit::Harness(m.into(), a.into()) }++#[test]+fn a_machine_lists_its_harnesses_not_open_here_three_then_more() {+ let mut app = with_grid(5);+ let (s, _) = screen(&mut app);+ assert!(s.contains("grid-dev"), "{s}");+ // (Equal recency: the name decides, so the first three are 0, 1, 2.)+ assert!(s.contains("Grid task 0") && s.contains("Grid task 2"), "{s}");+ assert!(!s.contains("Grid task 3"), "three rows at most: {s}");+ assert!(s.contains("+ 2 more"), "{s}");+ assert!(app.bar.hits.iter().any(|(_, h)| *h == Hit::More("grid".into())));+ // Not for a machine that is not Ready (`lab`: offline, a roster of two): none.+ assert!(!app.bar.hits.iter().any(|(_, h)| matches!(h, Hit::Harness(m, _) if m == "lab")));+}++#[test]+fn a_harness_open_in_a_window_here_is_shown_once() {+ let mut app = with_grid(5);+ let mut tab = Tab::new("Grid task 0");+ tab.root = Some(Node::new(5, 40, 20));+ tab.focus = Some(5);+ let mut pane = Pane::new(5, "grid", "g0", 40, 20);+ pane.phase = Phase::Live;+ app.panes.insert(5, pane);+ app.tabs.push(tab);+ app.fit_panes();+ let _ = screen(&mut app);+ // (Its window's row is in both lists; as a harness row it is not drawn.)+ assert!(!app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g0")));+ assert!(app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g1")));+}++#[tokio::test]+async fn clicking_a_harness_row_opens_it_and_more_opens_the_machines_list() {+ let mut app = with_grid(5);+ click_on(&mut app, |h| *h == harness("grid", "g1"));+ assert!(app.find_pane("grid", "g1").is_some(), "open-harness ran");+ // Again (a slow attach): the same window, not a second one.+ let windows = app.tabs.len();+ crate::commands::execute(&mut app, "open-harness -s grid:g1");+ assert_eq!(app.tabs.len(), windows);+ click_on(&mut app, |h| *h == Hit::More("grid".into()));+ assert!(matches!(&app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Open { machine: Some(m), .. }, .. }) if m == "grid"));+}++#[test]+fn a_roster_arriving_keeps_the_scroll_on_the_same_entry() {+ let mut app = with_grid(0);+ app.size.1 = 20; // few rows: the machines list scrolls+ let _ = screen(&mut app);+ assert!(app.bar.max_scroll[1] > 0, "lower the height until the machines list scrolls");+ wheel(&mut app, Hit::Machines, false);+ let top = |app: &mut App| { let _ = screen(app); app.bar.top[1].clone() };+ let before = top(&mut app);+ let rows: Vec<_> = (0..5).map(|i| json!({"id": format!("g{i}"), "name": format!("Grid task {i}"), "engine": "codex"})).collect();+ app.fleet.merge_roster("grid", &rows);+ assert_eq!(top(&mut app), before, "the first entry shown is the same one");+}+```+(`Tab`, `Node`, `Pane`, `Phase`, `json` are already imported by the tests module.)++- [ ] **Step 2: Run** — `cd tui && cargo test --locked bar::` → FAIL (does not compile: `Hit::Harness`, `Hit::More`, `bar.top`).+- [ ] **Step 3: Implement**+ - **Rows.** In `machine_entries`, the children of a machine are, in order: its window rows (as today), then its harness rows, then `+ N more`; the tree prefix is chosen over **all** of them (`├─ ` for each but the last child, `└─ ` for the last), so `window_entry(.., Some(prefix))` is called with the prefix of its position among all children, not only among windows (today the last window gets `└─ `). Harness rows only for `m.usable()` machines (the others have no roster): agents of `app.fleet.agents` with `a.machine_id == id`, `a.status != "stopped"`, `a.engine != "terminal"`, `app.find_pane(&id, &a.id).is_none()` (not open in a window of this session), sorted by `(Reverse(a.recency()), &a.name)`; the first 3 become `Entry { rows: vec![(1, [prefix, mark, name])], right: None, hit: Hit::Harness(id, a.id), current: false }` where mark is `mark(Some(app.fleet.state_of(a)), c, app.tick)` as `window_entry` builds it (no mark when it is a blank), then, when more remain, `Entry { rows: vec![(1, [prefix, "+ N more"])], hit: Hit::More(id), current: false }`.+ - **Offline label.** A machine that is not `online()` gets `right: Some(("offline", muted))` on its heading (`Entry.right` is drawn by `list`); `machine_spans` is given `width - 8` for it so the name is cut before the label.+ - **Scroll identity** (Review Focus). `State` gets `top: [Option<Hit>; 2]` (`State` derives `Default`, which covers it). In `scroll_list`, before clamping: if `!follow` and `app.bar.top[which]` is `Some(h)` and the entry at index `s` is not `h`, move `s` to the entry whose `hit == h` nearest to `s` (`min_by_key(|i| i.abs_diff(s))`; window rows repeat under several machines, so "nearest"), then clamp as today; after: `app.bar.top[which] = entries.get(s).map(|e| e.hit.clone())`. `wheel` still changes the index, and the next draw records the new top.+ - **Click/wheel.** As in **Files**. `devices::open_machine_list` is the `open` arm's body from `let kind = PickerKind::Open { … machine: Some(machine) … }` to `app.modal = Some(Modal::Picker { kind, picker: next })`, with `machine` a `&str` made `String`.+- [ ] **Step 4: Run** → PASS (and the existing bar tests: `the_bar_draws_…` is unchanged because `studio`'s harnesses are open in windows and `lab` is offline, so it gets no harness rows, only the `offline` label after ` · lab`, which `starts_with(" · lab")` still accepts)+- [ ] **Step 5: Commit** — `git commit -am "side bar: each machine's harnesses, opened with a click"`++### Task 2: A machine row always does something++**Files:**+- Modify: `tui/src/bar.rs:46` (`Hit::Machine(String, Option<usize>)` — the machine id too), `:323` (build it with the id), `:480-492` (`click` → `click_at(app, hit, at)`, `click(app, hit)` stays as `click_at(app, hit, None)` so `click(&mut app, Hit::Fold)` in the existing tests keeps compiling), `:535-536` (`mouse` passes `Some((ev.column, ev.row + 1))`), `:502` (`wheel`: `Hit::Machine(..)`), tests `:731-732` (see Interfaces)+- Modify: `tui/src/workspace_controls.rs:33` (`enabled` becomes `pub(crate)`), `:164-170` (the right-press branch: before the `let tab = …` lookup, `if let Some(crate::bar::Hit::Machine(m, _)) = crate::bar::hit_at(app, mouse.column, mouse.row) { begin_press(app, MouseButton::Right); crate::machine_menu::open(app, &m, at); return true; }`)+- Modify: `tui/src/devices.rs` (add `pub(crate) fn open_machine(app: &mut App, machine: &str)`: `open(app, View::Machines); sub(app, format!("m:{machine}"))` — Machines & devices on that machine's own actions; `sub` is private to `devices.rs`)+- Modify: `tui/src/commands.rs:90-97` (table: `("machine-menu", "machine-menu", "Actions for a machine: machine-menu <new-harness|new-terminal|open|connect|machine> <machine>")`), `:3537` (dispatch: `"machine-menu" => crate::machine_menu::command(app, &words[1..])`), `tui/src/main.rs:44` (`mod machine_menu;`)+- Create: `tui/src/machine_menu.rs` — `pub fn open(app: &mut App, machine: &str, at: Option<(u16, u16)>)` building a `workspace_menu` (items are `menu::item(label, key, format!("machine-menu {verb} {machine}"))`) and `pub fn command(app: &mut App, args: &[String])` running the verb+- Test: `tui/src/bar.rs` tests, `tui/src/machine_menu.rs` tests++**Interfaces:**+- Consumes: `devices::open_machine_list` (Task 1), `new_harness::open(app, Some(machine), None)`, `devices::connect_to(app, machine)` (`devices.rs:438`, `pub`), `devices::open_machine` (new), `crate::input::new_shell_from(app, Some((machine, String::new())), Placement::Auto(None), None, None)` (what the `terminal` key runs, `input.rs:1053`; `shell_machine` takes the machine from the first tuple field, `input.rs:1359`).+- Produces: `machine_menu::open`, `machine_menu::command`, `devices::open_machine`.+- `Hit::Machine` changing shape breaks, and Step 3 fixes: the construction `bar.rs:323`; the `click` arms `:488` (`Hit::Window(i) | Hit::Machine(Some(i))`) and `:490` (`Hit::Machine(None) | …`); the `wheel` arm `:502` (`Hit::Machine(_)` → `Hit::Machine(..)`); the test `a_click_on_the_bar_does_what_its_entry_says` `:731-732` (`Hit::Machine(Some(0))` → find `Hit::Machine(m, Some(0)) if m == "lab"`, and `hit_at` equals `Hit::Machine("lab".into(), Some(0))`). Task 1 must land first (same enum, same `click` match).+- Not for a read-only client or `tmux_look` (`workspace_controls::enabled`): a machine heading there keeps today's click (its window, else nothing) and gets no menu and no Connect/offline action.++| Machine | Left click | Right click |+|---|---|---|+| Has a window here | Its first window (today) | Menu |+| Ready, no window here | Menu | Menu |+| Online, needs a link (`reach == NeedsLink && online()`, mark `?`) | `devices::connect_to` (Connect view, password asked) | Menu (Connect… first) |+| Anything else — offline (and, not specified by the agreed behaviour, Connecting / Error / Unknown, treated as offline) | Status message `<name> is offline — start Harness on it` (`app.say(.., theme::WARN)`), then `devices::open_machine` | Menu (only Machines & devices…) |++Menu items (title = the machine's name; shown per the table): `New Harness on <name>…` (n, `new-harness`: `new_harness::open(app, Some(id), None)`), `New Terminal on <name>` (t, `new-terminal`: `new_shell_from` as above), `Open its harnesses` (o, `open`: `devices::open_machine_list`) — these three only when `usable()`; `Connect…` (c, `connect`: `devices::connect_to`, only when it needs a link and is online), `Machines & devices…` (m, `machine`: `devices::open_machine`).++- [ ] **Step 1: Failing tests** — in `bar.rs` tests (helpers `with_grid`, `rect_of`, `click_on`, `harness` from Task 1; `Machine` has no `Default`, so each machine is a full literal):++```rust+fn machine(id: &str, name: &str, status: &str, reach: crate::fleet::Reach) -> crate::fleet::Machine {+ crate::fleet::Machine { shared: false, id: id.into(), name: name.into(), local: false, status: status.into(), reach }+}++#[tokio::test]+async fn a_ready_machine_without_a_window_opens_its_menu() {+ let mut app = with_grid(2);+ click_on(&mut app, |h| *h == Hit::Machine("grid".into(), None));+ let Some(crate::modal::Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ assert_eq!(m.title, "grid-dev");+ let labels: Vec<_> = m.items.iter().map(|i| i.label.as_str()).collect();+ assert!(labels.contains(&"New Harness on grid-dev…") && labels.contains(&"Open its harnesses"), "{labels:?}");+ assert!(!labels.contains(&"Connect…"));+}++#[tokio::test]+async fn a_machine_that_needs_a_link_opens_connect_and_an_offline_one_says_so() {+ let mut app = app((120, 50), "left");+ app.fleet.machines.push(machine("lb", "linux-box", "online", crate::fleet::Reach::NeedsLink));+ click_on(&mut app, |h| *h == Hit::Machine("lb".into(), None));+ assert!(matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Devices(crate::devices::View::Connect), .. })));+ app.modal = None;+ app.fleet.machines.push(machine("air", "MacBook-Air.local", "offline", crate::fleet::Reach::Offline));+ click_on(&mut app, |h| *h == Hit::Machine("air".into(), None));+ assert!(app.toast.as_ref().is_some_and(|t| t.0.contains("MacBook-Air.local is offline")), "{:?}", app.toast);+ assert!(matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Devices(crate::devices::View::Machines), .. })));+}++#[tokio::test]+async fn a_machine_with_a_window_here_still_jumps_to_it_and_a_right_press_opens_its_menu() {+ let mut app = app((120, 50), "left");+ app.select_tab(1);+ click_on(&mut app, |h| matches!(h, Hit::Machine(m, Some(0)) if m == "lab"));+ assert_eq!(app.active, 0);+ // Right press: through the same path the real input takes (workspace_controls first).+ let r = rect_of(&mut app, |h| matches!(h, Hit::Machine(m, _) if m == "local"));+ let press = ev(MouseEventKind::Down(MouseButton::Right), r.x + 3, r.y);+ assert!(crate::workspace_controls::mouse(&mut app, &press));+ assert!(matches!(&app.modal, Some(crate::modal::Modal::Menu(m)) if m.title == "studio"));+}+```+(The third test needs `app.mouse` true; if the bar tests' `app()` leaves it false, set `app.mouse = true` first. A read-only client — `app.client_flags.push("read-only".into())` — gets no menu: assert `app.modal.is_none()` after the same right press and that the left click on `grid` does nothing.)++and in `tui/src/machine_menu.rs` tests (explicit app, as `workspace_menu.rs`'s tests build theirs):++```rust+#[cfg(test)]+mod tests {+ use super::*;+ use crate::modal::Modal;++ fn grid() -> App {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19798, tx, (160, 40));+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "grid".into(), name: "grid-dev".into(), local: false, status: "online".into(), reach: crate::fleet::Reach::Ready });+ app+ }++ /// Run the menu item with this label the way a chosen item runs: its command.+ fn choose(app: &mut App, label: &str) {+ let Some(Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ let command = m.items.iter().find(|i| i.label == label).unwrap_or_else(|| panic!("no item {label}")).command.clone();+ app.modal = None;+ crate::commands::execute(app, &command);+ }++ #[tokio::test]+ async fn new_harness_on_a_machine_opens_the_form_on_it() {+ let mut app = grid();+ open(&mut app, "grid", None);+ choose(&mut app, "New Harness on grid-dev…");+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!("the form") };+ assert_eq!(form.draft.machine, "grid");+ }++ #[tokio::test]+ async fn the_menu_lists_only_what_the_machine_can_do() {+ let mut app = grid();+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "air".into(), name: "air".into(), local: false, status: "offline".into(), reach: crate::fleet::Reach::Offline });+ open(&mut app, "air", None);+ let Some(Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ assert_eq!(m.items.iter().map(|i| i.label.as_str()).collect::<Vec<_>>(), ["Machines & devices…"]);+ }+}+```+- [ ] **Step 2: Run** → FAIL+- [ ] **Step 3: Implement** as in the table, **Files** and **Interfaces** above. `bar::click_at` guards the menu / Connect / offline paths with `crate::workspace_controls::enabled(app)`; when it is false the old arms apply (`Some(i)` → the window, `None` → nothing).+- [ ] **Step 4: Run** → PASS (`cd tui && cargo test --locked bar:: machine_menu::` and the commands-table tests, since `machine-menu` is a new table entry)+- [ ] **Step 5: Commit** — `git commit -am "side bar: a machine row opens its window, its menu, Connect…, or says it is offline"`++### Task 3: Fixture and gate++**Files:** Modify `tui/tests/workspace-controls.py` (the fixture already has a `Remote` computer, `api({'action': 'machines', 'remote': True})`; helpers `click_text(text, occurrence, button, row, before)`, `click(x, y, button)` — button `2` is the right button — `shown`, `wait`, `hn`, `screen`)++- [ ] **Step 1: Journey** — set the bar on the left (`hn('set', '-g', '@hn-status-bar', 'left')`); the remote machine's harnesses appear under it in the `machines` section; `click_text` one → a new window shows its terminal (`shown('Gamma remote task terminal')`); right-click the machine (`click_text('Remote', button=2)`) → the menu lists `New Harness on …`; Esc closes it; remove the remote (`api({'action': 'machines', 'remote': False})`) → its rows go. (If the fixture's remote roster has only harnesses already open in windows, add one the journey does not open, so a harness row exists to click.)+- [ ] **Step 2: Gate** — `cd tui && cargo test --locked && cargo build --release --locked && cd .. && python3 scripts/validate-tui-native.py tui/target/release/harness-tui`+- [ ] **Step 3: Commit** — `git commit -am "side bar machines: fixture journey"`++## Conflicts++Task pairs touching the same file or interface:++| Pair | Shared | Resolution |+|---|---|---|+| Task 1 – Task 2 | `bar.rs` `Hit` enum, `click` match, `wheel` match, `machine_entries`; `devices.rs` `machine_action` | Task 1 adds variants and `open_machine_list`; Task 2 reshapes `Hit::Machine` afterwards. Task 2 builds the machine heading entry (`:323`) that Task 1 left as is. Order: 1 then 2. |+| Task 2 – Task 3 | right-click menu, bar rows | The fixture only drives behaviour Tasks 1 and 2 provide; run after both. |+| Task 1 – Task 3 | harness rows | Same: the fixture needs the rows. |++Per task, do its tests match its code: Task 1 yes (real helpers, `Hit::More`/`Harness` exist after Step 3; the scroll test needs `State::top`, added in Step 3). Task 2 yes (the existing `bar.rs` test at `:731` is updated in the same task; `machine_menu` tests build their own app). Task 3 yes (real fixture helpers). Nothing contradicts the Global Constraints: the read-only / `tmux_look` opt-out is `workspace_controls::enabled`; window and pane rows are untouched; a harness open here is not drawn twice (`find_pane`).++Cross-plan overlaps (other plans are not changed):++| Plan | File | Overlap |+|---|---|---|+| 003 (button row) | `workspace_menu.rs` (`Layout.buttons`, `fit`) | Task 2 uses `workspace_menu::open` with plain items; 003's `actions are no longer items.last()` change only affects button menus. No code conflict; 008 does not use `buttons::Row`. |+| 003 | `devices.rs` (`prompt_actions` `:1382-1394`, clicks `:819-835`, `answer_key` `:870-880`) | 008 adds `open_machine_list` / `open_machine` and edits the `open` arm (`:1026-1034`), away from those lines; the Connect password prompt that `connect_to` shows gets 003's buttons. |+| 003 | `input.rs` menu keys `:1632-1681`, `menu_mouse` `:3549-3574` | 008 does not edit `input.rs`; its menu rides those handlers unchanged. |+| 006 (pane drag) | `workspace_controls.rs` `mouse` / `finish_press` (`:118-148`) and the right-press branch | 008 adds one arm in the right-press branch (`:164-170`) and makes `enabled` (`:33`) `pub(crate)`; 006 edits `finish_press` and the header press in the same function: merge by hand. 006 reads `bar::hit_at` only for `Hit::Window`. |+| 005 (flicker) | `input.rs` | 008 does not touch `input.rs`; no overlap. |+| 004, 007 | none of `bar.rs`, `devices.rs`, `workspace_menu.rs`, `input.rs` | none |diff --git a/tui/Cargo.lock b/tui/Cargo.lockindex 0a758424e..f32edc09f 100644--- a/tui/Cargo.lock+++ b/tui/Cargo.lock@@ -654,7 +654,7 @@ dependencies = [[[package]]name = "harness-tui"-version = "0.1.16"+version = "0.1.17"dependencies = ["alacritty_terminal","base64",diff --git a/tui/Cargo.toml b/tui/Cargo.tomlindex 860a56eb7..e7e9e347c 100644--- a/tui/Cargo.toml+++ b/tui/Cargo.toml@@ -1,6 +1,6 @@[package]name = "harness-tui"-version = "0.1.16"+version = "0.1.17"edition = "2024"[dependencies]diff --git a/tui/src/account.rs b/tui/src/account.rsindex 24058e643..2014086be 100644--- a/tui/src/account.rs+++ b/tui/src/account.rs@@ -31,6 +31,7 @@ enum Phase {Confirm(String),Completing,Committed,+ SigningOut,Failed(String),}@@ -64,7 +65,14 @@ fn visible(app: &App) -> bool { matches!(app.modal, Some(Modal::Picker { kind: Ppub(crate) fn identity_changed(app: &mut App) {app.account.checked = None; app.account.checking = false;- if app.account.driver.is_none() { app.account.status = Status::Unknown; app.account.phase = Phase::Ready; }+ // `harness logout` restarts the daemon before it exits; the sign-out finishes when it does.+ if app.account.driver.is_none() && app.account.phase != Phase::SigningOut { app.account.status = Status::Unknown; app.account.phase = Phase::Ready; }+}++/// The command panel's Sign out: on the account page, where its progress and any error show.+pub fn sign_out_command(app: &mut App) {+ open(app);+ sign_out(app);}pub fn refresh(app: &mut App, force: bool) {@@ -141,11 +149,13 @@ pub fn fill(app: &App, picker: &mut Picker) {Phase::Committed => {rows.push(Row::new("account:wait", "Signed in · connecting this computer…"));}+ Phase::SigningOut => rows.push(Row::new("account:wait", "Signing out…")),Phase::Ready | Phase::Failed(_) => match &app.account.status {Status::SignedIn { .. } => {rows.push(Row::new("account:machines", "Connect a machine"));rows.push(Row::new("account:phone", "Add your phone"));rows.push(Row::new("account:models", "Models on your machines"));+ rows.push(Row::new("account:signout", "Sign out"));}_ => {rows.push(Row::new("account:google", "Continue with Google"));@@ -159,7 +169,7 @@ pub fn fill(app: &App, picker: &mut Picker) {// across sign-in phases; set_rows still preserves the selected action by ID.picker.rows.clear();picker.set_rows(rows);- picker.busy = matches!(app.account.phase, Phase::Starting | Phase::Completing | Phase::Committed).then(|| "waiting".into());+ picker.busy = matches!(app.account.phase, Phase::Starting | Phase::Completing | Phase::Committed | Phase::SigningOut).then(|| "waiting".into());}fn refill(app: &mut App) {@@ -198,6 +208,7 @@ pub fn preview(app: &App, _: &str) -> Vec<Line<'static>> {}Phase::Failed(message) => lines.push(Line::raw(message.clone())),Phase::Starting => lines.push(Line::raw(app.account.waiting.clone().unwrap_or_else(|| "Opening sign-in…".into()))),+ Phase::SigningOut => lines.push(Line::raw(SIGNING_OUT)),_ => {}}lines@@ -252,20 +263,27 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, picker: &mut Picker) -> OptPhase::Starting => vec![Line::raw(app.account.waiting.clone().unwrap_or_else(|| "Opening sign-in…".into()))],Phase::Completing => vec![Line::raw("Finishing sign-in. You can return to your workspace.")],Phase::Committed => vec![Line::raw("Signed in. Connecting this computer…")],+ Phase::SigningOut => vec![Line::raw(SIGNING_OUT)],};if needs_room { lines.extend([Line::raw(""), Line::raw("Enlarge the terminal to scan, or copy the phone sign-in link.")]); }// Actions always remain reachable, including in a short terminal. The explanation uses// the remaining rows and wraps; wheel/arrow navigation still works in a one-row list.let compact = r.height < 14;- let bottom = r.bottom().saturating_sub(if compact { 2 } else { 3 });- let count = picker.rows.len().min(bottom.saturating_sub(r.y + if compact { 3 } else { 4 }) as usize).max(1) as u16;+ // Tight: the actions do not fit beside the explanation, so they take its rows and the+ // bottom padding instead.+ let tight = compact && picker.rows.len() as u16 > r.height.saturating_sub(5);+ let hint_y = r.bottom().saturating_sub(if tight { 1 } else { 2 });+ let bottom = r.bottom().saturating_sub(if tight { 1 } else if compact { 2 } else { 3 });+ let count = picker.rows.len().min(bottom.saturating_sub(r.y + if tight { 2 } else if compact { 3 } else { 4 }) as usize).max(1) as u16;let list_top = bottom.saturating_sub(count);let description_top = r.y + if compact { 2 } else { 3 };- Paragraph::new(lines).style(c.muted).wrap(Wrap { trim: false })- .render(Rect::new(x, description_top, width, list_top.saturating_sub(description_top + if compact { 0 } else { 1 })), buf);+ if !tight {+ Paragraph::new(lines).style(c.muted).wrap(Wrap { trim: false })+ .render(Rect::new(x, description_top, width, list_top.saturating_sub(description_top + if compact { 0 } else { 1 })), buf);+ }settings::list(buf, picker, Rect::new(x, list_top, width, count), &c, false);let hint = if picker.query.is_empty() { if compact { "↑↓ choose · Enter · Esc back".into() } else { "↑↓ choose enter open esc back".into() } } else { format!("Filter: {}", picker.query) };- put(buf, x, r.bottom() - 2, width, &hint, c.muted);+ put(buf, x, hint_y, width, &hint, c.muted);None}@@ -281,6 +299,7 @@ pub fn choose(app: &mut App, mut picker: Picker, id: &str) {app.modal = Some(Modal::Picker { kind: PickerKind::Account, picker });match action {"google" | "apple" | "qr" => start(app, action),+ "signout" => sign_out(app),"cancel" | "deny" => { cancel(app); refill(app); }"confirm" => {if matches!(app.account.phase, Phase::Confirm(_)) {@@ -325,15 +344,61 @@ fn start(app: &mut App, method: &str) {#[cfg(not(test))]{let sink = app.sink.clone();- let exe = std::env::var("HARNESS_CLI").unwrap_or_else(|_| "harness".into());- let script: Vec<String> = std::env::var("HARNESS_CLI_ARGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();- let mut command = tokio::process::Command::new(exe);- command.args(script).args(args);+ let mut command = cli();+ command.args(args);tokio::spawn(drive(command, generation, sink, receive));}let _ = generation;}+const SIGNING_OUT: &str = "Signing out. Harnesses on this computer keep running.";++#[cfg(not(test))]+fn cli() -> tokio::process::Command {+ let exe = std::env::var("HARNESS_CLI").unwrap_or_else(|_| "harness".into());+ let script: Vec<String> = std::env::var("HARNESS_CLI_ARGS").ok().and_then(|s| serde_json::from_str(&s).ok()).unwrap_or_default();+ let mut command = tokio::process::Command::new(exe);+ command.args(script);+ command+}++/// Sign out as the desktop app does: `harness logout` clears the sign-in and brings this+/// computer's daemon back signed out, so the harnesses here stay on screen.+fn sign_out(app: &mut App) {+ if app.account.driver.is_some() || app.account.phase == Phase::SigningOut || !matches!(app.account.status, Status::SignedIn { .. }) { return }+ app.account.generation += 1;+ let generation = app.account.generation;+ app.account.phase = Phase::SigningOut;+ refill(app);+ #[cfg(test)]+ app.account.started.push(vec!["logout".into()]);+ #[cfg(not(test))]+ {+ use std::process::Stdio;+ let mut command = cli();+ // Not piped: the daemon it restarts inherits these, and would hold a pipe open forever.+ command.arg("logout").stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null()).kill_on_drop(true);+ app.spawn(async move {+ tokio::time::timeout(Duration::from_secs(60), command.status()).await.is_ok_and(|s| s.is_ok_and(|s| s.success()))+ }, move |app, ok| signed_out(app, generation, ok));+ }+ let _ = generation;+}++fn signed_out(app: &mut App, generation: u64, ok: bool) {+ if generation != app.account.generation || app.account.phase != Phase::SigningOut { return }+ if ok {+ app.account.status = Status::SignedOut;+ app.account.phase = Phase::Ready;+ reconnect(app);+ refresh(app, true);+ } else {+ app.account.phase = Phase::Failed("Could not sign out. Try again.".into());+ refresh(app, true);+ }+ refill(app);+}+fn valid_url(url: &str) -> bool {// The CLI gets these links from SSO. They are never shell commands or local file URLs.url.starts_with("https://") && url.len() <= 8192 && !url.chars().any(|c| c.is_control() || c.is_whitespace())@@ -543,7 +608,7 @@ mod tests {app.account.status = if signed_in { Status::SignedIn { email:Some("[email protected]".into()), offline:false } } else { Status::SignedOut };crate::input::picker(&mut app, PickerKind::Account, "Your Harness account", "");let (text, _) = render(&mut app, 40, 12);- for label in if signed_in { vec!["Connect a machine", "Add your phone", "Models on your machines", "Back to workspace"] }+ for label in if signed_in { vec!["Connect a machine", "Add your phone", "Models on your machines", "Sign out", "Back to workspace"] }else { vec!["Continue with Google", "Continue with Apple", "Sign in with your phone", "Keep using locally"] } {assert!(text.contains(label), "{label}\n{text}");}@@ -553,6 +618,46 @@ mod tests {}}+ #[test]+ fn sign_out_runs_the_cli_once_and_ends_signed_out_on_this_computer() {+ let mut app = app();+ app.devices.runner = Some(Box::new(|_| None));+ // Signed out, the command panel's Sign out runs nothing.+ crate::input::run(&mut app, "signout");+ assert_eq!(app.account.started, Vec::<Vec<String>>::new());+ assert_eq!(app.account.phase, Phase::Ready);+ app.modal = None;+ app.account.status = Status::SignedIn { email: Some("[email protected]".into()), offline: false };+ open(&mut app);+ let (text, _) = render(&mut app, 80, 24);+ assert!(text.contains("Sign out"), "{text}");+ select(&mut app, "account:signout");+ assert_eq!(app.account.started, vec![vec!["logout"]]);+ let (text, _) = render(&mut app, 80, 24);+ assert!(text.contains("Signing out") && text.contains("keep running"), "{text}");+ // The daemon restarting signed out is part of the sign-out, not the end of it.+ identity_changed(&mut app);+ assert_eq!(app.account.phase, Phase::SigningOut);+ crate::input::run(&mut app, "signout");+ assert_eq!(app.account.started.len(), 1, "one sign-out at a time");++ let generation = app.account.generation;+ signed_out(&mut app, generation, false);+ assert_eq!(app.account.phase, Phase::Failed("Could not sign out. Try again.".into()));+ let (text, _) = render(&mut app, 80, 24);+ assert!(text.contains("Could not sign out") && text.contains("Sign out"), "{text}");++ crate::input::run(&mut app, "logout");+ assert_eq!(app.account.started.len(), 2);+ let generation = app.account.generation;+ signed_out(&mut app, generation - 1, true);+ assert_eq!(app.account.phase, Phase::SigningOut, "a stale result is ignored");+ signed_out(&mut app, generation, true);+ assert_eq!((app.account.status.clone(), app.account.phase.clone()), (Status::SignedOut, Phase::Ready));+ let (text, _) = render(&mut app, 80, 24);+ assert!(text.contains("Continue with Google") && !text.contains("Sign out"), "{text}");+ }+#[test]fn offline_and_failed_status_reads_do_not_offer_an_account_switch() {let mut app = app();diff --git a/tui/src/app.rs b/tui/src/app.rsindex 90713bc0f..3b557a5f8 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -105,6 +105,26 @@ pub fn scroll_settle_in(scrolled_at: Option<Instant>, now: Instant) -> Option<Duscrolled_at.map(|at| (at + SCROLL_SETTLE).saturating_duration_since(now))}+/// A frame that wrote more cells than this, one by one, is a burst worth one settle rewrite.+pub const SETTLE_CELLS: usize = 400;++/// When the next settle repaint was last owed: now when the overlay drawn last frame is gone or no+/// longer covers where it was (it closed, shrank or moved: cells under its old edge may be kept+/// wrongly), or the frame wrote over SETTLE_CELLS cells; otherwise what was owed already.+pub fn settle_due(overlay_before: Option<Rect>, overlay_now: Option<Rect>, cells: usize, owed_since: Option<Instant>, now: Instant) -> Option<Instant> {+ let uncovered = overlay_before.is_some_and(|b| overlay_now.is_none_or(|n| n.intersection(b) != b));+ if uncovered || cells > SETTLE_CELLS { Some(now) } else { owed_since }+}++/// What a drawn frame leaves the settle rewrite: when it is owed from ([settle_due]), and the rect+/// of an overlay gone or no longer covering where it was — its rows are written again then too.+/// A repaint frame wrote every row: it owes nothing more (what was owed stays as it was).+pub fn settle_after_frame(repainting: bool, overlay_before: Option<Rect>, overlay_now: Option<Rect>, cells: usize, owed_since: Option<Instant>, now: Instant) -> (Option<Instant>, Option<Rect>) {+ if repainting { return (owed_since, None) }+ let left = overlay_before.filter(|b| overlay_now.is_none_or(|n| n.intersection(*b) != *b));+ (settle_due(overlay_before, overlay_now, cells, owed_since, now), left)+}+pub fn use_order() -> u64 {static N: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);N.fetch_add(1, std::sync::atomic::Ordering::Relaxed)@@ -494,10 +514,14 @@ pub struct App {pub repeat_until: Option<Instant>,/// Redraw everything next frame (refresh-client).pub redraw_all: bool,- /// When the wheel last turned. A scroll rewrites most of the screen cell by cell; once it stops+ /// When the settle rewrite was last owed (the wheel turned, an overlay closed or shrank, or a+ /// frame wrote a great many cells). A scroll rewrites most of the screen cell by cell; once it stops/// for SCROLL_SETTLE the whole screen is written once more, so a cell the terminal missed/// (a ghost of the old text) is overwritten whatever the reason it was missed.pub scrolled_at: Option<Instant>,+ /// Where the last frame drew an overlay (a list, menu, form, popup, prompt or notice), set by+ /// `ui::draw`: a frame that finds it gone or smaller owes a settle rewrite.+ pub overlay_drawn: Option<Rect>,/// tmux `status-position`.pub status_top: bool,pub mouse: bool,@@ -1009,6 +1033,7 @@ impl App {repeat_until: None,redraw_all: false,scrolled_at: None,+ overlay_drawn: None,status_top: false,mouse: true,loop_seen: Vec::new(),@@ -6548,6 +6573,37 @@ mod scroll_settle_tests {assert_eq!(scroll_settle_in(Some(t0), t0 + SCROLL_SETTLE), Some(Duration::ZERO));assert_eq!(scroll_settle_in(Some(t0), t0 + SCROLL_SETTLE * 4), Some(Duration::ZERO));}++ #[test]+ fn a_closed_or_smaller_overlay_or_a_large_cell_by_cell_frame_owes_one_settle_repaint() {+ let t0 = Instant::now();+ let big = Some(Rect::new(10, 5, 40, 12));+ assert_eq!(settle_due(big, None, 10, None, t0), Some(t0), "an overlay closed");+ assert_eq!(settle_due(big, big, 10, None, t0), None, "still open, as it was");+ assert_eq!(settle_due(None, big, 10, None, t0), None, "one opened: nothing under it is stale");+ assert_eq!(settle_due(big, Some(Rect::new(10, 5, 40, 4)), 10, None, t0), Some(t0), "its rows dropped from 10 to 2");+ assert_eq!(settle_due(big, Some(Rect::new(12, 5, 40, 12)), 10, None, t0), Some(t0), "it moved");+ assert_eq!(settle_due(big, Some(Rect::new(8, 4, 44, 14)), 10, None, t0), None, "it grew over where it was");+ assert_eq!(settle_due(None, None, SETTLE_CELLS + 1, None, t0), Some(t0), "many cells one by one");+ assert_eq!(settle_due(None, None, 3, None, t0), None, "a key echo");+ let earlier = t0 - Duration::from_millis(100);+ assert_eq!(settle_due(big, None, 10, Some(earlier), t0), Some(t0), "a new burst pushes it later");+ assert_eq!(settle_due(None, None, 3, Some(earlier), t0), Some(earlier), "a quiet frame leaves what is owed as it was");+ }++ #[test]+ fn a_repaint_frame_owes_no_settle_and_an_overlay_that_left_owes_its_rows() {+ let t0 = Instant::now();+ let earlier = t0 - Duration::from_millis(100);+ let big = Some(Rect::new(10, 5, 40, 12));+ // A repaint that also closed a panel (close_popup, Settings) wrote every row already.+ assert_eq!(settle_after_frame(true, big, None, 0, None, t0), (None, None), "no second rewrite owed");+ assert_eq!(settle_after_frame(true, big, None, 0, Some(earlier), t0), (Some(earlier), None), "what was owed stays as it was");+ assert_eq!(settle_after_frame(false, big, None, 10, None, t0), (Some(t0), big), "a panel closed: its rows are owed");+ assert_eq!(settle_after_frame(false, big, Some(Rect::new(10, 5, 40, 4)), 10, None, t0), (Some(t0), big), "it shrank");+ assert_eq!(settle_after_frame(false, big, big, 10, None, t0), (None, None), "still open, as it was");+ assert_eq!(settle_after_frame(false, None, None, SETTLE_CELLS + 1, None, t0), (Some(t0), None), "a burst: its own rows only");+ }}#[cfg(test)]@@ -6749,8 +6805,10 @@ mod recovery_tests {async fn setting_the_tab_name_source_by_hand_changes_the_tab_at_once() {let mut app = fixture();let format = |app: &App| app.options.get("window-status-format", "", None).unwrap_or_default();- crate::commands::execute(&mut app, "set -g @hn-window-name pane");+ crate::commands::execute(&mut app, "set -g @hn-window-name full");assert!(format(&app).contains("#{pane_title}"), "{}", format(&app));+ crate::commands::execute(&mut app, "set -g @hn-window-name short");+ assert!(format(&app).contains("#{=/20/…:pane_title}"), "{}", format(&app));crate::commands::execute(&mut app, "set -g @hn-window-name tmux");assert!(format(&app).contains("#{window_short_name}") && !format(&app).contains("#{pane_title}"), "{}", format(&app));}diff --git a/tui/src/autoname.rs b/tui/src/autoname.rsindex 41c81abf1..acac586a9 100644--- a/tui/src/autoname.rs+++ b/tui/src/autoname.rs@@ -236,24 +236,29 @@ mod tests {assert_eq!(app.auto_name(0), None);}- /// The status bar shows the daemon's name, whole — also where it shows the selected pane's title- /// (`@hn-window-name pane`, the default); without one, as before.+ /// The status bar shows the daemon's name — whole with full names (and tmux's), cut to 20+ /// columns with short names (the default); without one, as before.#[tokio::test]- async fn the_status_bar_shows_the_name_whole_in_either_tab_name_mode() {+ async fn the_status_bar_shows_the_name_in_each_tab_name_mode() {let mut app = app();window(&mut app, &[1, 2]);let key = ask(&app, 0).unwrap().key;app.window_name_answer("m", key, Some(json!({"name": "Harness Deploy Release"})));let tab = |app: &App| crate::format::expand(app, &app.options.get("window-status-format", "", None).unwrap_or_default(), 0, app.tabs[0].focus, false);- for mode in ["pane", "tmux"] {+ crate::commands::execute(&mut app, "set -g @hn-auto-rename on");+ assert!(tab(&app).contains("Harness Deploy Relea…"), "short by default: {}", tab(&app));+ for mode in ["full", "tmux"] {crate::commands::execute(&mut app, &format!("set -g @hn-window-name {mode}"));crate::commands::execute(&mut app, "set -g @hn-auto-rename on");assert!(tab(&app).contains("Harness Deploy Release"), "{mode}: {}", tab(&app));crate::commands::execute(&mut app, "set -g @hn-auto-rename off");assert!(!tab(&app).contains("Harness Deploy Release"), "{mode}, off: {}", tab(&app));}- crate::commands::execute(&mut app, "set -g @hn-window-name pane");+ crate::commands::execute(&mut app, "set -g @hn-window-name full");assert!(tab(&app).contains("Lm studio respawn on quit"), "the selected pane's title: {}", tab(&app));+ crate::commands::execute(&mut app, "set -g @hn-window-name short");+ // (tmux's #{=/20/…:}: 20 kept, then the marker.)+ assert!(tab(&app).contains("Lm studio respawn on…"), "cut to 20 columns: {}", tab(&app));}/// A client of a server an older build started takes that build's status bar formats; it derivesdiff --git a/tui/src/bar.rs b/tui/src/bar.rsindex 114b99cf0..9a5afcce1 100644--- a/tui/src/bar.rs+++ b/tui/src/bar.rs@@ -12,6 +12,8 @@ use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};use ratatui::buffer::Buffer;use ratatui::layout::Rect;use ratatui::style::{Color, Modifier, Style};+use ratatui::text::Span;+use ratatui::widgets::{Block, Clear, Widget};use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};use crate::app::App;@@ -43,8 +45,12 @@ pub enum Hit {Pane(usize, u64),/// A window (by index): select it — its heading, or an entry under a machine.Window(usize),- /// A machine's heading: its first window, if it has one.- Machine(Option<usize>),+ /// A machine's heading (its id, and its first window, if it has one).+ Machine(String, Option<usize>),+ /// A harness on a machine (machine, agent) open in no window here: open it.+ Harness(String, String),+ /// `+ N more` under a machine: its harnesses, all of them.+ More(String),/// `«` folds the bar to a rail, `»` opens it again.Fold,Unfold,@@ -63,6 +69,9 @@ pub struct State {pub scroll: [usize; 2],/// How far each list can scroll, as last drawn.pub max_scroll: [usize; 2],+ /// The entry each list showed first, as last drawn: rows coming or going above it (a roster+ /// arriving) leave it where it was.+ pub top: [Option<Hit>; 2],/// Where each place was drawn, for the mouse.pub hits: Vec<(Rect, Hit)>,/// The focus the lists last followed (the window's id and its pane): when it moves, its@@ -198,14 +207,15 @@ fn repo(project: &str, branch: &str, width: usize) -> Vec<String> {}}-/// [spans] from column [x] of row [y], no further than [right]. Returns the column after them.+/// [spans] from column [x] of row [y], no further than [right], each a `Span` cut with `…` to the+/// room left. Returns the column after them.fn put(buf: &mut Buffer, mut x: u16, y: u16, right: u16, spans: &[(String, Style)]) -> u16 {for (text, style) in spans {if x >= right { break }- let room = (right - x) as usize;- let shown = cut(text, room);- buf.set_stringn(x, y, &shown, room, *style);- x += shown.width() as u16;+ let shown = cut(text, (right - x) as usize);+ let width = shown.width() as u16;+ Span::styled(shown, *style).render(Rect::new(x, y, right - x, 1), buf);+ x += width;}x}@@ -300,8 +310,23 @@ fn window_entries(app: &App, c: &Colours, width: u16) -> Vec<Entry> {out}+/// The harness rows under a machine, at most this many, then `+ N more`.+const HARNESS_ROWS: usize = 3;++/// A harness on a machine that no window here shows: `├─ ? name` (its mark, when it has one, as a+/// window row's), after [prefix].+fn harness_entry(app: &App, c: &Colours, width: u16, a: &crate::fleet::Agent, prefix: &str) -> Entry {+ let (glyph, colour) = mark(Some(app.fleet.state_of(a)), c, app.tick);+ let mut spans = vec![(prefix.to_string(), Style::default().fg(c.muted))];+ let mut used = 1 + 2 + prefix.width();+ if glyph != " " { spans.push((format!("{glyph} "), Style::default().fg(colour))); used += 2 }+ spans.push((cut(&a.name, (width as usize).saturating_sub(used)), Style::default().fg(c.soft)));+ Entry { rows: vec![(1, spans)], right: None, hit: Hit::Harness(a.machine_id.clone(), a.id.clone()), current: false }+}+/// The machines, each with the windows that have a pane on it (a window on several machines-/// under each; one with no pane yet, this computer's).+/// under each; one with no pane yet, this computer's), then — on a machine that is ready — its+/// harnesses no window here shows, the latest first, three of them and `+ N more`.fn machine_entries(app: &App, c: &Colours, width: u16) -> Vec<Entry> {let windows: Vec<usize> = (0..app.tabs.len()).collect();// Each window's machines: its panes', in order (none yet: this computer's).@@ -320,9 +345,28 @@ fn machine_entries(app: &App, c: &Colours, width: u16) -> Vec<Entry> {let mut out = Vec::new();for id in machines {let mine: Vec<usize> = windows.iter().copied().filter(|i| on[*i].contains(&id)).collect();- out.push(Entry { rows: vec![(1, machine_spans(app, c, &id, width))], right: None, hit: Hit::Machine(mine.first().copied()), current: false });- let n = mine.len();- for (k, i) in mine.into_iter().enumerate() { out.push(window_entry(app, c, width, i, Some(if k + 1 == n { "└─ " } else { "├─ " }))) }+ let machine = app.fleet.machine(&id);+ let mut harnesses: Vec<&crate::fleet::Agent> = if machine.is_some_and(|m| m.usable()) {+ app.fleet.agents.values().filter(|a| a.machine_id == id && a.status != "stopped" && a.engine != "terminal" && app.find_pane(&id, &a.id).is_none()).collect()+ } else { Vec::new() };+ harnesses.sort_by(|a, b| b.recency().cmp(&a.recency()).then_with(|| a.name.cmp(&b.name)));+ let more = harnesses.len().saturating_sub(HARNESS_ROWS);+ harnesses.truncate(HARNESS_ROWS);+ // (Away: said at the right, the name cut before it.)+ let offline = machine.is_some_and(|m| !m.online()) && id != app.fleet.local_id;+ let right = offline.then(|| ("offline".to_string(), Style::default().fg(c.muted)));+ let heading = machine_spans(app, c, &id, if offline { width.saturating_sub(8) } else { width });+ out.push(Entry { rows: vec![(1, heading)], right, hit: Hit::Machine(id.clone(), mine.first().copied()), current: false });+ // Its windows, its harnesses, `+ N more`: one tree, the last of them `└─`.+ let n = mine.len() + harnesses.len() + usize::from(more > 0);+ let prefix = |k: usize| if k + 1 == n { "└─ " } else { "├─ " };+ let windows = mine.len();+ for (k, i) in mine.into_iter().enumerate() { out.push(window_entry(app, c, width, i, Some(prefix(k)))) }+ for (k, a) in harnesses.into_iter().enumerate() { out.push(harness_entry(app, c, width, a, prefix(windows + k))) }+ if more > 0 {+ let spans = vec![(prefix(n - 1).to_string(), Style::default().fg(c.muted)), (format!("+ {more} more"), Style::default().fg(c.muted))];+ out.push(Entry { rows: vec![(1, spans)], right: None, hit: Hit::More(id.clone()), current: false });+ }}out}@@ -372,7 +416,8 @@ pub fn draw(buf: &mut Buffer, app: &mut App) {let c = colours();let mut hits = Vec::new();crate::term_out::clear_extras(bar);- for y in bar.y..bar.bottom() { for x in bar.x..bar.right() { if let Some(cell) = buf.cell_mut((x, y)) { cell.reset(); cell.set_style(Style::default().bg(c.bg)); } } }+ Clear.render(bar, buf);+ Block::new().style(Style::default().bg(c.bg)).render(bar, buf);// The separator: the bar's last column facing the panes (its first, on the right) — the// handle that resizes it, in the accent while it does.let sx = if bar.x == 0 { bar.right() - 1 } else { bar.x };@@ -435,9 +480,16 @@ pub fn draw(buf: &mut Buffer, app: &mut App) {fn scroll_list(app: &mut App, which: usize, entries: &[Entry], area: Rect, follow: bool) {let max = max_scroll(entries, area.height);app.bar.max_scroll[which] = max;- let mut s = app.bar.scroll[which].min(max);+ let mut s = app.bar.scroll[which];+ // Rows that came or went above the first one shown (a roster arriving) do not move the list:+ // that entry stays first — the nearest of its kind, as a window is under several machines.+ if let Some(top) = app.bar.top[which].as_ref().filter(|h| !follow && entries.get(s).is_none_or(|e| e.hit != **h)) {+ if let Some(i) = entries.iter().enumerate().filter(|(_, e)| e.hit == *top).map(|(i, _)| i).min_by_key(|i| i.abs_diff(s)) { s = i }+ }+ s = s.min(max);if follow { if let Some(t) = entries.iter().rposition(|e| e.current) { s = reveal(entries, area.height, s, t) } }app.bar.scroll[which] = s;+ app.bar.top[which] = entries.get(s).map(|e| e.hit.clone());}/// The bar folded to a rail: a number and a glyph for each pane of the current window, a rule,@@ -476,8 +528,10 @@ pub fn hit_at(app: &App, x: u16, y: u16) -> Option<Hit> {app.bar.hits.iter().rev().find(|(r, h)| inside(r) && !list(h)).or_else(|| app.bar.hits.iter().find(|(r, _)| inside(r))).map(|(_, h)| h.clone())}-/// What a click on [hit] does: the tmux command its key would run, or the bar's own change.-pub fn click(app: &mut App, hit: Hit) {+/// What a click on [hit], pressed at [at] (where a machine's menu opens), does: the tmux command+/// its key would run, or the bar's own change. A machine with no window here: its menu,+/// Connect…, or what is wrong with it — not for a read-only client or tmux's look.+pub fn click(app: &mut App, hit: Hit, at: Option<(u16, u16)>) {let select = |app: &mut App, i: usize| { let n = app.win_num(i); crate::commands::execute(app, &format!("select-window -t :{n}")) };match hit {Hit::Pane(i, id) => {@@ -485,9 +539,13 @@ pub fn click(app: &mut App, hit: Hit) {if i != app.active { select(app, i) }crate::commands::execute(app, &format!("select-pane -t {}", crate::pane::tag(id)))}- Hit::Window(i) | Hit::Machine(Some(i)) => { if i < app.tabs.len() { select(app, i) } }+ Hit::Window(i) | Hit::Machine(_, Some(i)) => { if i < app.tabs.len() { select(app, i) } }Hit::Fold | Hit::Unfold => { app.bar.folded = hit == Hit::Fold; app.redraw_all = true; app.fit_panes() }- Hit::Machine(None) | Hit::Separator | Hit::Windows | Hit::Machines => {}+ // (Open here already — a slow attach clicked twice: open-harness goes to its window.)+ Hit::Harness(m, a) => crate::commands::execute(app, &format!("open-harness -s {}", crate::tmuxconf::quote_word(&format!("{m}:{a}")))),+ Hit::More(m) => crate::devices::open_machine_list(app, &m),+ Hit::Machine(m, None) if crate::workspace_controls::enabled(app) => crate::machine_menu::click(app, &m, at),+ Hit::Machine(_, None) | Hit::Separator | Hit::Windows | Hit::Machines => {}}}@@ -499,11 +557,13 @@ pub fn wheel(app: &mut App, hit: Hit, up: bool) {let in_machines = app.bar.hits.iter().any(|(r, h)| *h == Hit::Machines && r.intersection(rect) == rect && rect.area() > 0);let k = match hit {Hit::Windows => 0,- Hit::Machines | Hit::Machine(_) | Hit::Fold => 1,+ Hit::Machines | Hit::Machine(..) | Hit::Harness(..) | Hit::More(_) | Hit::Fold => 1,Hit::Window(_) | Hit::Pane(..) => usize::from(in_machines),Hit::Separator | Hit::Unfold => return,};app.bar.scroll[k] = step(app.bar.scroll[k], app.bar.max_scroll[k]);+ // (Moved on purpose: the next draw keeps the entry it now starts at.)+ app.bar.top[k] = None;}/// The separator dragged to column [x]: the bar's width follows it.@@ -538,7 +598,7 @@ pub fn mouse(app: &mut App, ev: &MouseEvent) -> bool {if app.bar.pressed.take().is_some_and(|t| t.elapsed() < DOUBLE_CLICK) { app.set_bar_width(WIDTH); app.persist_look() }else { app.bar.pressed = Some(Instant::now()); app.bar.resizing = true; app.redraw_all = true }}- Some(h) => click(app, h),+ Some(h) => click(app, h, Some((ev.column, ev.row.saturating_add(1)))),None => {}},MouseEventKind::ScrollUp | MouseEventKind::ScrollDown => { if let Some(h) = hit { wheel(app, h, matches!(ev.kind, MouseEventKind::ScrollUp)) } }@@ -618,9 +678,9 @@ mod tests {assert_eq!(app.tab().root.as_ref().unwrap().size(), (body.width, body.height));let _ = screen(&mut app);// Folded, the rail's four columns.- click(&mut app, Hit::Fold);+ click(&mut app, Hit::Fold, None);assert_eq!(app.body().width, w - RAIL);- click(&mut app, Hit::Unfold);+ click(&mut app, Hit::Unfold, None);assert_eq!(app.body().width, w - WIDTH);}}@@ -643,7 +703,7 @@ mod tests {let x0 = if side == "left" { 0 } else { 120 - WIDTH as usize + 1 };let bar = |y: usize| row(&s, y).chars().skip(x0).take(WIDTH as usize - 1).collect::<String>();// The machine you are on (the focused pane's), online.- assert!(bar(0).starts_with(" ✓ studio") && bar(0).contains("+ …"), "{s}");+ assert!(bar(0).starts_with(" ✓ studio") && bar(0).contains(&format!("+ {}", crate::workspace_controls::MENU_GLYPH)), "{s}");// (Each window named for its harness, as automatic-rename names it; idle harnesses and// shells have no mark, and no room kept for one — the name sits close.)assert!(bar(2).starts_with(" 0:fix login") && bar(2).trim_end().ends_with('3'), "{}", bar(2));@@ -728,8 +788,8 @@ mod tests {assert_eq!((app.active, app.focused()), (0, Some(3)));// The machine `lab`'s heading: its first window. A click in a pane is not the bar's.let _ = screen(&mut app);- let (r, _) = app.bar.hits.iter().find(|(_, h)| *h == Hit::Machine(Some(0))).cloned().unwrap();- assert_eq!(hit_at(&app, r.x + 3, r.y), Some(Hit::Machine(Some(0))));+ let (r, _) = app.bar.hits.iter().find(|(_, h)| matches!(h, Hit::Machine(m, Some(0)) if m == "lab")).cloned().unwrap();+ assert_eq!(hit_at(&app, r.x + 3, r.y), Some(Hit::Machine("lab".into(), Some(0))));assert!(!mouse(&mut app, &ev(MouseEventKind::Down(MouseButton::Left), 60, 10)));// `«` folds the bar and `»` opens it.let _ = screen(&mut app);@@ -816,7 +876,7 @@ mod tests {assert!(!matches!(app.panes[&2].phase, Phase::Watching(_)), "a key to it takes it");let _ = screen(&mut app);let hit = app.bar.hits.iter().find(|(_, h)| *h == Hit::Pane(0, 3)).map(|(_, h)| h.clone()).unwrap();- click(&mut app, hit);+ click(&mut app, hit, None);assert_eq!(app.focused(), Some(3));assert!(!matches!(app.panes[&3].phase, Phase::Watching(_)), "a click on it takes it");}@@ -908,4 +968,206 @@ mod tests {assert_eq!((f[0].bottom(), f[2].bottom()), (canvas.bottom(), canvas.bottom()), "bottom edge {at}");} }}++ // ── each machine's harnesses ──++ /// The bar app of `app((120, 50), "left")` plus the machine `grid` (named `grid-dev`, Ready)+ /// with [n] harnesses that are open in no window here.+ fn with_grid(n: usize) -> App {+ let mut app = app((120, 50), "left");+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "grid".into(), name: "grid-dev".into(), local: false, status: "online".into(), reach: crate::fleet::Reach::Ready });+ let rows: Vec<_> = (0..n).map(|i| json!({"id": format!("g{i}"), "name": format!("Grid task {i}"), "engine": "codex"})).collect();+ app.fleet.merge_roster("grid", &rows);+ app+ }++ /// Draw, then the first bar rect whose hit [want] accepts.+ fn rect_of(app: &mut App, want: impl Fn(&Hit) -> bool) -> Rect {+ let _ = screen(app);+ app.bar.hits.iter().find(|(_, h)| want(h)).map(|(r, _)| *r).expect("that entry is drawn")+ }++ /// A left press on that entry (three columns in, on its first row).+ fn click_on(app: &mut App, want: impl Fn(&Hit) -> bool) {+ let r = rect_of(app, want);+ assert!(mouse(app, &ev(MouseEventKind::Down(MouseButton::Left), r.x + 3, r.y)));+ }++ fn harness(m: &str, a: &str) -> Hit { Hit::Harness(m.into(), a.into()) }++ /// `put` with `Span`s writes what it wrote with `set_stringn` (2026-10-08): marks, wide and+ /// cut names, on a screen already written over, up to and past the right edge.+ #[test]+ fn put_as_spans_draws_what_set_stringn_did() {+ fn old_put(buf: &mut Buffer, mut x: u16, y: u16, right: u16, spans: &[(String, Style)]) -> u16 {+ for (text, style) in spans {+ if x >= right { break }+ let room = (right - x) as usize;+ let shown = cut(text, room);+ buf.set_stringn(x, y, &shown, room, *style);+ x += shown.width() as u16;+ }+ x+ }+ let bold = Style::default().fg(Color::Rgb(9, 9, 9)).add_modifier(Modifier::BOLD);+ let sets: [Vec<(String, Style)>; 4] = [+ vec![("✓".into(), bold), (" ".into(), Style::default()), ("Mac Auto".into(), bold)],+ vec![("├─ ".into(), Style::default()), ("⠹ ".into(), bold), ("Harness TUI LMStudio work".into(), Style::default())],+ vec![("日本語の名前の機械".into(), bold), ("offline".into(), Style::default())],+ vec![],+ ];+ let area = Rect::new(0, 0, 30, 1);+ for spans in &sets { for x in [0u16, 5, 29] { for right in [0u16, 3, 12, 26, 30] {+ let mut ground = Buffer::empty(area);+ for p in area.positions() { ground[p].set_symbol("x").set_style(Style::default().fg(Color::Red).bg(Color::Blue)); }+ let (mut old, mut new) = (ground.clone(), ground);+ let was = old_put(&mut old, x, 0, right, spans);+ assert_eq!(put(&mut new, x, 0, right, spans), was, "{spans:?} at {x} to {right}");+ assert_eq!(new, old, "{spans:?} at {x} to {right}");+ } } }+ }++ #[test]+ fn a_machine_lists_its_harnesses_not_open_here_three_then_more() {+ let mut app = with_grid(5);+ let (s, _) = screen(&mut app);+ assert!(s.contains("grid-dev"), "{s}");+ // (Equal recency: the name decides, so the first three are 0, 1, 2.)+ assert!(s.contains("├─ Grid task 0") && s.contains("├─ Grid task 2"), "{s}");+ assert!(!s.contains("Grid task 3"), "three rows at most: {s}");+ assert!(s.contains("└─ + 2 more"), "the last of the tree:\n{s}");+ assert!(app.bar.hits.iter().any(|(_, h)| *h == Hit::More("grid".into())));+ // Not for a machine that is not Ready (`lab`: offline, a roster of two): none — and it+ // says it is offline, at the right of its heading.+ assert!(!app.bar.hits.iter().any(|(_, h)| matches!(h, Hit::Harness(m, _) if m == "lab")));+ assert!(s.lines().any(|l| l.contains(" · lab") && l.contains("offline")), "{s}");+ // Three or fewer: no `+ N more`, the last harness closes the tree.+ let mut app = with_grid(2);+ let (s, _) = screen(&mut app);+ assert!(s.contains("└─ Grid task 1") && !s.contains("more"), "{s}");+ }++ #[test]+ fn a_harness_open_in_a_window_here_is_shown_once() {+ let mut app = with_grid(5);+ let mut tab = Tab::new("Grid task 0");+ tab.root = Some(Node::new(5, 40, 20));+ tab.focus = Some(5);+ let mut pane = Pane::new(5, "grid", "g0", 40, 20);+ pane.phase = Phase::Live;+ app.panes.insert(5, pane);+ app.tabs.push(tab);+ app.fit_panes();+ let _ = screen(&mut app);+ // (Its window's row is in both lists; as a harness row it is not drawn.)+ assert!(!app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g0")));+ assert!(app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g1")));+ // A stopped harness, or a terminal, is not listed.+ app.fleet.merge_roster("grid", &[json!({"id": "g1", "name": "Grid task 1", "engine": "codex", "status": "stopped"}), json!({"id": "t", "name": "zsh", "engine": "terminal"})]);+ let _ = screen(&mut app);+ assert!(!app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g1") || *h == harness("grid", "t")), "{:?}", app.bar.hits);+ assert!(app.bar.hits.iter().any(|(_, h)| *h == harness("grid", "g2")), "the next one takes its row");+ }++ #[tokio::test]+ async fn clicking_a_harness_row_opens_it_and_more_opens_the_machines_list() {+ let mut app = with_grid(5);+ click_on(&mut app, |h| *h == harness("grid", "g1"));+ assert!(app.find_pane("grid", "g1").is_some(), "open-harness ran");+ // Again (a slow attach): the same window, not a second one.+ let windows = app.tabs.len();+ crate::commands::execute(&mut app, "open-harness -s grid:g1");+ assert_eq!(app.tabs.len(), windows);+ click_on(&mut app, |h| *h == Hit::More("grid".into()));+ assert!(matches!(&app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Open { machine: Some(m), .. }, .. }) if m == "grid"));+ }++ #[tokio::test]+ async fn a_machine_id_with_a_space_still_opens_its_harness() {+ let mut app = app((120, 50), "left");+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "my box".into(), name: "my box".into(), local: false, status: "online".into(), reach: crate::fleet::Reach::Ready });+ app.fleet.merge_roster("my box", &[json!({"id": "b1", "name": "Box task", "engine": "codex"})]);+ click_on(&mut app, |h| *h == harness("my box", "b1"));+ assert!(app.find_pane("my box", "b1").is_some(), "quoted as the command reads it");+ }++ #[test]+ fn a_roster_arriving_keeps_the_scroll_on_the_same_entry() {+ let mut app = with_grid(2);+ // (16 rows: both lists still drawn, five rows of machines for eight entries.)+ app.size.1 = 16;+ let _ = screen(&mut app);+ assert!(app.bar.max_scroll[1] >= 2, "a height where the machines list scrolls: {}", app.bar.max_scroll[1]);+ // Down past this computer's heading and its window, onto `lab`.+ wheel(&mut app, Hit::Machines, false);+ wheel(&mut app, Hit::Machines, false);+ let top = |app: &mut App| { let _ = screen(app); app.bar.top[1].clone() };+ let before = top(&mut app);+ assert_eq!(before, Some(Hit::Machine("lab".into(), Some(0))), "lab's heading first");+ // This computer gets harnesses no window shows: rows above the first one shown.+ let mut rows = vec![json!({"id": "a1", "name": "fix login", "engine": "claude"}), json!({"id": "a2", "name": "tests", "engine": "codex"})];+ rows.extend((0..3).map(|i| json!({"id": format!("n{i}"), "name": format!("New {i}"), "engine": "codex"})));+ app.fleet.merge_roster("local", &rows);+ let scroll = app.bar.scroll[1];+ assert_eq!(top(&mut app), before, "the first entry shown is the same one");+ assert!(app.bar.scroll[1] > scroll, "its index moved down with the rows above it");+ }++ // ── a machine row always does something ──++ fn machine(id: &str, name: &str, status: &str, reach: crate::fleet::Reach) -> crate::fleet::Machine {+ crate::fleet::Machine { shared: false, id: id.into(), name: name.into(), local: false, status: status.into(), reach }+ }++ #[tokio::test]+ async fn a_ready_machine_without_a_window_opens_its_menu() {+ let mut app = with_grid(2);+ app.mouse = true;+ click_on(&mut app, |h| *h == Hit::Machine("grid".into(), None));+ let Some(crate::modal::Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ assert_eq!(m.title, "grid-dev");+ let labels: Vec<_> = m.items.iter().map(|i| i.label.as_str()).collect();+ assert!(labels.contains(&"New Harness on grid-dev…") && labels.contains(&"Open its harnesses"), "{labels:?}");+ assert!(!labels.contains(&"Connect…"));+ }++ #[tokio::test]+ async fn a_machine_that_needs_a_link_opens_connect_and_an_offline_one_says_so() {+ let mut app = app((120, 50), "left");+ app.mouse = true;+ app.fleet.machines.push(machine("lb", "linux-box", "online", crate::fleet::Reach::NeedsLink));+ click_on(&mut app, |h| *h == Hit::Machine("lb".into(), None));+ assert!(matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Devices(crate::devices::View::Connect), .. })));+ app.modal = None;+ app.fleet.machines.push(machine("air", "MacBook-Air.local", "offline", crate::fleet::Reach::Offline));+ click_on(&mut app, |h| *h == Hit::Machine("air".into(), None));+ assert!(app.toast.as_ref().is_some_and(|t| t.0.contains("MacBook-Air.local is offline")), "{:?}", app.toast);+ assert!(matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Devices(crate::devices::View::Machines), .. })));+ }++ #[tokio::test]+ async fn a_machine_with_a_window_here_still_jumps_to_it_and_a_right_press_opens_its_menu() {+ let mut app = app((120, 50), "left");+ app.mouse = true;+ app.select_tab(1);+ click_on(&mut app, |h| matches!(h, Hit::Machine(m, Some(0)) if m == "lab"));+ assert_eq!(app.active, 0);+ // Right press: through the same path the real input takes (workspace_controls first).+ let r = rect_of(&mut app, |h| matches!(h, Hit::Machine(m, _) if m == "local"));+ let press = ev(MouseEventKind::Down(MouseButton::Right), r.x + 3, r.y);+ assert!(crate::workspace_controls::mouse(&mut app, &press));+ assert!(matches!(&app.modal, Some(crate::modal::Modal::Menu(m)) if m.title == "studio"));+ }++ #[tokio::test]+ async fn a_read_only_client_gets_no_menu_and_no_machine_action() {+ let mut app = with_grid(2);+ app.mouse = true;+ app.client_flags.push("read-only".into());+ let r = rect_of(&mut app, |h| matches!(h, Hit::Machine(m, _) if m == "grid"));+ assert!(!crate::workspace_controls::mouse(&mut app, &ev(MouseEventKind::Down(MouseButton::Right), r.x + 3, r.y)));+ assert!(app.modal.is_none());+ click_on(&mut app, |h| *h == Hit::Machine("grid".into(), None));+ assert!(app.modal.is_none(), "the left click keeps today's: nothing");+ }}diff --git a/tui/src/buttons.rs b/tui/src/buttons.rsnew file mode 100644index 000000000..9213256c3--- /dev/null+++ b/tui/src/buttons.rs@@ -0,0 +1,310 @@+//! The row of buttons every dialog ends with: `[ Cancel ] [ Stop ]`, the way out first and the+//! action last, right-aligned, with a muted keys hint at the left. Colours are the command panel's+//! (`settings::chrome()`): the chosen button is its chosen row, the others its panel. It draws as+//! a ratatui widget (`row.view(&chrome)`), its geometry from one `Layout` that clicks share.++use crossterm::event::{KeyCode, KeyModifiers};+use ratatui::buffer::Buffer;+use ratatui::layout::{Constraint, Flex, Layout, Position, Rect};+use ratatui::text::Line;+use ratatui::widgets::Widget;+use unicode_width::UnicodeWidthStr;++use crate::settings::Chrome;++/// Columns between two buttons, and between the hint and the first button.+const GAP: u16 = 2;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Button { pub label: String, pub key: Option<char> }++#[derive(Clone, Debug)]+pub struct Row { pub buttons: Vec<Button>, pub chosen: usize, pub hint: String }++/// The keys hint every question's row shows where it fits — one for all, read as the command+/// panel's keys line: every arrow moves, Enter chooses, Esc cancels. (A button's own letter — `y`,+/// `s` — still answers; the hint does not list them.)+pub const KEYS: &str = "↑↓←→ move enter choose esc cancel";++pub enum Answer { Chosen(usize), Cancel, Moved, Ignored }++fn cols(text: &str) -> u16 { text.width().min(u16::MAX as usize) as u16 }++impl Button {+ fn width(&self) -> u16 { cols(&self.label).saturating_add(4) }+}++impl Row {+ /// The buttons alone, with the gaps between them.+ pub fn buttons_width(&self) -> u16 {+ let n = self.buttons.len() as u16;+ let gaps = n.saturating_sub(1) * GAP;+ self.buttons.iter().fold(gaps, |w, b| w.saturating_add(b.width()))+ }++ /// The columns a dialog gives the row: the wider of its two lines — the buttons, and the hint+ /// on the dialog's last line under them.+ pub fn width(&self) -> u16 { self.buttons_width().max(cols(&self.hint)) }++ /// Where each button goes on the one-row [area]: right-aligned, GAP apart. Drawing and clicks+ /// both take them from here. Callers fit the dialog to `buttons_width()` first; a narrower+ /// row shrinks the buttons rather than overlap them. (The hint is not on this row: the+ /// dialog draws it on its last line, [Row::hint_line].)+ pub fn areas(&self, area: Rect) -> Vec<Rect> {+ Layout::horizontal(self.buttons.iter().map(|b| Constraint::Length(b.width())))+ .flex(Flex::End).spacing(GAP).split(area).to_vec()+ }++ /// The hint as the dialog's last line, muted.+ pub fn hint_line<'a>(&'a self, c: &Chrome) -> Line<'a> { Line::styled(self.hint.as_str(), c.muted) }++ /// The row as a ratatui widget in [c]'s colours: `row.view(&c).render(area, buf)`.+ pub fn view<'a>(&'a self, c: &'a Chrome) -> ButtonRow<'a> { ButtonRow { row: self, chrome: c } }++ /// A key: ← → Tab BackTab h l move (wrapping; h / l only when no button owns that letter, and+ /// only without Ctrl/Alt); Enter chooses the chosen button; Esc, Ctrl-C, Ctrl-G cancel;+ /// a button's letter (no Ctrl/Alt) chooses that button. Dialogs that use Tab for something else+ /// (the Open dialog) filter Tab/BackTab/Esc before calling.+ pub fn key(&mut self, code: KeyCode, mods: KeyModifiers) -> Answer {+ let held = mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT);+ let n = self.buttons.len();+ let owned = |ch: char| self.buttons.iter().position(|b| b.key == Some(ch));+ match code {+ KeyCode::Esc => return Answer::Cancel,+ KeyCode::Char('c' | 'g') if mods.contains(KeyModifiers::CONTROL) => return Answer::Cancel,+ _ => {}+ }+ if n == 0 { return Answer::Ignored }+ // (↑ ↓ as ← →: a question's arrows all move between its answers.)+ let step = match code {+ KeyCode::Right | KeyCode::Down | KeyCode::Tab => Some(1),+ KeyCode::Left | KeyCode::Up | KeyCode::BackTab => Some(n - 1),+ KeyCode::Char('l') if !held && owned('l').is_none() => Some(1),+ KeyCode::Char('h') if !held && owned('h').is_none() => Some(n - 1),+ _ => None,+ };+ if let Some(by) = step {+ self.chosen = (self.chosen + by) % n;+ return Answer::Moved;+ }+ match code {+ KeyCode::Enter => Answer::Chosen(self.chosen.min(n - 1)),+ KeyCode::Char(ch) if !held => owned(ch).map_or(Answer::Ignored, Answer::Chosen),+ _ => Answer::Ignored,+ }+ }++ /// The button a click [at] chooses on a row drawn in [area]: none on a gap.+ pub fn click(&self, area: Rect, at: Position) -> Option<usize> {+ self.areas(area).iter().position(|r| r.contains(at))+ }+}++/// A [Row]'s buttons drawn: each a `Line` over its area — the chosen one in the panel's chosen+/// row (`selected`), the others in its surface (`base`).+pub struct ButtonRow<'a> { row: &'a Row, chrome: &'a Chrome }++impl Widget for ButtonRow<'_> {+ fn render(self, area: Rect, buf: &mut Buffer) {+ let buttons = self.row.areas(area);+ for (i, (b, at)) in self.row.buttons.iter().zip(buttons).enumerate() {+ let style = if i == self.row.chosen { self.chrome.selected } else { self.chrome.base };+ Line::styled(format!("[ {} ]", b.label), style).render(at, buf);+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use ratatui::style::Modifier;++ fn row() -> Row { Row { buttons: vec![Button { label: "Cancel".into(), key: None }, Button { label: "Stop".into(), key: Some('s') }], chosen: 0, hint: "s stop · esc cancel".into() } }++ /// The row as drawn now, at [area] (one row).+ fn drawn(r: &Row, buf: &mut Buffer, area: Rect, c: &Chrome) { r.view(c).render(area, buf) }++ /// Which button a click on each column of [area]'s row would choose, now.+ fn clicks(r: &Row, area: Rect, width: u16) -> Vec<Option<usize>> { (0..width).map(|x| r.click(area, Position::new(x, area.y))).collect() }++ /// The buttons' areas on a row ending at column 50.+ fn at50(r: &Row) -> Vec<Rect> { r.areas(Rect::new(0, 3, 50, 1)) }++ /// The row draws and answers clicks exactly as before it was a ratatui widget: every cell's+ /// symbol, colours and modifiers, for one, two and three buttons (and wide labels), each+ /// chosen (and none, as the Machines panel's unfocused row), from the narrowest row that fits+ /// the buttons to 120 columns, in a dark and a light theme and NO_COLOR. (Its hint is the+ /// dialog's last line now, never on the row: the old row is drawn with none.)+ #[test]+ fn the_widget_draws_and_clicks_as_the_old_row() {+ let b = |label: &str, key| Button { label: label.into(), key };+ let rows = [+ row(),+ Row { buttons: vec![b("Don't save", None), b("Cancel", None), b("Save", None)], chosen: 2, hint: String::new() },+ Row { buttons: vec![b("Cancel", Some('n')), b("Continue", Some('y'))], chosen: 1, hint: "tab buttons".into() },+ Row { buttons: vec![b("Back", None)], chosen: 0, hint: String::new() },+ Row { buttons: vec![b("取消", None), b("保存", None)], chosen: 0, hint: "回车 保存".into() }, // wide characters+ ];+ for c in oracle::chromes() {+ for mut r in rows.clone() {+ for chosen in (0..r.buttons.len()).chain([usize::MAX]) {+ r.chosen = chosen;+ for w in r.buttons_width()..=120 {+ let area = Rect::new(3, 1, w, 1);+ let screen = Rect::new(0, 0, w + 6, 3);+ let (mut old, mut new) = (oracle::canvas(screen), oracle::canvas(screen));+ oracle::draw(&Row { hint: String::new(), ..r.clone() }, &mut old, area.x, area.right(), area.y, &c);+ drawn(&r, &mut new, area, &c);+ assert_eq!(new, old, "{:?} chosen {chosen} at {w} columns", r.buttons);+ let before: Vec<_> = (0..screen.width).map(|x| oracle::click(&r, x, area.right())).collect();+ assert_eq!(clicks(&r, area, screen.width), before, "{:?} at {w} columns", r.buttons);+ }+ }+ }+ }+ }++ #[test]+ fn buttons_sit_right_aligned_two_columns_apart() {+ let cells = at50(&row());+ assert_eq!(cells, vec![Rect::new(50 - 8 - 2 - 10, 3, 10, 1), Rect::new(50 - 8, 3, 8, 1)]); // "[ Cancel ]" 10, "[ Stop ]" 8+ }++ #[test]+ fn up_and_down_move_between_the_answers_too() {+ let mut r = row();+ assert!(matches!(r.key(KeyCode::Down, KeyModifiers::NONE), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(r.key(KeyCode::Down, KeyModifiers::NONE), Answer::Moved)); assert_eq!(r.chosen, 0, "wraps");+ assert!(matches!(r.key(KeyCode::Up, KeyModifiers::NONE), Answer::Moved)); assert_eq!(r.chosen, 1);+ }++ #[test]+ fn keys_move_wrap_choose_and_cancel() {+ let mut r = row();+ let k = |r: &mut Row, c| r.key(c, KeyModifiers::NONE);+ assert!(matches!(k(&mut r, KeyCode::Right), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(k(&mut r, KeyCode::Right), Answer::Moved)); assert_eq!(r.chosen, 0, "wraps");+ assert!(matches!(k(&mut r, KeyCode::BackTab), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(k(&mut r, KeyCode::Enter), Answer::Chosen(1)));+ assert!(matches!(k(&mut r, KeyCode::Char('s')), Answer::Chosen(1)));+ assert!(matches!(k(&mut r, KeyCode::Esc), Answer::Cancel));+ assert!(matches!(r.key(KeyCode::Char('c'), KeyModifiers::CONTROL), Answer::Cancel));+ assert!(matches!(r.key(KeyCode::Char('g'), KeyModifiers::CONTROL), Answer::Cancel));+ assert!(matches!(k(&mut r, KeyCode::Char('x')), Answer::Ignored));+ }++ #[test]+ fn h_and_l_move_unless_a_button_owns_them() {+ let mut r = row();+ assert!(matches!(r.key(KeyCode::Char('l'), KeyModifiers::NONE), Answer::Moved)); assert_eq!(r.chosen, 1);+ assert!(matches!(r.key(KeyCode::Char('h'), KeyModifiers::NONE), Answer::Moved)); assert_eq!(r.chosen, 0);+ assert!(matches!(r.key(KeyCode::Char('l'), KeyModifiers::CONTROL), Answer::Ignored));+ assert!(matches!(r.key(KeyCode::Char('s'), KeyModifiers::ALT), Answer::Ignored));+ r.buttons[0].key = Some('h');+ assert!(matches!(r.key(KeyCode::Char('h'), KeyModifiers::NONE), Answer::Chosen(0)));+ assert_eq!(r.chosen, 0);+ }++ #[test]+ fn the_chosen_button_is_the_panels_chosen_row() {+ if crate::theme::no_color() { return } // NO_COLOR: `selected` is REVERSED, with no bg to compare+ let c = crate::settings::chrome();+ let mut buf = Buffer::empty(Rect::new(0, 3, 50, 1));+ let mut r = row(); r.chosen = 1;+ r.view(&c).render(buf.area, &mut buf);+ let x = at50(&r)[1].x;+ assert_eq!(buf[(x, 3)].symbol(), "[");+ assert_eq!(buf[(x + 2, 3)].bg, c.selected.bg.unwrap());+ assert!(buf[(x + 2, 3)].modifier.contains(Modifier::BOLD));+ let x0 = at50(&r)[0].x;+ assert_ne!(buf[(x0 + 2, 3)].bg, c.selected.bg.unwrap());+ assert_eq!(buf[(0, 3)].symbol(), " ", "no hint on the buttons' row: it is the dialog's last line");+ assert_eq!(r.hint_line(&c).style, c.muted, "the hint is muted");+ }++ #[test]+ fn the_buttons_never_overlap_and_the_hint_is_not_on_their_row() {+ let c = crate::settings::chrome();+ let r = row();+ let right = r.buttons_width();+ let mut buf = Buffer::empty(Rect::new(0, 0, right, 1));+ r.view(&c).render(buf.area, &mut buf);+ let line: String = (0..right).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert_eq!(line, "[ Cancel ] [ Stop ]");+ assert_eq!(r.width(), r.buttons_width().max("s stop · esc cancel".chars().count() as u16), "the wider of the row and the hint's line");+ // narrower than the buttons: they shrink side by side, never overlap, never panic+ let cells = r.areas(Rect::new(0, 0, 5, 1));+ assert_eq!(cells.len(), 2);+ assert!(cells[0].right() <= cells[1].x);+ let mut buf = Buffer::empty(Rect::new(0, 0, 5, 1));+ r.view(&c).render(buf.area, &mut buf);+ }++ #[test]+ fn a_click_on_a_button_chooses_it_and_between_them_nothing() {+ let (r, area) = (row(), Rect::new(0, 3, 50, 1));+ let cells = at50(&r);+ assert_eq!(r.click(area, Position::new(cells[1].x + 1, 3)), Some(1));+ assert_eq!(r.click(area, Position::new(cells[0].right(), 3)), None, "the gap");+ assert_eq!(r.click(area, Position::new(0, 3)), None, "the hint");+ assert_eq!(r.click(area, Position::new(cells[1].x + 1, 2)), None, "another row");+ }+}++/// The row as it was drawn by hand, cell by cell, before it was a ratatui widget: what the+/// widget must still look like, cell for cell.+#[cfg(test)]+pub(crate) mod oracle {+ use super::{Row, GAP, cols};+ use crate::settings::Chrome;+ use ratatui::{buffer::Buffer, layout::Rect, style::{Color, Modifier, Style}};++ /// A dark theme, a light one and NO_COLOR.+ pub(crate) fn chromes() -> [Chrome; 3] {+ let of = |bg, fg| crate::settings::chrome_for(crate::theme::pane_palette_of(bg, fg));+ [of([28, 31, 36], [220, 225, 231]), of([250, 250, 250], [40, 40, 40]), crate::settings::chrome_with(true)]+ }++ /// A screen with something on it already, so a cell left alone or painted over shows.+ pub(crate) fn canvas(area: Rect) -> Buffer {+ let mut buf = Buffer::empty(area);+ let st = Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::ITALIC);+ for (i, cell) in buf.content.iter_mut().enumerate() { cell.set_symbol(if i % 2 == 0 { "." } else { "x" }).set_style(st); }+ buf+ }++ pub(crate) fn cells(r: &Row, right: u16) -> Vec<(usize, u16, u16)> {+ let mut x = right;+ let mut out: Vec<_> = r.buttons.iter().enumerate().rev().map(|(i, b)| {+ let w = b.width();+ x = x.saturating_sub(w);+ let cell = (i, x, w);+ x = x.saturating_sub(GAP);+ cell+ }).collect();+ out.reverse();+ out+ }++ pub(crate) fn draw(r: &Row, buf: &mut Buffer, left: u16, right: u16, y: u16, c: &Chrome) {+ let cells = cells(r, right);+ if let Some(&(_, first, _)) = cells.first() {+ let hint = cols(&r.hint);+ if hint > 0 && u32::from(left) + u32::from(hint) + u32::from(GAP) <= u32::from(first) {+ crate::settings::put(buf, left, y, hint, &r.hint, c.muted);+ }+ }+ for (i, x, w) in cells {+ let style = if i == r.chosen { c.selected } else { c.base };+ for dx in 0..w {+ if let Some(cell) = buf.cell_mut((x + dx, y)) { cell.set_style(style); }+ }+ crate::settings::put(buf, x, y, w, &format!("[ {} ]", r.buttons[i].label), style);+ }+ }++ /// The button at column [x] of a row whose right edge is [right].+ pub(crate) fn click(r: &Row, x: u16, right: u16) -> Option<usize> {+ cells(r, right).into_iter().find(|&(_, cx, w)| x >= cx && x - cx < w).map(|(i, ..)| i)+ }+}diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex e99ac9c1b..a58199815 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -93,9 +93,11 @@ pub const COMMANDS: &[(&str, &str, &str)] = &[("devices", "devices", "Manage computer connections"),("hardware-devices", "hardware-devices", "Manage physical Harness devices on your computers"),("account", "login", "Optional sign-in and your Harness account"),+ ("signout", "logout", "Sign out of your Harness account (harnesses on this computer keep running)"),("appearance", "appearance", "Choose the TUI appearance"),("pane-menu", "pane-menu", "Actions for a pane (-t target)"),("window-menu", "window-menu", "Actions for a window (-t target)"),+ ("machine-menu", "machine-menu", "Actions for a machine: machine-menu <new-harness|new-terminal|open|connect|machine> <machine>"),("pane-control", "pane-control", "Run an action from a captured pane or window menu"),("new-terminal", "newt", "A shell on this pane's machine"),("choose-command", "choosec", "Every command and setting by name (C-b Enter)"),@@ -3481,7 +3483,7 @@ fn run_words_in(app: &mut App, words: &[String]) {let from = (starting as usize).min(n - 1);(0..n).map(|k| (from + k) % n).find(|k| !items[*k].disabled && !items[*k].separator)};- app.modal = Some(Modal::Menu(crate::modal::Menu { title, items, choice, x, y, width, stay_open: args.has('O') > 0, no_mouse, mouse: app.mouse_ev.clone(), tree: None, complete: None, responsive: None }));+ app.modal = Some(Modal::Menu(crate::modal::Menu { title, items, choice, x, y, width, stay_open: args.has('O') > 0, no_mouse, mouse: app.mouse_ev.clone(), tree: None, complete: None, responsive: None, buttons: None }));app.wait_cli = app.capture.is_some();}"customize-mode" => {@@ -3537,6 +3539,7 @@ fn run_words_in(app: &mut App, words: &[String]) {"workspace-menu" => crate::workspace_controls::command(app, &words[1..]),"workspace-sync" => crate::agent_switch::retry_sync(app),"account" => crate::account::open(app),+ "signout" => crate::account::sign_out_command(app),"change-agent" => {if let Some((_, p)) = target_pane(app, words) { crate::agent_switch::open(app, p); }else { app.error("can't find pane"); }@@ -3550,6 +3553,7 @@ fn run_words_in(app: &mut App, words: &[String]) {if opt(words, "-t").is_some() && target.is_none() { app.error("can't find window"); }else { crate::workspace_controls::tab_menu(app, target.unwrap_or(app.active), None); }}+ "machine-menu" => crate::machine_menu::command(app, &words[1..]),"pane-control" => {let args = positional(words);if args.len() == 2 { crate::workspace_controls::run(app, &args[0], &args[1]); }diff --git a/tui/src/config.rs b/tui/src/config.rsindex 7ea9c52b0..8bb2ef7f7 100644--- a/tui/src/config.rs+++ b/tui/src/config.rs@@ -608,7 +608,8 @@ mod tests {let filled = Look { window_active: Some("filled".into()), window_name: Some("pane".into()), ..Default::default() }.assignments();assert!(get(&filled, "window-status-format").is_none(), "the other tabs: the default");let current = get(&filled, "window-status-current-format").unwrap();- assert!(current.contains("#{pane_title}"), "pane uses the active pane's title: {current}");+ assert!(current.contains("#{=/20/…:pane_title}"), "the active pane's title, cut short: {current}");+ assert!(!current.contains("window_last_flag"), "no `-` for the window used before: {current}");assert!(!current.contains("#{window_active,*"), "filled leaves no `*`: {current}");let style = get(&filled, "window-status-current-style").unwrap();assert!(style.contains("bold"), "{style}");diff --git a/tui/src/devices.rs b/tui/src/devices.rsindex 16f66e075..477b006b3 100644--- a/tui/src/devices.rs+++ b/tui/src/devices.rs@@ -7,9 +7,10 @@//! remove), the links made from here (unlink), and the steps that add another machine.//! - **Add phone…** — the QR code the app shows (the very same link), in half blocks.//!-//! Everything that writes asks y/n in the panel's footer first. The CLI and the daemon's REST go-//! through one [Req] → [Reply] runner, which tests replace with fake answers: nothing here reaches a-//! real daemon or CLI from a test.+//! Everything that writes asks y/n first, in a dialog over the panel (`dialog::Dialog`, the one+//! every question uses); a typed line is asked there too, never in the search line. The CLI and+//! the daemon's REST go through one [Req] → [Reply] runner, which tests replace with fake answers:+//! nothing here reaches a real daemon or CLI from a test.use std::collections::HashMap;use std::time::{Duration, Instant};@@ -23,6 +24,8 @@ use serde_json::{json, Value};use unicode_width::UnicodeWidthStr;use crate::app::App;+use crate::buttons::{self, Answer, Button};+use crate::dialog::{self, Dialog, Input, INPUT_W};use crate::fleet::{Reach, State};use crate::modal::{Modal, PickerKind};use crate::picker::{Picker, Row};@@ -138,15 +141,17 @@ pub enum Act {ArmPhone,}-/// The panel is asking: a line to type (a password shown as dots), or a y/n before a write.+/// The panel is asking, in a dialog over it: a line to type (a password shown as dots; the caret+/// [caret] characters in), or a y/n before a write.#[derive(Clone, Debug)]pub enum Ask {- Entry { what: Entry, label: String, value: String, secret: bool },+ Entry { what: Entry, label: String, value: String, caret: usize, secret: bool },Confirm { question: String, act: Act },}+/// Where the dialog drew its buttons and its input, for clicks on this screen size.#[derive(Clone, Copy)]-struct PromptActions { size: (u16, u16), accept: Rect, cancel: Rect }+struct PromptActions { size: (u16, u16), accept: Rect, cancel: Rect, input: Option<Rect> }pub struct Devices {/// `remote-password status --json` ({hasPassword, fingerprint, setAt}), or why it is unknown.@@ -158,6 +163,12 @@ pub struct Devices {pub phone: Phone,pub ask: Option<Ask>,prompt_actions: std::cell::Cell<Option<PromptActions>>,+ /// The chosen button of the prompt's row (0 Cancel, 1 the action), and whether the keys are on+ /// the buttons: a confirmation's always are, a typed line's only after Tab.+ prompt_row: std::cell::Cell<usize>,+ prompt_focus: std::cell::Cell<bool>,+ /// Set by a draw that had no room for the question: [cancel_unfit] ends it after the frame.+ unfit: std::cell::Cell<bool>,/// A level inside a view: a machine's actions (`m:<id>`).pub sub: Option<String>,/// The footer's line: what happened, or (true) what went wrong — until the next thing does.@@ -170,7 +181,7 @@ pub struct Devices {impl Default for Devices {fn default() -> Devices {Devices {- password: None, links: None, account: HashMap::new(), link: None, phone: Phone::default(), ask: None, prompt_actions: Default::default(), sub: None, footer: None, loading: Vec::new(), runner: default_runner(),+ password: None, links: None, account: HashMap::new(), link: None, phone: Phone::default(), ask: None, prompt_actions: Default::default(), prompt_row: Default::default(), prompt_focus: Default::default(), unfit: Default::default(), sub: None, footer: None, loading: Vec::new(), runner: default_runner(),}}}@@ -796,11 +807,20 @@ fn link_line(app: &mut App, line: &str) {fn entry(app: &mut App, what: Entry, label: impl Into<String>, value: &str, secret: bool) {app.devices.prompt_actions.set(None);- app.devices.ask = Some(Ask::Entry { what, label: label.into(), value: value.to_string(), secret });+ app.devices.prompt_row.set(1);+ app.devices.prompt_focus.set(false);+ app.devices.ask = Some(Ask::Entry { what, label: label.into(), value: value.to_string(), caret: value.chars().count(), secret });}+/// The byte where the [caret]th character of [value] starts.+fn at_char(value: &str, caret: usize) -> usize { value.char_indices().nth(caret).map_or(value.len(), |(i, _)| i) }+fn confirm(app: &mut App, question: impl Into<String>, act: Act) {app.devices.prompt_actions.set(None);+ // A destructive yes starts on Cancel, a safe one on Yes.+ let risky = matches!(act, Act::ClearPassword | Act::Unlink { .. } | Act::Remove { .. } | Act::Unpair { .. });+ app.devices.prompt_row.set(usize::from(!risky));+ app.devices.prompt_focus.set(true);app.devices.ask = Some(Ask::Confirm { question: question.into(), act });}@@ -808,20 +828,28 @@ fn confirm(app: &mut App, question: impl Into<String>, act: Act) {/// A paste cannot answer a confirmation, even if it contains "y" or a newline.pub fn paste(app: &mut App, text: &str) -> bool {if view_of(app).is_none() || app.devices.ask.is_none() { return false }- if let Some(Ask::Entry { value, .. }) = &mut app.devices.ask {- value.extend(text.chars().filter(|c| !c.is_control()));+ if let Some(Ask::Entry { value, caret, .. }) = &mut app.devices.ask {+ let pasted: String = text.chars().filter(|c| !c.is_control()).collect();+ value.insert_str(at_char(value, *caret), &pasted);+ *caret += pasted.chars().count();}true}/// While a prompt is open, clicks on the underlying list cannot become Enter.-/// Only the actions drawn for this prompt can advance it; an outside click cancels.+/// Only the actions drawn for this prompt can advance it; a click on its input gives the input+/// the keys; a click outside the panel cancels.pub fn mouse(app: &mut App, mouse: MouseEvent) -> bool {if view_of(app).is_none() || app.devices.ask.is_none() { return false }if mouse.kind != MouseEventKind::Down(MouseButton::Left) || !mouse.modifiers.is_empty() { return true }let at = Position::new(mouse.column, mouse.row);let action = app.devices.prompt_actions.get().filter(|a| a.size == app.size);+ if action.and_then(|a| a.input).is_some_and(|r| r.contains(at)) {+ app.devices.prompt_focus.set(false);+ return true;+ }let key = if action.is_some_and(|a| a.accept.contains(at)) {+ app.devices.prompt_focus.set(false); // a click on Continue is Enter on the line, not on a chosen CancelSome(if matches!(app.devices.ask, Some(Ask::Confirm { .. })) { KeyCode::Char('y') } else { KeyCode::Enter })} else if action.is_some_and(|a| a.cancel.contains(at)) {Some(KeyCode::Esc)@@ -871,24 +899,64 @@ fn answer_key(app: &mut App, key: KeyEvent) {app.devices.prompt_actions.set(None);let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);match app.devices.ask.take() {- Some(Ask::Confirm { question, act }) => match key.code {- KeyCode::Char('y' | 'Y') if !ctrl => run_act(app, act),- KeyCode::Char('n' | 'N') | KeyCode::Esc => note(app, "Nothing changed"),- KeyCode::Char('c' | 'g') if ctrl => note(app, "Nothing changed"),- _ => app.devices.ask = Some(Ask::Confirm { question, act }),- },- Some(Ask::Entry { what, label, mut value, secret }) => {+ Some(Ask::Confirm { question, act }) => {+ let mut row = prompt_row(app, true, "Yes");+ let answer = match key.code {+ KeyCode::Char('Y') if !ctrl => Answer::Chosen(1),+ KeyCode::Char('N') if !ctrl => Answer::Chosen(0),+ code => row.key(code, key.modifiers),+ };+ match answer {+ Answer::Chosen(1) => run_act(app, act),+ Answer::Chosen(_) | Answer::Cancel => note(app, "Nothing changed"),+ Answer::Moved => {+ app.devices.prompt_row.set(row.chosen);+ app.devices.ask = Some(Ask::Confirm { question, act });+ }+ Answer::Ignored => app.devices.ask = Some(Ask::Confirm { question, act }),+ }+ }+ Some(Ask::Entry { what, label, mut value, mut caret, secret }) => {+ // (↓ from the input to the buttons, ↑ back up, as Tab goes either way.)+ let on_buttons = app.devices.prompt_focus.get();+ let across = match key.code { KeyCode::Tab | KeyCode::BackTab => true, KeyCode::Down => !on_buttons, KeyCode::Up => on_buttons, _ => false };+ if across {+ app.devices.prompt_focus.set(!on_buttons);+ app.devices.ask = Some(Ask::Entry { what, label, value, caret, secret });+ return;+ }+ // A printable key is typed, wherever the keys were: the input has them again.+ if matches!(key.code, KeyCode::Char(_)) && !ctrl && !key.modifiers.contains(KeyModifiers::ALT) { app.devices.prompt_focus.set(false) }+ if app.devices.prompt_focus.get() {+ let mut row = prompt_row(app, false, "Continue");+ match row.key(key.code, key.modifiers) {+ Answer::Chosen(1) => { app.devices.footer = None; return submit(app, what, value) }+ Answer::Chosen(_) | Answer::Cancel => return note(app, "Nothing changed"),+ Answer::Moved => app.devices.prompt_row.set(row.chosen),+ Answer::Ignored => {}+ }+ app.devices.ask = Some(Ask::Entry { what, label, value, caret, secret });+ return;+ }+ // The input has the keys: they edit at the caret, which ← → Home End move.+ let len = value.chars().count();+ caret = caret.min(len);match key.code {KeyCode::Enter => { app.devices.footer = None; return submit(app, what, value) }KeyCode::Esc => return note(app, "Nothing changed"),KeyCode::Char('c' | 'g') if ctrl => return note(app, "Nothing changed"),- KeyCode::Char('u') if ctrl => value.clear(),- KeyCode::Char('h') if ctrl => { value.pop(); }- KeyCode::Backspace => { value.pop(); }- KeyCode::Char(c) if !ctrl && !key.modifiers.contains(KeyModifiers::ALT) => value.push(c),+ KeyCode::Char('u') if ctrl => { value.clear(); caret = 0 }+ KeyCode::Char('h') if ctrl && caret > 0 => { caret -= 1; value.remove(at_char(&value, caret)); }+ KeyCode::Backspace if caret > 0 => { caret -= 1; value.remove(at_char(&value, caret)); }+ KeyCode::Delete if caret < len => { value.remove(at_char(&value, caret)); }+ KeyCode::Left => caret = caret.saturating_sub(1),+ KeyCode::Right => caret = (caret + 1).min(len),+ KeyCode::Home => caret = 0,+ KeyCode::End => caret = len,+ KeyCode::Char(c) if !ctrl && !key.modifiers.contains(KeyModifiers::ALT) => { value.insert(at_char(&value, caret), c); caret += 1 }_ => {}}- app.devices.ask = Some(Ask::Entry { what, label, value, secret });+ app.devices.ask = Some(Ask::Entry { what, label, value, caret, secret });}None => {}}@@ -1025,17 +1093,28 @@ fn machine_action(app: &mut App, rest: &str) {"connect" => { switch(app, View::Connect); if let Some(p) = picker_mut(app) { p.select(&format!("m:{machine}")) } start_link(app, machine, name) }"open" => {app.devices.sub = None;- let kind = PickerKind::Open { filter: crate::modal::Filter::All, machine: Some(machine), project: None };- let (title, placeholder) = crate::modal::launcher_title(app, &kind);- let mut next = Picker::new(title, placeholder);- next.prefixed = true;- crate::input::fill(app, &kind, &mut next);- app.modal = Some(Modal::Picker { kind, picker: next });+ open_machine_list(app, &machine);}_ => {}}}+/// Machines & devices on [machine]: its own actions (rename, connect, remove…).+pub(crate) fn open_machine(app: &mut App, machine: &str) {+ open(app, View::Machines);+ sub(app, format!("m:{machine}"));+}++/// [machine]'s harnesses: the Open list on it ("Open its harnesses").+pub(crate) fn open_machine_list(app: &mut App, machine: &str) {+ let kind = PickerKind::Open { filter: crate::modal::Filter::All, machine: Some(machine.to_string()), project: None };+ let (title, placeholder) = crate::modal::launcher_title(app, &kind);+ let mut next = Picker::new(title, placeholder);+ next.prefixed = true;+ crate::input::fill(app, &kind, &mut next);+ app.modal = Some(Modal::Picker { kind, picker: next });+}+// ── rows ─────────────────────────────────────────────────────────────────────fn span(text: impl Into<String>, style: Style) -> Span<'static> { Span::styled(text.into(), style) }@@ -1361,15 +1440,9 @@ fn head(buf: &mut Buffer, app: &App, title: &str, x: u16, y: u16, right: u16, c:settings::put(buf, right.saturating_sub(3), y, 3, "esc", c.muted);}-/// The query line — or, while the panel asks for a line, that line (a password as dots).+/// The query line: always the search (what the panel asks is asked in its dialog).fn query_line(buf: &mut Buffer, app: &App, picker: &Picker, x: u16, y: u16, right: u16, c: &Chrome) -> Option<Position> {let w = right.saturating_sub(x);- if let Some(Ask::Entry { label, value, secret, .. }) = &app.devices.ask {- let at = x + settings::put(buf, x, y, w, &format!("{label} › "), c.accent);- let shown = if *secret { "•".repeat(value.chars().count()) } else { value.clone() };- settings::put(buf, at, y, right.saturating_sub(at), &shown, c.base);- return Some(Position::new((at + shown.width() as u16).min(right), y));- }settings::put(buf, x, y, 2, "›", c.accent);let shown = if picker.query.is_empty() { (picker.placeholder.as_str(), c.muted) } else { (picker.query.as_str(), c.base) };settings::put(buf, x + 2, y, w.saturating_sub(2), shown.0, shown.1);@@ -1378,24 +1451,84 @@ fn query_line(buf: &mut Buffer, app: &App, picker: &Picker, x: u16, y: u16, righ(app.devices.ask.is_none()).then(|| Position::new((x + 2 + before.width() as u16).min(right), y))}-/// Mouse actions occupy the existing footer only while a prompt needs an answer.-fn prompt_actions(buf: &mut Buffer, app: &App, x: u16, y: u16, w: u16, c: &Chrome) {- let confirm = matches!(app.devices.ask, Some(Ask::Confirm { .. }));- let accept = if confirm { " Yes " } else if w < 19 { " Next " } else { " Continue " };- let cancel = " Cancel ";- let needed = accept.width() as u16 + cancel.width() as u16 + 1;- if w < needed { return }- let yes = Rect::new(x, y, accept.width() as u16, 1);- let no = Rect::new(yes.right() + 1, y, cancel.width() as u16, 1);- settings::put(buf, yes.x, y, yes.width, accept, c.selected);- settings::put(buf, no.x, y, no.width, cancel, c.selected);- if confirm && w >= needed + 5 { settings::put(buf, no.right() + 2, y, 3, "y/n", c.muted); }- app.devices.prompt_actions.set(Some(PromptActions { size:app.size, accept:yes, cancel:no }));+/// What is being asked, as the shared dialog centred over [over] (the panel, or Add phone's words+/// beside its QR code): its title, the question — or the input under its label, with what to do+/// or what went wrong under it — and the buttons. Its buttons and input are kept for clicks;+/// returns where the terminal cursor goes. Nothing is drawn where its buttons cannot fit.+fn ask_dialog(buf: &mut Buffer, app: &App, over: Rect, c: &Chrome) -> Option<Position> {+ let ask = app.devices.ask.as_ref()?;+ let room = over.width.saturating_sub(4);+ let confirm = matches!(ask, Ask::Confirm { .. });+ let mut row = prompt_row(app, confirm, action(ask, room));+ // (A question that cannot be drawn must not stay open to answering keys: the frame ends it.)+ if row.buttons_width() > room { app.devices.unfit.set(true); return None }+ let input_focus = !app.devices.prompt_focus.get();+ if !confirm && input_focus { row.chosen = usize::MAX } // the input has the keys: no button chosen+ let mut d = Dialog::new(&ask_title(app, ask), Vec::new(), &row, c);+ d.border = crate::ui::dialog_border(&app.style_spec("menu-border-lines", app.active, app.focused()));+ match ask {+ Ask::Confirm { question, .. } => d.body = dialog::wrap(question, room.min(INPUT_W), c.base),+ Ask::Entry { label, value, caret, secret, .. } => {+ d.input = Some(Input { label, value, caret: *caret, select: None, secret: *secret, focused: input_focus, width: INPUT_W });+ if let Some((m, error, _)) = &app.devices.footer { d.message = dialog::wrap(m, room.min(INPUT_W), if *error { c.danger } else { c.muted }) }+ }+ }+ if !d.fit(over.height) { app.devices.unfit.set(true); return None }+ let area = d.place(over);+ d.render_over(over, area, buf);+ let a = d.areas(area);+ let cells = row.areas(a.row);+ app.devices.prompt_actions.set(Some(PromptActions { size: app.size, accept: cells[1], cancel: cells[0], input: a.input }));+ d.cursor(area)}-fn confirmation(buf: &mut Buffer, app: &App, r: Rect, c: &Chrome) {- let Some(Ask::Confirm { question, .. }) = &app.devices.ask else { return };- text(buf, r, &[Line::from(Span::styled(question.clone(), c.accent))], c);+/// After a frame: a question that had no room to be drawn is cancelled, as Close Tab's is when+/// the terminal shrinks under it, and the person told why.+pub fn cancel_unfit(app: &mut App) {+ if !app.devices.unfit.take() || app.devices.ask.is_none() { return }+ app.devices.ask = None;+ app.devices.prompt_actions.set(None);+ note(app, "Nothing changed");+ app.say(crate::workspace_menu::TOO_SMALL_TO_ANSWER, theme::WARN);+}++/// The dialog's title: what is being done, and to what.+fn ask_title(app: &App, ask: &Ask) -> String {+ match ask {+ Ask::Entry { what: Entry::Link { name, .. }, .. } | Ask::Confirm { act: Act::Link { name, .. }, .. } => format!("Connect · {name}"),+ Ask::Entry { what: Entry::NewPassword | Entry::RepeatPassword { .. }, .. } | Ask::Confirm { act: Act::SetPassword(_), .. } => "Set Remote Password".into(),+ Ask::Confirm { act: Act::ClearPassword, .. } => "Clear Remote Password".into(),+ Ask::Entry { what: Entry::Rename { name, .. }, .. } => format!("Rename Computer · {name}"),+ Ask::Confirm { act: Act::Rename { machine, .. }, .. } => format!("Rename Computer · {}", name_of(app, machine)),+ Ask::Confirm { act: Act::Unlink { name, .. }, .. } => format!("Unlink · {name}"),+ // (The row says "Remove from account…".)+ Ask::Confirm { act: Act::Remove { name, .. }, .. } => format!("Remove from Account · {name}"),+ Ask::Confirm { act: Act::Unpair { name, .. }, .. } => format!("Remove Access · {name}"),+ Ask::Confirm { act: Act::ArmPhone, .. } => "Add Your Phone".into(),+ }+}++/// The action button's word: Yes to a question; for a typed line what Enter does — Connect, Save,+/// else Continue — or Next where [room] is narrower than `[ Cancel ] [ <that> ]`.+fn action(ask: &Ask, room: u16) -> &'static str {+ let word = match ask {+ Ask::Confirm { .. } => return "Yes",+ Ask::Entry { what: Entry::Link { .. }, .. } => "Connect",+ Ask::Entry { what: Entry::Rename { .. }, .. } => "Save",+ Ask::Entry { .. } => "Continue",+ };+ if "[ Cancel ] [ ]".width() + word.width() > room as usize { "Next" } else { word }+}++/// `[ Cancel ] [ Yes ]`, or `[ Cancel ] [ <action> ]` for a typed line, with the chosen button+/// from the panel's state. [confirm] is passed because a key takes the ask out while it answers.+fn prompt_row(app: &App, confirm: bool, action: &str) -> buttons::Row {+ let key = |ch: char| confirm.then_some(ch);+ buttons::Row {+ buttons: vec![Button { label: "Cancel".into(), key: key('n') }, Button { label: action.into(), key: key('y') }],+ chosen: app.devices.prompt_row.get().min(1),+ hint: buttons::KEYS.into(),+ }}/// [lines] in [r], each wrapped at its words; a dim span in the panel's muted colour. Returns the@@ -1423,21 +1556,12 @@ fn text(buf: &mut Buffer, r: Rect, lines: &[Line<'static>], c: &Chrome) -> u16 {y.saturating_sub(r.y)}-/// What the footer says: the question being asked, the typed line's keys, what just happened or-/// went wrong, else the keys.+/// What the footer says: what just happened or went wrong, else the keys — nothing while the+/// dialog asks (what it says is in the dialog).fn footer(buf: &mut Buffer, app: &App, picker: &Picker, x: u16, y: u16, w: u16, c: &Chrome) {- let danger = c.base.patch(fg(theme::DANGER));- if app.devices.ask.is_some() {- if matches!(app.devices.ask, Some(Ask::Entry { .. })) {- if let Some((message, error, _)) = &app.devices.footer {- settings::put(buf, x, y.saturating_sub(1), w, message, if *error { danger } else { c.muted });- }- }- prompt_actions(buf, app, x, y, w, c);- return;- }+ if app.devices.ask.is_some() { return }let (line, style) = match app.devices.footer.as_ref().filter(|(_, err, at)| *err || at.elapsed() < Duration::from_secs(6)) {- Some((t, err, _)) => (t.clone(), if *err { danger } else { c.accent }),+ Some((t, err, _)) => (t.clone(), if *err { c.danger } else { c.accent }),None => (format!("↑↓ move enter choose type to search esc {}", if app.devices.sub.is_some() || picker.from_commands { "back" } else { "close" }), c.muted),};// (Too long for one line — a question beside the QR code — it takes the line above too.)@@ -1451,6 +1575,7 @@ fn footer(buf: &mut Buffer, app: &App, picker: &Picker, x: u16, y: u16, w: u16,pub fn draw(buf: &mut Buffer, app: &App, body: Rect, view: View, picker: &mut Picker) -> Option<Position> {let c = settings::chrome();app.devices.prompt_actions.set(None);+ app.devices.unfit.set(false);app.devices.phone.drawn.set(None);picker.screen_area.set(body);picker.list_area.set(Rect::default());@@ -1459,6 +1584,7 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, view: View, picker: &mut Pipicker.bar.set(None);settings::backdrop(buf, body, c.backdrop);if body.width < 24 || body.height < 8 {+ if app.devices.ask.is_some() { app.devices.unfit.set(true) }settings::put(buf, body.x, body.y, body.width, &format!("{} · resize or Esc", view.title()), c.base);return None;}@@ -1471,11 +1597,6 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, view: View, picker: &mut Pilet (x, right) = (r.x + 2, r.right().saturating_sub(2));let inner_w = right.saturating_sub(x);head(buf, app, view.title(), x, r.y + 1, right, &c);- if matches!(app.devices.ask, Some(Ask::Confirm { .. })) {- confirmation(buf, app, Rect::new(x, r.y + 3, inner_w, r.height.saturating_sub(5)), &c);- footer(buf, app, picker, x, r.bottom().saturating_sub(2), inner_w, &c);- return None;- }let cursor = query_line(buf, app, picker, x, r.y + 3, right, &c);let (top, bottom) = (r.y + 5, r.bottom().saturating_sub(3));let side = inner_w >= 64;@@ -1487,6 +1608,7 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, view: View, picker: &mut Pitext(buf, Rect::new(px, r.y + 3, right.saturating_sub(px), bottom.saturating_sub(r.y + 3)), &lines, &c);}footer(buf, app, picker, x, r.bottom().saturating_sub(2), inner_w, &c);+ if app.devices.ask.is_some() { return ask_dialog(buf, app, r, &c) }cursor}@@ -1517,9 +1639,6 @@ fn phone_draw(buf: &mut Buffer, app: &App, r: Rect, picker: &mut Picker, c: &Chrhead(buf, app, View::Phone.title(), tx, r.y + 1, right, c);let computer = this_computer();let mut lines: Vec<Line<'static>> = Vec::new();- if let Some(Ask::Confirm { question, .. }) = &app.devices.ask {- lines.extend([Line::from(Span::styled(question.clone(), c.accent)), Line::raw("")]);- }let status = |text: String, color: Color| Line::from(Span::styled(text, fg(color)));if p.signed_out {lines.push(Line::raw("Sign in to add your phone."));@@ -1550,7 +1669,8 @@ fn phone_draw(buf: &mut Buffer, app: &App, r: Rect, picker: &mut Picker, c: &Chrlet bottom = r.bottom().saturating_sub(3);if top < bottom { settings::list(buf, picker, Rect::new(tx, top, tw, bottom - top), c, false) } else { picker.row_at.clear() }footer(buf, app, picker, tx, r.bottom().saturating_sub(2), tw, c);- None+ // (The question goes over the words beside the code, so the code stays in view while it asks.)+ ask_dialog(buf, app, Rect::new(tx, r.y, r.right().saturating_sub(tx), r.height), c)}#[cfg(test)]@@ -1623,14 +1743,16 @@ mod tests {}#[test]- fn the_commands_panel_lists_the_three_views_under_machines() {+ fn the_commands_panel_lists_connect_machines_and_add_phone_under_machines() {let app = app((150, 42));let rows = crate::modal::command_rows(&app);- for view in View::ALL {- let row = rows.iter().find(|r| r.id == format!("cmd:{}", view.id())).unwrap_or_else(|| panic!("{} missing", view.id()));- assert_eq!(row.group.as_deref(), Some("Machines"));- assert!(crate::input::is_command(view.id()));+ // (Connect a computer… only went to Connect machines…: one way in. Its command still runs.)+ for (id, label) in [("devices", "Connect machines…"), ("add-phone", "Add phone…"), ("machines", "List machines")] {+ let row = rows.iter().find(|r| r.id == format!("cmd:{id}")).unwrap_or_else(|| panic!("{id} missing"));+ assert_eq!((row.label.as_str(), row.group.as_deref()), (label, Some("Machines")));}+ assert!(!rows.iter().any(|r| r.id == "cmd:connect-machine"), "no second way to the same view");+ for view in View::ALL { assert!(crate::input::is_command(view.id())) }}#[test]@@ -1705,7 +1827,7 @@ mod tests {assert_eq!(app.devices.footer.as_ref().map(|f| f.0.as_str()), Some("Enter the remote password first"));typed(&mut app, "hunter2");let (s, _) = screen(&mut app, 150, 42);- assert!(s.contains("Remote password for gpu-box › •••••••") && !s.contains("hunter2"), "shown as dots:\n{s}");+ assert!(s.contains("│ Remote password for gpu-box") && s.contains("│••••••• ") && !s.contains("hunter2"), "shown as dots:\n{s}");press(&mut app, KeyCode::Enter);assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")), "nothing runs before the yes");assert!(matches!(app.devices.ask, Some(Ask::Confirm { .. })));@@ -1805,12 +1927,14 @@ mod tests {let log = fake(&mut app);crate::input::run(&mut app, "devices");let clear = cli(&["remote-password", "clear", "--json"], None);- for (w, h) in [(150, 42), (80, 24), (40, 12), (24, 10)] {+ // (27 wide at the least: `[ Cancel ] [ Yes ]` is 19 columns and the panel is 4 narrower+ // than the screen, with 2 columns of inset each side; the old buttons fit in 24.)+ for (w, h) in [(150, 42), (80, 24), (40, 12), (27, 10)] {go_to(&mut app, "pw:clear");press(&mut app, KeyCode::Enter);crate::input::handle(&mut app, crossterm::event::Event::Resize(w, h));let (visible, _) = screen(&mut app, w, h);- assert!(visible.contains(" Yes ") && visible.contains(" Cancel "), "{w}x{h}:\n{visible}");+ assert!(visible.contains("[ Yes ]") && visible.contains("[ Cancel ]"), "{w}x{h}:\n{visible}");click_prompt(&mut app, false);assert!(app.devices.ask.is_none());assert!(!has(&log, &clear));@@ -1818,17 +1942,282 @@ mod tests {go_to(&mut app, "pw:clear"); press(&mut app, KeyCode::Enter);crate::input::handle(&mut app, crossterm::event::Event::Resize(80, 24));screen(&mut app, 80, 24);+ // Too small to draw: the question is cancelled, never kept invisible to answer keys.crate::input::handle(&mut app, crossterm::event::Event::Resize(12, 5));screen(&mut app, 12, 5);assert!(app.devices.prompt_actions.get().is_none());- click_at(&mut app, 4, 3);+ assert!(app.devices.ask.is_none(), "cancelled");+ assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Make the terminal larger to answer this"));+ press(&mut app, KeyCode::Char('y'));+ assert!(!has(&log, &clear), "nothing answered it");+ assert_eq!(app.devices.footer.as_ref().map(|f| f.0.as_str()), Some("Nothing changed"), "the cancel path ran");+ }++ #[test]+ fn a_typed_line_that_cannot_fit_is_cancelled_too() {+ let mut app = app((150, 42));+ let log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "pw");+ crate::input::handle(&mut app, crossterm::event::Event::Resize(20, 6));+ screen(&mut app, 20, 6);+ assert!(app.devices.ask.is_none());+ assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Make the terminal larger to answer this"));+ press(&mut app, KeyCode::Enter);+ assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")), "the typed password went nowhere");+ }++ #[test]+ fn dialog_titles_follow_the_naming_system() {+ let mut app = app((150, 42));+ let _log = fake(&mut app);+ let title = |app: &mut App| { let (s, _) = screen(app, 150, 42); s.lines().find_map(|l| l.find("┌─").map(|i| l[i..].chars().skip(2).take_while(|c| *c != '─').collect::<String>().trim_end().to_string())).unwrap_or_default() };+ connect_to(&mut app, REMOTE.into());+ assert_eq!(title(&mut app), "Connect · gpu-box");+ press(&mut app, KeyCode::Esc);+ crate::input::run(&mut app, "devices");+ go_to(&mut app, "pw:set");+ press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Set Remote Password");+ typed(&mut app, "a"); press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Set Remote Password", "the repeat step too");+ typed(&mut app, "a"); press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Set Remote Password", "and its question");+ press(&mut app, KeyCode::Esc);+ go_to(&mut app, "pw:clear");+ press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Clear Remote Password");+ press(&mut app, KeyCode::Esc);+ go_to(&mut app, &format!("m:{REMOTE}"));+ press(&mut app, KeyCode::Enter);+ go_to(&mut app, &format!("act:rename:{REMOTE}"));+ press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Rename Computer · gpu-box");+ typed(&mut app, "2"); press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Rename Computer · gpu-box", "and its question");+ press(&mut app, KeyCode::Esc);+ go_to(&mut app, &format!("act:remove:{REMOTE}"));+ press(&mut app, KeyCode::Enter);+ assert_eq!(title(&mut app), "Remove from Account · gpu-box", "echoing the row \"Remove from account…\"");+ }++ #[test]+ fn typing_while_the_buttons_have_the_keys_goes_back_to_the_input() {+ let mut app = app((150, 42));+ let _log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "ab");+ press(&mut app, KeyCode::Tab);+ assert!(app.devices.prompt_focus.get(), "on the buttons");+ // (h and l move between buttons there, but they are letters too.)+ typed(&mut app, "hl");+ assert!(!app.devices.prompt_focus.get(), "the input has the keys again");+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, caret: 4, .. }) if value == "abhl"), "{:?}", app.devices.ask);+ press(&mut app, KeyCode::Tab);+ press(&mut app, KeyCode::Right);+ assert!(app.devices.prompt_focus.get(), "arrows still move between the buttons");+ }++ #[test]+ fn prevent_new_links_starts_on_cancel_and_arrows_move_between_the_buttons() {+ let mut app = app((150, 42));+ let log = fake(&mut app);+ crate::input::run(&mut app, "devices");+ let clear = cli(&["remote-password", "clear", "--json"], None);+ // The background under the first letter of [text]'s label.+ let bg_of = |s: &str, buf: &Buffer, text: &str| {+ let (y, line) = s.lines().enumerate().find(|(_, l)| l.contains(text)).expect("button row");+ let x = line[..line.find(text).unwrap()].chars().count() as u16 + 2;+ buf[(x, y as u16)].bg+ };+ let selected = settings::chrome().selected.bg;+ go_to(&mut app, "pw:clear");+ press(&mut app, KeyCode::Enter);+ let (s, buf) = screen(&mut app, 150, 42);+ assert!(s.contains("[ Cancel ] [ Yes ]") && s.contains(buttons::KEYS), "the one keys hint every question shows: {s}");+ if !crate::theme::no_color() {+ assert_eq!(Some(bg_of(&s, &buf, "[ Cancel ]")), selected, "starts on Cancel");+ assert_ne!(Some(bg_of(&s, &buf, "[ Yes ]")), selected);+ }+ press(&mut app, KeyCode::Enter);+ assert!(app.devices.ask.is_none(), "Enter on Cancel closes");assert!(!has(&log, &clear));- assert!(matches!(app.devices.ask, Some(Ask::Confirm { .. })));- crate::input::handle(&mut app, crossterm::event::Event::Resize(80, 24));- click_prompt(&mut app, true);+ go_to(&mut app, "pw:clear");+ press(&mut app, KeyCode::Enter);+ press(&mut app, KeyCode::Right);+ assert!(matches!(app.devices.ask, Some(Ask::Confirm { .. })), "an arrow keeps the prompt");+ let (s, buf) = screen(&mut app, 150, 42);+ if !crate::theme::no_color() { assert_eq!(Some(bg_of(&s, &buf, "[ Yes ]")), selected, "Right chose Yes"); }+ press(&mut app, KeyCode::Left);+ press(&mut app, KeyCode::Right);+ press(&mut app, KeyCode::Enter);assert_eq!(clis(&log, "remote-password").iter().filter(|r| **r == clear).count(), 1);}+ #[test]+ fn the_password_input_keeps_the_arrows_until_tab_moves_the_keys_to_the_buttons() {+ let mut app = app((150, 42));+ let log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "abc");+ press(&mut app, KeyCode::Right);+ press(&mut app, KeyCode::Left);+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "abc"), "arrows leave the typed value");+ press(&mut app, KeyCode::Tab);+ typed(&mut app, "y");+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "abyc"), "a letter is typed at the caret, not a button's");+ press(&mut app, KeyCode::Tab);+ press(&mut app, KeyCode::Left);+ press(&mut app, KeyCode::Enter);+ assert!(app.devices.ask.is_none(), "Enter on [ Cancel ] cancels, it does not submit");+ assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")));+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "abc");+ press(&mut app, KeyCode::Tab);+ press(&mut app, KeyCode::Tab);+ press(&mut app, KeyCode::Enter);+ assert!(matches!(app.devices.ask, Some(Ask::Confirm { .. })), "Tab back to the input: Enter continues");+ }++ /// The screen and where the terminal cursor is left.+ fn screen_cursor(app: &mut App, w: u16, h: u16) -> (String, Buffer, Option<Position>) {+ let (s, buf) = screen(app, w, h);+ // (The panel's own answer, drawn again: a test terminal does not say where its cursor is.)+ let Some(Modal::Picker { kind, mut picker }) = app.modal.take() else { panic!("no panel") };+ let PickerKind::Devices(view) = kind else { panic!("not a devices view") };+ let cursor = draw(&mut Buffer::empty(Rect::new(0, 0, w, h)), app, app.body(), view, &mut picker);+ app.modal = Some(Modal::Picker { kind, picker });+ (s, buf, cursor)+ }++ /// The screen's line with [text] on it.+ fn line_with<'a>(s: &'a str, text: &str) -> &'a str { s.lines().find(|l| l.contains(text)).unwrap_or_else(|| panic!("no {text:?} on screen:\n{s}")) }++ #[test]+ fn the_password_is_asked_in_a_dialog_and_the_search_line_stays_the_search() {+ let mut app = app((150, 42));+ let log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ let (s, _, _) = screen_cursor(&mut app, 150, 42);+ assert!(s.contains("Search machines not linked yet"), "the search line is the panel's own:\n{s}");+ assert!(!s.contains("› Remote password"), "no prompt in the search line:\n{s}");+ assert!(s.contains("Connect · gpu-box") && s.contains("[ Cancel ] [ Connect ]"), "the dialog:\n{s}");+ assert!(s.contains("│ Remote password for gpu-box"), "the label inside the box:\n{s}");+ assert!(s.contains("│ Enter the remote password set on this machine."), "the message inside the box:\n{s}");+ typed(&mut app, "pass");+ let (s, buf, cursor) = screen_cursor(&mut app, 150, 42);+ assert!(line_with(&s, "••••").contains("│••••"), "typed into the input box, masked:\n{s}");+ let at = cursor.expect("the terminal cursor is at the caret");+ assert_eq!((buf[(at.x - 1, at.y)].symbol(), buf[(at.x, at.y)].symbol()), ("•", " "), "after the last dot");+ // ← → move the caret; a paste goes in at it, never into the search.+ press(&mut app, KeyCode::Left);+ press(&mut app, KeyCode::Left);+ crate::input::handle(&mut app, crossterm::event::Event::Paste("XY".into()));+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "paXYss"), "{:?}", app.devices.ask);+ assert!(picker_mut(&mut app).unwrap().query.is_empty());+ let (_, _, moved) = screen_cursor(&mut app, 150, 42);+ assert_eq!(moved, Some(Position::new(at.x, at.y)), "the caret after the paste: 4 dots in, as before");+ // Tab: the keys to the buttons, Connect chosen; Enter on it goes on to the yes.+ press(&mut app, KeyCode::Tab);+ let (s, buf, cursor) = screen_cursor(&mut app, 150, 42);+ assert_eq!(cursor, None, "no text cursor while the buttons have the keys");+ if !crate::theme::no_color() {+ let (y, line) = s.lines().enumerate().find(|(_, l)| l.contains("[ Connect ]")).unwrap();+ let x = line[..line.find("[ Connect ]").unwrap()].chars().count() as u16 + 2;+ assert_eq!(Some(buf[(x, y as u16)].bg), settings::chrome().selected.bg, "Connect is chosen");+ }+ press(&mut app, KeyCode::Enter);+ assert!(matches!(&app.devices.ask, Some(Ask::Confirm { act: Act::Link { password, .. }, .. }) if password == "paXYss"));+ let (s, _, _) = screen_cursor(&mut app, 150, 42);+ assert!(s.contains("Connect · gpu-box") && s.contains("Link gpu-box with this password?") && s.contains("[ Cancel ] [ Yes ]"), "{s}");+ assert!(s.contains("Search machines not linked yet"), "{s}");+ press(&mut app, KeyCode::Esc);+ assert!(app.devices.ask.is_none());+ assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")), "Esc sent nothing");+ }++ #[test]+ fn a_click_on_the_input_gives_it_the_keys_and_a_click_beside_the_dialog_keeps_it() {+ let mut app = app((150, 42));+ app.mouse = true;+ let log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "ab");+ press(&mut app, KeyCode::Tab);+ screen(&mut app, 150, 42);+ let input = app.devices.prompt_actions.get().and_then(|a| a.input).expect("the input box is kept for clicks");+ click_at(&mut app, input.x + 3, input.y + 1);+ typed(&mut app, "c");+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "abc"), "typing goes to the input again: {:?}", app.devices.ask);+ // Beside the dialog, still on the panel: nothing happens; the typed line stays.+ let panel = picker_mut(&mut app).unwrap().screen_area.get();+ click_at(&mut app, panel.x + 3, panel.bottom() - 3);+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "abc"));+ assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")));+ }++ #[test]+ fn an_error_shows_in_the_dialog_and_rename_starts_from_the_current_name() {+ let mut app = app((150, 42));+ let _log = fake(&mut app);+ connect_to(&mut app, REMOTE.into());+ press(&mut app, KeyCode::Enter);+ let (s, buf, _) = screen_cursor(&mut app, 150, 42);+ let (y, line) = s.lines().enumerate().find(|(_, l)| l.contains("Enter the remote password first")).expect("the error");+ assert!(line.contains("│ Enter the remote password first"), "inside the dialog:\n{s}");+ if !crate::theme::no_color() {+ let x = line[..line.find("Enter the remote").unwrap()].chars().count() as u16;+ assert_eq!(buf[(x, y as u16)].fg, settings::chrome().danger.fg.unwrap(), "in the danger colour");+ }+ press(&mut app, KeyCode::Esc);+ crate::input::run(&mut app, "devices");+ go_to(&mut app, &format!("m:{REMOTE}"));+ press(&mut app, KeyCode::Enter);+ go_to(&mut app, &format!("act:rename:{REMOTE}"));+ press(&mut app, KeyCode::Enter);+ let (s, _, cursor) = screen_cursor(&mut app, 150, 42);+ assert!(s.contains("Rename Computer · gpu-box") && s.contains("[ Cancel ] [ Save ]"), "{s}");+ assert!(line_with(&s, "│gpu-box").contains("│gpu-box"), "the current name in the input:\n{s}");+ assert!(cursor.is_some());+ press(&mut app, KeyCode::Backspace);+ typed(&mut app, "X");+ assert!(matches!(&app.devices.ask, Some(Ask::Entry { value, .. }) if value == "gpu-boX"));+ }++ #[test]+ fn typed_line_prompts_say_next_when_narrow_and_continue_when_there_is_room() {+ let mut app = app((150, 42));+ app.mouse = true;+ let log = fake(&mut app);+ // (Screen width -> room in the dialog: 28 -> 20 for `[ Cancel ] [ Next ]`, 31 -> 23 for+ // Connect, 32 -> 24 for Continue.)+ for (w, h, label) in [(28, 12, "[ Next ]"), (31, 12, "[ Connect ]"), (80, 24, "[ Connect ]")] {+ connect_to(&mut app, REMOTE.into());+ typed(&mut app, "pw");+ crate::input::handle(&mut app, crossterm::event::Event::Resize(w, h));+ let (visible, _) = screen(&mut app, w, h);+ assert!(visible.contains(label) && visible.contains("[ Cancel ]"), "{w}x{h}:\n{visible}");+ click_prompt(&mut app, true);+ assert!(matches!(app.devices.ask, Some(Ask::Confirm { .. })), "{w}x{h}: the click continues");+ press(&mut app, KeyCode::Esc);+ }+ assert!(clis(&log, "link").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "connect")));+ crate::input::run(&mut app, "devices");+ for (w, h, label) in [(28, 12, "[ Next ]"), (31, 12, "[ Next ]"), (32, 12, "[ Continue ]"), (80, 24, "[ Continue ]")] {+ crate::input::handle(&mut app, crossterm::event::Event::Resize(150, 42));+ go_to(&mut app, "pw:set");+ press(&mut app, KeyCode::Enter);+ typed(&mut app, "pw");+ crate::input::handle(&mut app, crossterm::event::Event::Resize(w, h));+ let (visible, _) = screen(&mut app, w, h);+ assert!(visible.contains(label) && visible.contains("[ Cancel ]"), "{w}x{h}:\n{visible}");+ click_prompt(&mut app, true);+ assert!(matches!(app.devices.ask, Some(Ask::Entry { what: Entry::RepeatPassword { .. }, .. })), "{w}x{h}: the click continues");+ press(&mut app, KeyCode::Esc);+ }+ assert!(clis(&log, "remote-password").iter().all(|r| !matches!(r, Req::Cli { args, .. } if args[1] == "set")));+ }+/// M-l on a machine (the machines list) is this same flow: the panel, its password asked for.#[test]fn m_l_opens_connect_with_the_password_asked() {@@ -2014,7 +2403,7 @@ mod tests {View::Phone if w == 80 => assert!(s.contains("to show the QR code") && app.devices.phone.drawn.get().is_none(), "too small says so:\n{s}"),View::Phone => assert!(app.devices.phone.drawn.get().is_some(), "{s}"),}- if view == View::Phone { assert!(s.contains("y/n"), "asks before handing over the code:\n{s}") }+ if view == View::Phone { assert!(s.contains("[ Cancel ] [ Yes ]"), "asks before handing over the code:\n{s}") }}}}diff --git a/tui/src/dialog.rs b/tui/src/dialog.rsnew file mode 100644index 000000000..6264ec6c6--- /dev/null+++ b/tui/src/dialog.rs@@ -0,0 +1,408 @@+//! The box every question is asked in — Close Tab, Stop Harness, the Machines prompts, Files'+//! Delete and names, the editor's Save changes, hn's own Rename / Send / Broadcast / Answer /+//! Message: a bordered box in the command panel's colours with its+//! title in the top rule, the question, an optional one-line input (its label above it, a password+//! as dots), a line for what went wrong, and the button row (`buttons::Row`) at the bottom. It is+//! a ratatui widget; [areas] is the one place its parts are laid out, for drawing and clicks alike.++use ratatui::buffer::Buffer;+use ratatui::layout::{Constraint, Layout, Margin, Position, Rect};+use ratatui::style::Style;+use ratatui::symbols::border;+use ratatui::text::{Line, Span, Text};+use ratatui::widgets::{Block, Clear, Paragraph, Widget};+use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};++use crate::buttons::Row;+use crate::settings::Chrome;++/// The input box's rows: its border above and below the text.+const INPUT_ROWS: u16 = 3;++/// The columns a typed line's input box wants.+pub const INPUT_W: u16 = 48;++/// A one-line input: [label] above a bordered box with [value] in it — dots when [secret] — and+/// the caret [caret] characters in. [focused]: the input has the keys (not the buttons). [width]:+/// the columns it wants, so the box does not grow as it is typed into. [select]: the characters+/// `(from, to)` that typing replaces, drawn in the chosen style.+pub struct Input<'a> { pub label: &'a str, pub value: &'a str, pub caret: usize, pub select: Option<(usize, usize)>, pub secret: bool, pub focused: bool, pub width: u16 }++pub struct Dialog<'a> {+ pub title: Line<'a>,+ pub body: Vec<Line<'a>>,+ pub input: Option<Input<'a>>,+ /// What went wrong (or what to do), under the input: wrapped lines, which fitting drops last first.+ pub message: Vec<Line<'a>>,+ pub row: &'a Row,+ pub border: border::Set<'a>,+ pub chrome: &'a Chrome,+ /// The row's keys hint on the last line, under the buttons (the row has one, and there is+ /// room: fitting drops it first).+ pub hint: bool,+}++/// Which optional parts a dialog has (and how many lines its message is): its geometry depends on+/// nothing else.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+pub struct Parts { pub label: bool, pub input: bool, pub message: u16, pub hint: bool }++/// Where each part of a dialog goes inside its box.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Areas { pub body: Rect, pub label: Option<Rect>, pub input: Option<Rect>, pub field: Option<Rect>, pub message: Option<Rect>, pub row: Rect, pub hint: Option<Rect> }++/// The parts of a dialog drawn in [area] (its box), two columns in from each side: the body,+/// then the label, the input box, the message, a blank row, the buttons' row and — a blank row+/// above it, always the last line — the keys hint.+pub fn areas(area: Rect, parts: Parts) -> Areas {+ let optional = [(parts.label, 1), (parts.input, INPUT_ROWS), (parts.message > 0, parts.message)];+ let constraints = std::iter::once(Constraint::Fill(1))+ .chain(optional.iter().filter(|(on, _)| *on).map(|&(_, rows)| Constraint::Length(rows)))+ .chain([Constraint::Length(1), Constraint::Length(1)]) // a blank row, the buttons+ .chain(parts.hint.then_some([Constraint::Length(1), Constraint::Length(1)]).into_iter().flatten()); // a blank row, the hint+ let rects = Layout::vertical(constraints).split(area.inner(Margin::new(2, 1)));+ let mut next = rects.iter().copied();+ let body = next.next().unwrap_or_default();+ let mut take = |on: bool| if on { next.next() } else { None };+ let (label, input, message) = (take(parts.label), take(parts.input), take(parts.message > 0));+ let (_blank, row) = (take(true), take(true).unwrap_or_default());+ let (_blank, hint) = (take(parts.hint), take(parts.hint));+ Areas { body, label, input, field: input.map(|r| r.inner(Margin::new(1, 1))), message, row, hint }+}++/// [text] as lines of at most [width] columns, broken between words, in [style].+pub fn wrap(text: &str, width: u16, style: Style) -> Vec<Line<'static>> {+ if text.is_empty() { return Vec::new() }+ crate::workspace_menu::wrap(text, width as usize).into_iter().map(|l| Line::styled(l, style)).collect()+}++/// [text] cut to [width] columns, ending in … where it was cut.+fn cut(text: &str, width: u16) -> String {+ if text.width() <= width as usize { return text.to_string() }+ let mut used = 1; // the …+ let kept: String = text.chars().take_while(|ch| { used += ch.width().unwrap_or(0); used <= width as usize }).collect();+ kept + "…"+}++impl Input<'_> {+ /// What the box shows: the value, or a dot for each of its characters.+ fn shown(&self) -> String {+ if self.secret { "•".repeat(self.value.chars().count()) } else { self.value.to_string() }+ }++ /// [shown] as a `Line`, the selection in [selected]'s style.+ fn line(&self, selected: Style) -> Line<'static> {+ let shown = self.shown();+ let Some((from, to)) = self.select.filter(|(a, b)| a < b) else { return Line::raw(shown) };+ let part = |skip: usize, take: usize| shown.chars().skip(skip).take(take).collect::<String>();+ Line::from(vec![Span::raw(part(0, from)), Span::styled(part(from, to - from), selected), Span::raw(part(to, usize::MAX))])+ }++ /// The caret's column in what is shown, and how far that is scrolled so the caret stays in a+ /// field [room] columns wide.+ fn caret(&self, room: u16) -> (u16, u16) {+ let before: String = self.shown().chars().take(self.caret).collect();+ let col = before.width().min(u16::MAX as usize) as u16;+ (col, col.saturating_sub(room.saturating_sub(1)))+ }+}++impl<'a> Dialog<'a> {+ /// A dialog titled [title] in [c]'s muted colour, with the default single-line border.+ pub fn new(title: &str, body: Vec<Line<'a>>, row: &'a Row, c: &'a Chrome) -> Dialog<'a> {+ Dialog { title: Line::from(Span::styled(title.to_string(), c.muted)), body, input: None, message: Vec::new(), row, border: border::PLAIN, chrome: c, hint: true }+ }++ pub fn parts(&self) -> Parts {+ let input = self.input.as_ref();+ Parts { label: input.is_some_and(|i| !i.label.is_empty()), input: input.is_some(), message: self.message.len().min(u16::MAX as usize / 2) as u16,+ hint: self.hint && !self.row.hint.is_empty() }+ }++ pub fn areas(&self, area: Rect) -> Areas { areas(area, self.parts()) }++ /// The columns the box wants: its widest part, and two columns each side for the border and margin.+ pub fn width(&self) -> u16 {+ let label = self.input.as_ref().map_or(0, |i| i.label.width().max(i.width as usize));+ let message = self.message.iter().map(Line::width).max().unwrap_or(0);+ let widest = self.body.iter().map(Line::width).chain([self.title.width(), label, message, self.row.width() as usize]).max().unwrap_or(0);+ widest.min(u16::MAX as usize - 4) as u16 + 4+ }++ /// The rows the box needs.+ pub fn height(&self) -> u16 {+ let p = self.parts();+ // (The hint: a blank row and its line.)+ let optional = u16::from(p.label) + if p.input { INPUT_ROWS } else { 0 } + p.message + 2 * u16::from(p.hint);+ (self.body.len().min(u16::MAX as usize / 2) as u16).saturating_add(optional + 2 + 2)+ }++ /// Fitted into [rows]: the keys hint goes first, then the body's last lines (the last one+ /// kept ends in …), then the message, then the label — and with an input, which is the+ /// question then, the body. False when even the rest does not fit.+ pub fn fit(&mut self, rows: u16) -> bool {+ if self.height() > rows { self.hint = false }+ let others = self.height() as usize - self.body.len();+ let room = (rows as usize).saturating_sub(others).max(1);+ if self.body.len() > room {+ let widest = self.body.iter().map(Line::width).max().unwrap_or(0);+ self.body.truncate(room);+ if let Some(last) = self.body.last_mut() {+ let style = last.spans.first().map_or(last.style, |s| last.style.patch(s.style));+ let mut used = 1; // the …+ let cut: String = last.to_string().chars().take_while(|ch| { used += ch.width().unwrap_or(0); used <= widest }).collect();+ *last = Line::styled(cut + "…", style);+ }+ }+ while self.height() > rows && self.message.pop().is_some() {}+ if self.height() > rows && let Some(input) = &mut self.input { input.label = "" }+ if self.height() > rows && self.input.is_some() { self.body.clear() }+ self.height() <= rows+ }++ /// Where the box goes: centred over [over], no bigger than it.+ pub fn place(&self, over: Rect) -> Rect {+ over.centered(Constraint::Length(self.width().min(over.width)), Constraint::Length(self.height().min(over.height)))+ }++ /// Where the terminal cursor goes for a box drawn at [area]: at the input's caret, while it+ /// has the keys.+ pub fn cursor(&self, area: Rect) -> Option<Position> {+ let input = self.input.as_ref().filter(|i| i.focused)?;+ let field = self.areas(area).field.filter(|f| f.width > 0)?;+ let (col, offset) = input.caret(field.width);+ Some(Position::new(field.x + col - offset, field.y))+ }++ /// The box at [area] as an overlay on [over]: what it is over dimmed first, with the command+ /// panel's backdrop, so the question stands apart and is not read as text drawn over text.+ pub fn render_over(&self, over: Rect, area: Rect, buf: &mut Buffer) {+ crate::settings::backdrop(buf, over, self.chrome.backdrop);+ Widget::render(self, area, buf);+ }+}++/// `Clear`, then a `Block` in the command panel's surface with its border in the muted colour+/// and the title over the top rule; the body a `Paragraph`; the input a bordered `Block` (in the+/// accent while it has the keys) round a `Paragraph` scrolled to its caret; the message a `Line`;+/// the buttons the row widget.+impl Widget for &Dialog<'_> {+ fn render(self, area: Rect, buf: &mut Buffer) {+ let c = self.chrome;+ let mut block = Block::bordered().border_set(self.border).border_style(c.muted).style(c.base);+ if self.title.width() > 0 {+ // A Block's title starts next to the corner, tmux's a column later: one more of the rule first.+ let rule = Span::styled(self.border.horizontal_top, c.muted);+ block = block.title(Line::from_iter(std::iter::once(rule).chain(self.title.spans.iter().cloned())).style(self.title.style));+ }+ crate::term_out::clear_extras(area);+ Clear.render(area, buf);+ block.render(area, buf);+ let a = self.areas(area);+ Paragraph::new(Text::from(self.body.clone())).render(a.body, buf);+ if let (Some(input), Some(r), Some(field)) = (&self.input, a.input, a.field) {+ if let Some(label) = a.label { Line::styled(cut(input.label, label.width), c.base).render(label, buf) }+ Block::bordered().border_set(self.border).border_style(if input.focused { c.accent } else { c.muted }).render(r, buf);+ let (_, offset) = input.caret(field.width);+ Paragraph::new(input.line(c.selected)).style(c.base).scroll((0, offset)).render(field, buf);+ }+ if let Some(r) = a.message { Paragraph::new(Text::from(self.message.clone())).render(r, buf) }+ self.row.view(c).render(a.row, buf);+ if let Some(r) = a.hint { self.row.hint_line(c).render(r, buf) }+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::buttons::{oracle, Button};+ use ratatui::style::Modifier;++ fn connect() -> Row {+ let b = |label: &str| Button { label: label.into(), key: None };+ Row { buttons: vec![b("Cancel"), b("Connect")], chosen: 1, hint: String::new() }+ }++ fn text(buf: &Buffer) -> Vec<String> {+ let a = buf.area;+ (a.top()..a.bottom()).map(|y| (a.left()..a.right()).map(|x| buf[(x, y)].symbol()).collect()).collect()+ }++ fn password<'a>(row: &'a Row, c: &'a Chrome, value: &'a str, focused: bool) -> Dialog<'a> {+ let mut d = Dialog::new("Connect · linux-box", vec![Line::styled("Enter the password.", c.base)], row, c);+ d.input = Some(Input { label: "Remote password", value, caret: value.chars().count(), select: None, secret: true, focused, width: 0 });+ d.message = vec![Line::styled("Wrong password", c.danger)];+ d+ }++ #[test]+ fn it_draws_the_title_body_masked_input_message_and_buttons() {+ for c in oracle::chromes() {+ let mut row = connect();+ row.chosen = usize::MAX; // the input has the keys+ let d = password(&row, &c, "pass", true);+ assert_eq!((d.width(), d.height()), (27, 10));+ let area = Rect::new(2, 1, d.width() + 4, d.height());+ let mut buf = oracle::canvas(Rect::new(0, 0, 40, 12));+ (&d).render(area, &mut buf);+ // 31 columns: 27 inside the margins.+ let shown: Vec<String> = text(&buf)[1..11].iter().map(|l| l.chars().skip(2).take(31).collect()).collect();+ let (rule, gap) = (|n: usize| "─".repeat(n), |n: usize| " ".repeat(n));+ assert_eq!(shown, [+ format!("┌─Connect · linux-box{}┐", rule(9)),+ format!("│ Enter the password.{} │", gap(8)),+ format!("│ Remote password{} │", gap(12)),+ format!("│ ┌{}┐ │", rule(25)),+ format!("│ │••••{}│ │", gap(21)),+ format!("│ └{}┘ │", rule(25)),+ format!("│ Wrong password{} │", gap(13)),+ format!("│{}│", gap(29)),+ format!("│ {}[ Cancel ] [ Connect ] │", gap(4)),+ format!("└{}┘", rule(29)),+ ], "{:?}", text(&buf));+ assert!(!text(&buf)[5].contains("pass"), "masked");+ let cell = &buf[(4, 7)];+ let reset = ratatui::style::Color::Reset;+ assert_eq!((cell.fg, cell.bg), (c.danger.fg.unwrap_or(reset), c.danger.bg.unwrap_or(reset)), "the message in the danger style");+ assert!(cell.modifier.contains(c.danger.add_modifier));+ assert_eq!(d.cursor(area), Some(Position::new(5 + 4, 5)), "after the fourth dot");+ assert!(buf[(4, 4)].modifier.contains(Modifier::BOLD), "the input with the keys is bordered in the accent");+ assert_eq!(buf[(1, 1)].symbol(), "x", "nothing drawn outside the box");+ }+ }++ #[test]+ fn under_no_color_the_chosen_button_is_reversed_and_the_message_bold() {+ let c = crate::settings::chrome_with(true);+ let row = connect();+ let d = password(&row, &c, "pw", false);+ let area = Rect::new(0, 0, d.width(), d.height());+ let mut buf = Buffer::empty(area);+ (&d).render(area, &mut buf);+ let a = d.areas(area);+ let connect = row.areas(a.row)[1];+ assert!(buf[(connect.x, connect.y)].modifier.contains(Modifier::REVERSED));+ assert!(buf[(a.message.unwrap().x, a.message.unwrap().y)].modifier.contains(Modifier::BOLD));+ assert_eq!(buf[(a.input.unwrap().x, a.input.unwrap().y)].modifier, Modifier::DIM, "the input without the keys is muted");+ assert_eq!(d.cursor(area), None, "no caret while the buttons have the keys");+ assert_eq!(buf[(a.input.unwrap().x, a.input.unwrap().y)].fg, ratatui::style::Color::Reset, "no colour at all");+ }++ #[test]+ fn drawing_and_clicks_share_one_geometry() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let d = password(&row, &c, "", true);+ let area = Rect::new(10, 5, 40, 12);+ let a = d.areas(area);+ assert_eq!(a.body, Rect::new(12, 6, 36, 3), "the body takes what is left");+ assert_eq!((a.label, a.input, a.field), (Some(Rect::new(12, 9, 36, 1)), Some(Rect::new(12, 10, 36, 3)), Some(Rect::new(13, 11, 34, 1))));+ assert_eq!(a.message, Some(Rect::new(12, 13, 36, 1)));+ assert_eq!(a.row, Rect::new(12, 15, 36, 1), "a blank row above the buttons");+ let connect = row.areas(a.row)[1];+ assert_eq!(row.click(a.row, Position::new(connect.x, connect.y)), Some(1));+ // A question with no input is notes, a blank row and the buttons — the Close Tab box.+ let plain = areas(area, Parts::default());+ assert_eq!((plain.body, plain.row, plain.input), (Rect::new(12, 6, 36, 8), Rect::new(12, 15, 36, 1), None));+ }++ #[test]+ fn a_long_value_scrolls_to_keep_the_caret_in_view() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let value = "abcdefghijklmnopqrstuvwxyz";+ let mut d = Dialog::new("Rename Machine", vec![], &row, &c);+ d.input = Some(Input { label: "", value, caret: 26, select: None, secret: false, focused: true, width: 30 });+ assert_eq!(d.width(), 34, "the box as wide as the input wants, not as its value");+ let area = Rect::new(0, 0, 18, d.height());+ let field = d.areas(area).field.unwrap();+ assert_eq!(field.width, 12);+ let mut buf = Buffer::empty(area);+ (&d).render(area, &mut buf);+ let line = |buf: &Buffer| (field.x..field.right()).map(|x| buf[(x, field.y)].symbol()).collect::<String>();+ assert_eq!(line(&buf), "pqrstuvwxyz ", "the end, and room for the caret");+ assert_eq!(d.cursor(area), Some(Position::new(field.right() - 1, field.y)));+ d.input.as_mut().unwrap().caret = 0;+ let mut buf = Buffer::empty(area);+ (&d).render(area, &mut buf);+ assert_eq!(line(&buf), "abcdefghijkl");+ assert_eq!(d.cursor(area), Some(Position::new(field.x, field.y)));+ }++ #[test]+ fn fitting_cuts_the_body_then_drops_the_message_then_the_label() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let mut d = Dialog::new("Remote Password", wrap("Prevent new links using this password? Existing links and sessions stay connected.", 20, c.base), &row, &c);+ assert_eq!(d.body.len(), 5);+ assert!(d.body.iter().all(|l| l.width() <= 20));+ assert_eq!(d.height(), 2 + 5 + 2);+ assert!(d.fit(7));+ assert_eq!(d.body.len(), 3);+ assert!(d.body[2].to_string().ends_with('…'), "{:?}", d.body[2]);+ assert!(!d.fit(4), "no room for one line of the question and the buttons");+ let mut d = password(&row, &c, "", true);+ assert!(d.fit(9) && d.message.is_empty() && d.input.as_ref().unwrap().label == "Remote password" && d.body.len() == 1);+ // (With an input, the input is the question: the body may go too.)+ assert!(d.fit(7) && d.input.as_ref().unwrap().label.is_empty() && d.body.is_empty());+ assert_eq!(d.height(), 7);+ assert!(!d.fit(6));+ }++ #[test]+ fn a_long_message_wraps_and_fitting_drops_its_last_lines_first() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let mut d = password(&row, &c, "", true);+ d.message = wrap("Passwords do not match, so nothing was changed.", 20, c.danger);+ assert_eq!(d.message.iter().map(|l| l.to_string()).collect::<Vec<_>>(), ["Passwords do not", "match, so nothing", "was changed."]);+ assert_eq!(d.parts(), Parts { label: true, input: true, message: 3, hint: false });+ assert_eq!(d.areas(Rect::new(0, 0, 30, 20)).message.map(|r| r.height), Some(3));+ assert_eq!(d.height(), 1 + 1 + 3 + 3 + 4, "the body, the label, the input box, three message lines, two rules and two rows");+ assert!(d.fit(d.height() - 1));+ assert_eq!(d.message.iter().map(|l| l.to_string()).collect::<Vec<_>>(), ["Passwords do not", "match, so nothing"], "the last line went first");+ assert!(d.fit(9) && d.message.is_empty(), "then the rest of the message, before the label");+ assert!(d.input.as_ref().unwrap().label == "Remote password");+ }++ #[test]+ fn a_label_cut_to_the_box_ends_in_an_ellipsis() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let mut d = password(&row, &c, "", true);+ d.input.as_mut().unwrap().label = "Remote password set on this computer";+ let area = Rect::new(0, 0, 24, d.height());+ let mut buf = Buffer::empty(area);+ (&d).render(area, &mut buf);+ let label = d.areas(area).label.unwrap();+ let shown: String = (label.x..label.right()).map(|x| buf[(x, label.y)].symbol()).collect();+ assert_eq!(shown, "Remote password set…");+ }++ #[test]+ fn a_selection_in_the_input_is_drawn_in_the_chosen_style() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let mut d = Dialog::new("Rename · notes.txt", vec![], &row, &c);+ d.input = Some(Input { label: "", value: "notes.txt", caret: 5, select: Some((0, 5)), secret: false, focused: true, width: 20 });+ let area = Rect::new(0, 0, 30, d.height());+ let mut buf = Buffer::empty(area);+ (&d).render(area, &mut buf);+ let field = d.areas(area).field.unwrap();+ let bg = |i: u16| buf[(field.x + i, field.y)].bg;+ assert_eq!((bg(0), bg(4)), (c.selected.bg.unwrap(), c.selected.bg.unwrap()), "notes");+ assert_ne!(bg(5), c.selected.bg.unwrap(), ".txt is not");+ assert_eq!(d.cursor(area), Some(Position::new(field.x + 5, field.y)));+ }++ #[test]+ fn it_is_placed_in_the_middle_of_what_it_is_over() {+ let c = crate::settings::chrome_with(false);+ let row = connect();+ let d = Dialog::new("Hi", vec![Line::raw("Stop?")], &row, &c);+ let r = d.place(Rect::new(10, 4, 60, 20));+ assert_eq!((r.width, r.height), (d.width(), 5));+ assert!((r.x - 10).abs_diff(60 - r.right() + 10) <= 1 && (r.y - 4).abs_diff(24 - r.bottom()) <= 1, "{r:?}");+ assert_eq!(d.place(Rect::new(0, 0, 20, 3)), Rect::new(0, 0, 20, 3), "no bigger than it");+ }+}diff --git a/tui/src/draw.rs b/tui/src/draw.rsindex 758a6fa85..f938ca77d 100644--- a/tui/src/draw.rs+++ b/tui/src/draw.rs@@ -5,6 +5,7 @@//! `#[fill=…]`, `#[push-default]` / `#[pop-default]` — laid out and trimmed as tmux does.use ratatui::style::{Color, Modifier, Style};+use ratatui::text::{Line, Span};use unicode_width::UnicodeWidthChar;#[derive(Clone, Copy, PartialEq, Eq, Debug)]@@ -281,6 +282,23 @@ pub fn format_draw_over(expanded: &str, base: Style, avail: u16) -> Vec<Option<(format_draw_on(expanded, base, avail, GAP).0.into_iter().map(|c| (c.0 != GAP).then_some(c)).collect()}+/// format_draw_over as a `Line` of at most [avail] columns: a span for each run of one style,+/// [under] (what is there already: a box's rule, its surface) where it writes nothing, and+/// nothing after its last character.+pub fn format_line(expanded: &str, base: Style, avail: u16, under: (&str, Style)) -> Line<'static> {+ let mut cells = format_draw_over(expanded, base, avail);+ while matches!(cells.last(), Some(None)) { cells.pop(); }+ let mut spans: Vec<Span<'static>> = Vec::new();+ for (symbol, style) in cells.into_iter().map(|c| c.unwrap_or_else(|| (under.0.to_string(), under.1))) {+ if symbol.is_empty() { continue } // a wide character's second column: its span has it+ match spans.last_mut() {+ Some(last) if last.style == style => last.content.to_mut().push_str(&symbol),+ _ => spans.push(Span::styled(symbol, style)),+ }+ }+ Line::from(spans)+}+/// format_width: the columns a format's text takes — its #[…] styles none, ## one.pub fn format_width(expanded: &str) -> usize {let b: Vec<char> = expanded.chars().collect();diff --git a/tui/src/files.rs b/tui/src/files.rsindex 2f92c28be..08ffaff1f 100644--- a/tui/src/files.rs+++ b/tui/src/files.rs@@ -20,11 +20,14 @@ use std::time::SystemTime;use crossterm::event::{KeyCode, KeyModifiers};use ratatui::buffer::Buffer;-use ratatui::layout::Rect;+use ratatui::layout::{Position, Rect};use ratatui::style::{Color, Modifier, Style};+use ratatui::symbols::border;use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};use crate::app::{App, At, Placement};+use crate::buttons::{Answer, Button, Row as ButtonRow};+use crate::dialog::{Dialog, Input};use crate::keys::{self, Chord, MouseKind};use crate::layout::Dir;use crate::theme;@@ -154,11 +157,26 @@ struct Menu { target: Target, items: Vec<Option<Item>>, x: u16, y: u16, sel: Opt#[derive(Clone, Debug, PartialEq, Eq)]enum Ask { NewFile, NewFolder, Rename(PathBuf) }-/// The name prompt: what for, in which folder, its text, the cursor and where a selection starts.+/// The name prompt: what for, in which folder, its text, the cursor and where a selection starts;+/// and whether the keys are on its buttons (Tab) and which one is chosen (0 Cancel, 1 the action).#[derive(Clone, Debug)]-struct Prompt { ask: Ask, dir: PathBuf, text: Vec<char>, cursor: usize, mark: Option<usize> }+struct Prompt { ask: Ask, dir: PathBuf, text: Vec<char>, cursor: usize, mark: Option<usize>, buttons: bool, chosen: usize }++/// The columns the name prompt's input box wants.+const PROMPT_W: u16 = 40;impl Prompt {+ fn new(ask: Ask, dir: PathBuf, text: Vec<char>, cursor: usize, mark: Option<usize>) -> Prompt {+ Prompt { ask, dir, text, cursor, mark, buttons: false, chosen: 1 }+ }++ /// `[ Cancel ] [ Create ]` (`[ Rename ]`), the chosen button only while the keys are on them.+ fn row(&self) -> ButtonRow {+ let button = |label: &str| Button { label: label.into(), key: None };+ let action = if matches!(self.ask, Ask::Rename(_)) { "Rename" } else { "Create" };+ ButtonRow { buttons: vec![button("Cancel"), button(action)], chosen: if self.buttons { self.chosen } else { usize::MAX }, hint: crate::buttons::KEYS.into() }+ }+/// The selection, from the mark to the cursor, when there is one.fn selection(&self) -> Option<(usize, usize)> { self.mark.filter(|m| *m != self.cursor).map(|m| (m.min(self.cursor), m.max(self.cursor))) }/// The selection gone (what is typed replaces it).@@ -176,7 +194,7 @@ impl Prompt {#[derive(Clone, Debug, PartialEq, Eq)]enum Doom { Trash(PathBuf), Purge(PathBuf, String) }-/// A confirmation: its question and which of its two buttons (0 yes, 1 no) has the keys.+/// A confirmation: its question and which of its two buttons (0 Cancel, 1 Delete) has the keys.#[derive(Clone, Debug)]struct Confirm { doom: Doom, focus: usize }@@ -211,7 +229,7 @@ fn geom(w: u16, h: u16, view: View) -> Geom {}/// The colours it draws with: mode-style for what is selected, as choose-tree's current line.-pub struct Look { mode: Style, accent: Style, muted: Style, text: Style, warn: Style, code: Style, media: Style }+pub struct Look { mode: Style, accent: Style, muted: Style, text: Style, warn: Style, code: Style, media: Style, border: border::Set<'static> }impl Look {/// The theme's colours, with [mode] for the selection.@@ -224,6 +242,7 @@ impl Look {warn: theme::fg(theme::WARN),code: theme::fg(theme::ONLINE),media: theme::fg(Color::Magenta),+ border: border::PLAIN,}}}@@ -543,7 +562,7 @@ impl Files {Act::External => { if let Some((path, false)) = item { return Outcome::Edit(path) } }Act::NewFile | Act::NewFolder => {let ask = if act == Act::NewFile { Ask::NewFile } else { Ask::NewFolder };- self.prompt = Some(Prompt { ask, dir: t.folder(), text: Vec::new(), cursor: 0, mark: None });+ self.prompt = Some(Prompt::new(ask, t.folder(), Vec::new(), 0, None));}Act::Terminal => return Outcome::Terminal(t.folder()),Act::Cut | Act::Copy => {@@ -577,7 +596,7 @@ impl Files {let text: Vec<char> = name_of(&path).chars().collect();// The stem selected, as VS Code and Finder do (a folder's whole name).let stem = if dir { text.len() } else { text.iter().rposition(|c| *c == '.').filter(|i| *i > 0).unwrap_or(text.len()) };- self.prompt = Some(Prompt { ask: Ask::Rename(path.clone()), dir: t.folder_of_item(), text, cursor: stem, mark: Some(0) });+ self.prompt = Some(Prompt::new(Ask::Rename(path.clone()), t.folder_of_item(), text, stem, Some(0)));}Act::Delete => { if let Some((path, _)) = item { self.confirm = Some(Confirm { doom: Doom::Trash(path), focus: 0 }) } }Act::Hidden => { self.hidden = !self.hidden; self.reload() }@@ -760,6 +779,22 @@ impl Files {fn prompt_key(&mut self, k: Chord) -> Outcome {let Some(p) = self.prompt.as_mut() else { return Outcome::None };let typed = matches!(k.code, KeyCode::Char(_)) && !k.mods.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER);+ // Tab takes the keys to the buttons and back; a printable key is typed wherever they were.+ // (↓ from the input to the buttons, ↑ back up, as Tab goes either way.)+ let across = match k.code { KeyCode::Tab | KeyCode::BackTab => true, KeyCode::Down => !p.buttons, KeyCode::Up => p.buttons, _ => false };+ if across { p.buttons = !p.buttons; return Outcome::None }+ if typed { p.buttons = false }+ if p.buttons {+ let mut row = p.row();+ let code = if is_ctrl(&k, 'm') { KeyCode::Enter } else { k.code };+ match row.key(code, k.mods) {+ Answer::Moved => p.chosen = row.chosen,+ Answer::Chosen(1) => self.accept(),+ Answer::Chosen(_) | Answer::Cancel => self.prompt = None,+ Answer::Ignored => {}+ }+ return Outcome::None;+ }match k.code {KeyCode::Esc => self.prompt = None,_ if is_ctrl(&k, 'c') || is_ctrl(&k, 'g') => self.prompt = None,@@ -770,6 +805,7 @@ impl Files {KeyCode::Right => { p.mark = None; p.cursor = (p.cursor + 1).min(p.text.len()) }KeyCode::Home => { p.mark = None; p.cursor = 0 }KeyCode::End => { p.mark = None; p.cursor = p.text.len() }+ _ if is_ctrl(&k, 'u') => { p.mark = None; p.text.clear(); p.cursor = 0 }_ if is_ctrl(&k, 'a') => { p.mark = None; p.cursor = 0 }_ if is_ctrl(&k, 'e') => { p.mark = None; p.cursor = p.text.len() }KeyCode::Char(c) if typed => {@@ -808,16 +844,26 @@ impl Files {}fn confirm_key(&mut self, k: Chord) -> Outcome {- let Some(c) = self.confirm.as_mut() else { return Outcome::None };- match () {- _ if matches!(k.code, KeyCode::Left | KeyCode::Right | KeyCode::Tab | KeyCode::BackTab) || is_char(&k, 'h') || is_char(&k, 'l') => c.focus ^= 1,- _ if k.code == KeyCode::Enter || is_ctrl(&k, 'm') => { if c.focus == 0 { self.confirmed() } else { self.confirm = None } }- _ if k.code == KeyCode::Esc || is_char(&k, 'q') || is_char(&k, 'n') || is_ctrl(&k, 'g') || is_ctrl(&k, 'c') => self.confirm = None,- _ => {}+ if self.confirm.is_none() { return Outcome::None }+ let mut row = self.confirm_row();+ let code = if is_ctrl(&k, 'm') { KeyCode::Enter } else { k.code };+ match row.key(code, k.mods) {+ Answer::Moved => if let Some(c) = self.confirm.as_mut() { c.focus = row.chosen },+ Answer::Chosen(1) => self.confirmed(),+ Answer::Chosen(_) | Answer::Cancel => self.confirm = None,+ // The files' own way out besides Esc: q and n.+ Answer::Ignored => if is_char(&k, 'q') || is_char(&k, 'n') { self.confirm = None },}Outcome::None}+ /// The confirmation's buttons, Cancel first, the one with the keys chosen.+ fn confirm_row(&self) -> ButtonRow {+ let yes = match self.confirm.as_ref().map(|c| &c.doom) { Some(Doom::Purge(..)) => "Delete Permanently", _ => "Delete" };+ let button = |label: &str| Button { label: label.into(), key: None };+ ButtonRow { buttons: vec![button("Cancel"), button(yes)], chosen: self.confirm.as_ref().map_or(0, |c| c.focus), hint: crate::buttons::KEYS.into() }+ }+/// Yes to the confirmation: to the Trash — or, when it can't go there, a second question before/// it is gone for good; never without one.fn confirmed(&mut self) {@@ -825,7 +871,7 @@ impl Files {match c.doom {Doom::Trash(path) => match ops::trash(&path, &self.trash) {Ok(_) => { self.gone(&path); self.message = Some(format!("Moved '{}' to the Trash", name_of(&path))); self.reload() }- Err(e) => self.confirm = Some(Confirm { doom: Doom::Purge(path, e.to_string()), focus: 1 }),+ Err(e) => self.confirm = Some(Confirm { doom: Doom::Purge(path, e.to_string()), focus: 0 }),},Doom::Purge(path, _) => match ops::remove_all(&path) {Ok(()) => { self.gone(&path); self.message = Some(format!("Deleted '{}'", name_of(&path))); self.reload() }@@ -851,12 +897,21 @@ impl Files {fn click_at(&mut self, x: u16, y: u16, double: bool, g: Geom) -> Outcome {if self.confirm.is_some() {- let (_, _, buttons, by) = self.confirm_layout(g);- if let Some(b) = buttons.iter().position(|(a, z, _)| y == by && x >= *a && x < *z) { if b == 0 { self.confirmed() } else { self.confirm = None } }+ let Some((.., row)) = self.confirm_layout(g) else { return Outcome::None };+ if let Some(b) = self.confirm_row().click(row, Position::new(x, y)) { if b == 1 { self.confirmed() } else { self.confirm = None } }return Outcome::None;}if self.prompt.is_some() {- if !contains(prompt_box(g), x, y) { self.prompt = None }+ let at = Position::new(x, y);+ match self.prompt_layout(g) {+ // On the dialog: a button answers, the input gets the keys; its rule does nothing.+ Some((r, a)) if r.contains(at) => {+ let Some(p) = self.prompt.as_mut() else { return Outcome::None };+ if let Some(b) = p.row().click(a.row, at) { if b == 1 { self.accept() } else { self.prompt = None } }+ else if a.input.is_some_and(|i| i.contains(at)) { p.buttons = false }+ }+ _ => self.prompt = None,+ }return Outcome::None;}if self.menu.is_some() {@@ -1017,6 +1072,12 @@ impl Files {self.draw_footer(buf, area, g, look);self.draw_tree(buf, area, g, look);self.draw_popups(buf, area, g, look);+ // A question with no room to be drawn must not stay open to answering keys.+ let unfit = (self.prompt.is_some() && self.prompt_layout(g).is_none()) || (self.confirm.is_some() && self.confirm_layout(g).is_none());+ if unfit {+ (self.prompt, self.confirm) = (None, None);+ self.message = Some(crate::workspace_menu::TOO_SMALL_TO_ANSWER.into());+ }}/// What the grid says in place of entries: why the folder can't be read, or that it is empty.@@ -1163,53 +1224,68 @@ impl Files {}}if let Some(p) = &self.prompt {- let r = at(prompt_box(g));- frame(buf, r, look.accent);- let title = match &p.ask { Ask::NewFile => " New File ".to_string(), Ask::NewFolder => " New Folder ".to_string(), Ask::Rename(path) => format!(" Rename '{}' ", fit(&name_of(path), 30)) };- put(buf, r.x + 2, r.y, r.width.saturating_sub(4), &title, look.accent.add_modifier(Modifier::BOLD));- // The text, from where the cursor stays in view; the selection and the cursor marked.- let field = r.width.saturating_sub(4) as usize;- let start = (p.cursor + 1).saturating_sub(field);- let sel = p.selection();- for (k, i) in (start..=p.text.len()).take(field).enumerate() {- let ch = p.text.get(i).copied().unwrap_or(' ');- let st = if i == p.cursor { look.text.add_modifier(Modifier::REVERSED) } else if sel.is_some_and(|(a, b)| i >= a && i < b) { look.mode } else { look.text.add_modifier(Modifier::UNDERLINED) };- put(buf, r.x + 2 + k as u16, r.y + 1, 1, &ch.to_string(), st);+ let (row, c, value) = (p.row(), crate::settings::chrome(), p.text.iter().collect::<String>());+ if let Some((r, d)) = self.prompt_dialog(g, p, &value, &row, &c, look.border) {+ let r = at(r);+ d.render_over(area, r, buf);+ // (A pane has no terminal cursor to put in the box: the caret is a reversed cell.)+ if let Some(caret) = d.cursor(r) { buf.set_style(Rect::new(caret.x, caret.y, 1, 1), Style::new().add_modifier(Modifier::REVERSED)) }}- put(buf, r.x + 2, r.y + 2, r.width.saturating_sub(4), "Enter OK · Esc cancel", look.muted);}if self.confirm.is_some() {- let (r, lines, buttons, by) = self.confirm_layout(g);- let r = at(r);- frame(buf, r, look.warn);- for (k, line) in lines.iter().enumerate() { put(buf, r.x + 2, r.y + 1 + k as u16, r.width.saturating_sub(4), line, look.text); }- let focus = self.confirm.as_ref().map(|c| c.focus).unwrap_or(1);- for (b, (a, _, label)) in buttons.iter().enumerate() { put(buf, area.x + a, area.y + by, label.width() as u16, label, if b == focus { look.mode } else { look.text }); }+ let (row, c) = (self.confirm_row(), crate::settings::chrome());+ if let Some((r, d)) = self.confirm_dialog(g, &row, &c, look.border) { d.render_over(area, at(r), buf) }}}- /// The confirmation's box (in the middle of the view), its lines, its buttons' columns and- /// words, and their row.- fn confirm_layout(&self, g: Geom) -> ConfirmLayout {- let (lines, yes) = match self.confirm.as_ref().map(|c| &c.doom) {- Some(Doom::Trash(p)) => ([format!("Delete '{}'?", fit(&name_of(p), 40)), "It goes to the Trash.".to_string()], "Delete"),- Some(Doom::Purge(p, why)) => ([format!("'{}' can't go to the Trash: {why}.", fit(&name_of(p), 30)), "Delete it permanently? This can't be undone.".to_string()], "Delete Permanently"),- None => ([String::new(), String::new()], ""),+ /// The name prompt as the shared dialog over the grid: titled with what it does, the name in+ /// an input box (its selection marked) and `[ Cancel ] [ Create ]`. None where the buttons,+ /// or the input, cannot fit.+ fn prompt_dialog<'a>(&self, g: Geom, p: &'a Prompt, value: &'a str, row: &'a ButtonRow, c: &'a crate::settings::Chrome, border: border::Set<'a>) -> Option<(Rect, Dialog<'a>)> {+ let (title, label) = match &p.ask {+ Ask::NewFile => ("New File".to_string(), "File name"),+ Ask::NewFolder => ("New Folder".to_string(), "Folder name"),+ Ask::Rename(path) => (format!("Rename · {}", fit(&name_of(path), 30)), "New name"),};- let labels = [format!("[ {yes} ]"), "[ Cancel ]".to_string()];- let need = lines.iter().map(|l| l.width()).max().unwrap_or(0).max(labels.iter().map(|l| l.width() + 2).sum::<usize>()) as u16 + 4;- let w = need.min(g.size.0);- let h = 6u16.min(g.size.1);- let r = Rect::new(g.size.0.saturating_sub(w) / 2, g.size.1.saturating_sub(h) / 2, w, h);- let by = r.y + 4;- let mut x = (r.x + r.width).saturating_sub(2 + labels.iter().map(|l| l.width() as u16 + 2).sum::<u16>() - 2);- let buttons = labels.map(|l| { let w = l.width() as u16; let b = (x, x + w, l); x += w + 2; b });- (r, lines, buttons, by)+ let mut d = Dialog::new(&title, Vec::new(), row, c);+ d.border = border;+ d.input = Some(Input { label, value, caret: p.cursor, select: p.selection(), secret: false, focused: !p.buttons, width: PROMPT_W });+ if row.buttons_width() > g.grid.width.saturating_sub(4) || !d.fit(g.grid.height) { return None }+ Some((d.place(g.grid), d))+ }++ /// The name prompt's box and the parts inside it (for drawing and clicks alike).+ fn prompt_layout(&self, g: Geom) -> Option<(Rect, crate::dialog::Areas)> {+ let p = self.prompt.as_ref()?;+ let (row, c, value) = (p.row(), crate::settings::chrome(), p.text.iter().collect::<String>());+ let (r, d) = self.prompt_dialog(g, p, &value, &row, &c, border::PLAIN)?;+ Some((r, d.areas(r)))+ }++ /// The confirmation as the shared dialog, in the middle of the view: titled with what goes,+ /// its question wrapped to the view, a line in the danger colour where it can't be undone,+ /// and its buttons. None where the buttons, or one line of the question, cannot fit.+ fn confirm_dialog<'a>(&self, g: Geom, row: &'a ButtonRow, c: &'a crate::settings::Chrome, border: border::Set<'a>) -> Option<(Rect, Dialog<'a>)> {+ let (title, lines, undone) = match self.confirm.as_ref().map(|c| &c.doom) {+ Some(Doom::Trash(p)) => (format!("Delete · {}", fit(&name_of(p), 30)), vec![format!("Delete '{}'?", fit(&name_of(p), 40)), "It goes to the Trash.".to_string()], ""),+ Some(Doom::Purge(p, why)) => (format!("Delete Permanently · {}", fit(&name_of(p), 30)), vec![format!("'{}' can't go to the Trash: {why}.", fit(&name_of(p), 30)), "Delete it permanently?".to_string()], "This can't be undone."),+ None => (String::new(), Vec::new(), ""),+ };+ let room = g.size.0.saturating_sub(4).clamp(1, 60);+ let mut d = Dialog::new(&title, lines.iter().flat_map(|l| crate::dialog::wrap(l, room, c.base)).collect(), row, c);+ d.border = border;+ d.message = crate::dialog::wrap(undone, room, c.danger);+ if row.buttons_width() > g.size.0.saturating_sub(4) || !d.fit(g.size.1) { return None }+ Some((d.place(Rect::new(0, 0, g.size.0, g.size.1)), d))}-}-/// The confirmation's box, its two lines, its buttons (columns and words) and their row.-type ConfirmLayout = (Rect, [String; 2], [(u16, u16, String); 2], u16);+ /// The confirmation's box and its buttons' row (for drawing and clicks alike).+ fn confirm_layout(&self, g: Geom) -> Option<(Rect, Rect)> {+ let (row, c) = (self.confirm_row(), crate::settings::chrome());+ let (r, d) = self.confirm_dialog(g, &row, &c, border::PLAIN)?;+ Some((r, d.areas(r).row))+ }+}/// The menu's box: as wide as its longest item and key.fn menu_box(m: &Menu) -> Rect {@@ -1217,12 +1293,6 @@ fn menu_box(m: &Menu) -> Rect {Rect::new(m.x, m.y, w, m.items.len() as u16 + 2)}-/// The name prompt's box, a third of the way down the grid.-fn prompt_box(g: Geom) -> Rect {- let w = g.grid.width.saturating_sub(4).clamp(20.min(g.size.0), 56);- Rect::new(g.grid.x + g.grid.width.saturating_sub(w) / 2, g.grid.y + g.grid.height.saturating_sub(4) / 3, w, 4)-}-fn contains(r: Rect, x: u16, y: u16) -> bool { x >= r.x && x < r.x + r.width && y >= r.y && y < r.y + r.height }/// A box with rounded corners round [r], what was inside it cleared.@@ -1434,7 +1504,8 @@ pub fn exit(app: &mut App, pane: u64) {/// Draws [pane]'s file manager into [area] (the pane's cells).pub fn draw(app: &mut App, pane: u64, buf: &mut Buffer, area: Rect) {let window = app.tabs.iter().position(|t| t.panes().contains(&pane)).unwrap_or(app.active);- let look = Look::with_mode(crate::draw::style_over(&app.style_spec("mode-style", window, Some(pane)), Style::default()));+ let mut look = Look::with_mode(crate::draw::style_over(&app.style_spec("mode-style", window, Some(pane)), Style::default()));+ look.border = crate::ui::dialog_border(&app.style_spec("menu-border-lines", window, Some(pane)));if let Some(f) = app.panes.get_mut(&pane).and_then(|p| p.files.as_mut()) { f.draw(buf, area, &look) }}@@ -2125,11 +2196,12 @@ mod tests {assert_eq!(names(&f)[f.selected], "a copy 2.txt");// Delete: asked first; Cancel leaves it.press(&mut f, KeyCode::Delete);- assert!(matches!(f.confirm.as_ref().map(|c| &c.doom), Some(Doom::Trash(_))));- press(&mut f, KeyCode::Right);+ assert!(matches!(f.confirm.as_ref().map(|c| (&c.doom, c.focus)), Some((Doom::Trash(_), 0))), "a risky action starts on Cancel");press(&mut f, KeyCode::Enter);assert!(f.confirm.is_none() && s.0.join("a copy 2.txt").exists());press(&mut f, KeyCode::Delete);+ press(&mut f, KeyCode::Right);+ assert_eq!(f.confirm.as_ref().map(|c| c.focus), Some(1));press(&mut f, KeyCode::Enter);assert!(!s.0.join("a copy 2.txt").exists());assert!(s.0.join(".Trash/files/a copy 2.txt").exists() && s.0.join(".Trash/info/a copy 2.txt.trashinfo").exists());@@ -2157,18 +2229,202 @@ mod tests {std::fs::write(s.0.join("not-a-folder"), "").unwrap();f.trash = s.0.join("not-a-folder/Trash");press(&mut f, KeyCode::Delete);+ press(&mut f, KeyCode::Right);press(&mut f, KeyCode::Enter);- assert!(matches!(f.confirm.as_ref().map(|c| (&c.doom, c.focus)), Some((Doom::Purge(..), 1))), "asked again, Cancel first");+ assert!(matches!(f.confirm.as_ref().map(|c| (&c.doom, c.focus)), Some((Doom::Purge(..), 0))), "asked again, Cancel first");assert!(s.0.join("x.txt").exists());press(&mut f, KeyCode::Enter);assert!(f.confirm.is_none() && s.0.join("x.txt").exists(), "Enter on Cancel keeps it");press(&mut f, KeyCode::Delete);+ press(&mut f, KeyCode::Right);press(&mut f, KeyCode::Enter);- press(&mut f, KeyCode::Left);+ press(&mut f, KeyCode::Right);press(&mut f, KeyCode::Enter);assert!(!s.0.join("x.txt").exists());}+ #[test]+ fn the_delete_confirm_is_one_row_cancel_first_the_chosen_button_lifted() {+ let s = Scratch::new(&["x.txt"]);+ let mut f = files(&s);+ press(&mut f, KeyCode::Delete);+ let (area, g) = (Rect::new(0, 0, 100, 30), geom(100, 30, f.view));+ let (r, row) = f.confirm_layout(g).expect("fits");+ let buttons = f.confirm_row().areas(row);+ let by = row.y;+ let screen = |f: &mut Files| { let mut buf = Buffer::empty(area); f.draw(&mut buf, area, &Look::default()); buf };+ let word = |buf: &Buffer, b: Rect| (b.x..b.right()).map(|x| buf[(x, by)].symbol()).collect::<String>();+ let shown = screen(&mut f);+ assert_eq!([word(&shown, buttons[0]), word(&shown, buttons[1])], ["[ Cancel ]", "[ Delete ]"]);+ // The shared dialog: its title in the top rule, the question inside, the panel's surface.+ let text = contents(&shown);+ assert!(text.contains("┌─Delete · x.txt") && text.contains("│ Delete 'x.txt'?") && text.contains("│ It goes to the Trash."), "{text}");+ let c = crate::settings::chrome();+ let q = (r.x + 1, r.y + 1);+ assert_eq!((shown[(r.x, r.y + 1)].symbol(), shown[q].bg), ("│", c.base.bg.unwrap_or(ratatui::style::Color::Reset)), "{text}");+ assert!(buttons[0].right() + 2 <= buttons[1].x, "two columns apart");+ let bg = |f: &mut Files, b: usize| screen(f)[(buttons[b].x + 2, by)].bg;+ let c = crate::settings::chrome();+ if !crate::theme::no_color() {+ assert_eq!(bg(&mut f, 0), c.selected.bg.unwrap());+ assert_ne!(bg(&mut f, 1), c.selected.bg.unwrap());+ press(&mut f, KeyCode::Tab);+ assert_eq!(bg(&mut f, 1), c.selected.bg.unwrap());+ }+ // A click on Cancel closes; between the buttons nothing runs.+ f.click_at(buttons[0].right() + 1, by, false, g);+ assert!(f.confirm.is_some());+ f.click_at(buttons[0].x + 1, by, false, g);+ assert!(f.confirm.is_none() && s.0.join("x.txt").exists());+ }++ fn type_in(f: &mut Files, text: &str) { for ch in text.chars() { press(f, KeyCode::Char(ch)); } }++ /// The Files drawn at [w]×[h] as text.+ fn drawn(f: &mut Files, look: &Look, w: u16, h: u16) -> (String, Buffer) {+ let area = Rect::new(0, 0, w, h);+ let mut buf = Buffer::empty(area);+ f.draw(&mut buf, area, look);+ (contents(&buf), buf)+ }++ #[test]+ fn the_name_prompt_is_the_shared_dialog_with_an_input_and_buttons() {+ let s = Scratch::new(&["here.txt"]);+ let mut f = files(&s);+ let g = gal(100, 30);+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ type_in(&mut f, "abc");+ let (text, buf) = drawn(&mut f, &Look::default(), 100, 30);+ assert!(text.contains("┌─New File") && text.contains("[ Cancel ] [ Create ]"), "{text}");+ assert!(text.contains("│abc"), "the name in the input box:\n{text}");+ assert!(!text.contains("Enter OK") && !text.contains("╭"), "not the old rounded box:\n{text}");+ let (r, _) = f.prompt_layout(g).expect("fits");+ let c = crate::settings::chrome();+ assert_eq!(buf[(r.x + 1, r.y + 1)].bg, c.base.bg.unwrap_or(ratatui::style::Color::Reset), "the panel's surface");+ // The caret moves in the input; Home, End, Delete and C-u edit at it.+ press(&mut f, KeyCode::Left);+ press(&mut f, KeyCode::Char('X'));+ assert_eq!(f.prompt.as_ref().map(|p| p.text.iter().collect::<String>()), Some("abXc".into()));+ press(&mut f, KeyCode::Home);+ press(&mut f, KeyCode::Delete);+ assert_eq!(f.prompt.as_ref().map(|p| (p.text.iter().collect::<String>(), p.cursor)), Some(("bXc".into(), 0)));+ press(&mut f, KeyCode::End);+ assert_eq!(f.prompt.as_ref().map(|p| p.cursor), Some(3));+ ctrl(&mut f, 'u');+ assert_eq!(f.prompt.as_ref().map(|p| p.text.len()), Some(0));+ // Tab to the buttons: Create is chosen; a letter there is typed and brings the keys back.+ type_in(&mut f, "n.md");+ press(&mut f, KeyCode::Tab);+ assert!(f.prompt.as_ref().is_some_and(|p| p.buttons && p.chosen == 1));+ press(&mut f, KeyCode::Left);+ assert_eq!(f.prompt.as_ref().map(|p| p.chosen), Some(0), "← → move between the buttons");+ press(&mut f, KeyCode::Char('h'));+ assert!(f.prompt.as_ref().is_some_and(|p| !p.buttons && p.text.iter().collect::<String>() == "n.mdh"), "h is typed");+ press(&mut f, KeyCode::Backspace);+ // Back on the buttons, the choice is kept (as the Machines inputs keep it). Enter on Cancel+ // closes; on Create makes it.+ press(&mut f, KeyCode::Tab);+ assert_eq!(f.prompt.as_ref().map(|p| p.chosen), Some(0));+ press(&mut f, KeyCode::Enter);+ assert!(f.prompt.is_none() && !s.0.join("n.md").exists());+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ type_in(&mut f, "n.md");+ press(&mut f, KeyCode::Tab);+ press(&mut f, KeyCode::Enter);+ assert!(f.prompt.is_none() && s.0.join("n.md").is_file());+ // The mouse: Create, Cancel, the input, beside the dialog and outside it.+ let click = |f: &mut Files, at: Position| f.click_at(at.x, at.y, false, g);+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ type_in(&mut f, "m.md");+ press(&mut f, KeyCode::Tab);+ let (r, a) = f.prompt_layout(g).expect("fits");+ click(&mut f, Position::new(a.input.unwrap().x + 2, a.input.unwrap().y + 1));+ assert!(f.prompt.as_ref().is_some_and(|p| !p.buttons), "a click on the input gives it the keys");+ click(&mut f, Position::new(r.x + 1, r.y + 1));+ assert!(f.prompt.is_some(), "the dialog's own rule does nothing");+ let (cancel, create) = { let b = f.prompt.as_ref().unwrap().row().areas(a.row); (b[0], b[1]) };+ click(&mut f, Position::new(create.x + 1, create.y));+ assert!(f.prompt.is_none() && s.0.join("m.md").is_file(), "Create");+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ click(&mut f, Position::new(cancel.x + 1, cancel.y));+ assert!(f.prompt.is_none(), "Cancel");+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ click(&mut f, Position::new(0, 29));+ assert!(f.prompt.is_none(), "outside cancels");+ }++ #[test]+ fn rename_is_titled_with_the_name_says_rename_and_replaces_the_selected_stem() {+ let s = Scratch::new(&["here.txt"]);+ let mut f = files(&s);+ f.selected = 0;+ press(&mut f, KeyCode::F(2));+ let (text, buf) = drawn(&mut f, &Look::default(), 100, 30);+ assert!(text.contains("┌─Rename · here.txt") && text.contains("[ Cancel ] [ Rename ]"), "{text}");+ let (_, a) = f.prompt_layout(gal(100, 30)).unwrap();+ let field = a.field.unwrap();+ let c = crate::settings::chrome();+ assert_eq!(buf[(field.x, field.y)].bg, c.selected.bg.unwrap_or(ratatui::style::Color::Reset), "the stem is marked");+ assert_ne!(buf[(field.x + 5, field.y)].bg, c.selected.bg.unwrap_or(ratatui::style::Color::Reset), "the extension is not");+ type_in(&mut f, "there");+ press(&mut f, KeyCode::Enter);+ assert!(s.0.join("there.txt").is_file());+ }++ #[test]+ fn a_dialog_that_cannot_fit_cancels_the_name_prompt() {+ let s = Scratch::new(&[]);+ let mut f = files(&s);+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ drawn(&mut f, &Look::default(), 20, 8);+ assert!(f.prompt.is_none(), "an invisible question must not keep answering keys");+ assert_eq!(f.message.as_deref(), Some("Make the terminal larger to answer this"));+ }++ #[test]+ fn dialogs_follow_the_border_lines_they_are_given() {+ let s = Scratch::new(&["x.txt"]);+ let mut f = files(&s);+ let mut look = Look::default();+ look.border = crate::ui::dialog_border("double");+ press(&mut f, KeyCode::Delete);+ let (text, _) = drawn(&mut f, &look, 100, 30);+ assert!(text.contains("╔═Delete · x.txt") && text.contains("╚"), "{text}");+ press(&mut f, KeyCode::Esc);+ f.act(Act::NewFile, Target::Space(s.0.clone()));+ let (text, _) = drawn(&mut f, &look, 100, 30);+ assert!(text.contains("╔═New File") && text.matches('╔').count() >= 2, "the input box too:\n{text}");+ let (text, _) = drawn(&mut f, &Look::default(), 100, 30);+ assert!(text.contains("┌─New File"), "single lines by default:\n{text}");+ }++ #[test]+ fn delete_permanently_says_it_cannot_be_undone_in_the_danger_colour_and_long_text_wraps() {+ let s = Scratch::new(&["x.txt"]);+ let mut f = files(&s);+ f.confirm = Some(Confirm { doom: Doom::Purge(s.0.join("x.txt"), "the Trash folder is on another disk".into()), focus: 0 });+ let (text, buf) = drawn(&mut f, &Look::default(), 100, 30);+ assert!(text.contains("This can't be undone."), "{text}");+ let (y, line) = text.lines().enumerate().find(|(_, l)| l.contains("This can't be undone.")).unwrap();+ let x = line[..line.find("This").unwrap()].chars().count() as u16;+ let c = crate::settings::chrome();+ assert_eq!(buf[(x, y as u16)].fg, c.danger.fg.unwrap_or(ratatui::style::Color::Reset));+ assert!(buf[(x, y as u16)].modifier.contains(c.danger.add_modifier));+ // A narrow view: the question is wrapped at its words, not cut.+ let (text, _) = drawn(&mut f, &Look::default(), 40, 16);+ for word in ["can't", "Trash:", "another", "disk.", "permanently?", "undone."] {+ assert!(text.contains(word), "{word} lost:\n{text}");+ }+ let dialog: Vec<&str> = text.lines().skip_while(|l| !l.contains("┌─Delete")).take_while(|l| !l.contains('└')).collect();+ assert!(dialog.len() > 6 && dialog.iter().all(|l| !l.contains('…')), "{text}");+ assert!(text.contains("[ Cancel ] [ Delete Permanently ]"), "the buttons whole:\n{text}");+ // Narrower than its buttons: the question is cancelled, never drawn cut or kept invisible.+ drawn(&mut f, &Look::default(), 36, 16);+ assert!(f.confirm.is_none() && s.0.join("x.txt").exists());+ assert_eq!(f.message.as_deref(), Some("Make the terminal larger to answer this"));+ }+#[test]fn tiles_are_big_with_a_picture_and_the_name_under_it() {let s = Scratch::new(&["folder/", "main.rs"]);diff --git a/tui/src/files/dialog.rs b/tui/src/files/dialog.rsindex 80c5d29ad..7854ce6cf 100644--- a/tui/src/files/dialog.rs+++ b/tui/src/files/dialog.rs@@ -9,11 +9,13 @@ use std::time::SystemTime;use crossterm::event::{KeyCode, KeyModifiers};use ratatui::buffer::Buffer;-use ratatui::layout::Rect;+use ratatui::layout::{Position, Rect};use ratatui::style::Modifier;+use ratatui::widgets::Widget;use unicode_width::UnicodeWidthStr;use super::{art, editor, file_style, fit, frame, home, icon, list, name_of, ops, put, shorten, tile, Entry, Look, TILE_H, TILE_W};+use crate::buttons::{Answer, Button, Row};use crate::keys::Chord;/// The sidebar's width, and a column's (its separator in it).@@ -65,13 +67,15 @@ enum Tool { Back, Forward, Columns, Icons, Path, Search }pub(super) enum DOut { None, Cancel, Open(PathBuf, bool) }/// Where a dialog's things are at a size: its sidebar, main area and bottom row.+/// [bottom]: the buttons' row; [hint]: the box's last line, a blank row under the buttons — what+/// was said, else the keys (as every dialog keeps its keys hint there, never on the buttons' row).#[derive(Clone, Copy, Debug)]-struct Layout { side: Rect, main: Rect, bottom: u16 }+struct Layout { side: Rect, main: Rect, bottom: u16, hint: u16 }fn layout(w: u16, h: u16) -> Layout {let side_w = SIDE_W.min(w / 4);- let body_h = h.saturating_sub(6);- Layout { side: Rect::new(1, 3, side_w, body_h), main: Rect::new(2 + side_w, 3, w.saturating_sub(3 + side_w), body_h), bottom: h.saturating_sub(2) }+ let body_h = h.saturating_sub(8);+ Layout { side: Rect::new(1, 3, side_w, body_h), main: Rect::new(2 + side_w, 3, w.saturating_sub(3 + side_w), body_h), bottom: h.saturating_sub(4), hint: h.saturating_sub(2) }}/// A history entry: the columns' folders and which one is active.@@ -309,12 +313,20 @@ impl Dialog {}fn button_key(&mut self, k: Chord) -> DOut {- match k.code {- KeyCode::Left | KeyCode::Right => self.button ^= 1,- KeyCode::Enter => return if self.button == 1 { self.open(self.target()) } else { DOut::Cancel },- _ => {}+ let mut row = self.row();+ let out = row.key(k.code, k.mods);+ self.button = row.chosen;+ match out {+ Answer::Chosen(1) => self.open(self.target()),+ Answer::Chosen(_) | Answer::Cancel => DOut::Cancel,+ Answer::Moved | Answer::Ignored => DOut::None,}- DOut::None+ }++ /// Cancel, Open — Open the one that has the keys until moved. No hint: the bottom row keeps its own.+ fn row(&self) -> Row {+ let button = |label: &str| Button { label: label.into(), key: None };+ Row { buttons: vec![button("Cancel"), button("Open")], chosen: self.button, hint: String::new() }}fn column_key(&mut self, k: Chord) -> DOut {@@ -421,16 +433,15 @@ impl Dialog {c.selected().filter(|e| !e.dir).map(|e| (c.dir.join(&e.name), e))}- /// The buttons at the right of the bottom row: Cancel, Open.- fn buttons(&self) -> [(u16, u16, &'static str); 2] {- let right = self.size.0.saturating_sub(2);- let open = "[ Open ]";- let cancel = "[ Cancel ]";- let ox = right - open.width() as u16;- let cx = ox - 2 - cancel.width() as u16;- [(cx, cx + cancel.width() as u16, cancel), (ox, right, open)]+ /// The bottom row's buttons (Cancel, Open) at its right, inside the frame: for drawing and+ /// clicks alike.+ fn button_row(&self) -> Rect {+ Rect::new(0, layout(self.size.0, self.size.1).bottom, self.size.0.saturating_sub(2), 1)}+ /// Where Cancel and Open are.+ fn buttons(&self) -> Vec<Rect> { self.row().areas(self.button_row()) }+/// A click at (x, y), a [double] one opening what it is on.pub(super) fn click(&mut self, x: u16, y: u16, double: bool) -> DOut {self.message = None;@@ -454,7 +465,7 @@ impl Dialog {return DOut::None;}if y == l.bottom {- match self.buttons().iter().position(|(a, z, _)| x >= *a && x < *z) { Some(0) => return DOut::Cancel, Some(_) => return self.open(self.target()), None => {} }+ match self.row().click(self.button_row(), Position::new(x, y)) { Some(0) => return DOut::Cancel, Some(_) => return self.open(self.target()), None => {} }return DOut::None;}if contains(l.side, x, y) {@@ -550,16 +561,12 @@ impl Dialog {self.draw_toolbar(buf, area, look);self.draw_sidebar(buf, area, l, look);match self.view { DView::Columns => self.draw_columns(buf, area, l, look), DView::Icons => self.draw_icons(buf, area, l, look) }- // The bottom row: what was said, else the keys; Cancel and Open.- let buttons = self.buttons();- let room = buttons[0].0.saturating_sub(3);+ // Cancel and Open; under them, the last line: what was said, else the keys.+ let room = area.width.saturating_sub(4);let (text, st) = match &self.message { Some(m) => (m.clone(), look.warn), None => ("Enter open · Esc cancel · Tab sidebar/columns/buttons · / search".to_string(), look.muted) };- put(buf, ox + 2, oy + l.bottom, room, &fit(&text, room as usize), st);- for (b, (a, _, label)) in buttons.iter().enumerate() {- let mut st = if b == 1 { look.mode.add_modifier(Modifier::BOLD) } else { look.text };- if self.focus == Focus::Buttons && self.button == b { st = st.add_modifier(Modifier::UNDERLINED | Modifier::BOLD) }- put(buf, ox + a, oy + l.bottom, label.width() as u16, label, st);- }+ put(buf, ox + 2, oy + l.hint, room, &fit(&text, room as usize), st);+ let row = self.button_row();+ self.row().view(&crate::settings::chrome()).render(Rect { x: ox + row.x, y: oy + row.y, ..row }, buf);if let Some((items, sel)) = &self.popup {let (px, py, pw) = self.popup_at();let r = Rect::new(ox + px, oy + py, pw, items.len() as u16 + 2).intersection(area);@@ -732,10 +739,30 @@ mod tests {assert!(lines[1].contains("◀ ▶") && lines[1].contains("Columns") && lines[1].contains("Icons") && lines[1].contains("app ▾") && lines[1].contains("⌕ Search"), "{}", lines[1]);assert!(t.contains("Favorites") && t.contains("Home") && t.contains("Locations") && t.contains("Computer"), "{t}");assert!(t.contains("[/] app") && t.contains("main.py") && t.contains("Python script") && t.contains("print('xin chào')"), "{t}");- assert!(lines[32].contains("[ Cancel ]") && lines[32].contains("[ Open ]"));+ // The buttons' row, and under it — the box's last line — the keys.+ assert!(lines[30].contains("[ Cancel ]") && lines[30].contains("[ Open ]") && !lines[30].contains("Enter open"), "{t}");+ assert!(!lines[31].contains("Enter open") && lines[32].contains("Enter open · Esc cancel"), "a blank row, then the keys: {t}");+ // Open is chosen even unfocused; Tab to the buttons, Left chooses Cancel, Enter cancels.+ if !crate::theme::no_color() {+ let c = crate::settings::chrome();+ let area = Rect::new(0, 0, 130, 34);+ let mut buf = Buffer::empty(area);+ d.draw(&mut buf, area, &Look::default());+ let (cx, ox) = (d.buttons()[0].x, d.buttons()[1].x);+ assert_eq!(buf[(ox + 2, 30)].bg, c.selected.bg.unwrap());+ assert_ne!(buf[(cx + 2, 30)].bg, c.selected.bg.unwrap());+ }+ d.focus = Focus::Columns;+ d.key(k(KeyCode::Tab));+ assert_eq!(d.focus, Focus::Buttons);+ d.key(k(KeyCode::Left));+ assert_eq!(d.button, 0);+ assert_eq!(d.key(k(KeyCode::Enter)), DOut::Cancel);+ d.key(k(KeyCode::Right));+ assert_eq!(d.button, 1);// It fits a small window too.let small = text(&mut d, 90, 24);- assert!(small.lines().nth(22).unwrap().contains("[ Open ]") && small.contains("main.py"), "{small}");+ assert!(small.lines().nth(20).unwrap().contains("[ Open ]") && small.contains("main.py"), "{small}");}#[test]@@ -794,7 +821,7 @@ mod tests {d.key(k(KeyCode::Right));assert_eq!(d.key(k(KeyCode::Enter)), DOut::Open(s.0.join("me/app/main.py"), false));let mut e = s.dialog();- let (ox, ..) = e.buttons()[1];+ let ox = e.buttons()[1].x;assert_eq!(e.click(ox + 1, layout(130, 34).bottom, false), DOut::Open(s.0.join("me"), true));// Recent: the latest first, once each, those still there.let recent = load_recent(&s.0.join("state/open-recent.json"));diff --git a/tui/src/files/editor.rs b/tui/src/files/editor.rsindex 9c2116d0f..335755442 100644--- a/tui/src/files/editor.rs+++ b/tui/src/files/editor.rs@@ -8,12 +8,12 @@ use std::path::{Path, PathBuf};use crossterm::event::{KeyCode, KeyModifiers};use ratatui::buffer::Buffer;-use ratatui::layout::Rect;+use ratatui::layout::{Position, Rect};use ratatui::style::{Modifier, Style};use unicode_segmentation::UnicodeSegmentation;use unicode_width::UnicodeWidthStr;-use super::{frame, name_of, put, Look};+use super::{name_of, put, Look};use crate::keys::Chord;/// The largest file opened here.@@ -319,7 +319,7 @@ impl Editor {pub(super) fn key(&mut self, k: Chord) -> EdOut {self.message = None;- if let Some(focus) = self.asking { return self.ask_key(k, focus) }+ if self.asking.is_some() { return self.ask_key(k) }if self.bar.is_some() { self.bar_key(k); self.fit(); return EdOut::None }let (shift, ctrl) = (k.mods.contains(KeyModifiers::SHIFT), k.mods.contains(KeyModifiers::CONTROL));let ctrl_is = |c: char| ctrl && matches!(k.code, KeyCode::Char(x) if x.eq_ignore_ascii_case(&c));@@ -382,28 +382,35 @@ impl Editor {/// Esc, Ctrl+Q, Ctrl+W: closed — after asking, when there are changes to lose.fn close(&mut self) -> EdOut {- if self.modified() { self.asking = Some(0); EdOut::None } else { EdOut::Close }+ if self.modified() { self.asking = Some(2); EdOut::None } else { EdOut::Close }+ }++ /// The "Save changes?" buttons, in the order shown, the one with the keys chosen.+ fn ask_row(&self) -> crate::buttons::Row {+ let button = |label: &str| crate::buttons::Button { label: label.into(), key: None };+ crate::buttons::Row { buttons: vec![button("Don't save"), button("Cancel"), button("Save")], chosen: self.asking.unwrap_or(2), hint: crate::buttons::KEYS.into() }}/// The "Save changes?" question's keys: Left/Right/Tab between its buttons, Enter, Esc cancels.- fn ask_key(&mut self, k: Chord, focus: usize) -> EdOut {- match k.code {- KeyCode::Left | KeyCode::BackTab => self.asking = Some((focus + 2) % 3),- KeyCode::Right | KeyCode::Tab => self.asking = Some((focus + 1) % 3),- KeyCode::Esc => self.asking = None,- KeyCode::Enter => return self.answer(focus),- _ => {}+ fn ask_key(&mut self, k: Chord) -> EdOut {+ use crate::buttons::Answer;+ let mut row = self.ask_row();+ match row.key(k.code, k.mods) {+ Answer::Moved => self.asking = Some(row.chosen),+ Answer::Chosen(i) => return self.answer(i),+ Answer::Cancel => self.asking = None,+ Answer::Ignored => {}}EdOut::None}- /// Save (0), Don't save (1) or Cancel (2).+ /// Don't save (0), Cancel (1) or Save (2).fn answer(&mut self, button: usize) -> EdOut {self.asking = None;match button {- 0 => match self.save() { Ok(()) => EdOut::Close, Err(e) => { self.message = Some(e); EdOut::None } },- 1 => EdOut::Close,- _ => EdOut::None,+ 0 => EdOut::Close,+ 1 => EdOut::None,+ _ => match self.save() { Ok(()) => EdOut::Close, Err(e) => { self.message = Some(e); EdOut::None } },}}@@ -440,8 +447,8 @@ impl Editor {/// A click (or a drag, [drag]) at (x, y): the cursor there; a drag selects from where it went down.pub(super) fn click(&mut self, x: u16, y: u16, drag: bool) {if let Some(focus) = self.asking {- let (_, buttons, by) = self.ask_layout();- if let Some(b) = buttons.iter().position(|(a, z, _)| y == by && x >= *a && x < *z) { let _ = self.answer(b); } else { self.asking = Some(focus) }+ let (_, row) = self.ask_layout();+ if let Some(b) = self.ask_row().click(row, Position::new(x, y)) { let _ = self.answer(b); } else { self.asking = Some(focus) }return;}let (_, r) = self.text_area();@@ -525,25 +532,29 @@ impl Editor {};let st = if self.message.is_some() && self.bar.is_none() { look.accent } else { look.muted };put(buf, ox + 1, sy, w.saturating_sub(2), &super::fit(&status, w.saturating_sub(2) as usize), st);- if let Some(focus) = self.asking {- let (r, buttons, by) = self.ask_layout();- let r = Rect::new(ox + r.x, oy + r.y, r.width, r.height).intersection(area);- frame(buf, r, look.warn);- put(buf, r.x + 2, r.y + 1, r.width.saturating_sub(4), &format!("Save changes to '{}'?", name_of(&self.path)), look.text);- for (b, (a, _, label)) in buttons.iter().enumerate() { put(buf, ox + a, oy + by, label.width() as u16, label, if b == focus { look.mode } else { look.text }); }+ if self.asking.is_some() {+ let (row, c) = (self.ask_row(), crate::settings::chrome());+ let (r, d) = self.ask_dialog(&row, &c, look.border);+ d.render_over(area, Rect::new(ox + r.x, oy + r.y, r.width, r.height).intersection(area), buf);}}- /// The "Save changes?" box in the middle, its buttons' columns and words, and their row.- fn ask_layout(&self) -> (Rect, [(u16, u16, &'static str); 3], u16) {- const LABELS: [&str; 3] = ["[ Save ]", "[ Don't save ]", "[ Cancel ]"];- let q = format!("Save changes to '{}'?", name_of(&self.path)).width() as u16 + 4;- let w = q.max(LABELS.iter().map(|l| l.width() as u16 + 2).sum::<u16>() + 2).min(self.size.0);- let r = Rect::new(self.size.0.saturating_sub(w) / 2, self.size.1.saturating_sub(5) / 2, w, 5);- let by = r.y + 3;- let mut x = r.x + 2;- let buttons = LABELS.map(|l| { let b = (x, x + l.width() as u16, l); x += l.width() as u16 + 2; b });- (r, buttons, by)+ /// "Save changes?" as the shared dialog, in the middle of the editor: its question wrapped to+ /// the editor, in the border lines [border] says.+ fn ask_dialog<'a>(&self, row: &'a crate::buttons::Row, c: &'a crate::settings::Chrome, border: ratatui::symbols::border::Set<'a>) -> (Rect, crate::dialog::Dialog<'a>) {+ let name = name_of(&self.path);+ let question = crate::dialog::wrap(&format!("Save changes to '{name}'?"), self.size.0.saturating_sub(4).clamp(1, 60), c.base);+ let mut d = crate::dialog::Dialog::new(&format!("Save Changes · {}", super::fit(&name, 30)), question, row, c);+ d.border = border;+ d.fit(self.size.1);+ (d.place(Rect::new(0, 0, self.size.0, self.size.1)), d)+ }++ /// The "Save changes?" box and its buttons' row (for drawing and clicks alike).+ fn ask_layout(&self) -> (Rect, Rect) {+ let (row, c) = (self.ask_row(), crate::settings::chrome());+ let (r, d) = self.ask_dialog(&row, &c, ratatui::symbols::border::PLAIN);+ (r, d.areas(r).row)}}@@ -690,9 +701,9 @@ mod tests {assert_eq!(e.key(k(KeyCode::Esc)), EdOut::Close, "nothing changed: closed at once");typing(&mut e, "y");assert_eq!(e.key(k(KeyCode::Esc)), EdOut::None);- assert_eq!(e.asking, Some(0));- e.key(k(KeyCode::Right));- e.key(k(KeyCode::Right));+ assert_eq!(e.asking, Some(2), "Save is chosen");+ e.key(k(KeyCode::Left));+ assert_eq!(e.asking, Some(1));assert_eq!(e.key(k(KeyCode::Enter)), EdOut::None, "Cancel: still editing");assert!(e.asking.is_none() && e.modified());e.key(ctrl('q'));@@ -701,6 +712,63 @@ mod tests {let _ = std::fs::remove_dir_all(d);}+ #[test]+ fn save_changes_is_one_row_dont_save_cancel_save_with_the_chosen_one_lifted() {+ let (p, d) = scratch("b.txt", b"x\n");+ let mut e = Editor::open(&p, "b.txt".into()).unwrap();+ typing(&mut e, "y");+ e.key(k(KeyCode::Esc));+ let (_, row) = e.ask_layout();+ let buttons = e.ask_row().areas(row);+ let by = row.y;+ let area = Rect::new(0, 0, 80, 24);+ let screen = |e: &mut Editor| { let mut buf = Buffer::empty(area); e.draw(&mut buf, area, &Look::default()); buf };+ let shown = screen(&mut e);+ let words: Vec<String> = buttons.iter().map(|b| (b.x..b.right()).map(|x| shown[(x, by)].symbol()).collect()).collect();+ assert_eq!(words, ["[ Don't save ]", "[ Cancel ]", "[ Save ]"]);+ // The shared dialog: its title in the top rule, the question inside, the panel's surface.+ let (r, _) = e.ask_layout();+ let line = |y: u16| (r.x..r.right()).map(|x| shown[(x, y)].symbol()).collect::<String>();+ assert!(line(r.y).starts_with("┌─Save Changes · b.txt") && line(r.y + 1).starts_with("│ Save changes to 'b.txt'?"), "{}\n{}", line(r.y), line(r.y + 1));+ assert_eq!(shown[(r.x + 1, r.y + 1)].bg, crate::settings::chrome().base.bg.unwrap_or(ratatui::style::Color::Reset));+ let bg = |e: &mut Editor, b: usize| screen(e)[(buttons[b].x + 2, by)].bg;+ if !crate::theme::no_color() {+ let c = crate::settings::chrome();+ assert_eq!(bg(&mut e, 2), c.selected.bg.unwrap());+ assert_ne!(bg(&mut e, 0), c.selected.bg.unwrap());+ e.key(k(KeyCode::Left)); e.key(k(KeyCode::Left));+ assert_eq!(bg(&mut e, 0), c.selected.bg.unwrap());+ }+ // Esc (and C-c) leave the editor open on the text; Don't save closes it unsaved.+ e.key(k(KeyCode::Esc));+ assert!(e.asking.is_none() && e.modified());+ e.key(ctrl('q'));+ assert_eq!(e.key(ctrl('c')), EdOut::None);+ assert!(e.asking.is_none());+ e.key(ctrl('q')); e.key(k(KeyCode::Left)); e.key(k(KeyCode::Left));+ assert_eq!(e.key(k(KeyCode::Enter)), EdOut::Close);+ assert_eq!(std::fs::read_to_string(&p).unwrap(), "x\n");+ let _ = std::fs::remove_dir_all(d);+ }++ #[test]+ fn save_changes_follows_the_border_lines_and_wraps_to_a_narrow_editor() {+ let (p, d) = scratch("a-very-long-file-name-for-a-narrow-editor.txt", b"x\n");+ let mut e = Editor::open(&p, "a-very-long-file-name-for-a-narrow-editor.txt".into()).unwrap();+ typing(&mut e, "y");+ e.key(k(KeyCode::Esc));+ let mut look = Look::default();+ look.border = crate::ui::dialog_border("heavy");+ e.size = (36, 12);+ let area = Rect::new(0, 0, 36, 12);+ let mut buf = Buffer::empty(area);+ e.draw(&mut buf, area, &look);+ let text: String = (0..12).map(|y| (0..36).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>() + "\n").collect();+ assert!(text.contains("┏━Save Changes") && text.contains("┗"), "{text}");+ for word in ["Save changes to", "txt'?"] { assert!(text.contains(word), "{word} lost:\n{text}") }+ let _ = std::fs::remove_dir_all(d);+ }+#[test]fn a_read_only_file_is_shown_not_changed() {use std::os::unix::fs::PermissionsExt;diff --git a/tui/src/input.rs b/tui/src/input.rsindex e9c54ab27..7998faa5a 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -24,6 +24,14 @@ pub fn handle(app: &mut App, event: CEvent) {// A key is the session's activity (session_update_activity): a script's command with no -t// goes to the session used last.CEvent::Key(key) if key.kind != KeyEventKind::Release => {+ // Escape lets go of a held pane (and is used up only when a drag was showing); the+ // release that follows still belongs to the header press.+ if key.code == KeyCode::Esc {+ if let Some(live) = app.controls.grab.as_ref().map(|g| g.live) {+ crate::pane_drag::cancel(app);+ if live { return }+ }+ }let now = crate::app::epoch_secs();// (This client used now: a shell's command with no target comes here — each second.)if now != app.session_activity { crate::ipc::mark_active() }@@ -264,7 +272,17 @@ pub fn send_to_pane(app: &mut App, focus: u64, bytes: Vec<u8>) {fn on_paste(app: &mut App, text: String) {if paste_form(app, &text) { return }if let Some(Modal::Picker { picker, .. }) = &mut app.modal { for c in text.chars().filter(|c| !c.is_control()) { picker.type_char(c) } return }- if let Some(Modal::Prompt(prompt)) = &mut app.modal { prompt.value.push_str(&text.replace(['\r', '\n'], " ")); return }+ // (At the cursor, which goes after it, as a typed line does; a dialog's input has the keys again.)+ if let Some(Modal::Prompt(prompt)) = &mut app.modal {+ let mut chars: Vec<char> = prompt.value.chars().collect();+ let at = prompt.cursor.min(chars.len());+ let pasted: Vec<char> = text.replace(['\r', '\n'], " ").chars().collect();+ prompt.cursor = at + pasted.len();+ chars.splice(at..at, pasted);+ prompt.value = chars.into_iter().collect();+ prompt.buttons = false;+ return;+ }app.tab_mut().home = false;if let Some(buffer) = app.shell_inputs.get(&app.tab().id) { buffer.lock().unwrap().push(text.into_bytes()); return }let Some(focus) = app.focused() else { return };@@ -322,6 +340,7 @@ fn on_mouse(app: &mut App, mouse: MouseEvent) {/// preview, whichever it is over; a click takes a row, a second one opens it; in the preview a/// drag scrolls it and a drag on its border resizes it; a click outside the box closes it.fn modal_mouse(app: &mut App, mouse: MouseEvent) {+ if matches!(&app.modal, Some(Modal::Prompt(p)) if p.dialog()) { return prompt_mouse(app, mouse) }if matches!(app.modal, Some(Modal::NewHarness(_))) { return crate::new_harness::mouse(app, mouse) }// --no-mouse: a list the mouse does nothing to.if theme::fzf_opts().no_mouse && matches!(app.modal, Some(Modal::Picker { .. })) { return }@@ -954,14 +973,11 @@ fn local_offset_hours() -> u64 {((24 + sign * hours) % 24) as u64}-/// A status-line prompt, tmux's way: `(rename-window) name`. [label] becomes the hint shown dim-/// at the right when the line has room.-fn prompt(app: &mut App, kind: PromptKind, title: &str, label: &str, hint: &str, value: &str, secret: bool) {- let tag = format!("({}) ", title.to_lowercase().replace(' ', "-"));- let mut p = Prompt::status(kind, &tag, value);- p.title = title.into();- p.hint = if hint.is_empty() { label.to_string() } else { hint.to_string() };- p.secret = secret;+/// One of hn's own questions, as the shared dialog: titled [title], [body] above an input box+/// labelled [field] with [value] in it, the caret at its end.+fn prompt(app: &mut App, kind: PromptKind, title: &str, field: &str, body: &str, value: &str) {+ let mut p = Prompt::status(kind, "", value);+ (p.title, p.field, p.body) = (title.into(), field.into(), body.into());app.modal = Some(Modal::Prompt(p));}@@ -1028,6 +1044,7 @@ fn remode(app: &App, kind: PickerKind, picker: &mut Picker) -> (PickerKind, boolpub fn run(app: &mut App, command: &str) {match command {"account" | "login" => crate::account::open(app),+ "signout" | "logout" => crate::account::sign_out_command(app),"hardware-devices" => crate::hardware::open(app),"open" => launch(app, "", Filter::All),"palette" => launch(app, ">", Filter::All),@@ -1052,11 +1069,11 @@ pub fn run(app: &mut App, command: &str) {let focused = focused_agent(app);new_shell_from(app, focused, Placement::Auto(None), None, None);}- "send" => prompt(app, PromptKind::Send, "Send to harness", "What should be done?", "Harness picks the harness that fits best; you confirm.", "", false),+ "send" => prompt(app, PromptKind::Send, "Send to Harness", "What should be done?", "Harness picks the harness that fits best; you confirm.", ""),"broadcast" => {let n = app.tab().panes().len();if n == 0 { app.say("No harnesses in this tab", theme::MUTED); return }- prompt(app, PromptKind::Broadcast, &format!("Broadcast to {n} harness{}", if n == 1 { "" } else { "es" }), "Message", "Sent as a turn to every harness in this tab.", "", false)+ prompt(app, PromptKind::Broadcast, &format!("Broadcast · {n} Harness{}", if n == 1 { "" } else { "es" }), "Message", "Sent as a turn to every harness in this tab.", "")}"clone" => {let Some((machine, agent)) = focused_agent(app) else { app.say("This pane has no harness in it", theme::MUTED); return };@@ -1076,13 +1093,13 @@ pub fn run(app: &mut App, command: &str) {"rename" => {let Some((machine, agent)) = focused_agent(app) else { return };let name = app.fleet.agent(&machine, &agent).map(|a| a.name.clone()).unwrap_or_default();- prompt(app, PromptKind::RenameHarness { machine, agent }, "Rename Harness", "New name", "", &name, false)+ prompt(app, PromptKind::RenameHarness { machine, agent }, &format!("Rename Harness · {}", crate::format::short_name(&name, 30)), "New name", "", &name)}"tab" => crate::commands::execute(app, "new-window"),"rename-tab" => {let name = app.tab().name.clone();let target = PromptKind::RenameTab { session:app.session_id, window:app.tab().id.clone(), owner:app.fleet.local_id.clone() };- prompt(app, target, "Rename Tab", "Tab name", "", &name, false);+ prompt(app, target, &format!("Rename Tab · {}", crate::format::short_name(&name, 30)), "Tab name", "", &name);}"close-tab" => crate::session_close::tab(app, app.active),"next-tab" => { let n = app.tabs.len(); let i = (app.active + 1) % n; app.select_tab(i) }@@ -1281,8 +1298,7 @@ fn new_what(app: &mut App, machine: String) { crate::new_harness::open(app, Somepub fn popup(app: &mut App, (x, y, w, h): (u16, u16, u16, u16), border: bool, cwd: Option<String>, command: Option<String>, title: String, close_on_exit: bool, look: crate::modal::PopupLook) {let focused = focused_agent(app);let machine = shell_machine(app, focused.as_ref());- let live = focused.as_ref().and_then(|(m, a)| app.find_pane(m, a)).and_then(|(_, p)| app.panes.get(&p)).and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()));- let cwd = cwd.or(live).or_else(|| focused.as_ref().and_then(|(m, a)| app.fleet.agent(m, a)).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()));+ let cwd = shell_cwd(app, focused.as_ref(), &machine, cwd);let Some(link) = app.link(&machine) else { app.print_new = None; return app.error("That machine is not connected") };let mut payload = json!({ "engine": "terminal", "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": false });if let Some(cwd) = &cwd { payload["cwd"] = json!(cwd) }@@ -1361,6 +1377,18 @@ pub fn shell_machine(app: &App, focused: Option<&(String, String)>) -> String {if app.daemon_down && app.fleet.machine(&machine).is_some_and(|m| m.local) { crate::local::MACHINE.into() } else { machine }}+/// The folder a new shell on [machine] starts in: [cwd] (`-c`), else where the focused pane's+/// shell says it is now (OSC 7), else where its harness started. On this computer, a folder that+/// is gone — a deleted worktree, a cleaned /tmp — is none (the shell starts at home): a shell+/// started there cannot tell where it is, and line editors can hang on it (zsh-syntax-highlighting+/// does at the first key).+fn shell_cwd(app: &App, focused: Option<&(String, String)>, machine: &str, cwd: Option<String>) -> Option<String> {+ let live = focused.and_then(|(m, a)| app.find_pane(m, a)).and_then(|(_, p)| app.panes.get(&p)).and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()));+ let cwd = cwd.or(live).or_else(|| focused.and_then(|(m, a)| app.fleet.agent(m, a)).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()));+ let here = crate::local::is_local(machine) || app.fleet.machine(machine).is_some_and(|m| m.local);+ cwd.filter(|c| !here || std::path::Path::new(c).is_dir())+}+pub(crate) fn configure_local_shell(app: &App, machine: &str, payload: &mut serde_json::Value) {if crate::local::is_local(machine) {payload["paneId"] = json!(crate::ids::next(crate::ids::Kind::Pane));@@ -1389,9 +1417,7 @@ pub fn new_shell_with_picker(app: &mut App, focused: Option<(String, String)>, pif choose_agent && app.capture.is_none() && !app.headless { init.push("--pick-agent".into()); }init});- // The folder: -c, else where the pane's shell says it is now (OSC 7), else where it started.- let live = focused.as_ref().and_then(|(m, a)| app.find_pane(m, a)).and_then(|(_, p)| app.panes.get(&p)).and_then(|p| p.cwd.clone().or_else(|| p.live_path.clone()));- let cwd = cwd.or(live).or_else(|| focused.as_ref().and_then(|(m, a)| app.fleet.agent(m, a)).map(|a| a.cwd.clone()).filter(|c| !c.is_empty()));+ let cwd = shell_cwd(app, focused.as_ref(), &machine, cwd);let Some(link) = app.link(&machine) else { app.print_new = None; return app.error("That machine is not connected") };let mut payload = json!({ "engine": "terminal", "creationId": uuid::Uuid::new_v4().to_string(), "bypassPermission": false });if let Some(cwd) = &cwd { payload["cwd"] = json!(cwd) }@@ -1653,6 +1679,20 @@ pub(crate) fn modal_key(app: &mut App, key: KeyEvent) {return;}}+ // A confirmation's buttons own the keys; the vertical menu's keys (q, j, k …) do nothing here.+ if let Some(b) = menu.buttons.as_mut() {+ use crate::buttons::Answer;+ let command = match b.row.key(key.code, key.modifiers) {+ Answer::Chosen(i) => b.actions.get(i).cloned(),+ Answer::Cancel => b.actions.first().cloned(),+ // q leaves like Esc; j, k and the rest do nothing.+ Answer::Ignored if key.code == KeyCode::Char('q') && !ctrl => b.actions.first().cloned(),+ Answer::Moved | Answer::Ignored => None,+ };+ if let Some(command) = command { return commands::execute_in(app, &command, menu.mouse.clone()) }+ app.modal = Some(Modal::Menu(menu));+ return;+ }if let Some(i) = menu.items.iter().position(|it| !it.disabled && !it.separator && !it.key.is_empty() && it.key == name) {menu.choice = Some(i);return menu_chosen(app, menu);@@ -1699,14 +1739,38 @@ pub(crate) fn modal_key(app: &mut App, key: KeyEvent) {Modal::Copy { pane } => { app.modal = Some(Modal::Copy { pane }); mode_key(app, pane, &keys::of(&key)); }Modal::Prompt(p) => {prompt_key(app, key, p);- // A message or an answer typed from the list: back to it, its query and place kept.- if app.modal.is_none() { if let Some(back) = app.back_to_list.take() { app.modal = Some(Modal::Picker { kind: back.0, picker: back.1 }); refill(app) } }- else if !matches!(app.modal, Some(Modal::Prompt(_))) { app.back_to_list = None }+ after_prompt(app);}Modal::Picker { kind, picker } => picker_key(app, key, kind, picker),}}+/// After a prompt's key or click: a message or an answer typed from the list goes back to it, its+/// query and place kept.+fn after_prompt(app: &mut App) {+ if app.modal.is_none() { if let Some(back) = app.back_to_list.take() { app.modal = Some(Modal::Picker { kind: back.0, picker: back.1 }); refill(app) } }+ else if !matches!(app.modal, Some(Modal::Prompt(_))) { app.back_to_list = None }+}++/// The mouse on one of hn's question dialogs: a button answers, a click on the input gives it the+/// keys, the rest of the box does nothing and a click outside it cancels.+fn prompt_mouse(app: &mut App, mouse: MouseEvent) {+ let Some((r, a)) = crate::ui::prompt_layout(app) else { return };+ if !matches!(mouse.kind, MouseEventKind::Down(MouseButton::Left)) { return }+ let at = ratatui::layout::Position::new(mouse.column, mouse.row);+ let Some(Modal::Prompt(mut p)) = app.modal.take() else { return };+ if !r.contains(at) { return after_prompt(app) }+ match p.row().click(a.row, at) {+ Some(1) => submit_prompt(app, p),+ Some(_) => {}+ None => {+ if a.input.is_some_and(|i| i.contains(at)) { p.buttons = false }+ app.modal = Some(Modal::Prompt(p));+ }+ }+ after_prompt(app);+}+/// The status-line prompt (status_prompt_key): tmux's `status-keys emacs` — each change runs an/// incremental prompt's template again; Up/Down its type's history; Tab completes.fn prompt_key(app: &mut App, key: KeyEvent, mut p: Prompt) {@@ -1736,9 +1800,30 @@ fn prompt_key(app: &mut App, key: KeyEvent, mut p: Prompt) {if ask.single() { if let KeyCode::Char(c) = key.code { if !ctrl && !alt { return crate::tree::answer(app, pane, ask, Some(&c.to_string())) } } }if (key.code == KeyCode::Esc && !vi) || (ctrl && matches!(key.code, KeyCode::Char('c' | 'g'))) { return crate::tree::answer(app, pane, ask, None) }}+ // hn's own questions are dialogs, keyed as the Machines inputs are: Tab takes the keys to the+ // buttons and back, a printable key is typed wherever they were, Esc cancels (status-keys vi+ // is the status line's). In the input the keys below edit the line as in tmux's prompt.+ if p.dialog() {+ // (↓ from the input to the buttons, ↑ back up, as Tab goes either way.)+ let across = match key.code { KeyCode::Tab | KeyCode::BackTab => true, KeyCode::Down => !p.buttons, KeyCode::Up => p.buttons, _ => false };+ if across { p.buttons = !p.buttons; app.modal = Some(Modal::Prompt(p)); return }+ if matches!(key.code, KeyCode::Char(_)) && !ctrl && !alt { p.buttons = false }+ if p.buttons {+ let mut row = p.row();+ match row.key(key.code, key.modifiers) {+ crate::buttons::Answer::Chosen(1) => return submit_prompt(app, p),+ crate::buttons::Answer::Chosen(_) | crate::buttons::Answer::Cancel => return,+ crate::buttons::Answer::Moved => p.chosen = row.chosen,+ crate::buttons::Answer::Ignored => {}+ }+ app.modal = Some(Modal::Prompt(p));+ return;+ }+ if key.code == KeyCode::Esc { return }+ }let (single, incremental, ptype) = match &p.kind { PromptKind::Command { one, incremental, ptype, .. } => (*one, *incremental, *ptype), PromptKind::Tree { ask, .. } => (false, false, ask.ptype()), _ => (false, false, 0) };// status-keys vi (tmux's default when $EDITOR names vi): Esc leaves insert for normal mode.- let vi = app.options.get("status-keys", "", None).as_deref() == Some("vi");+ let vi = !p.dialog() && app.options.get("status-keys", "", None).as_deref() == Some("vi");if vi && p.vi_normal { prompt_vi_normal(app, key, p); return }if vi && key.code == KeyCode::Esc && !ctrl && !alt { p.vi_normal = true; app.modal = Some(Modal::Prompt(p)); return }// Entry mode (status_prompt_translate_key): these keys do what emacs's do, a character is@@ -1982,7 +2067,7 @@ fn prompt_menu(app: &App, p: &Prompt, items: Vec<crate::modal::MenuItem>, list:let y = if app.status_top { lines } else { app.size.1.saturating_sub(3 + height) };let x = (offset + unicode_width::UnicodeWidthStr::width(p.label.as_str())).saturating_sub(2) as u16;let x = x.min(app.size.0.saturating_sub(width + 4));- crate::modal::Menu { title: String::new(), items, choice: Some(0), x, y, width, stay_open: false, no_mouse: true, mouse: None, tree: None, responsive: None,+ crate::modal::Menu { title: String::new(), items, choice: Some(0), x, y, width, stay_open: false, no_mouse: true, mouse: None, tree: None, responsive: None, buttons: None,complete: Some(Box::new(crate::modal::Complete { prompt: p.clone(), list, flag, window_target })) }}@@ -2426,7 +2511,7 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {if let Some((machine, agent)) = picker.current_id().and_then(|id| split_key(&id)) {let name = app.fleet.agent(&machine, &agent).map(|a| a.name.clone()).unwrap_or_default();app.back_to_list = Some(Box::new((kind, picker)));- return prompt(app, PromptKind::Message { machine, agent }, "Message", &name, &format!("to {name}"), "", false);+ return prompt(app, PromptKind::Message { machine, agent }, &format!("Message · {}", crate::format::short_name(&name, 30)), "Message", "", "");}}// M-a: the question's answer typed — option numbers (several for a multi-choice one) or@@ -2437,15 +2522,11 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {let row = format!("{machine}:{agent}");let row = picker.current_id().unwrap_or(row);let request = match answerable(app, &picker, &row) { Ok(r) => r, Err(why) => { picker.say(why); app.modal = Some(Modal::Picker { kind, picker }); return } };- let how = if q.multi { format!("1–{} (several: 1,3) or your own words", q.options.len()) } else if q.options.is_empty() { "your answer".to_string() } else { format!("1–{} or your own words", q.options.len()) };+ let how = if q.multi { format!("1–{} (several: 1,3) or your own words", q.options.len()) } else if q.options.is_empty() { "Your answer".to_string() } else { format!("1–{} or your own words", q.options.len()) };// Who asks and what, while you type (the list is gone behind the prompt).- let name = app.fleet.agent(&machine, &agent).map(|a| crate::format::short_name(&a.name, 24)).unwrap_or_default();- let mut p = Prompt::status(PromptKind::Answer { machine, agent, request }, &format!("({name}) "), "");- p.title = "Answer".into();- p.hint = format!("{} — {how}", q.prompt);+ let name = app.fleet.agent(&machine, &agent).map(|a| crate::format::short_name(&a.name, 30)).unwrap_or_default();app.back_to_list = Some(Box::new((kind, picker)));- app.modal = Some(Modal::Prompt(p));- return;+ return prompt(app, PromptKind::Answer { machine, agent, request }, &format!("Answer · {name}"), &how, &q.prompt, "");}}}@@ -3214,7 +3295,7 @@ fn submit_prompt(app: &mut App, p: Prompt) {// kept, offered as a message to it — Enter sends it, Escape drops it.let keep = |app: &mut App, why: &str| {let name = app.fleet.agent(&machine, &agent).map(|a| a.name.clone()).unwrap_or_default();- prompt(app, PromptKind::Message { machine: machine.clone(), agent: agent.clone() }, "Message", &name, &format!("{why} — send it to {name} as a message?"), &value, false);+ prompt(app, PromptKind::Message { machine: machine.clone(), agent: agent.clone() }, &format!("Message · {}", crate::format::short_name(&name, 30)), "Message", &format!("{why}. Send it to {name} as a message?"), &value);};if q.as_ref().is_some_and(|q| q.request_id != request) { return keep(app, "That question changed while you typed") }let text = q.and_then(|q| crate::fleet::answer_text(&q, &value));@@ -3289,7 +3370,7 @@ pub fn is_command(id: &str) -> bool {| "last-tab" | "next-waiting" | "prev-waiting" | "resume-focused" | "last-harness" | "tree" | "files" | "info" | "messages" | "keys"| "theme" | "appearance" | "commands" | "choose-buffer" | "quit" | "keybinds"// ── machines & devices ──- | "connect-machine" | "add-phone" | "devices" | "hardware-devices" | "account" | "login" | "change-agent")+ | "connect-machine" | "add-phone" | "devices" | "hardware-devices" | "account" | "login" | "signout" | "logout" | "change-agent")}@@ -3565,16 +3646,30 @@ pub fn menu_mouse(app: &mut App, m: &crate::mouse::Event) {app.modal = Some(Modal::Menu(menu));return;}- let count = menu.items.len() as u16;+ // A confirmation's blank row, button row and hint line sit under its notes.+ let count = if menu.buttons.is_some() { crate::workspace_menu::dialog_box(&menu).height.saturating_sub(2) } else { menu.items.len() as u16 };let (px, py, width) = (menu.x, menu.y, menu.width);if m.x < px || m.x > px + 4 + width || m.y < py + 1 || m.y > py + count {let close = if !menu.stay_open { is_release(m.b) } else { !is_release(m.b) && !is_wheel(m.b) && !is_drag(m.b) };- if close { return }+ if close {+ // A confirmation closed from outside is a cancel, not a vanished question.+ let cancel = menu.buttons.as_ref().and_then(|b| b.actions.first().cloned());+ if let Some(command) = cancel { commands::execute_in(app, &command, menu.mouse.clone()) }+ return;+ }menu.choice = None;app.modal = Some(Modal::Menu(menu));return;}let chosen = if !menu.stay_open { is_release(m.b) } else { !is_release(m.b) && !is_wheel(m.b) && !is_drag(m.b) };+ if let Some(b) = &menu.buttons {+ // Only a button does anything: the notes, the blank row and the gaps and hint keep the dialog.+ let row = crate::dialog::areas(crate::workspace_menu::dialog_box(&menu), crate::workspace_menu::dialog_parts(&menu)).row;+ let hit = if chosen { b.row.click(row, ratatui::layout::Position::new(m.x, m.y)) } else { None };+ if let Some(command) = hit.and_then(|i| b.actions.get(i)).cloned() { return commands::execute_in(app, &command, menu.mouse.clone()) }+ app.modal = Some(Modal::Menu(menu));+ return;+ }// The click's row is authoritative even if no mouse-motion report preceded it.// In particular, a menu opened by the keyboard must not run its previous selection.menu.choice = Some((m.y - (py + 1)) as usize);@@ -3586,6 +3681,29 @@ pub fn menu_mouse(app: &mut App, m: &crate::mouse::Event) {mod tests {use super::*;+ /// A new shell on this computer never starts in a folder that is gone (a cleaned /tmp, a+ /// deleted worktree): it starts at home. Another computer's folders are its daemon's to check.+ #[test]+ fn a_new_shell_on_this_computer_never_starts_in_a_folder_that_is_gone() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (100, 30));+ app.fleet.local_id = "here".into();+ for (id, local) in [("here", true), ("far", false)] {+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: id.into(), name: id.into(), local, status: "online".into(), reach: crate::fleet::Reach::Ready });+ }+ let gone = std::env::temp_dir().join(format!("hn-gone-{}", uuid::Uuid::new_v4())).to_string_lossy().into_owned();+ let kept = std::env::temp_dir().to_string_lossy().into_owned();+ for (machine, agent, cwd) in [("here", "gone", &gone), ("here", "kept", &kept), ("far", "remote", &gone)] {+ app.fleet.agents.insert((machine.into(), agent.into()), crate::fleet::agent_from(machine, &json!({"id":agent,"engine":"codex","project":{"cwd":cwd}}), None));+ }+ let focus = |m: &str, a: &str| Some((m.to_string(), a.to_string()));+ assert_eq!(shell_cwd(&app, focus("here", "gone").as_ref(), "here", None), None, "home, not a folder that is gone");+ assert_eq!(shell_cwd(&app, focus("here", "kept").as_ref(), "here", None), Some(kept.clone()));+ assert_eq!(shell_cwd(&app, None, "here", Some(gone.clone())), None, "-c to a gone folder too");+ assert_eq!(shell_cwd(&app, focus("here", "gone").as_ref(), crate::local::MACHINE, None), None, "hn's own local shells too");+ assert_eq!(shell_cwd(&app, focus("far", "remote").as_ref(), "far", None), Some(gone), "another computer's daemon checks its own");+ }+#[test]fn conversation_owner_matches_computer_engine_and_prefers_running_harness() {let (sink, _) = tokio::sync::mpsc::unbounded_channel();@@ -3677,6 +3795,42 @@ mod tests {assert_eq!(app.options.get("@clicked", "", None).as_deref(), Some("yes"));}+ #[tokio::test]+ async fn a_click_on_a_confirmation_button_runs_it_and_between_buttons_nothing() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (100, 30));+ app.mouse = true;+ let button = |label: &str, key| crate::buttons::Button { label: label.into(), key };+ let row = crate::buttons::Row { buttons: vec![button("Cancel", None), button("Stop", Some('s'))], chosen: 0, hint: String::new() };+ let ask = |app: &mut App| {+ let row = row.clone();+ assert!(crate::workspace_menu::open_buttons(app, "Close Tab", vec![crate::workspace_menu::note("Stop?")], row,+ vec!["set -g @clicked cancel".into(), "set -g @clicked stop".into()]));+ };+ ask(&mut app);+ let Some(Modal::Menu(m)) = &app.modal else { panic!("closed") };+ let y = m.y + 1 + m.items.len() as u16 + 1;+ let cells = m.buttons.as_ref().unwrap().row.areas(ratatui::layout::Rect::new(m.x + 2, y, m.width, 1));+ let press = |x, y| MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: x, row: y, modifiers: KeyModifiers::NONE };+ let gap = cells[0].right();+ handle(&mut app, CEvent::Mouse(press(gap, y)));+ assert!(matches!(app.modal, Some(Modal::Menu(_))), "the gap between the buttons keeps the dialog");+ assert!(app.options.get("@clicked", "", None).is_none());+ handle(&mut app, CEvent::Mouse(press(cells[1].x + 2, y - 1)));+ assert!(matches!(app.modal, Some(Modal::Menu(_))), "the blank row above the buttons does nothing");+ handle(&mut app, CEvent::Mouse(press(cells[1].x + 2, y)));+ assert!(app.modal.is_none());+ assert_eq!(app.options.get("@clicked", "", None).as_deref(), Some("stop"));++ // A press outside the box cancels: the question never just vanishes.+ let mut app = App::new(19789, tokio::sync::mpsc::unbounded_channel().0, (100, 30));+ app.mouse = true;+ ask(&mut app);+ handle(&mut app, CEvent::Mouse(press(0, 0)));+ assert!(app.modal.is_none());+ assert_eq!(app.options.get("@clicked", "", None).as_deref(), Some("cancel"));+ }+#[test]fn os_actions_are_unavailable_in_ordinary_hn_and_install_is_live_only() {let (sink, _) = tokio::sync::mpsc::unbounded_channel();@@ -3893,4 +4047,17 @@ mod tests {assert!(picker.rows.iter().all(|r| r.id.starts_with("theme:")), "the section's options show");assert!(picker.rows.iter().any(|r| r.lead.iter().any(|s| s.content.as_ref() == "✓ ")), "the current option is marked");}++ /// Focus-in and a resize each ask the main loop for a full repaint: `redraw_all`, one flag the+ /// loop takes once per pass, so requests in one pass are one repaint.+ #[test]+ fn focus_in_and_a_resize_ask_for_a_repaint() {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, (100, 30));+ for event in [CEvent::FocusGained, CEvent::Resize(100, 30)] {+ app.redraw_all = false;+ handle(&mut app, event.clone());+ assert!(app.redraw_all, "{event:?}");+ }+ }}diff --git a/tui/src/layout.rs b/tui/src/layout.rsindex 62bd16370..197953fc3 100644--- a/tui/src/layout.rs+++ b/tui/src/layout.rs@@ -98,6 +98,16 @@ impl Node {pub fn leaves(&self) -> Vec<u64> { self.walk(self.root).into_iter().map(|i| self.c[i].pane).collect() }+ /// The pane right before [pane] (or after it) in the split it is directly in, when that split+ /// is [dir] and the neighbour a pane, not a split of its own.+ pub fn neighbour(&self, pane: u64, dir: Dir, before: bool) -> Option<u64> {+ let i = self.find(pane)?;+ let (p, _) = self.index_in_parent(i)?;+ if self.c[p].dir != Some(dir) { return None }+ let n = if before { self.prev(i)? } else { self.next(i)? };+ self.is_pane(n).then(|| self.c[n].pane)+ }+/// The window's size in cells.pub fn size(&self) -> (u16, u16) { (self.c[self.root].sx as u16, self.c[self.root].sy as u16) }diff --git a/tui/src/machine_menu.rs b/tui/src/machine_menu.rsnew file mode 100644index 000000000..a87f6e624--- /dev/null+++ b/tui/src/machine_menu.rs@@ -0,0 +1,151 @@+//! A machine's menu, from the side bar (a right press on its heading, or a click on one with no+//! window here): what can be done on it — New Harness, New Terminal, its harnesses — Connect… when+//! it needs a link, and Machines & devices on it. A `workspace_menu`, its items `machine-menu`+//! commands.++use crate::app::{App, Placement};+use crate::fleet::Reach;+use crate::theme;+use crate::workspace_menu as menu;++/// [machine]'s name, as the side bar shows it.+fn name(app: &App, machine: &str) -> String {+ app.fleet.machine(machine).map(|m| m.name.clone()).filter(|n| !n.is_empty()).unwrap_or_else(|| machine.to_string())+}++/// The menu for [machine] at [at] (the press), titled with its name, with only what it can do now.+pub fn open(app: &mut App, machine: &str, at: Option<(u16, u16)>) {+ let Some(m) = app.fleet.machine(machine) else { return };+ let (usable, link) = (m.usable(), m.reach == Reach::NeedsLink && m.online());+ let name = name(app, machine);+ // (Its id quoted as the command line reads it: an id with a space is one word.)+ let id = crate::tmuxconf::quote_word(machine);+ let run = |verb: &str| format!("machine-menu {verb} {id}");+ let mut items = Vec::new();+ if link { items.push(menu::item("Connect…", "c", run("connect"))) }+ if usable {+ items.push(menu::item(&format!("New Harness on {name}…"), "n", run("new-harness")));+ items.push(menu::item(&format!("New Terminal on {name}"), "t", run("new-terminal")));+ items.push(menu::item("Open its harnesses", "o", run("open")));+ }+ items.push(menu::item("Machines & devices…", "m", run("machine")));+ menu::open(app, &name, items, at, Some(0));+}++/// A left click on [machine]'s heading when no window here is on it: its menu when it is ready,+/// Connect… when it needs a link, else Machines & devices on it and what is wrong with it.+pub fn click(app: &mut App, machine: &str, at: Option<(u16, u16)>) {+ let Some(m) = app.fleet.machine(machine).cloned() else { return };+ let name = name(app, machine);+ let (said, colour) = match &m.reach {+ Reach::Ready => return open(app, machine, at),+ Reach::NeedsLink if m.online() => return crate::devices::connect_to(app, machine.to_string()),+ Reach::Connecting => (format!("{name} is connecting…"), theme::SOFT),+ Reach::Error(why) => (format!("{name}: {why}"), theme::WARN),+ _ => (format!("{name} is offline — start Harness on it"), theme::WARN),+ };+ crate::devices::open_machine(app, machine);+ app.say(said, colour);+}++/// `machine-menu <new-harness|new-terminal|open|connect|machine> <machine>`: an item of the menu.+pub fn command(app: &mut App, args: &[String]) {+ let [verb, machine] = args else { return };+ match verb.as_str() {+ "new-harness" => crate::new_harness::open(app, Some(machine.clone()), None),+ "new-terminal" => crate::input::new_shell_from(app, Some((machine.clone(), String::new())), Placement::Auto(None), None, None),+ "open" => crate::devices::open_machine_list(app, machine),+ "connect" => crate::devices::connect_to(app, machine.clone()),+ "machine" => crate::devices::open_machine(app, machine),+ _ => {}+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::modal::Modal;++ fn grid() -> App {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19798, tx, (160, 40));+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: "grid".into(), name: "grid-dev".into(), local: false, status: "online".into(), reach: Reach::Ready });+ app+ }++ fn machine(app: &mut App, id: &str, status: &str, reach: Reach) {+ app.fleet.machines.push(crate::fleet::Machine { shared: false, id: id.into(), name: id.into(), local: false, status: status.into(), reach });+ }++ fn labels(app: &App) -> Vec<String> {+ let Some(Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ m.items.iter().map(|i| i.label.clone()).collect()+ }++ /// Run the menu item with this label the way a chosen item runs: its command.+ fn choose(app: &mut App, label: &str) {+ let Some(Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ let command = m.items.iter().find(|i| i.label == label).unwrap_or_else(|| panic!("no item {label}")).command.clone();+ app.modal = None;+ crate::commands::execute(app, &command);+ }++ #[tokio::test]+ async fn new_harness_on_a_machine_opens_the_form_on_it() {+ let mut app = grid();+ open(&mut app, "grid", None);+ let Some(Modal::Menu(m)) = &app.modal else { panic!("a menu") };+ assert_eq!(m.title, "grid-dev");+ choose(&mut app, "New Harness on grid-dev…");+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!("the form") };+ assert_eq!(form.draft.machine, "grid");+ }++ #[tokio::test]+ async fn its_harnesses_and_machines_and_devices_open_on_it() {+ let mut app = grid();+ open(&mut app, "grid", None);+ choose(&mut app, "Open its harnesses");+ assert!(matches!(&app.modal, Some(Modal::Picker { kind: crate::modal::PickerKind::Open { machine: Some(m), .. }, .. }) if m == "grid"));+ open(&mut app, "grid", None);+ choose(&mut app, "Machines & devices…");+ assert!(matches!(&app.modal, Some(Modal::Picker { kind: crate::modal::PickerKind::Devices(crate::devices::View::Machines), .. })));+ assert_eq!(app.devices.sub.as_deref(), Some("m:grid"), "on that machine's own actions");+ }++ #[tokio::test]+ async fn the_menu_lists_only_what_the_machine_can_do() {+ let mut app = grid();+ machine(&mut app, "air", "offline", Reach::Offline);+ open(&mut app, "air", None);+ assert_eq!(labels(&app), ["Machines & devices…"]);+ machine(&mut app, "lb", "online", Reach::NeedsLink);+ open(&mut app, "lb", None);+ assert_eq!(labels(&app), ["Connect…", "Machines & devices…"], "Connect… first");+ open(&mut app, "grid", None);+ assert!(!labels(&app).contains(&"Connect…".to_string()));+ }++ #[tokio::test]+ async fn a_machine_id_with_a_space_or_a_quote_is_one_word() {+ let mut app = grid();+ machine(&mut app, "my 'box'", "online", Reach::Ready);+ open(&mut app, "my 'box'", None);+ choose(&mut app, "Open its harnesses");+ assert!(matches!(&app.modal, Some(Modal::Picker { kind: crate::modal::PickerKind::Open { machine: Some(m), .. }, .. }) if m == "my 'box'"));+ }++ #[tokio::test]+ async fn a_click_says_what_is_wrong_with_a_machine_that_cannot_be_used() {+ let mut app = grid();+ machine(&mut app, "c", "online", Reach::Connecting);+ machine(&mut app, "e", "online", Reach::Error("certificate expired".into()));+ machine(&mut app, "u", "online", Reach::Unknown);+ for (id, said) in [("c", "c is connecting…"), ("e", "e: certificate expired"), ("u", "u is offline — start Harness on it")] {+ app.modal = None;+ click(&mut app, id, None);+ assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some(said));+ assert_eq!(app.devices.sub.as_deref(), Some(format!("m:{id}").as_str()), "Machines & devices on it");+ }+ }+}diff --git a/tui/src/main.rs b/tui/src/main.rsindex a631ea0a7..41eaa7f28 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -40,7 +40,10 @@ mod input;mod layout;mod desk_layout;mod local;+mod machine_menu;mod modal;+mod buttons;+mod dialog;mod workspace_menu;mod workspace_controls;mod workspace_events;@@ -56,6 +59,7 @@ mod os_welcome;mod paste;mod pane;mod pane_frame;+mod pane_drag;mod picker;mod proto;mod theme;@@ -418,6 +422,8 @@ async fn run(config: config::Config) -> io::Result<()> {// Whether some pane was selecting last frame (a selection starting is when a ghost is seen).let mut was_selecting = false;term.clear()?;+ // (Not `Write::flush`: only the backend's own flush closes the synchronized update the clear opened.)+ ratatui::backend::Backend::flush(term.backend_mut())?;let size = terminal::size()?;let (tx, mut rx) = mpsc::unbounded_channel::<Event>();@@ -503,6 +509,13 @@ async fn run(config: config::Config) -> io::Result<()> {let frame_budget = Duration::from_millis(6);let mut last_draw = Instant::now() - frame_budget;let mut need_draw = true;+ // A full repaint asked for, kept until the pass that draws: its clear and its frame are one+ // synchronized update, never split across passes.+ let mut repaint_due = false;+ // Where the frame before drew an overlay (the settle rewrite follows one that closed or shrank).+ let mut overlay_before: Option<ratatui::layout::Rect> = None;+ // The size the terminal was last drawn at: a repaint erases only when it differs.+ let mut drawn_size = term.size()?;// Rendered animation and timed UI messages schedule their next frame.// Maintenance and incoming input/output keep their own cadence.let mut next_repaint: Option<Instant> = None;@@ -590,13 +603,21 @@ async fn run(config: config::Config) -> io::Result<()> {// Welcome forms also need connection and catalog updates, including drafts in// background windows. Refill leaves unrelated overlays alone.if refill { input::refill(&mut app) }- // A scroll that has rested: every row of the screen written again, once — row by row over- // what is there, not after erasing it, so it never flashes.+ // A scroll, a burst or a closed overlay that has rested: the rows written since the last+ // settle are written again, once — each its text over what is there, so none flashes.let settle = app::scroll_settle_in(app.scrolled_at, Instant::now()) == Some(Duration::ZERO);- if settle { app.scrolled_at = None }- if std::mem::take(&mut app.redraw_all) { term.clear()?; need_draw = true; }- else if settle { term.backend_mut().soft_clear_next(); term.clear()?; need_draw = true; }+ if settle { app.scrolled_at = None; term.backend_mut().settle_next(); need_draw = true }+ // Two requests in one pass (or one that waited for the frame budget) are one repaint.+ if std::mem::take(&mut app.redraw_all) { repaint_due = true; need_draw = true; }if need_draw && last_draw.elapsed() >= frame_budget {+ // A changed size is cleared by `draw`'s own resize, inside the frame's update; a clear+ // here would be a second erase, and a soft one would leave text outside the new rows.+ let size_changed = !term_out::repaint_is_soft(drawn_size, term.size()?);+ let repainting = repaint_due || size_changed;+ if std::mem::take(&mut repaint_due) && !size_changed {+ term.backend_mut().soft_clear_next();+ term.clear()?;+ }// (The backend makes each frame's changes one synchronized update, and writes nothing// for a frame that changed nothing.)let frame_started = Instant::now();@@ -608,6 +629,13 @@ async fn run(config: config::Config) -> io::Result<()> {}let done = term.draw(|frame| ui::draw(frame, &mut app))?;if let Some(v) = verifier.as_mut() { v.check(done.buffer) }+ drawn_size = term.size()?;+ // A burst of cell updates, or an overlay gone or smaller, owes one rewrite of its rows+ // once the screen rests; a repaint wrote every row, so it owes none.+ let (due, left) = app::settle_after_frame(repainting, overlay_before, app.overlay_drawn, term.backend().last_cells(), app.scrolled_at, Instant::now());+ app.scrolled_at = due;+ if let Some(r) = left { term.backend_mut().owe_rows(r.y..r.bottom()) }+ overlay_before = app.overlay_drawn;// The focused program's cursor shape (vim's block and bar), passed through as tmux does.let shape = app.focused().filter(|_| app.modal.is_none()).and_then(|f| app.panes.get(&f)).map(|p| p.cursor_style()).unwrap_or(cursor::SetCursorStyle::DefaultUserShape);let code = format!("{shape:?}");diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex 4854d9a4e..bc1df6879 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -95,7 +95,8 @@ pub enum PromptKind {Tree { pane: u64, ask: crate::tree::Ask },}-/// A line typed in the status line, tmux-style: `(rename-window) name`, `:split-window -h`.+/// A line typed: tmux's in the status line (`(rename-window) name`, `:split-window -h`), hn's own+/// in a dialog ([Prompt::dialog]).#[derive(Clone, Debug)]pub struct Prompt {pub kind: PromptKind,@@ -112,11 +113,35 @@ pub struct Prompt {pub vi_normal: bool,/// What C-w last cut (prompt_saved): C-y puts it back before the newest paste buffer.pub saved: Option<String>,+ /// hn's own questions ([Prompt::dialog]): the input's label, the line above it, whether the+ /// keys are on the buttons (Tab) and which one is chosen (0 Cancel, 1 the action).+ pub field: String,+ pub body: String,+ pub buttons: bool,+ pub chosen: usize,}impl Prompt {pub fn status(kind: PromptKind, label: &str, initial: &str) -> Prompt {- Prompt { kind, title: String::new(), label: label.to_string(), hint: String::new(), value: initial.to_string(), secret: false, cursor: initial.chars().count(), history_at: None, vi_normal: false, saved: None }+ Prompt { kind, title: String::new(), label: label.to_string(), hint: String::new(), value: initial.to_string(), secret: false, cursor: initial.chars().count(), history_at: None, vi_normal: false, saved: None, field: String::new(), body: String::new(), buttons: false, chosen: 1 }+ }++ /// hn's own questions are dialogs; tmux's (command-prompt, choose-tree's) keep the status line.+ pub fn dialog(&self) -> bool {+ matches!(self.kind, PromptKind::RenameTab { .. } | PromptKind::RenameHarness { .. } | PromptKind::Send | PromptKind::Broadcast | PromptKind::Answer { .. } | PromptKind::Message { .. })+ }++ /// The dialog's `[ Cancel ] [ Rename ]` (Send, Broadcast, Answer), the chosen button only+ /// while the keys are on them.+ pub fn row(&self) -> crate::buttons::Row {+ let action = match self.kind {+ PromptKind::RenameTab { .. } | PromptKind::RenameHarness { .. } => "Rename",+ PromptKind::Broadcast => "Broadcast",+ PromptKind::Answer { .. } => "Answer",+ _ => "Send",+ };+ let button = |label: &str| crate::buttons::Button { label: label.into(), key: None };+ crate::buttons::Row { buttons: vec![button("Cancel"), button(action)], chosen: if self.buttons { self.chosen } else { usize::MAX }, hint: crate::buttons::KEYS.into() }}}@@ -148,6 +173,8 @@ pub struct Menu {/// Harness menus reflow from their original labels when the terminal changes size./// Explicit tmux display-menu coordinates keep tmux's existing behavior.pub responsive: Option<Box<crate::workspace_menu::Layout>>,+ /// A confirmation's buttons, drawn on the row under the notes.+ pub buttons: Option<crate::workspace_menu::Buttons>,}/// What a completion menu completes: the prompt, the words its items stand for, the flag they@@ -182,6 +209,7 @@ pub const ENGINES: [&str; 15] = ["claude", "codex", "opencode", "cursor", "pi",/// The palette's commands: (id, title, keys, hint, group).pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("account", "Account / sign in…", "", "connect computers, sync your workspace and add your phone", "General"),+ ("signout", "Sign out", "", "leave your Harness account here — harnesses on this computer keep running", "General"),("open", "Harnesses…", "⌥P", "every harness on every machine", "Harness"),("projects", "Projects…", "⌥O", "a project, then one of its harnesses", "Harness"),("models", "Models…", "⌥I", "local, shared, subscriptions, APIs — use one on this harness", "Harness"),@@ -213,12 +241,13 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("find", "Find in pane…", "⌥⇧F", "search this pane's history", "Panes"),// (Not "keyboard": `keyb` is Keybinds.)("copy-mode", "Copy mode", "⌥V", "move over the pane's text, select and copy", "Panes"),- ("machines", "Machines", "⌥M", "", "Machines"),+ // (The machines and what runs on each; Connect machines… is where one is linked, its password+ // asked — the one way in: a separate "Connect a computer…" only went there.)+ ("machines", "List machines", "⌥M", "your machines and the harnesses on each", "Machines"),("store", "Harness store", "⌥S", "", "Machines"),// ── machines & devices ──- ("connect-machine", "Connect a computer…", "", "a computer not linked yet, with its remote password", "Machines"),+ ("devices", "Connect machines…", "", "link a machine, this computer's password, your machines and links", "Machines"),("add-phone", "Add phone…", "", "a QR code your phone scans to sign in and pair", "Machines"),- ("devices", "Machines…", "", "this computer's password, your machines, links, add a machine", "Machines"),("hardware-devices", "Devices…", "", "Harness hardware, brightness, sound and voice language", "Machines"),// (hn itself: how it looks, its keys, and closing it.)("theme", "Appearance…", "", "theme, status bar, borders, focus, layout — settings", "Settings & help"),@@ -764,8 +793,14 @@ pub fn theme_options(app: &App, section: &str) -> Vec<Row> {[("box", "on", "every pane its own box"), ("line", "off", "tmux's lines between panes")].iter().map(|(v, label, hint)| opt(format!("border_style:{v}"), label, cur == *v, hint)).collect() }"tab" => { let cur = tab_active_of(app);+ // (`pane`, an older tui.toml's word, is `short`.)+ let named = match o.get("@hn-window-name", "", None).as_deref() { Some("full") => "full", Some("tmux") => "tmux", _ => "short" };+ let short = format!("names cut to {} columns, as tmux's", crate::options::TAB_NAME_COLS);[("star", "star", "the current tab is marked *"), ("filled", "filled", "the current tab is filled (inverted)")]- .iter().map(|(v, label, hint)| opt(format!("window_active:{v}"), label, cur == *v, hint)).collect() }+ .iter().map(|(v, label, hint)| opt(format!("window_active:{v}"), label, cur == *v, hint))+ .chain([("short", "short names", short.as_str()), ("full", "full names", "each tab's whole name")]+ .iter().map(|(v, label, hint)| opt(format!("window_name:{v}"), label, named == *v, hint)))+ .collect() }"autorename" => { let cur = if o.auto_rename() { "on" } else { "off" };[("on", "a window with a repo is named for it and its work, by a small model, in the background (Harness TUI LMStudio)"),("off", "windows keep the names they have")]@@ -909,7 +944,9 @@ mod theme_row_tests {let a0 = app();let tab_rows = theme_options(&a0, "tab");let tab_ids: Vec<&str> = tab_rows.iter().map(|r| r.id.as_str()).collect();- assert_eq!(tab_ids, vec!["window_active:star", "window_active:filled"]);+ // (How long a tab's name is shown is in the same section: short, the default, or full.)+ assert_eq!(tab_ids, vec!["window_active:star", "window_active:filled", "window_name:short", "window_name:full"]);+ assert!(tab_rows[2].lead.iter().any(|s| s.content.contains('✓')), "short names by default");// The mark follows the option in use.let mut a1 = app();let global = crate::options::SetFlags { global: true, ..Default::default() };diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rsindex c7026ac73..9008646cb 100644--- a/tui/src/new_harness.rs+++ b/tui/src/new_harness.rs@@ -26,7 +26,7 @@ use ratatui::{};use serde_json::{Value, json};use std::{collections::HashMap, time::Duration};-use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};+use unicode_width::UnicodeWidthStr;pub use view::draw;#[derive(Clone, Debug)]@@ -140,6 +140,11 @@ pub struct Form {modes: HashMap<String, String>,}impl Form {+ /// Where the form was last drawn, with a side chooser beside it (empty before its first frame).+ pub(crate) fn drawn_area(&self) -> Rect {+ if self.child_area.is_empty() { self.area } else { self.area.union(self.child_area) }+ }+fn project_payload(&self) -> Result<(Option<String>, Value), String> {// A confirmed failure may have already made a clone or worktree. Reuse that// exact folder until the user explicitly chooses another project/branch.@@ -190,20 +195,20 @@ impl Form {&& data::git(&self.git)&& self.draft.worktree.unwrap_or(true)}- fn blocked(&self, field: Field) -> Option<&str> {+ fn blocked(&self, field: Field) -> Option<String> {if self.local_only && matches!(field, Field::Branch | Field::Worktree | Field::Create) && self.draft.what.engine != "terminal" {- Some("Start the Harness daemon first")+ Some("Start the Harness daemon first".into())} else if field == Field::Task && !task::supported(&self.draft.what.engine) && self.draft.task.trim().is_empty() {- Some("Not available for this agent")+ Some(format!("Not available for {}", self.draft.what.label))} else if matches!(field, Field::Branch | Field::Worktree) {if self.git_loading {- Some("Checking Git…")+ Some("Checking Git…".into())} else if self.git["error"] == "OFFLINE" {- Some("Waiting for machine…")+ Some("Waiting for machine…".into())} else if self.git["error"].is_string() {- Some("Could not read Git · Enter to retry")+ Some("Could not read Git · Enter to retry".into())} else if !data::git(&self.git) || self.draft.what.engine == "terminal" {- Some("Not a Git repository")+ Some("Not a Git repository".into())} else {None}@@ -328,7 +333,7 @@ impl Form {} else {label.into()},- self.blocked(field).map(str::to_string).unwrap_or(value),+ self.blocked(field).unwrap_or(value),)}}@@ -438,6 +443,14 @@ pub fn open(app: &mut App, machine: Option<String>, cwd: Option<String>) {{let mut form = app.new_harness_draft.take().unwrap();form.surface = Surface::Dialog;+ // A draft reopened to go on writing starts on its task, no chooser open. (One whose+ // launch failed keeps Start in focus: Enter retries it.)+ if !form.starting && form.attempt.is_none() {+ if task::supported(&form.draft.what.engine) && form.error.is_empty() { form.focus = Field::Task; }+ form.child = None;+ form.child_active = false;+ form.trail.clear();+ }resolve_launch_machine(app, &mut form);refresh_form(app, &mut form);app.modal = Some(Modal::NewHarness(form));@@ -1358,11 +1371,25 @@ fn choose(app: &mut App, form: &mut Form) {}form.child_active = false;form.trail.clear();- form.focus = Field::Create;+ // (Chosen from the task, by `@ : %`: back to writing it.)+ if form.focus != Field::Task { form.focus = Field::Create; }form.error.clear();refresh_form(app, form);sync_git(app, form, false);}+/// `@ : %` typed where a word starts in the task: the chooser of that scope (the shell composer's+/// `@ computer`, `: project`, `% model`). Inside a word each is a letter.+fn scope_choice(form: &Form, ch: char) -> Option<Choice> {+ let task = &form.draft.task;+ let before = task.get(..form.task_editor.cursor).unwrap_or(task);+ if !before.chars().next_back().is_none_or(char::is_whitespace) { return None }+ match ch {+ '@' => Some(Choice::Machine(None)),+ ':' => Some(Choice::Project),+ '%' if form.fields().contains(&Field::Model) => Some(Choice::Model),+ _ => None,+ }+}fn back(app: &mut App, form: &mut Form) -> bool {if form.child_active {if let Some(previous) = form.trail.pop() {@@ -1429,12 +1456,23 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {}return;}- if !form.child_active && matches!(key.code, KeyCode::Enter | KeyCode::Char(' '))+ // → opens these rows as Enter does: they have no chooser to enter.+ if !form.child_active && matches!(key.code, KeyCode::Enter | KeyCode::Char(' ') | KeyCode::Right)&& matches!(form.focus, Field::Terminal | Field::Recent(_) | Field::Browse) {return welcome::activate(app, form);}let mut launch = false;- if !form.child_active && form.focus == Field::Task {+ let scope = match key.code {+ KeyCode::Char(ch) if !form.child_active && form.focus == Field::Task+ && !key.modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)+ && form.blocked(Field::Task).is_none() => scope_choice(&form, ch),+ _ => None,+ };+ if let Some(kind) = scope {+ // The chooser drops down under the task; Esc leaves the task as it was.+ child(app, &mut form, kind, "");+ form.child_active = true;+ } else if !form.child_active && form.focus == Field::Task {match key.code {KeyCode::Tab | KeyCode::BackTab => {form.move_by(match key.code { KeyCode::Up | KeyCode::BackTab => -1, _ => 1 });@@ -1461,7 +1499,14 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {let editing = c.kind.editing();match key.code {KeyCode::Enter => choose(app, &mut form),- KeyCode::Tab | KeyCode::BackTab => form.child_active = false,+ KeyCode::Tab | KeyCode::BackTab => {+ form.child_active = false;+ // (Opened from the task by `@ : %`: nothing stays open behind it.)+ if form.focus == Field::Task {+ form.child = None;+ form.trail.clear();+ }+ }KeyCode::Char('l') if ctrl && matches!(c.kind, Choice::Folder(_)) => {let path = if let Choice::Folder(path) = &c.kind {path.clone()@@ -1528,6 +1573,11 @@ pub fn key(app: &mut App, mut form: Box<Form>, key: KeyEvent) {KeyCode::Right if form.focus != Field::Create => {activate(app, &mut form);}+ // ← steps back to the task, as in the command panel (→ in, ← back).+ KeyCode::Left if matches!(form.focus, Field::Recent(_) | Field::Browse | Field::Terminal) => {+ form.focus = Field::Task;+ reveal(app, &mut form);+ }KeyCode::Left | KeyCode::PageUp | KeyCode::PageDownif form.focus == Field::Worktree =>{@@ -1931,6 +1981,177 @@ mod tests {}}+ fn press(app: &mut App, code: KeyCode) {+ let Some(Modal::NewHarness(form)) = app.modal.take() else { panic!() };+ key(app, form, KeyEvent::new(code, KeyModifiers::NONE));+ }+ fn form_of(app: &App) -> &Form {+ let Some(Modal::NewHarness(form)) = &app.modal else { panic!() };+ form+ }++ #[tokio::test]+ async fn a_chooser_drops_down_under_its_field_in_the_panels_style() {+ let _l = crate::term_out::colours_lock();+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ form.focus = Field::Project;+ child(&mut app, &mut form, Choice::Project, "");+ let body = Rect::new(0, 0, 120, 36);+ draw(&mut Buffer::empty(body), body, &mut form);+ assert!(form.child_area.is_empty(), "arrowing onto a field drops nothing down");+ form.child_active = true;+ let mut buf = Buffer::empty(body);+ draw(&mut buf, body, &mut form);+ let at = form.hits.iter().find(|(_, f)| *f == Field::Project).unwrap().0;+ assert_eq!(form.child_area.y, at.y + 1, "right under the Project row");+ assert_eq!(form.child_area.intersection(form.area), form.child_area, "inside the form: no side panel");+ assert!(form.task_area.intersection(form.child_area).is_empty(), "never over the Task line");+ assert_eq!(buf[(form.child_area.x + 1, form.child_area.y)].symbol(), "›", "the query line first");+ let rule: String = (form.child_area.x + 1..form.child_area.right() - 1).map(|x| buf[(x, form.child_area.y + 1)].symbol()).collect();+ assert!(rule.contains('/') && rule.ends_with('─'), "the count rule: {rule}");+ let keys: String = (form.child_area.x..form.child_area.right()).map(|x| buf[(x, form.child_area.bottom() - 1)].symbol()).collect();+ assert!(keys.contains("↑↓ move") && keys.contains("esc back"), "the keys line: {keys}");+ let c = crate::settings::chrome();+ let (y, _) = form.child.as_ref().unwrap().picker.row_at[0];+ // (Under NO_COLOR the chosen row has no band, only a modifier.)+ assert_eq!(buf[(form.child_area.x + 3, y)].bg, c.selected.bg.unwrap_or(ratatui::style::Color::Reset), "the chosen row on the panel's band");+ assert!(buf[(form.child_area.x + 3, y)].modifier.contains(c.selected.add_modifier));+ // A chooser's error: in the dropdown, not again in the form's footer.+ form.error = "That machine is not connected".into();+ let mut buf = Buffer::empty(body);+ draw(&mut buf, body, &mut form);+ let text: String = buf.content().iter().map(|c| c.symbol()).collect();+ assert_eq!(text.matches("That machine is not connected").count(), 1, "{text}");+ }++ #[test]+ fn the_dropdown_says_what_it_waits_for_and_its_error_in_place_of_its_keys() {+ use ratatui::widgets::StatefulWidget;+ let mut picker = Picker::new("", "Search folders");+ picker.busy = Some("Loading folders…".into());+ let area = Rect::new(0, 0, 50, 6);+ let mut buf = Buffer::empty(area);+ let mut dropdown = view::Dropdown { editing: false, error: "That machine is not connected", chrome: crate::settings::chrome_with(true), cursor: None };+ (&mut dropdown).render(area, &mut buf, &mut picker);+ assert_eq!(dropdown.cursor, Some(Position::new(3, 0)), "the text cursor where the query starts");+ let row = |y| (0..50).map(|x| buf[(x, y)].symbol()).collect::<String>();+ assert!(row(0).starts_with(" › Search folders"), "{}", row(0));+ assert!(row(1).starts_with(" 0/0 ─") && row(1).trim_end().ends_with("Loading folders…"), "{}", row(1));+ assert!(row(2).trim().is_empty(), "no empty-list notice while it loads: {}", row(2));+ assert_eq!(row(5).trim(), "That machine is not connected");+ }++ /// The dropdown drawn with the panel's line widgets is the dropdown the hand-drawn lines drew:+ /// a list or a path being typed, loading, failed, every width up to 160, in a dark theme, a+ /// light one and NO_COLOR.+ #[test]+ fn the_dropdown_draws_what_it_did_with_the_hand_drawn_lines() {+ use crate::settings::oracle::{chromes, grounds, LONG};+ use ratatui::widgets::StatefulWidget;+ let _l = crate::term_out::colours_lock();+ // (The spinner still, so the two draws a moment apart show the same frame.)+ theme::begin_animation_frame(false);+ let n = LONG.chars().count();+ // (editing, query, its cursor, loading, the error)+ let cases: [(bool, &str, usize, Option<&str>, &str); 7] = [+ (false, "", 0, None, ""),+ (false, "pro", 3, None, ""),+ (false, LONG, n, None, ""),+ (false, LONG, 0, None, ""),+ (false, "", 0, Some("Loading folders…"), ""),+ (false, "", 0, None, "That machine is not connected"),+ (true, "~/code/api", 10, None, ""),+ ];+ // (From 3 columns: narrower, the old query line drew its mark past the dropdown's padding,+ // or past the dropdown; the widget keeps to its area. Wider ones in steps — every width the+ // line widgets are checked at is too slow here.)+ let widths = [3, 4, 5, 8, 23, 24, 25, 30, 40, 47, 64, 80, 96, 120, 159, 160];+ for c in chromes() { for w in widths { for h in [1, 2, 3, 4, 6, 12] {+ let area = Rect::new(2, 1, w, h);+ // (Over cells already written: the dropdown clears what it covers and touches nothing else.)+ let [_, ground] = grounds(Rect::new(0, 0, w + 4, h + 2));+ {+ for (editing, query, at, busy, error) in cases {+ let make = || {+ let mut p = Picker::new("", "Search projects");+ p.set_rows((0..9).map(|i| crate::picker::Row::new(format!("p{i}"), format!("project-{i}")).right("~/code")).collect());+ p.query = query.into();+ p.refilter();+ p.qcursor = at;+ p.busy = busy.map(String::from);+ p+ };+ let (mut a, mut b) = (make(), make());+ let (mut old, mut new) = (ground.clone(), ground.clone());+ let mut was = view::Dropdown { editing, error, chrome: crate::settings::Chrome { ..c }, cursor: None };+ view::oracle::render(&mut was, area, &mut old, &mut a);+ let mut now = view::Dropdown { editing, error, chrome: crate::settings::Chrome { ..c }, cursor: None };+ (&mut now).render(area, &mut new, &mut b);+ let what = format!("{w}x{h} editing {editing} {query:?} at {at} {busy:?} {error:?}");+ assert_eq!(was.cursor, now.cursor, "{what}");+ assert_eq!((a.xoffset.get(), a.prompt_at.get(), &a.row_at, a.page_rows.get()), (b.xoffset.get(), b.prompt_at.get(), &b.row_at, b.page_rows.get()), "{what}");+ assert!(old == new, "{what}: the cells that differ, as drawn now: {:?}", old.diff(&new));+ }+ }+ } } }+ }++ #[tokio::test]+ async fn at_colon_percent_in_the_task_open_their_choosers() {+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ for ch in "fix the login ".chars() { press(&mut app, KeyCode::Char(ch)); }+ press(&mut app, KeyCode::Char('@'));+ let f = form_of(&app);+ assert_eq!(f.child.as_ref().map(|c| c.kind.clone()), Some(Choice::Machine(None)));+ assert!(f.child_active);+ assert_eq!(f.draft.task, "fix the login ", "the @ is not typed into the task");+ press(&mut app, KeyCode::Esc);+ let f = form_of(&app);+ assert!(f.child.is_none());+ assert_eq!((f.focus, f.draft.task.as_str()), (Field::Task, "fix the login "));+ press(&mut app, KeyCode::Char('%'));+ assert_eq!(form_of(&app).child.as_ref().map(|c| c.kind.clone()), Some(Choice::Model));+ press(&mut app, KeyCode::Esc);+ press(&mut app, KeyCode::Char(':'));+ assert_eq!(form_of(&app).child.as_ref().map(|c| c.kind.clone()), Some(Choice::Project));+ // The dropdown opens under the task, its text still in view.+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ let body = Rect::new(0, 0, 120, 36);+ draw(&mut Buffer::empty(body), body, &mut form);+ assert_eq!(form.child_area.y, form.task_area.bottom());+ app.modal = Some(Modal::NewHarness(form));+ press(&mut app, KeyCode::Esc);+ // Tab leaves it as Esc does: no chooser left behind the task.+ press(&mut app, KeyCode::Char('@'));+ press(&mut app, KeyCode::Tab);+ let f = form_of(&app);+ assert_eq!((f.focus, f.child.is_none(), f.child_active), (Field::Task, true, false));+ for ch in "a@b".chars() { press(&mut app, KeyCode::Char(ch)); }+ assert!(form_of(&app).child.is_none());+ assert_eq!(form_of(&app).draft.task, "fix the login a@b", "inside a word it is a letter");+ }++ #[tokio::test]+ async fn a_task_the_agent_cannot_take_names_it_and_a_reopened_form_is_on_the_task() {+ let mut app = app();+ open(&mut app, None, Some("/home/dev/project".into()));+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ set_engine(&mut form, "terminal");+ form.draft.what.label = "Terminal".into();+ assert_eq!(form.blocked(Field::Task).as_deref(), Some("Not available for Terminal"));+ set_engine(&mut form, "codex");+ form.focus = Field::Model;+ app.modal = Some(Modal::NewHarness(form));+ press(&mut app, KeyCode::Esc);+ assert!(app.modal.is_none());+ open(&mut app, None, None);+ let f = form_of(&app);+ assert_eq!((f.focus, f.child.is_none(), f.child_active), (Field::Task, true, false));+ }+#[tokio::test]async fn local_shell_entry_does_not_override_the_registered_launch_machine() {let mut app = app();@@ -2245,8 +2466,29 @@ mod tests {assert_eq!(form.draft.task, format!("{expected}\n"));}+ /// What the settle rewrite keeps as the form's overlay: the form, and the chooser dropped down+ /// from a field.#[tokio::test]- async fn compact_form_and_side_choosers_stay_anchored_at_every_terminal_size() {+ async fn the_drawn_area_takes_in_a_chooser() {+ let mut app = app();+ open(&mut app, None, None);+ let Some(Modal::NewHarness(mut form)) = app.modal.take() else { panic!() };+ let area = Rect::new(0, 0, 150, 42);+ draw(&mut Buffer::empty(area), area, &mut form);+ assert_eq!(form.drawn_area(), form.area, "no chooser: the form");+ form.focus = Field::Project;+ child(&mut app, &mut form, Choice::Project, "");+ form.child_active = true;+ draw(&mut Buffer::empty(area), area, &mut form);+ assert!(!form.child_area.is_empty(), "the chooser drops down");+ assert_eq!(form.drawn_area(), form.area.union(form.child_area));+ form.child = None;+ draw(&mut Buffer::empty(area), area, &mut form);+ assert_eq!(form.drawn_area(), form.area, "the chooser closed");+ }++ #[tokio::test]+ async fn compact_form_and_dropdown_choosers_stay_anchored_at_every_terminal_size() {let mut app = app();open(&mut app, None, None);let Some(Modal::NewHarness(mut form)) = app.modal.take() else {@@ -2260,7 +2502,10 @@ mod tests {let mut anchor = None;for engine in ["claude", "codex", "terminal"] {set_engine(&mut form, engine);- for chooser in [None, Some(Choice::Agent), Some(Choice::Clone), Some(Choice::Path), None] {+ let choosers = [None, Some(Choice::Agent), Some(Choice::Clone), Some(Choice::Path), None];+ // (Under the task, and under a field below it.)+ for (focus, chooser) in [Field::Task, Field::Agent].into_iter().flat_map(|f| choosers.clone().map(|c| (f, c))) {+ form.focus = focus;if let Some(kind) = chooser {let text = "/home/dev/项目";child(&mut app, &mut form, kind, text);@@ -2295,19 +2540,14 @@ mod tests {assert_eq!(form.area.intersection(area), form.area);}if form.child_area.width > 0 {+ assert!(active, "a chooser drops down only when entered");assert_eq!(form.child_area.intersection(area), form.child_area);- assert_eq!(form.child_area.y, form.area.y);- if form.child_area.x == form.area.x {- assert!(active, "narrow previews must leave the form visible");- assert_eq!(form.child_area, form.area);- } else {- assert_eq!(form.child_area.x, form.area.right() + 2);- assert!(form.child_area.width >= 32);+ assert_eq!(form.child_area.intersection(form.area), form.child_area, "inside the form: no side panel");+ if form.child_area != form.area && focus != Field::Task {+ assert!(form.task_area.intersection(form.child_area).is_empty(), "over the task in {area:?}");}}- if width >= 80 && height >= 24- && (form.child_area.is_empty() || form.child_area.x > form.area.x)- {+ if width >= 80 && height >= 24 && form.child_area != form.area {assert_eq!(form.hits.len(), form.fields().len(), "all settings stay visible");}}diff --git a/tui/src/new_harness/task/editor.rs b/tui/src/new_harness/task/editor.rsindex 9e7f8da32..f129ac35c 100644--- a/tui/src/new_harness/task/editor.rs+++ b/tui/src/new_harness/task/editor.rs@@ -182,7 +182,9 @@ impl Editor {if self.free_scroll { self.scroll = self.scroll.min(rows.len().saturating_sub(area.height as usize)); }else { self.scroll = self.scroll.min(row).max(row.saturating_sub(area.height as usize - 1)); }if text.is_empty() {- view::put(buf, area.x, area.y, area.width, "What task should this agent work on?", muted);+ // The scopes `@ : %` open, whole ones only, as the panel's query line shows its own.+ let ghost = crate::settings::whole_parts("What should it do? @ computer : project % model", area.width);+ view::put(buf, area.x, area.y, area.width, &ghost, muted);} else {for (dy, line) in rows.iter().skip(self.scroll).take(area.height as usize).enumerate() {view::put(buf, area.x, area.y + dy as u16, area.width, &line.text.replace('\t', " "), base);@@ -200,6 +202,18 @@ mod tests {assert!(editor.key(text, KeyEvent::new(code, modifiers), 8));}#[test]+ fn the_empty_task_names_its_scopes_whole() {+ let ghost = |w: u16| {+ let area = Rect::new(0, 0, w, 1);+ let mut buf = Buffer::empty(area);+ Editor::default().draw(&mut buf, area, "", false, Style::default(), Style::default());+ (0..w).map(|x| buf[(x, 0)].symbol()).collect::<String>().trim_end().to_string()+ };+ assert_eq!(ghost(60), "What should it do? @ computer : project % model");+ assert_eq!(ghost(40), "What should it do? @ computer");+ assert_eq!(ghost(20), "What should it do?");+ }+ #[test]fn editing_never_splits_a_grapheme_and_paste_preserves_newlines() {let mut editor = Editor::default();let mut text = String::new();diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rsindex 4471e05e3..9551bc84b 100644--- a/tui/src/new_harness/view.rs+++ b/tui/src/new_harness/view.rs@@ -1,5 +1,6 @@//! Terminal rendering of the compact desktop form.use super::*;+use ratatui::{text::{Line, Span}, widgets::{Block, Clear, Padding, Paragraph, StatefulWidget, Widget}};use unicode_segmentation::UnicodeSegmentation;// Keep the recovery instruction readable, including long project names and wide glyphs.@@ -72,29 +73,51 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {return None;}let page = matches!(form.surface, Surface::Window(_));- let crate::settings::Chrome { base, muted, accent, backdrop, .. } = crate::settings::chrome();+ let crate::settings::Chrome { base, muted, accent, backdrop, selected, .. } = crate::settings::chrome();if page {panel(buf, body, Style::default().bg(ratatui::style::Color::Reset).fg(ratatui::style::Color::Reset));} else { crate::settings::backdrop(buf, body, backdrop); }// Only the terminal's size changes this anchor. Task wrapping, history, and choosers do not.let r = crate::settings::area(body, crate::settings::PanelSize::Form, if page { 28 } else { HEIGHT });let (x, y, form_w, form_h) = (r.x, r.y, r.width, r.height);- let side_w = body.right().saturating_sub(r.right() + 4).min(60);- let side = side_w >= 32;- let child_w = if side { side_w } else { form_w };- let child_h = if side { body.bottom().saturating_sub(y + 1).min(22).max(form_h.min(22)) } else { form_h };let spacious = if page { form_h >= 27 } else { form_h >= HEIGHT };let task_h = if spacious { 3 } else if page && form_h >= 21 { 2 } else { 1 };let mut task_cursor = None;let fields_y = y + if spacious { if page { 4 } else { 3 } } else if form_h >= 9 { 2 } else { 1 };let live_error = task::error(&form.draft.what.engine, &form.draft.task);- let message = if form.error.is_empty() { live_error.as_deref().unwrap_or("") } else { &form.error };+ // (While a chooser is dropped down its error is in it, in place of its keys: not twice.)+ let dropped = form.child.is_some() && form.child_active;+ let message = if form.error.is_empty() || dropped { live_error.as_deref().unwrap_or("") } else { &form.error };let errors = error_lines(message, form_w.saturating_sub(4) as usize);let footer_h = if message.is_empty() { 2 } else { errors.len().max(2) as u16 }.min(r.bottom().saturating_sub(fields_y + 1 + u16::from(spacious)).max(1));let footer_y = r.bottom().saturating_sub(footer_h + u16::from(spacious));form.area = r;- if form.child.is_none() || side || !form.child_active {+ let capacity = footer_y.saturating_sub(fields_y);+ let mut row: u16 = 0;+ let mut recent_header = None;+ let rows: Vec<_> = form.fields().into_iter().map(|field| {+ if spacious && matches!(field, Field::Branch | Field::Create) { row += 1; }+ if page && field == Field::Browse {+ if spacious { row += 1; }+ recent_header = Some(row);+ }+ let at = row;+ row += if field == Field::Task { task_h } else if page && field == Field::Browse { 2 } else { 1 };+ (at, field)+ }).collect();+ let focus = rows.iter().find(|(_, field)| *field == form.focus).map(|(row, _)| *row).unwrap_or(0);+ let skip = focus.saturating_sub(capacity.saturating_sub(1));+ // An entered chooser drops down under its field (under the task's text when `@ : %` opened+ // it there). Where too few rows are left it covers the form, as it always did when narrow.+ let under = rows.iter().find(|(row, field)| *field == form.focus && *row >= skip && *row < skip + capacity)+ .map(|(row, field)| {+ let fy = fields_y + row - skip;+ fy + if *field == Field::Task { task_h.min(footer_y.saturating_sub(fy)) } else { 1 }+ });+ let chooser = form.child.as_ref().filter(|_| form.child_active)+ .map(|c| under.and_then(|at| dropdown(c, x + 1, at, form_w - 2, r.bottom() - 1)).unwrap_or(r));+ if chooser != Some(r) {panel(buf, r, base);if form_h >= 9 {let title = if page { if form.first_run { "Welcome to Harness" } else { "New Window" } } else { "New Harness" };@@ -103,21 +126,6 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {put(buf, x + 3, y + 2, form_w - 6, "Start a task. Your agent takes it from here.", muted);}}- let capacity = footer_y.saturating_sub(fields_y);- let mut row: u16 = 0;- let mut recent_header = None;- let rows: Vec<_> = form.fields().into_iter().map(|field| {- if spacious && matches!(field, Field::Branch | Field::Create) { row += 1; }- if page && field == Field::Browse {- if spacious { row += 1; }- recent_header = Some(row);- }- let at = row;- row += if field == Field::Task { task_h } else if page && field == Field::Browse { 2 } else { 1 };- (at, field)- }).collect();- let focus = rows.iter().find(|(_, field)| *field == form.focus).map(|(row, _)| *row).unwrap_or(0);- let skip = focus.saturating_sub(capacity.saturating_sub(1));if let Some(row) = recent_header.filter(|row| *row >= skip && *row < skip + capacity) {put(buf, x + 3, fields_y + row - skip, form_w.saturating_sub(12), &form.recent_status, muted);}@@ -157,16 +165,14 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {put(buf, value_x + name_width, fy, suffix_width, &suffix, st);} else { put(buf, value_x, fy, value_width, &format!("@ {}", form.machine_label), st); }} else if let Field::Recent(i) = field {- let st = if active {- if theme::fzf().bw { st.add_modifier(Modifier::REVERSED) }- else { st.bg(theme::fzf().bg_plus) }- } else { st };+ // The chosen row as the panel's lists mark it, as the welcome page's Recent does.+ let st = if active { selected } else { st };if active { panel(buf, Rect::new(x + 3, fy, form_w - 6, 1), st); }if let Some((title, detail)) = form.recent_labels.get(i) {let room = form_w - 6;let detail_w = if room >= 42 { (detail.width() as u16).min(22) } else { 0 };put(buf, x + 3, fy, room.saturating_sub(detail_w + u16::from(detail_w > 0)), title, st);- if detail_w > 0 { put(buf, r.right() - 3 - detail_w, fy, detail_w, detail, if active { accent } else { muted }); }+ if detail_w > 0 { put(buf, r.right() - 3 - detail_w, fy, detail_w, detail, if active { st.remove_modifier(Modifier::BOLD) } else { muted }); }}} else if !action { put(buf, value_x, fy, value_width, &value, st); }form.hits.push((Rect::new(x + 1, fy, form_w - 2, height), field));@@ -190,140 +196,131 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {}}}- if !side && !form.child_active {- return task_cursor;+ match chooser {+ Some(at) => draw_child(buf, at, form).or(task_cursor),+ None => task_cursor,+ }+}++/// The rows [c] wants: the query, the count rule, its list (a group's heading and the blank before+/// it count too) and the keys line, at most 12 — a path or a name being typed, the query and keys.+fn wanted(c: &Child) -> u16 {+ if c.kind.editing() { return 2 }+ (3 + crate::settings::list_lines(&c.picker)).min(12) as u16+}++/// Where an entered chooser drops down: at (x, y), [width] wide, as tall as it wants down to+/// [bottom]; None when fewer rows are left than its list (or its query and keys) needs.+pub(super) fn dropdown(c: &Child, x: u16, y: u16, width: u16, bottom: u16) -> Option<Rect> {+ let room = bottom.saturating_sub(y);+ (room >= if c.kind.editing() { 2 } else { 4 } && width > 0).then(|| Rect::new(x, y, width, wanted(c).min(room)))+}++/// An entered chooser, dropped down: on the panel's surface, the command panel's query line,+/// count rule, rows and keys line, as the shell composer draws them (the chooser's error in place+/// of its keys). A path or a name being typed has no list: its query and keys only. Rendered by+/// reference, it leaves the query's text cursor in [cursor].+pub(super) struct Dropdown<'a> {+ pub editing: bool,+ pub error: &'a str,+ pub chrome: crate::settings::Chrome,+ pub cursor: Option<Position>,+}++impl StatefulWidget for &mut Dropdown<'_> {+ type State = Picker;+ fn render(self, area: Rect, buf: &mut Buffer, picker: &mut Picker) {+ use ratatui::layout::{Constraint::{Fill, Length}, Layout};+ let c = &self.chrome;+ crate::term_out::clear_extras(area);+ Clear.render(area, buf);+ let surface = Block::new().style(c.base).padding(Padding::horizontal(1));+ let inner = surface.inner(area);+ surface.render(area, buf);+ picker.row_at.clear();+ // (Too short for a list: the query and keys only, as a path being typed has.)+ let list = !self.editing && inner.height >= 4;+ let rows = if list { Layout::vertical([Length(1), Length(1), Fill(1), Length(1)]).split(inner) }+ else { Layout::vertical([Length(1), Fill(1)]).split(inner) };+ // The query, rule, keys and rows are the command panel's own helpers, so the three+ // read as one list (and its rows report where they are drawn, for the mouse).+ let ghost = picker.placeholder.clone();+ let mut query = crate::settings::QueryLine::new(picker, &ghost, c);+ query.render(rows[0], buf);+ self.cursor = Some(query.cursor);+ let keys = rows[rows.len() - 1];+ if keys.height > 0 {+ if self.error.is_empty() {+ let what: &[(&str, &str)] = if list { &[("↑↓", "move"), ("enter", "choose"), ("esc", "back")] } else { &[("enter", "choose"), ("esc", "back")] };+ crate::settings::KeysLine { keys: what, chrome: c }.render(keys, buf);+ } else {+ Paragraph::new(Line::styled(self.error, c.base.patch(theme::fg(theme::DANGER)))).render(keys, buf);+ }+ }+ if !list { return }+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ // While it loads, the rule ends in what it waits for, as the shell composer's does.+ let wait = picker.busy.as_ref().map(|b| format!(" {} {b}", theme::spinner(0)));+ let room = wait.as_ref().map_or(0, |t| (t.width() as u16).min(rows[1].width / 2));+ let [rule, waiting] = Layout::horizontal([Fill(1), Length(room)]).areas(rows[1]);+ crate::settings::CountRule { shown: picker.visible.len(), total, marked: None, chrome: c }.render(rule, buf);+ if let Some(t) = wait { Paragraph::new(Span::styled(t, c.muted)).render(waiting, buf) }+ picker.page_rows.set(rows[2].height as i64);+ if picker.busy.is_none() || !picker.visible.is_empty() {+ crate::settings::list_from(buf, picker, rows[2], c, true, false);+ }}- let r = Rect::new(if side { x + form_w + 2 } else { x }, y, child_w, child_h);- draw_child(buf, r, form).or(task_cursor)}pub(super) fn draw_child(buf: &mut Buffer, r: Rect, form: &mut Form) -> Option<Position> {let Some(c) = &mut form.child else { return None };- let crate::settings::Chrome { base, muted, accent, .. } = crate::settings::chrome();form.child_area = r;- panel(buf, r, base);- let query_x = r.x + 4;- let query_y = r.y + 2;- let query_w = r.width.saturating_sub(6) as usize;- put(buf, r.x + 2, query_y, 1, "›", accent);- let chars: Vec<_> = c.picker.query.chars().collect();- let at = c.picker.qcursor.min(chars.len());- let mut from = at;- let mut width = 0;- while from > 0 && width + chars[from - 1].width().unwrap_or(0) < query_w {- from -= 1;- width += chars[from].width().unwrap_or(0);- }- let query: String = chars[from..].iter().collect();- put(- buf,- query_x,- query_y,- query_w as u16,- if query.is_empty() {- &c.picker.placeholder- } else {- &query- },- if query.is_empty() { muted } else { base },- );- c.picker.row_at.clear();- if !c.kind.editing() {- // Project's blank line between folder actions and recents occupies a display row too.- // Reserve it in the scroll window so the selected item cannot hide under the footer.- let separated = c.kind == Choice::Project && c.picker.query.is_empty()- && c.picker.visible.windows(2).any(|pair| {- !c.picker.rows[pair[0].0].id.starts_with("at:")- && c.picker.rows[pair[1].0].id.starts_with("at:")- });- let rows = r.height.saturating_sub(6 + u16::from(separated)) as usize;- c.picker.page_rows.set(rows as i64);- c.picker.scroll = c- .picker- .scroll- .min(c.picker.cursor)- .max(c.picker.cursor.saturating_sub(rows.saturating_sub(1)));- if c.picker.visible.is_empty() {- put(- buf,- r.x + 3,- r.y + 3,- r.width - 6,- c.picker.busy.as_deref().unwrap_or(&c.picker.empty),- muted,- );- }- let mut separator = 0;- for (row, (index, _)) in c- .picker- .visible- .iter()- .enumerate()- .skip(c.picker.scroll)- .take(rows)- {- if c.kind == Choice::Project- && c.picker.query.is_empty()- && c.picker.rows[*index].id.starts_with("at:")- && row > 0- && !c.picker.rows[c.picker.visible[row - 1].0]- .id- .starts_with("at:")- {- separator = 1;- }- let at_y = r.y + 4 + (row - c.picker.scroll) as u16 + separator;- if at_y >= r.bottom() - 2 {- break;+ let mut dropdown = Dropdown { editing: c.kind.editing(), error: &form.error, chrome: crate::settings::chrome(), cursor: None };+ (&mut dropdown).render(r, buf, &mut c.picker);+ dropdown.cursor.filter(|_| form.child_active)+}++/// The dropdown as it was drawn (2026-10-08), on the command panel's hand-drawn lines, kept so the+/// widgets that replaced those lines can be shown to draw the very same buffer.+#[cfg(test)]+pub(super) mod oracle {+ use super::*;++ pub fn render(d: &mut Dropdown<'_>, area: Rect, buf: &mut Buffer, picker: &mut Picker) {+ use ratatui::layout::{Constraint::{Fill, Length}, Layout};+ let c = &d.chrome;+ crate::term_out::clear_extras(area);+ Clear.render(area, buf);+ let surface = Block::new().style(c.base).padding(Padding::horizontal(1));+ let inner = surface.inner(area);+ surface.render(area, buf);+ picker.row_at.clear();+ // (Too short for a list: the query and keys only, as a path being typed has.)+ let list = !d.editing && inner.height >= 4;+ let rows = if list { Layout::vertical([Length(1), Length(1), Fill(1), Length(1)]).split(inner) }+ else { Layout::vertical([Length(1), Fill(1)]).split(inner) };+ let ghost = picker.placeholder.clone();+ let (at, _) = crate::settings::oracle::query_line(buf, picker, rows[0].x, rows[0].y, rows[0].width, &ghost, c);+ d.cursor = Some(at);+ let keys = rows[rows.len() - 1];+ if keys.height > 0 {+ if d.error.is_empty() {+ let what: &[(&str, &str)] = if list { &[("↑↓", "move"), ("enter", "choose"), ("esc", "back")] } else { &[("enter", "choose"), ("esc", "back")] };+ crate::settings::oracle::keys_line(buf, what, keys.x, keys.y, keys.width, c);+ } else {+ Paragraph::new(Line::styled(d.error, c.base.patch(theme::fg(theme::DANGER)))).render(keys, buf);}- let selected = row == c.picker.cursor;- put(- buf,- r.x + 1,- at_y,- 1,- if selected { "›" } else { " " },- accent,- );- put(- buf,- r.x + 3,- at_y,- r.width - 6,- &c.picker.rows[*index].label,- if c.picker.rows[*index].disabled {- muted- } else if selected {- accent- } else {- base- },- );- c.picker.row_at.push((at_y, row));}- let total = c.picker.visible.len();- if total > rows && rows > 0 {- let thumb = (rows * rows / total).max(1);- let top = (rows - thumb) * c.picker.scroll / (total - rows);- for dy in top..top + thumb {- put(buf, r.right() - 2, r.y + 4 + dy as u16, 1, "│", muted);- }+ if !list { return }+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ let wait = picker.busy.as_ref().map(|b| format!(" {} {b}", theme::spinner(0)));+ let room = wait.as_ref().map_or(0, |t| (t.width() as u16).min(rows[1].width / 2));+ let [rule, waiting] = Layout::horizontal([Fill(1), Length(room)]).areas(rows[1]);+ crate::settings::oracle::count_rule(buf, picker.visible.len(), total, None, rule.x, rule.y, rule.width, c);+ if let Some(t) = wait { Paragraph::new(Span::styled(t, c.muted)).render(waiting, buf) }+ picker.page_rows.set(rows[2].height as i64);+ if picker.busy.is_none() || !picker.visible.is_empty() {+ crate::settings::list_from(buf, picker, rows[2], c, true, false);}}- let hint = if !form.error.is_empty() {- &form.error- } else {- c.picker.busy.as_deref().unwrap_or(if form.child_active {- "Enter select · Esc back"- } else {- "Enter or → to choose"- })- };- put(buf, r.x + 2, r.bottom() - 2, r.width - 4, hint, muted);- form.child_active.then(|| {- Position::new(- query_x + (width as u16).min(r.width.saturating_sub(7)),- query_y,- )- })}diff --git a/tui/src/new_harness/welcome.rs b/tui/src/new_harness/welcome.rsindex 2b4e4309d..7fdfaed3f 100644--- a/tui/src/new_harness/welcome.rs+++ b/tui/src/new_harness/welcome.rs@@ -282,7 +282,7 @@ mod tests {let mut buf=Buffer::empty(area);draw(&mut buf,&mut app,area);let text=(0..h).map(|y|(0..w).map(|x|buf[(x,y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n");- for expected in ["What task should this agent work on?","New Harness","All","New Terminal","Recent task"] {+ for expected in ["What should it do?","New Harness","All","New Terminal","Recent task"] {assert!(text.contains(expected),"{w}x{h} missing {expected}: {text}");}for removed in ["machines connected", " Task ", "Browse All Harnesses", "Open Terminal", "Enter start", "Task is optional"] {@@ -300,6 +300,66 @@ mod tests {}}+ #[tokio::test]+ async fn the_welcome_chooser_drops_down_under_the_settings_and_leaves_the_task_in_view() {+ let mut app = app();+ ensure(&mut app, None, Some("/work/project".into()));+ let tab = app.tab().id.clone();+ let mut form = take_active(&mut app).unwrap();+ form.focus = Field::Project;+ child(&mut app, &mut form, Choice::Project, "");+ store_form(&mut app, form);+ let area = Rect::new(0, 0, 120, 40);+ let mut buf = Buffer::empty(area);+ draw(&mut buf, &mut app, area);+ assert!(app.welcome.forms[&tab].child_area.is_empty(), "not entered yet: nothing drops down");+ app.welcome.forms.get_mut(&tab).unwrap().child_active = true;+ draw(&mut buf, &mut app, area);+ let form = &app.welcome.forms[&tab];+ let chips = form.hits.iter().find(|(_, f)| *f == Field::Model).unwrap().0;+ assert_eq!((form.child_area.x, form.child_area.y), (form.area.x, chips.y + 1), "under the settings row");+ assert_eq!(form.child_area.width, form.area.width.min(60));+ assert!(form.task_area.intersection(form.child_area).is_empty(), "the task box stays visible");+ assert_eq!(buf[(form.child_area.x + 1, form.child_area.y)].symbol(), "›");+ }++ #[tokio::test]+ async fn the_welcome_task_box_says_when_the_agent_takes_no_task() {+ let mut app = app();+ ensure(&mut app, None, None);+ let mut form = take_active(&mut app).unwrap();+ set_engine(&mut form, "terminal");+ form.draft.what.label = "Terminal".into();+ form.focus = Field::Task;+ store_form(&mut app, form);+ let area = Rect::new(0, 0, 120, 40);+ let mut buf = Buffer::empty(area);+ draw(&mut buf, &mut app, area);+ let text = (0..40).map(|y| (0..120).map(|x| buf[(x, y)].symbol()).collect::<String>()).collect::<Vec<_>>().join("\n");+ assert!(text.contains("Not available for Terminal"), "{text}");+ assert!(!text.contains("What should it do?"), "{text}");+ }++ #[tokio::test]+ async fn a_chosen_recent_row_on_the_small_page_uses_the_panels_chosen_row() {+ let _l = crate::term_out::colours_lock();+ let mut app = app();+ ensure(&mut app, None, Some("/work/project".into()));+ let mut form = take_active(&mut app).unwrap();+ form.recent = (0..3).map(|i| HomeRow::Harness("local".into(), format!("{i}"))).collect();+ form.recent_labels = (0..3).map(|i| (format!("Previous work {i}"), "office · app".into())).collect();+ form.focus = Field::Recent(1);+ let area = Rect::new(0, 0, 50, 30);+ let mut buf = Buffer::empty(area);+ view::draw(&mut buf, area, &mut form);+ let row = form.hits.iter().find(|(_, f)| *f == Field::Recent(1)).unwrap().0;+ let c = crate::settings::chrome();+ let cell = &buf[(row.x + 2, row.y)];+ assert_eq!(cell.symbol(), "P");+ assert_eq!(cell.bg, c.selected.bg.unwrap_or(ratatui::style::Color::Reset));+ assert!(cell.modifier.contains(c.selected.add_modifier));+ }+#[tokio::test]async fn machine_header_scopes_projects_and_remembers_each_destinations_folder() {let mut app = app();@@ -626,6 +686,49 @@ mod tests {assert_eq!(form.focus, Field::Browse);}+ /// A bare app with three agents, the page on `focus`, and the key pressed.+ fn press_on(focus: Field, code: KeyCode) -> (App, String) {+ let mut app = app();+ for i in 0..3 {+ let a = crate::fleet::agent_from("local", &json!({"id":format!("{i}"), "name":format!("Work {i}"), "engine":"codex"}), None);+ app.fleet.agents.insert(a.key(), a);+ }+ ensure(&mut app, None, Some("/work/project".into()));+ let tab = app.tab().id.clone();+ let mut form = take_active(&mut app).unwrap();+ prepare(&app, &mut form);+ form.focus = focus;+ store_form(&mut app, form);+ event(&mut app, code, KeyModifiers::NONE);+ (app, tab)+ }++ #[tokio::test]+ async fn right_opens_a_recent_row_and_left_goes_back_to_the_task() {+ let (app, tab) = press_on(Field::Recent(1), KeyCode::Left);+ assert_eq!(app.welcome.forms[&tab].focus, Field::Task);+ assert!(app.tab().home, "← opens nothing");+ // Enter is the reference: whatever it does to the app, → does the same.+ let (enter, etab) = press_on(Field::Recent(1), KeyCode::Enter);+ let (right, rtab) = press_on(Field::Recent(1), KeyCode::Right);+ assert!(!enter.tab().home && !right.tab().home, "the harness opened, so the page is left");+ assert_eq!((right.tab().home, right.welcome.forms.contains_key(&rtab)),+ (enter.tab().home, enter.welcome.forms.contains_key(&etab)));+ assert!(right.welcome.forms.get(&rtab).is_none_or(|f| f.child.is_none() && !f.child_active),+ "→ on a row never leaves an empty chooser open");+ }++ #[tokio::test]+ async fn right_on_browse_and_terminal_does_what_enter_does() {+ for field in [Field::Browse, Field::Terminal] {+ let (enter, etab) = press_on(field, KeyCode::Enter);+ let (right, rtab) = press_on(field, KeyCode::Right);+ assert_eq!(right.welcome.forms.contains_key(&rtab), enter.welcome.forms.contains_key(&etab), "{field:?}");+ assert!(right.welcome.forms.get(&rtab).is_none_or(|f| f.child.is_none() && !f.child_active),+ "{field:?}: → leaves no empty chooser");+ }+ }+#[tokio::test]async fn closing_a_pending_window_preserves_its_receipt_and_the_other_dialog_draft() {let mut app = app();diff --git a/tui/src/new_harness/welcome_view.rs b/tui/src/new_harness/welcome_view.rsindex 4dae92a92..da4136707 100644--- a/tui/src/new_harness/welcome_view.rs+++ b/tui/src/new_harness/welcome_view.rs@@ -2,7 +2,7 @@//! same recent sessions. All controls use the existing form and launch receipt.use super::*;use crate::input::HomeRow;-use ratatui::{style::Color, widgets::{Block, BorderType, Widget}};+use ratatui::{style::Color, widgets::{Block, BorderType, Paragraph, Widget}};struct Chip { field: Field, text: String, x: u16, width: u16 }fn settings(form: &Form, width: u16) -> Vec<Chip> {@@ -103,8 +103,14 @@ pub(super) fn draw(buf: &mut Buffer, app: &App, body: Rect, form: &mut Form) ->.style(chrome.base).border_style(if form.focus == Field::Task { accent } else { muted }).render(task_box, buf);form.task_area = Rect::new(x + 3, y + 1, width - 6, task_box.height - 3);- let cursor = form.task_editor.draw(buf, form.task_area, &form.draft.task,- form.focus == Field::Task && !form.child_active && !form.starting && form.attempt.is_none(), chrome.base, chrome.muted);+ // An agent that takes no task says so where the task goes, as the form page does.+ let cursor = if let Some(blocked) = form.blocked(Field::Task) {+ Paragraph::new(ratatui::text::Line::styled(blocked, chrome.muted)).render(form.task_area, buf);+ None+ } else {+ form.task_editor.draw(buf, form.task_area, &form.draft.task,+ form.focus == Field::Task && !form.child_active && !form.starting && form.attempt.is_none(), chrome.base, chrome.muted)+ };let action = if form.starting || form.attempt.is_some() { form.describe(Field::Create).0 } else { "New Harness".into() };let button = format!("[ {action} ]");let button_w = (button.width() as u16).min(width - 6);@@ -119,9 +125,12 @@ pub(super) fn draw(buf: &mut Buffer, app: &App, body: Rect, form: &mut Form) ->let style = if form.blocked(chip.field).is_some() { muted } else { plain };control(buf, form, Rect::new(x + chip.x, y, chip.width, 1), chip.field, &chip.text, style, accent);}+ let chips_y = y;y += settings_h;let live_error = task::error(&form.draft.what.engine, &form.draft.task);- let error = if form.error.is_empty() { live_error.as_deref().unwrap_or("") } else { &form.error };+ // (While a chooser is dropped down its error is in it, in place of its keys: not twice.)+ let dropped = form.child.is_some() && form.child_active;+ let error = if form.error.is_empty() || dropped { live_error.as_deref().unwrap_or("") } else { &form.error };let footer_y = rect.bottom() - 1;let recent_bottom = footer_y.saturating_sub(section_gap);let latest_heading_y = recent_bottom.saturating_sub(2);@@ -183,14 +192,12 @@ pub(super) fn draw(buf: &mut Buffer, app: &App, body: Rect, form: &mut Form) ->}control(buf, form, Rect::new(x, footer_y, 12, 1), Field::Terminal, "New Terminal", muted, accent);- if form.child.is_some() {- let side_w = body.right().saturating_sub(rect.right() + 3).min(60);- let side = side_w >= 32;- if side || form.child_active {- let child = Rect::new(if side { rect.right() + 2 } else { x }, controls_y,- if side { side_w } else { width }, body.bottom().saturating_sub(controls_y).min(22));- return view::draw_child(buf, child, form).or_else(|| (!form.child_active).then_some(cursor).flatten());- }+ // An entered chooser drops down under the settings row, the task box above it still in view;+ // where too few rows are left it covers the page from the controls down.+ if let Some(c) = form.child.as_ref().filter(|_| form.child_active) {+ let child = view::dropdown(c, x, chips_y + 1, width.min(60), body.bottom()).unwrap_or_else(||+ Rect::new(x, controls_y, width, body.bottom().saturating_sub(controls_y).min(22)));+ return view::draw_child(buf, child, form);}cursor}diff --git a/tui/src/options/mod.rs b/tui/src/options/mod.rsindex 859aaff90..b9c30b311 100644--- a/tui/src/options/mod.rs+++ b/tui/src/options/mod.rs@@ -142,21 +142,25 @@ pub fn defaults() -> &'static BTreeMap<String, String> {})}-/// What a tab shows unless `@hn-window-name` says otherwise: the selected pane's title (`pane`), or-/// auto rename's name for the window. (No longer a choice in Appearance; `tmux` from a tmux.conf or-/// an older tui.toml still shows the window's name.)-pub const DEFAULT_TAB_NAME: &str = "pane";--/// The status bar's per-window text. [name] is the tab name source (`tmux` = the window's short-/// name, `pane` = the window's full name); [star] is whether the window you are on is marked `*`-/// (`false` for a filled tab, which needs no `*` beside its name).+/// What a tab shows unless `@hn-window-name` says otherwise (Appearance › Tab names): its name cut+/// to [TAB_NAME_COLS] columns with `…` (`short`), or whole (`full`). (`pane`, an older tui.toml's+/// word, reads as `short`; `tmux` from a tmux.conf shows the window's own short name.)+pub const DEFAULT_TAB_NAME: &str = "short";++/// The columns a `short` tab name keeps (as tmux's window names are short).+pub const TAB_NAME_COLS: usize = 20;++/// The status bar's per-window text. [name] is how the tab's name is shown (`short` | `full` |+/// `tmux`); [star] is whether the window you are on is marked `*` (`false` for a filled tab, which+/// needs no `*` beside its name). No `-` for the window used before: tmux's last-window flag says+/// nothing hn's tabs need.pub fn status_window_format(name: &str, star: bool) -> String {- // `tmux` keeps hn's window name, `pane` the active pane's own title (a harness's task, not the- // window's auto-renamed name) — the two can differ, which is the point of the option. A window- // auto rename has named (its repo and its work) shows that name either way, whole: it is four- // words at most already.- let name_part = if name == "pane" { "#{?window_auto_named,#{window_name},#{pane_title}}" } else { "#{?window_auto_named,#{window_name},#{window_short_name}}" };- let mark = if star { "#{?window_active,*,#{?window_last_flag,-,}}" } else { "#{?window_last_flag,-,}" };+ // The active pane's own title (a harness's task), or the name auto rename gave the window (its+ // repo and its work); `tmux` the window's own name.+ let cut = |var: &str| if name == "full" { format!("#{{{var}}}") } else { format!("#{{=/{TAB_NAME_COLS}/…:{var}}}") };+ let name_part = if name == "tmux" { "#{?window_auto_named,#{window_name},#{window_short_name}}".to_string() }+ else { format!("#{{?window_auto_named,{},{}}}", cut("window_name"), cut("pane_title")) };+ let mark = if star { "#{?window_active,*,}" } else { "" };// (Two closing braces: the idle test's and the icon's. With one, the icon never showed.)format!("#I:{name_part}{mark}#{{s/[*-]//:window_flags}}#{{?#{{==:#{{window_agent_state}},idle}},,#{{?window_agent_icon, #{{window_agent_icon}},}}}}")}diff --git a/tui/src/pane_drag.rs b/tui/src/pane_drag.rsnew file mode 100644index 000000000..bc3e0a567--- /dev/null+++ b/tui/src/pane_drag.rs@@ -0,0 +1,570 @@+//! Where a dragged pane would land: the pointer over the screen -> what releasing there does.+use ratatui::{buffer::Buffer, layout::{Constraint, Layout, Position, Rect}, style::{Color, Modifier, Style}, text::Line, widgets::{Block, Widget}};+use unicode_width::UnicodeWidthStr;+use crate::{app::App, bar::Hit, draw::RangeKind, layout::Dir, theme};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Side { Left, Right, Top, Bottom }++/// A tab is named by its id (`Tab.id`), not its index: a desk update mid-drag can renumber the tabs.+#[derive(Clone, Debug, PartialEq, Eq)]+pub enum Drop { Swap(u64), Beside(u64, Side), Tab(String), Nothing }++/// The cells of tab [i] in the side bar, else its status-bar range.+pub fn tab_cell(app: &App, i: usize) -> Option<Rect> {+ if app.bar_side().is_some() {+ return app.bar.hits.iter().find(|(_, h)| *h == Hit::Window(i)).map(|(r, _)| *r);+ }+ let number = app.win_num(i) as u64;+ let top = if app.status_top { 0 } else { app.size.1.saturating_sub(app.status_lines()) };+ app.status_ranges.iter().find(|(_, r)| matches!(r.kind, RangeKind::Window(n) if n == number))+ .map(|(row, r)| Rect::new(r.start, top + row, r.end.saturating_sub(r.start), 1))+}++/// The tab under (x, y). A machine heading in the side bar is not one.+fn tab_at(app: &App, x: u16, y: u16) -> Option<usize> {+ if app.bar_side().is_some() {+ return match crate::bar::hit_at(app, x, y) { Some(Hit::Window(i)) => Some(i), _ => None };+ }+ (0..app.tabs.len()).find(|i| tab_cell(app, *i).is_some_and(|r| r.contains(Position { x, y })))+}++/// [x, y] over the screen while pane [src] is dragged: what releasing there does.+pub fn drop_target(app: &App, src: u64, x: u16, y: u16) -> Drop {+ if let Some(i) = tab_at(app, x, y) {+ return if i == app.active { Drop::Nothing } else { Drop::Tab(app.tabs[i].id.clone()) };+ }+ let Some((id, r)) = app.rects.iter().find(|(_, r)| r.contains(Position { x, y })).copied() else { return Drop::Nothing };+ if id == src { return Drop::Nothing }+ let (bx, by) = ((r.width / 4).max(1), (r.height / 4).max(1));+ let (dl, dr, dt, db) = (x - r.x, r.right() - 1 - x, y - r.y, r.bottom() - 1 - y);+ // the nearest edge band wins (distance as a share of the band); outside every band, the middle swaps+ let near = [(dl, bx, Side::Left), (dr, bx, Side::Right), (dt, by, Side::Top), (db, by, Side::Bottom)]+ .into_iter().filter(|(d, b, _)| d < b).min_by_key(|(d, b, _)| *d as u32 * 1000 / *b as u32);+ let Some((_, _, side)) = near else { return Drop::Swap(id) };+ // Already there (its neighbour on that side, in the same split): join-pane would only halve [id].+ let (dir, before) = match side { Side::Left => (Dir::Horizontal, true), Side::Right => (Dir::Horizontal, false), Side::Top => (Dir::Vertical, true), Side::Bottom => (Dir::Vertical, false) };+ if app.tab().root.as_ref().and_then(|root| root.neighbour(id, dir, before)) == Some(src) { return Drop::Nothing }+ Drop::Beside(id, side)+}++/// The cells that show [drop]: the zone of the target pane (a side half or the whole pane) or the tab's cells.+pub fn zone(app: &App, drop: &Drop) -> Option<Rect> {+ let pane = |id: &u64| app.rects.iter().find(|(i, _)| i == id).map(|(_, r)| *r);+ match drop {+ Drop::Nothing => None,+ Drop::Swap(id) => pane(id),+ Drop::Beside(id, side) => pane(id).map(|r| {+ let (w, h) = (r.width / 2, r.height / 2);+ match side {+ Side::Left => Rect::new(r.x, r.y, w, r.height),+ Side::Right => Rect::new(r.x + w, r.y, r.width - w, r.height),+ Side::Top => Rect::new(r.x, r.y, r.width, h),+ Side::Bottom => Rect::new(r.x, r.y + h, r.width, r.height - h),+ }+ }),+ Drop::Tab(tab) => app.tabs.iter().position(|t| t.id == *tab).and_then(|i| tab_cell(app, i)),+ }+}++/// The held pane follows the pointer: a drag once it moved 2 cells from the press, a click until then.+pub fn follow(app: &mut App, x: u16, y: u16) {+ let_go_if_gone(app);+ let Some(grab) = &app.controls.grab else { return };+ let (pane, live) = (grab.pane, grab.moved(x, y));+ let drop = if live { drop_target(app, pane, x, y) } else { Drop::Nothing };+ if let Some(grab) = &mut app.controls.grab { grab.live = live; grab.drop = drop; }+}++/// A held pane closed (or its window emptied) mid-drag is let go: its release may never reach+/// the header press (a welcome screen in its place takes it).+pub fn let_go_if_gone(app: &mut App) {+ let Some(pane) = app.controls.grab.as_ref().map(|g| g.pane) else { return };+ if app.panes.contains_key(&pane) && app.tabs.iter().any(|t| t.panes().contains(&pane)) { return }+ cancel(app);+}++/// What the zone says, in a few words.+fn hint(app: &App, drop: &Drop) -> Option<String> {+ let name = |id: &u64| app.panes.get(id).and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id)).map(|a| a.name.clone());+ match drop {+ Drop::Nothing => None,+ Drop::Swap(id) => Some(format!("swap with {}", name(id)?)),+ Drop::Beside(id, side) => {+ let word = match side { Side::Left => "left of", Side::Right => "right of", Side::Top => "above", Side::Bottom => "below" };+ Some(format!("{word} {}", name(id)?))+ }+ Drop::Tab(tab) => app.tabs.iter().find(|t| t.id == *tab).map(|t| format!("to {}", t.name)),+ }+}++/// The zone a dragged pane will land in: tinted (what is under it stays) with a hint on its middle row.+pub struct DropZone<'a> { hint: Option<&'a str>, tint: Style }++impl<'a> DropZone<'a> {+ /// [reverse] is the cue for NO_COLOR, which paints no colour at all. (Underlined too: NO_COLOR's+ /// status bar is reversed already, so a tab reversed again would show nothing.)+ pub fn new(hint: Option<&'a str>, bg: Color, fg: Color, reverse: bool) -> Self {+ let tint = Style::new().bg(bg).fg(fg);+ DropZone { hint, tint: if reverse { tint.add_modifier(Modifier::REVERSED | Modifier::UNDERLINED) } else { tint } }+ }+}++impl Widget for DropZone<'_> {+ /// The hint is centred and cut to the zone; a zone of one row (a tab) keeps its own label+ /// unless the whole hint fits.+ fn render(self, zone: Rect, buf: &mut Buffer) {+ let zone = zone.intersection(buf.area);+ Block::new().style(self.tint).render(zone, buf);+ let Some(text) = self.hint else { return };+ let width = text.width() as u16;+ if zone.height == 1 && width > zone.width { return }+ let [_, middle, _] = Layout::vertical([Constraint::Length(zone.height / 2), Constraint::Length(1), Constraint::Fill(1)]).areas(zone);+ let [_, hint] = Layout::horizontal([Constraint::Length(zone.width.saturating_sub(width) / 2), Constraint::Fill(1)]).areas(middle);+ Line::raw(text).render(hint, buf);+ }+}++/// While a pane is dragged: the zone it will land in, in the theme's accent, with a hint.+pub fn draw(buf: &mut Buffer, app: &App) {+ let Some(grab) = app.controls.grab.as_ref().filter(|g| g.live) else { return };+ let Some(zone) = zone(app, &grab.drop) else { return };+ // (NO_COLOR paints nothing, so the zone is drawn reversed instead.)+ let (bg, fg) = (theme::paint(theme::accent()), theme::paint(theme::pane_palette().background));+ DropZone::new(hint(app, &grab.drop).as_deref(), bg, fg, theme::no_color()).render(zone, buf);+}++/// What releasing pane [src] over [drop] does: tmux's own swap-pane / join-pane, so the layout+/// reaches the desk and every other client as those commands' does. Another client may have+/// moved or closed either pane while it was dragged: then nothing happens. The held pane keeps+/// the focus wherever it lands (join-pane focuses it; after swap-pane it is selected again).+pub fn release(app: &mut App, src: u64, drop: Drop) {+ let home = |app: &App, id: u64| if app.panes.contains_key(&id) { app.tabs.iter().position(|t| t.panes().contains(&id)) } else { None };+ let Some(from) = home(app, src) else { return };+ let tag = crate::pane::tag;+ let command = match drop {+ Drop::Swap(dst) if dst != src && home(app, dst).is_some() => format!("swap-pane -s {0} -t {1} ; select-pane -t {0}", tag(src), tag(dst)),+ Drop::Beside(dst, side) if dst != src && home(app, dst).is_some() => {+ let flags = match side { Side::Left => "-h -b", Side::Right => "-h", Side::Top => "-v -b", Side::Bottom => "-v" };+ format!("join-pane {flags} -s {} -t {}", tag(src), tag(dst))+ }+ // (`:N` is that window's active pane, as join-pane -t :N is in tmux.)+ Drop::Tab(id) => match app.tabs.iter().position(|t| t.id == id).filter(|i| *i != from) {+ Some(i) => format!("join-pane -s {} -t :{}", tag(src), app.win_num(i)),+ None => return,+ },+ _ => return,+ };+ crate::commands::execute(app, &command);+}++/// Escape: the pane is let go where it was.+pub fn cancel(app: &mut App) {+ if app.controls.grab.take().is_some_and(|g| g.live) { app.redraw_all = true; }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::layout::Dir;+ use crate::workspace_controls::tests::{app, render};++ /// Panes 1 | 2 side by side in one window (pane 2's own window is gone).+ fn two() -> App {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, Dir::Horizontal);+ app.fit_panes();+ render(&mut app);+ app+ }++ fn rect(app: &App, id: u64) -> Rect { app.rects.iter().find(|(i, _)| *i == id).unwrap().1 }++ #[tokio::test]+ async fn the_middle_swaps_the_outer_quarter_puts_beside_itself_is_nothing() {+ let app = two();+ assert_eq!(app.rects.len(), 2, "this test needs both panes laid out");+ let r2 = rect(&app, 2);+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.y + r2.height / 2), Drop::Swap(2));+ // (1 is already left of 2: see the test below)+ assert_eq!(drop_target(&app, 1, r2.x + 1, r2.y + r2.height / 2), Drop::Nothing);+ assert_eq!(drop_target(&app, 1, r2.right() - 2, r2.y + r2.height / 2), Drop::Beside(2, Side::Right));+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.y + 1), Drop::Beside(2, Side::Top));+ assert_eq!(drop_target(&app, 1, r2.x + r2.width / 2, r2.bottom() - 2), Drop::Beside(2, Side::Bottom));+ let r1 = rect(&app, 1);+ assert_eq!(drop_target(&app, 1, r1.x + 3, r1.y + 3), Drop::Nothing);+ }++ #[tokio::test]+ async fn beside_a_pane_on_the_side_it_already_is_is_nothing() {+ // 1 | 2: 1 is already left of 2, 2 already right of 1 (join-pane would only halve the target)+ let side = two();+ let (r1, r2) = (rect(&side, 1), rect(&side, 2));+ assert_eq!(drop_target(&side, 1, r2.x + 1, r2.y + r2.height / 2), Drop::Nothing);+ assert_eq!(drop_target(&side, 2, r1.right() - 2, r1.y + r1.height / 2), Drop::Nothing);+ assert_eq!(drop_target(&side, 2, r1.x + 1, r1.y + r1.height / 2), Drop::Beside(1, Side::Left), "the far side is a move");+ // 1 over 2+ let mut stack = app(100);+ stack.tabs.truncate(1);+ stack.tabs[0].root.as_mut().unwrap().split(1, 2, Dir::Vertical);+ stack.fit_panes(); render(&mut stack);+ let (r1, r2) = (rect(&stack, 1), rect(&stack, 2));+ assert_eq!(drop_target(&stack, 1, r2.x + r2.width / 2, r2.y + 1), Drop::Nothing);+ assert_eq!(drop_target(&stack, 2, r1.x + r1.width / 2, r1.bottom() - 2), Drop::Nothing);+ assert_eq!(drop_target(&stack, 1, r2.x + r2.width / 2, r2.bottom() - 2), Drop::Beside(2, Side::Bottom), "below 2 is a move");+ // 1 | 2 | 3: left of 3 is a move for 1 (2 is between them), not for 2+ let mut row = three(120);+ render(&mut row);+ let r3 = rect(&row, 3);+ assert_eq!(drop_target(&row, 1, r3.x + 1, r3.y + r3.height / 2), Drop::Beside(3, Side::Left));+ assert_eq!(drop_target(&row, 2, r3.x + 1, r3.y + r3.height / 2), Drop::Nothing);+ }++ #[test]+ fn under_no_color_the_zone_shows_on_an_already_reversed_cell() {+ // NO_COLOR draws the status bar reversed: reversing a tab's cells again would show nothing.+ let mut buf = Buffer::empty(Rect::new(0, 0, 10, 1));+ buf.set_string(0, 0, "1:work", Style::new().add_modifier(Modifier::REVERSED));+ let before = buf.clone();+ DropZone::new(Some("to work"), Color::Reset, Color::Reset, true).render(Rect::new(0, 0, 6, 1), &mut buf);+ for x in 0..6 { assert_ne!(look(&buf, x, 0), look(&before, x, 0), "cell {x} of the tab shows the zone"); }+ }++ #[tokio::test]+ async fn outside_every_pane_is_nothing() {+ let app = two();+ assert_eq!(drop_target(&app, 1, 500, 500), Drop::Nothing);+ }++ #[tokio::test]+ async fn a_tab_in_the_status_bar_is_a_target_and_the_current_tab_is_not() {+ let mut app = app(100); // window 1 holds pane 1, window 2 pane 2+ render(&mut app); // fills app.status_ranges+ assert!(app.status_lines() > 0 && app.bar_side().is_none(), "this test needs the status bar");+ let other = tab_cell(&app, 1).expect("the other tab has a range");+ assert_eq!(drop_target(&app, 1, other.x, other.y), Drop::Tab(app.tabs[1].id.clone()));+ let here = tab_cell(&app, 0).expect("this tab has a range");+ assert_eq!(drop_target(&app, 1, here.x, here.y), Drop::Nothing);+ assert_eq!(zone(&app, &Drop::Tab(app.tabs[1].id.clone())), Some(other));+ }++ #[tokio::test]+ async fn a_tab_in_the_side_bar_is_a_target() {+ let mut app = app(100);+ app.options.set("@hn-status-bar", Some("left"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes();+ render(&mut app);+ assert!(app.bar_side().is_some(), "this test needs the side bar");+ let other = tab_cell(&app, 1).expect("the side bar lists the other tab");+ assert_eq!(drop_target(&app, 1, other.x, other.y), Drop::Tab(app.tabs[1].id.clone()));+ assert_eq!(zone(&app, &Drop::Tab(app.tabs[1].id.clone())), Some(other));+ }++ #[tokio::test]+ async fn a_machine_heading_in_the_side_bar_is_not_a_target() {+ let mut app = app(100);+ app.options.set("@hn-status-bar", Some("left"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes();+ render(&mut app);+ let (heading, _) = app.bar.hits.iter().find(|(_, h)| matches!(h, crate::bar::Hit::Machine(..)))+ .expect("this test needs a machine heading in the side bar").clone();+ assert_eq!(drop_target(&app, 1, heading.x, heading.y), Drop::Nothing);+ }++ #[tokio::test]+ async fn the_zone_is_the_half_the_moved_pane_will_take() {+ let app = two();+ let r2 = rect(&app, 2);+ assert_eq!(zone(&app, &Drop::Swap(2)), Some(r2));+ let left = zone(&app, &Drop::Beside(2, Side::Left)).unwrap();+ let right = zone(&app, &Drop::Beside(2, Side::Right)).unwrap();+ assert_eq!((left.x, left.y, left.height), (r2.x, r2.y, r2.height));+ assert_eq!(left.width + right.width, r2.width);+ assert_eq!(right.right(), r2.right());+ assert_eq!(left.right(), right.x);+ let top = zone(&app, &Drop::Beside(2, Side::Top)).unwrap();+ let bottom = zone(&app, &Drop::Beside(2, Side::Bottom)).unwrap();+ assert_eq!((top.x, top.y, top.width), (r2.x, r2.y, r2.width));+ assert_eq!(top.height + bottom.height, r2.height);+ assert_eq!(bottom.bottom(), r2.bottom());+ assert_eq!(top.bottom(), bottom.y);+ }++ /// How a cell looks, apart from its symbol.+ fn look(buf: &Buffer, x: u16, y: u16) -> (Color, Color, Modifier) { let c = &buf[(x, y)]; (c.bg, c.fg, c.modifier) }++ fn row_text(buf: &Buffer, z: Rect, y: u16) -> String { (z.x..z.right()).map(|x| buf[(x, y)].symbol()).collect() }++ #[tokio::test]+ async fn the_zone_is_shaded_with_a_hint_and_cleared_after() {+ let mut app = two();+ let r2 = rect(&app, 2);+ let before = render(&mut app);+ app.controls.grab = Some(crate::workspace_controls::Grab::live_for_test(1, Drop::Beside(2, Side::Left)));+ let buf = render(&mut app);+ let z = zone(&app, &Drop::Beside(2, Side::Left)).unwrap();+ assert!(z.x == r2.x && z.width < r2.width);+ assert_ne!(look(&buf, z.x, z.y + 1), look(&before, z.x, z.y + 1), "the left half is shaded");+ let row = row_text(&buf, z, z.y + z.height / 2);+ assert!(row.contains("left of Task 2"), "{row}");+ assert_eq!(look(&buf, r2.right() - 1, r2.y + 1), look(&before, r2.right() - 1, r2.y + 1), "outside the zone is untouched");+ app.controls.grab = None;+ assert_eq!(render(&mut app), before, "no zone once the drag is over");+ }++ #[tokio::test]+ async fn a_click_not_yet_a_drag_draws_nothing() {+ let mut app = two();+ let before = render(&mut app);+ let mut grab = crate::workspace_controls::Grab::live_for_test(1, Drop::Swap(2));+ grab.live = false;+ app.controls.grab = Some(grab);+ assert_eq!(render(&mut app), before);+ }++ #[tokio::test]+ async fn each_drop_says_what_it_does() {+ let app = two();+ let tab = app.tabs[0].id.clone();+ let name = app.tabs[0].name.clone();+ assert_eq!(hint(&app, &Drop::Swap(2)).as_deref(), Some("swap with Task 2"));+ assert_eq!(hint(&app, &Drop::Beside(2, Side::Left)).as_deref(), Some("left of Task 2"));+ assert_eq!(hint(&app, &Drop::Beside(2, Side::Right)).as_deref(), Some("right of Task 2"));+ assert_eq!(hint(&app, &Drop::Beside(2, Side::Top)).as_deref(), Some("above Task 2"));+ assert_eq!(hint(&app, &Drop::Beside(2, Side::Bottom)).as_deref(), Some("below Task 2"));+ assert_eq!(hint(&app, &Drop::Tab(tab)), Some(format!("to {name}")));+ assert_eq!(hint(&app, &Drop::Nothing), None);+ }++ #[test]+ fn the_shade_takes_the_theme_accent_and_cuts_the_hint_to_the_zone() {+ let (accent, back) = (theme::accent(), theme::pane_palette().background);+ assert_ne!(accent, back, "this test needs an accent that differs from the pane background");+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 5));+ buf.set_string(0, 0, "x", ratatui::style::Style::default());+ DropZone::new(Some("swap with a long name"), accent, back, false).render(Rect::new(2, 1, 8, 3), &mut buf);+ assert_eq!(buf[(2, 1)].bg, accent);+ assert_eq!(buf[(9, 3)].bg, accent);+ assert_ne!(buf[(10, 2)].bg, accent, "just outside");+ assert_ne!(buf[(1, 2)].bg, accent, "just outside");+ let row: String = (2..10).map(|x| buf[(x, 2)].symbol()).collect();+ assert_eq!(row, "swap wit", "cut at the zone's edge");+ assert_eq!(buf[(10, 2)].symbol(), " ");+ // one row (a tab): its own label stays unless the whole hint fits+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 2));+ buf.set_string(2, 0, "abcd", ratatui::style::Style::default());+ DropZone::new(Some("to a longer tab"), accent, back, false).render(Rect::new(2, 0, 4, 1), &mut buf);+ assert_eq!((2..6).map(|x| buf[(x, 0)].symbol()).collect::<String>(), "abcd");+ DropZone::new(Some("to b"), accent, back, true).render(Rect::new(2, 0, 6, 1), &mut buf);+ assert_eq!((3..7).map(|x| buf[(x, 0)].symbol()).collect::<String>(), "to b");+ assert!(buf[(2, 0)].modifier.contains(Modifier::REVERSED));+ }++ /// The cell loops the zone was first drawn with, kept to prove the widget draws the same cells+ /// (their NO_COLOR cue since underlined as well, as the widget's is).+ fn oracle_shade(buf: &mut Buffer, zone: Rect, text: Option<&str>, bg: Color, fg: Color, reverse: bool) {+ let zone = zone.intersection(buf.area);+ for pos in zone.positions() {+ let Some(cell) = buf.cell_mut(pos) else { continue };+ cell.set_bg(bg).set_fg(fg);+ if reverse { cell.modifier.insert(Modifier::REVERSED | Modifier::UNDERLINED) }+ }+ let Some(text) = text else { return };+ let width = UnicodeWidthStr::width(text) as u16;+ if zone.height == 1 && width > zone.width { return }+ let (mut x, y) = (zone.x + zone.width.saturating_sub(width) / 2, zone.y + zone.height / 2);+ for ch in text.chars() {+ let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0) as u16;+ if w == 0 { continue }+ if x + w > zone.right() { break }+ if let Some(cell) = buf.cell_mut((x, y)) { cell.set_char(ch); }+ x += w;+ }+ }++ /// A screen of busy cells (symbols, colours and a modifier that differ cell to cell) to shade.+ fn backdrop() -> Buffer {+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 12));+ for (i, pos) in buf.area.positions().enumerate() {+ let cell = &mut buf[pos];+ cell.set_char((b'a' + (i % 26) as u8) as char).set_fg(Color::Rgb(i as u8, 90, 200)).set_bg(Color::Indexed((i % 200) as u8));+ if i % 7 == 0 { cell.modifier.insert(Modifier::BOLD | Modifier::REVERSED) }+ }+ buf+ }++ #[test]+ fn the_widget_draws_what_the_cell_loops_drew() {+ let dark = theme::pane_palette_of([28, 31, 36], [220, 225, 231]).background;+ let light = theme::pane_palette_of([250, 250, 245], [30, 30, 30]).background;+ let (field, ink) = (Rect::new(0, 0, 40, 12), Rect::new(4, 2, 14, 7));+ let beside = |side| { // the four halves the way `zone` cuts a pane+ let (w, h) = (ink.width / 2, ink.height / 2);+ match side {+ Side::Left => Rect::new(ink.x, ink.y, w, ink.height),+ Side::Right => Rect::new(ink.x + w, ink.y, ink.width - w, ink.height),+ Side::Top => Rect::new(ink.x, ink.y, ink.width, h),+ Side::Bottom => Rect::new(ink.x, ink.y + h, ink.width, ink.height - h),+ }+ };+ let zones = [+ ("swap", ink), ("left", beside(Side::Left)), ("right", beside(Side::Right)), ("top", beside(Side::Top)), ("bottom", beside(Side::Bottom)),+ ("tab", Rect::new(6, 0, 12, 1)), ("narrow tab", Rect::new(6, 0, 3, 1)), ("hanging off the screen", Rect::new(34, 8, 12, 9)),+ ("edge", field), ("empty", Rect::new(3, 3, 0, 0)),+ ];+ let hints = [None, Some("swap with Task 2"), Some("to b"), Some("swap with a much longer agent name than the zone")];+ for (palette, bg) in [("dark", dark), ("light", light)] {+ for fg in [Color::Rgb(230, 120, 30), Color::Reset] {+ for reverse in [false, true] {+ for (what, z) in zones {+ for hint in hints {+ let (mut old, mut new) = (backdrop(), backdrop());+ oracle_shade(&mut old, z, hint, fg, bg, reverse);+ DropZone::new(hint, fg, bg, reverse).render(z, &mut new);+ assert_eq!(new, old, "{palette}, reverse {reverse}, {what} zone {z:?}, hint {hint:?}");+ }+ }+ }+ }+ }+ }++ #[test]+ fn a_wide_glyph_in_the_hint_takes_two_cells_and_is_cut_whole() {+ // Only the continuation cell differs from the cell loops: they left the old letter+ // there, which a terminal never shows; ratatui blanks it.+ let (bg, fg) = (Color::Rgb(230, 120, 30), Color::Rgb(28, 31, 36));+ for zone in [Rect::new(4, 2, 14, 7), Rect::new(4, 2, 5, 3)] {+ let (mut old, mut new) = (backdrop(), backdrop());+ oracle_shade(&mut old, zone, Some("to 日本語 tab"), bg, fg, false);+ DropZone::new(Some("to 日本語 tab"), bg, fg, false).render(zone, &mut new);+ for pos in new.area.positions() {+ let wide_tail = pos.x > 0 && new[(pos.x - 1, pos.y)].symbol().width() == 2;+ if wide_tail { assert_eq!(new[pos].symbol(), " ", "{pos:?} under a wide glyph"); continue }+ assert_eq!(new[pos], old[pos], "{pos:?}, zone {zone:?}");+ }+ }+ }++ #[test]+ fn an_accent_in_the_hint_stays_with_its_letter() {+ // The cell loops dropped zero-width marks ("ex"); ratatui keeps them with their letter.+ let mut buf = backdrop();+ DropZone::new(Some("e\u{301}x"), Color::Red, Color::Black, false).render(Rect::new(4, 2, 6, 3), &mut buf);+ let row: Vec<&str> = (4..10).map(|x| buf[(x, 3)].symbol()).collect();+ assert!(row.contains(&"e\u{301}") && row.contains(&"x"), "{row:?}");+ }++ /// Panes 1 | 2 | 3 in one window [width] wide, on the desk so that layout changes are queued.+ fn three(width: u16) -> App {+ let mut app = app(width);+ app.tabs.truncate(1);+ let mut pane = crate::pane::Pane::new(3, "local", "a3", width, 30);+ pane.phase = crate::pane::Phase::Live;+ app.panes.insert(3, pane);+ let root = app.tabs[0].root.as_mut().unwrap();+ root.split(1, 2, Dir::Horizontal);+ root.split(2, 3, Dir::Horizontal);+ app.session_desk = true;+ app.tabs[0].on_desk = true;+ app.fit_panes();+ app+ }++ #[tokio::test]+ async fn dropping_runs_swap_and_join_and_publishes_the_layout() {+ let mut app = three(120);+ assert_eq!(app.tabs[0].focus, Some(1));+ release(&mut app, 1, Drop::Swap(3));+ assert_eq!(app.tabs[0].panes(), vec![3, 2, 1]);+ assert_eq!(app.tabs[0].focus, Some(1), "the held pane keeps the focus, not the one it displaced");+ assert!(app.desk_layouts.contains(&app.tabs[0].id), "queued for the desk");+ app.desk_layouts.clear();+ release(&mut app, 3, Drop::Beside(1, Side::Bottom));+ let layout = app.tabs[0].root.as_ref().unwrap().to_tmux();+ assert_eq!(layout.matches('[').count(), 1, "1 and 3 are stacked: {layout}");+ assert_eq!(app.tabs[0].panes(), vec![2, 1, 3]);+ assert_eq!(app.tabs[0].focus, Some(3));+ assert!(app.desk_layouts.contains(&app.tabs[0].id));+ // -b puts it before: on the left of 2+ app.tabs[0].set_active(1);+ release(&mut app, 3, Drop::Beside(2, Side::Left));+ assert_eq!(app.tabs[0].panes(), vec![3, 2, 1]);+ assert_eq!(app.tabs[0].root.as_ref().unwrap().to_tmux().matches('[').count(), 0, "a row again");+ assert_eq!(app.tabs[0].focus, Some(3));+ // a pane that was not the focused one is focused once dropped+ release(&mut app, 2, Drop::Swap(1));+ assert_eq!(app.tabs[0].panes(), vec![3, 1, 2]);+ assert_eq!(app.tabs[0].focus, Some(2));+ }++ #[tokio::test]+ async fn dropping_on_a_tab_moves_the_pane_into_that_window() {+ let mut app = app(100); // window 1: pane 1; window 2: pane 2+ let other = app.tabs[1].id.clone();+ release(&mut app, 1, Drop::Tab(other.clone()));+ let tab = app.tabs.iter().find(|t| t.id == other).unwrap();+ assert!(tab.panes().contains(&1) && tab.panes().contains(&2));+ assert_eq!(app.tabs.len(), 1, "a window left with no pane closes, as join-pane does");+ assert_eq!((app.tab().id.clone(), app.tab().focus), (other, Some(1)), "the view follows the held pane");+ }++ #[tokio::test]+ async fn a_tab_drop_publishes_both_windows_and_follows_the_pane() {+ // window 1: panes 1 | 3; window 2: pane 2; both on the desk+ let mut app = app(100);+ let mut pane = crate::pane::Pane::new(3, "local", "a3", 100, 30);+ pane.phase = crate::pane::Phase::Live;+ app.panes.insert(3, pane);+ app.tabs[0].root.as_mut().unwrap().split(1, 3, Dir::Horizontal);+ app.session_desk = true;+ for tab in &mut app.tabs { tab.on_desk = true }+ app.fit_panes();+ let (left, other) = (app.tabs[0].id.clone(), app.tabs[1].id.clone());+ assert_eq!((app.active, app.tab().focus), (0, Some(1)));+ release(&mut app, 3, Drop::Tab(other.clone()));+ assert_eq!(app.tabs[0].panes(), vec![1]);+ assert_eq!(app.tabs[1].panes(), vec![2, 3]);+ assert!(app.desk_layouts.contains(&left) && app.desk_layouts.contains(&other), "{:?}", app.desk_layouts);+ assert_eq!((app.active, app.tab().focus), (1, Some(3)), "the view follows the held pane into its window");+ }++ #[tokio::test]+ async fn a_gone_source_or_target_does_nothing() {+ let mut app = three(120);+ let before = app.tabs[0].panes();+ let own = app.tabs[0].id.clone();+ release(&mut app, 99, Drop::Swap(2));+ release(&mut app, 1, Drop::Swap(99));+ release(&mut app, 1, Drop::Beside(99, Side::Left));+ release(&mut app, 1, Drop::Tab("no-such-window".into()));+ release(&mut app, 1, Drop::Tab(own));+ release(&mut app, 1, Drop::Swap(1));+ release(&mut app, 1, Drop::Nothing);+ assert_eq!(app.tabs[0].panes(), before);+ assert!(app.desk_layouts.is_empty());+ assert_eq!(app.errors, 0, "nothing ran, so nothing failed");+ }++ #[tokio::test]+ async fn a_pane_too_small_to_split_refuses_the_drop_and_nothing_moves() {+ let mut app = three(8);+ let (before, layout) = (app.tabs[0].panes(), app.tabs[0].root.as_ref().unwrap().to_tmux());+ release(&mut app, 1, Drop::Beside(3, Side::Left));+ assert_eq!(app.tabs[0].panes(), before);+ assert_eq!(app.tabs[0].root.as_ref().unwrap().to_tmux(), layout);+ let toast = app.toast.as_ref().map(|(t, ..)| t.clone()).unwrap_or_default();+ assert!(toast.contains("pane too small"), "the command's own message: {toast:?}");+ assert!(app.desk_layouts.is_empty());+ }++ #[tokio::test]+ async fn a_pane_or_tab_that_is_gone_has_no_zone() {+ let app = two();+ assert_eq!(zone(&app, &Drop::Nothing), None);+ assert_eq!(zone(&app, &Drop::Swap(99)), None);+ assert_eq!(zone(&app, &Drop::Beside(99, Side::Left)), None);+ assert_eq!(zone(&app, &Drop::Tab("no-such-tab".into())), None);+ }+}diff --git a/tui/src/picker.rs b/tui/src/picker.rsindex 7463deb79..6ac7e9840 100644--- a/tui/src/picker.rs+++ b/tui/src/picker.rs@@ -129,6 +129,8 @@ pub struct Picker {pub prefixed: bool,/// An inline composer can use a scope character not used by the app launcher.pub scope_prefix: Option<char>,+ /// The shell composer is drawn with the command panel's pieces rather than fzf's frame.+ pub shell_panel: bool,/// Screen row → visible index, from the last draw (for clicks).pub row_at: Vec<(u16, usize)>,/// A row whose action needs a second Enter (a big download).@@ -285,6 +287,7 @@ impl Picker {scroll: 0,prefixed: false,scope_prefix: None,+ shell_panel: false,row_at: Vec::new(),armed: None,qcursor: 0,diff --git a/tui/src/session_close.rs b/tui/src/session_close.rsindex c3ac9b7c4..ea03c69bd 100644--- a/tui/src/session_close.rs+++ b/tui/src/session_close.rs@@ -148,7 +148,8 @@ fn begin(app: &mut App, panes: Vec<u64>, title: &str, return_to_shell: bool) {}fn showing(app: &App, id: &str) -> bool {- matches!(&app.modal, Some(Modal::Menu(m)) if m.items.iter().any(|i| i.command == format!("close-harness -x {id}")))+ let cancel = format!("close-harness -x {id}");+ matches!(&app.modal, Some(Modal::Menu(m)) if m.buttons.as_ref().is_some_and(|b| b.actions.contains(&cancel)))}fn show(app: &mut App, message: &str, confirm: bool) -> bool {@@ -160,20 +161,28 @@ fn show(app: &mut App, message: &str, confirm: bool) -> bool {if confirm {let remaining: Vec<_> = op.targets.iter().filter(|t| !t.closed).collect();for t in remaining.iter().take(room.saturating_sub(1)) {- let state = match t.activity.as_str() {- "idle" => "Idle", "working" => "Working", "needs_input" => "Waiting for input", "draft" => "Unsent text", _ => "Activity unknown",- };- items.push(menu::note(&format!("{state} · {}", t.name)));+ // (What it is doing, said as a sentence.)+ let name = &t.name;+ items.push(menu::note(&match t.activity.as_str() {+ "idle" => format!("{name} is idle."),+ "working" => format!("{name} is still working."),+ "needs_input" => format!("{name} is waiting for your input."),+ "draft" => format!("{name} has text you haven't sent."),+ _ => format!("Not sure what {name} is doing right now."),+ }));}let shown = items.len();if remaining.len() > shown { items.push(menu::note(&format!("and {} more", remaining.len() - shown))); }if op.shells && items.len() < room { items.push(menu::note("The terminal and its running commands will end.")); }}if !message.is_empty() { items.push(menu::note(message)); }- let cancel = items.len();- items.push(menu::item(if matches!(op.stage, Stage::Failed | Stage::Stop) { "Back" } else { "Cancel" }, "Escape", format!("close-harness -x {id}")));- if confirm { items.push(menu::item("Stop", "s", format!("close-harness -y {id}"))); }- menu::open(app, &title, items, None, Some(cancel))+ let button = |label: &str, key| crate::buttons::Button { label: label.into(), key };+ let mut buttons = vec![button(if matches!(op.stage, Stage::Failed | Stage::Stop) { "Back" } else { "Cancel" }, None)];+ if confirm { buttons.push(button("Stop", Some('s'))); }+ // (One button, Back: nothing to move between.)+ let hint = if confirm { crate::buttons::KEYS } else { "" };+ let row = crate::buttons::Row { buttons, chosen: 0, hint: hint.into() };+ menu::open_buttons(app, &title, items, row, vec![format!("close-harness -x {id}"), format!("close-harness -y {id}")])}fn fail(app: &mut App, message: String) {@@ -428,6 +437,43 @@ mod tests {}}+ #[tokio::test]+ async fn right_then_enter_stops_and_the_buttons_are_one_row_model() {+ let mut app = app();+ pane(&mut app, 1);+ answer(&mut app, "inspect", json!({"activity":"working"}));+ let Some(Modal::Menu(m)) = &app.modal else { panic!("no confirmation") };+ let b = m.buttons.as_ref().expect("a button row");+ assert_eq!(b.row.buttons.iter().map(|x| x.label.as_str()).collect::<Vec<_>>(), ["Cancel", "Stop"]);+ assert_eq!(b.row.chosen, 0, "a destructive action starts on Cancel");+ key(&mut app, KeyCode::Right);+ key(&mut app, KeyCode::Enter);+ assert_eq!(modes(&app), ["inspect", "now"]);+ }++ #[tokio::test]+ async fn every_way_out_of_the_buttons_cancels_and_other_keys_do_nothing() {+ let press = |app: &mut App, code, mods| crate::input::modal_key(app, KeyEvent::new(code, mods));+ let ask = || { let mut app = app(); pane(&mut app, 1); answer(&mut app, "inspect", json!({"activity":"working"})); app };+ for (code, mods) in [(KeyCode::Esc, KeyModifiers::NONE), (KeyCode::Char('q'), KeyModifiers::NONE),+ (KeyCode::Char('c'), KeyModifiers::CONTROL), (KeyCode::Char('g'), KeyModifiers::CONTROL)] {+ let mut app = ask();+ press(&mut app, code, mods);+ assert!(app.modal.is_none(), "{code:?} {mods:?} leaves the dialog");+ assert!(app.session_close.operation.is_none(), "{code:?} {mods:?} must not leave the close pending");+ assert_eq!(modes(&app), ["inspect"], "{code:?} {mods:?} stops nothing");+ }+ let mut app = ask();+ for (code, mods) in [(KeyCode::Char('j'), KeyModifiers::NONE), (KeyCode::Char('k'), KeyModifiers::NONE), (KeyCode::Char('q'), KeyModifiers::CONTROL),+ (KeyCode::Tab, KeyModifiers::NONE), (KeyCode::BackTab, KeyModifiers::SHIFT)] {+ press(&mut app, code, mods);+ assert!(matches!(app.modal, Some(Modal::Menu(_))), "{code:?} keeps the dialog");+ assert_eq!(modes(&app), ["inspect"]);+ }+ let Some(Modal::Menu(m)) = &app.modal else { unreachable!() };+ assert_eq!(m.buttons.as_ref().unwrap().row.chosen, 0, "Tab then Shift-Tab returns to Cancel");+ }+#[tokio::test]async fn explicit_stop_keeps_its_target_when_focus_moves() {let mut app = app();diff --git a/tui/src/settings.rs b/tui/src/settings.rsindex fcf131bd6..477ffe753 100644--- a/tui/src/settings.rs+++ b/tui/src/settings.rs@@ -3,8 +3,10 @@//! section. The list is on the left; the right is one preview of the whole look (every section at//! once), which only changes where the row under the cursor would change it.use ratatui::buffer::Buffer;-use ratatui::layout::{Position, Rect};+use ratatui::layout::{Constraint, Layout, Position, Rect};use ratatui::style::{Color, Modifier, Style};+use ratatui::text::{Line, Span};+use ratatui::widgets::{Block, Clear, Fill, StatefulWidget, Widget};use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};use crate::app::App;@@ -18,6 +20,7 @@ use crate::theme;static FZF_LISTS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);pub fn set_fzf_lists(on: bool) { FZF_LISTS.store(on, std::sync::atomic::Ordering::Relaxed) }+pub fn fzf_lists() -> bool { FZF_LISTS.load(std::sync::atomic::Ordering::Relaxed) }/// The lists drawn as this panel rather than as fzf's full-screen list: every one, unless/// `@hn-lists fzf` asks for fzf's.@@ -277,13 +280,16 @@ fn rebind(app: &mut App, command: &str, title: &str, own: bool, chord: crate::ke}/// The panel's colours, shared with the New Harness form so the two read as one component:-/// its surface, muted and accent text, and the backdrop laid over the panes behind it.-pub struct Chrome { pub base: Style, pub muted: Style, pub accent: Style, pub backdrop: Style, pub selected: Style }+/// its surface, muted and accent text, what went wrong, and the backdrop laid over the panes behind it.+pub struct Chrome { pub base: Style, pub muted: Style, pub accent: Style, pub backdrop: Style, pub selected: Style, pub danger: Style }-pub fn chrome() -> Chrome {- if theme::no_color() {+pub fn chrome() -> Chrome { chrome_with(theme::no_color()) }++/// [chrome] with NO_COLOR decided by the caller, not by the environment.+pub fn chrome_with(no_color: bool) -> Chrome {+ if no_color {let base = Style::default();- return Chrome { base, muted: base.add_modifier(Modifier::DIM), accent: base.add_modifier(Modifier::BOLD), backdrop: base.add_modifier(Modifier::DIM), selected: base.add_modifier(Modifier::REVERSED) };+ return Chrome { base, muted: base.add_modifier(Modifier::DIM), accent: base.add_modifier(Modifier::BOLD), backdrop: base.add_modifier(Modifier::DIM), selected: base.add_modifier(Modifier::REVERSED), danger: base.add_modifier(Modifier::BOLD) };}chrome_for(theme::pane_palette())}@@ -307,7 +313,7 @@ pub fn chrome_for(pal: theme::PanePalette) -> Chrome {let panel_fit = theme::depth_fit(panel);let lifted = [10, 18, 28, 40].iter().map(|a| theme::depth_fit(mix(panel, fg, *a))).find(|c| *c != panel_fit).unwrap_or(panel_fit);let selected = base.add_modifier(Modifier::BOLD).bg(lifted);- Chrome { base, muted, accent, backdrop, selected }+ Chrome { base, muted, accent, backdrop, selected, danger: base.patch(theme::fg(theme::DANGER)) }}/// A pane you are not in, a little quieter (`@hn-dim on`): every cell's text moved toward its@@ -333,21 +339,32 @@ fn mix(a: Color, b: Color, amount: u16) -> Color {Color::Rgb(c(ar, br), c(ag, bg), c(ab, bb))}-/// Dim every cell of [area] under the panel, keeping what is drawn there visible.+/// Dim every cell of [area] under the panel, keeping what is drawn there visible: a borderless+/// `Block` in [style].pub fn backdrop(buf: &mut Buffer, area: Rect, style: Style) {crate::term_out::clear_extras(area);- for y in area.y..area.bottom() { for x in area.x..area.right() { if let Some(c) = buf.cell_mut((x, y)) { c.set_style(style); } } }+ Block::new().style(style).render(area, buf);}-/// Fill [r] with the panel's surface — no border: the surface against the backdrop is the edge.-pub fn fill(buf: &mut Buffer, r: Rect, base: Style) {- crate::term_out::clear_extras(r);- for y in r.y..r.bottom() { for x in r.x..r.right() { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(base); } } }+/// The panel's surface — no border: the surface against the backdrop is the edge. What was drawn+/// under it is cleared first (ratatui's popup way), its underlines and links too.+pub struct Surface(pub Style);++impl Widget for Surface {+ fn render(self, area: Rect, buf: &mut Buffer) {+ crate::term_out::clear_extras(area);+ Clear.render(area, buf);+ Block::new().style(self.0).render(area, buf);+ }}-/// [text] at (x, y) in at most [width] columns, cut with an ellipsis. Returns the columns used.-pub fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) -> u16 {- if width == 0 { return 0 }+/// Fill [r] with the panel's surface.+pub fn fill(buf: &mut Buffer, r: Rect, base: Style) { Surface(base).render(r, buf) }++/// [text] cut to [width] columns with an ellipsis (ratatui cuts without one), and the columns it+/// takes.+pub fn fit(text: &str, width: u16) -> (String, u16) {+ if width == 0 { return (String::new(), 0) }let limit = width as usize;let cut = text.width() > limit;let (mut out, mut used) = (String::new(), 0);@@ -358,8 +375,126 @@ pub fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Stylused += w;}if cut { out.push('…'); used += 1 }- buf.set_stringn(x, y, out, limit, style);- used as u16+ (out, used as u16)+}++/// [text] at (x, y) in at most [width] columns, cut with an ellipsis: a `Span` in [style] (only+/// its own cells take the style, as a `Line`'s would take the whole width). Returns the columns+/// used.+pub fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) -> u16 {+ if width == 0 { return 0 }+ let (out, used) = fit(text, width);+ Span::styled(out, style).render(Rect::new(x, y, width, 1), buf);+ used+}++/// The parts of [ghost] (` `-separated: `@ computer : project`) that fit [w] whole, joined by+/// ` `. A ghost without separators is returned as is (the caller cuts it with `…`).+pub fn whole_parts(ghost: &str, w: u16) -> String {+ if !ghost.contains(" ") { return ghost.to_string() }+ let mut out = String::new();+ for part in ghost.split(" ") {+ let next = if out.is_empty() { part.to_string() } else { format!("{out} {part}") };+ if next.width() > w as usize && !out.is_empty() { break }+ out = next;+ }+ out+}++/// `› query` (or the ghost, muted, when empty) across its line. Rendered by reference, it leaves+/// the text cursor in [cursor] and the columns the query or ghost took in [used] (the launcher puts+/// its tabs after it). A query wider than the line scrolls: it is shown from [Picker::xoffset],+/// moved only as far as keeps the cursor in view, so moving the cursor moves the cursor, not the+/// text (fzf's way; a click maps through it too).+pub struct QueryLine<'a> {+ picker: &'a Picker,+ ghost: &'a str,+ chrome: &'a Chrome,+ pub cursor: Position,+ pub used: u16,+}++impl<'a> QueryLine<'a> {+ pub fn new(picker: &'a Picker, ghost: &'a str, chrome: &'a Chrome) -> Self {+ QueryLine { picker, ghost, chrome, cursor: Position::default(), used: 0 }+ }+}++impl Widget for &mut QueryLine<'_> {+ fn render(self, area: Rect, buf: &mut Buffer) {+ let (picker, c) = (self.picker, self.chrome);+ let [mark, text] = Layout::horizontal([Constraint::Length(2), Constraint::Fill(1)]).areas(area);+ Span::styled("›", c.accent).render(mark, buf);+ let room = text.width;+ // (Where the text starts, past the mark's two columns — even on a line too narrow for any.)+ let start = area.x + 2;+ picker.prompt_at.set((area.y, start));+ let at = |cols: usize| Position::new((start + cols as u16).min(area.right()), area.y);+ if picker.query.is_empty() {+ picker.xoffset.set(0);+ // (The ghost's scopes whole, a ghost of words cut with `…`.)+ let (ghost, used) = fit(&whole_parts(self.ghost, room), room);+ Span::styled(ghost, c.muted).render(text, buf);+ (self.cursor, self.used) = (at(0), used);+ return;+ }+ let chars: Vec<char> = picker.query.chars().collect();+ let to = picker.qcursor.min(chars.len());+ let width = |s: &[char]| s.iter().map(|ch| ch.width().unwrap_or(0)).sum::<usize>();+ // (The cursor's own cell is in the room too: what is before it takes at most room - 1.)+ let mut from = if width(&chars) < room as usize { 0 } else { picker.xoffset.get().min(to) };+ while from < to && width(&chars[from..to]) >= room as usize { from += 1 }+ picker.xoffset.set(from);+ let shown = Line::from(Span::styled(chars[from..].iter().collect::<String>(), c.base));+ self.used = (shown.width() as u16).min(room);+ shown.render(text, buf);+ self.cursor = at(width(&chars[from..to]));+ }+}++/// `shown/total ───…` (and ` (marked)` after the total when [marked] is Some), muted, across its+/// line.+pub struct CountRule<'a> {+ pub shown: usize,+ pub total: usize,+ pub marked: Option<usize>,+ pub chrome: &'a Chrome,+}++impl Widget for CountRule<'_> {+ fn render(self, area: Rect, buf: &mut Buffer) {+ let CountRule { shown, total, marked, chrome: c } = self;+ let count = match marked { Some(m) => format!("{shown}/{total} ({m})"), None => format!("{shown}/{total}") };+ let (count, cw) = fit(&count, area.width);+ // (The rule a column after the count, to the line's end.)+ let [n, rule] = Layout::horizontal([Constraint::Length(cw.saturating_add(1)), Constraint::Fill(1)]).areas(area);+ Span::styled(count, c.muted).render(n, buf);+ Fill::new("─").style(c.muted.remove_modifier(Modifier::BOLD)).render(rule, buf);+ }+}++/// `key what · key what`, the keys bold, the words muted; cut with `…` where the line ends.+pub struct KeysLine<'a> {+ pub keys: &'a [(&'a str, &'a str)],+ pub chrome: &'a Chrome,+}++impl Widget for KeysLine<'_> {+ fn render(self, area: Rect, buf: &mut Buffer) {+ let c = self.chrome;+ let parts = self.keys.iter().enumerate().flat_map(|(i, (k, what))| {+ let sep = (i > 0).then(|| (" · ".to_string(), c.muted));+ sep.into_iter().chain([(k.to_string(), c.base.add_modifier(Modifier::BOLD)), (format!(" {what}"), c.muted)])+ });+ let (mut line, mut room) = (Line::default(), area.width);+ for (text, style) in parts {+ if room == 0 { break }+ let (text, used) = fit(&text, room);+ line.push_span(Span::styled(text, style));+ room -= used;+ }+ line.render(area, buf);+ }}// ── sizes ──@@ -459,13 +594,10 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:// of the launcher's lists, fzf's way, its keys and its count over it (below).let launcher = crate::modal::is_launcher(kind);let qy = if launcher { r.bottom().saturating_sub(2) } else { r.y + 3 };- put(buf, x, qy, 2, "›", c.accent);let hint = if launcher { format!("Search {}", title(app, kind, picker).to_lowercase()) } else { picker.placeholder.clone() };- let shown = if picker.query.is_empty() { (hint.as_str(), c.muted) } else { (picker.query.as_str(), c.base) };- let qw = put(buf, x + 2, qy, inner_w.saturating_sub(2), shown.0, shown.1);- picker.prompt_at.set((qy, x + 2));- let before: String = picker.query.chars().take(picker.qcursor).collect();- let cursor = Position::new((x + 2 + before.width() as u16).min(right), qy);+ let mut query = QueryLine::new(picker, &hint, &c);+ query.render(Rect::new(x, qy, inner_w, 1), buf);+ let (cursor, qw) = (query.cursor, query.used);// (On the tab row the keys are not the query's: no text cursor.)let cursor = Some(cursor).filter(|_| !picker.on_tabs);@@ -483,19 +615,11 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:sx += put(buf, sx, qy, right.saturating_sub(sx), &text, style) + 3;}// Over it: how many rows match of how many (and how many marked), a rule after.- let count = format!("{}/{} ({})", picker.visible.len(), picker.rows.len(), picker.marked.len());- let cw = put(buf, x, qy - 1, inner_w, &count, c.muted);- for cx in x + cw + 1..right { put(buf, cx, qy - 1, 1, "─", c.muted.remove_modifier(Modifier::BOLD)); }+ CountRule { shown: picker.visible.len(), total: picker.rows.len(), marked: Some(picker.marked.len()), chrome: &c }.render(Rect::new(x, qy - 1, inner_w, 1), buf);// Over that: this list's keys, `key what` · `key what`, the keys bold (the tab row's own,// while it has the keys).- let mut kx = x;let tab_keys = [("← →", "switch"), ("↑", "list"), ("type", "to search")];- for (i, (k, what)) in if picker.on_tabs { &tab_keys[..] } else { &picker.hints[..] }.iter().enumerate() {- if i > 0 { kx += put(buf, kx, qy - 2, right.saturating_sub(kx), " · ", c.muted); }- kx += put(buf, kx, qy - 2, right.saturating_sub(kx), k, c.base.add_modifier(Modifier::BOLD));- kx += put(buf, kx, qy - 2, right.saturating_sub(kx), &format!(" {what}"), c.muted);- if kx >= right { break }- }+ KeysLine { keys: if picker.on_tabs { &tab_keys[..] } else { &picker.hints[..] }, chrome: &c }.render(Rect::new(x, qy - 2, inner_w, 1), buf);}// The list, and beside it the preview when there is room for both.@@ -588,31 +712,98 @@ pub fn section_title(section: &str) -> &'static str {}}+/// Whether [list_from] titles the groups: not while typing, when the best matches come first,+/// untitled — as opencode's search reads. (A launcher's scope character alone — `:` — is no+/// search yet: its list keeps its headings.)+fn grouped(picker: &Picker) -> bool {+ picker.query.is_empty() || (picker.prefixed && crate::picker::scope_of(&picker.query).is_some() && picker.query.trim().chars().count() == 1)+}++/// The lines [list] draws for [picker]'s rows, top-down: each row, a heading where the group+/// changes and a blank line before every heading but the first (at least one: the empty notice).+pub fn list_lines(picker: &Picker) -> usize {+ let (grouped, mut lines, mut last) = (grouped(picker), 0, None);+ for (i, _) in &picker.visible {+ let group = picker.rows[*i].group.as_deref().filter(|_| grouped);+ if group.is_some() && group != last { lines += 1 + usize::from(lines > 0) }+ last = group;+ lines += 1;+ }+ lines.max(1)+}+/// The rows, top-down, the cursor's row marked as the New Harness chooser marks its own.pub fn list(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, details: bool) { list_from(buf, picker, r, c, details, false) }/// [list], [bottom_up]: the first row at the bottom, by the query under it, the rest going up/// (fzf's way, for the launcher's lists) — a group's heading over its rows still.pub fn list_from(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, details: bool, bottom_up: bool) {- picker.list_area.set(r);- let mut row_at = Vec::new();- let n = r.height as usize;- if n == 0 { picker.row_at = row_at; return }- if picker.visible.is_empty() {- // (A list says what its emptiness means — "no harnesses yet" — where it can.)- let empty = if picker.empty.is_empty() || !picker.query.is_empty() { "Nothing matches".to_string() } else { picker.empty.clone() };- put(buf, r.x + 2, if bottom_up { r.bottom() - 1 } else { r.y }, r.width.saturating_sub(2), &empty, c.muted);+ PanelList { chrome: c, details, bottom_up }.render(r, buf, picker)+}++/// The command panel's list — the panel's, the launcher's, the shell composer's and the New+/// Harness choosers' — as a ratatui `StatefulWidget` whose state is its [Picker]: it scrolls the+/// picker to keep the cursor's row (and its group's heading) in view, unless the wheel moved it,+/// and keeps where each row went for the mouse (`row_at`, `list_area`). Each row is a line of+/// `Span`s at their columns — the pointer, a mark, the row's lead and label, its hint or what it+/// says, its right column — over a `Block` in the chosen style for the cursor's row. (Not a+/// ratatui `List` or `Table`: a row's right column has its own width, the hint a column only+/// where both fit, and a bottom-up list keeps each heading over its rows.) [details]: the hint+/// beside the name; [bottom_up]: the first row at the bottom.+pub struct PanelList<'a> { pub chrome: &'a Chrome, pub details: bool, pub bottom_up: bool }++impl StatefulWidget for PanelList<'_> {+ type State = Picker;++ fn render(self, r: Rect, buf: &mut Buffer, picker: &mut Picker) {+ let (c, bottom_up) = (self.chrome, self.bottom_up);+ picker.list_area.set(r);+ picker.row_at = Vec::new();+ let n = r.height as usize;+ if n == 0 { return }+ if picker.visible.is_empty() {+ let empty = empty_notice(picker);+ if !empty.is_empty() { put(buf, r.x + 2, if bottom_up { r.bottom() - 1 } else { r.y }, r.width.saturating_sub(2), &empty, c.muted); }+ return;+ }+ let (lines, titles) = list_layout(picker, bottom_up);+ scroll_to_cursor(picker, &lines, &titles, n, bottom_up);+ let mut row_at = Vec::new();+ for (slot, i) in (picker.scroll..lines.len()).take(n).enumerate() {+ let y = if bottom_up { r.bottom() - 1 - slot as u16 } else { r.y + slot as u16 };+ let line = Rect::new(r.x, y, r.width, 1);+ match lines[i] {+ Some(vi) => { self.row(buf, picker, vi, line); row_at.push((y, vi)) }+ None => if let Some((_, title)) = titles.iter().find(|(at, _)| *at == i) { put(buf, r.x + 2, y, r.width.saturating_sub(2), title, c.muted.add_modifier(Modifier::BOLD)); },+ }+ }+ // (No scrollbar: the list follows the cursor, the wheel scrolls it.)picker.row_at = row_at;- return;}+}++/// What an empty list says: what its emptiness means — "no harnesses yet" — where it can.+fn empty_notice(picker: &Picker) -> String {+ let mut empty = if picker.empty.is_empty() || !picker.query.is_empty() { "Nothing matches".to_string() } else { picker.empty.clone() };+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ if picker.shell_panel && total == 0 {+ // The shell composer's list with no rows at all reads as its fzf frame's: blank while it+ // loads (a failure being retried is said in the rule), else why — a failed request, a+ // directory it could not read — under a query too.+ if picker.busy.is_some() { empty.clear() } else if !picker.empty.is_empty() { empty = picker.empty.clone() }+ }+ empty+}++/// The lines as drawn, first to last (bottom to top when [bottom_up]): each visible row by its+/// index, and None for a heading (titled, at its line) or the blank line before one.+fn list_layout(picker: &Picker, bottom_up: bool) -> (Vec<Option<usize>>, Vec<(usize, String)>) {// The lines as drawn: each row, and a titled heading (a blank line before it) wherever the// group changes — as opencode's palette groups its commands. The scroll counts lines.let mut lines: Vec<Option<usize>> = Vec::new();let mut titles: Vec<(usize, String)> = Vec::new();let mut last: Option<&str> = None;- // (While typing, the best matches come first, untitled — as opencode's search reads.)- // (A launcher's scope character alone — `:` — is no search yet: its list keeps its headings.)- let grouped = picker.query.is_empty() || (picker.prefixed && crate::picker::scope_of(&picker.query).is_some() && picker.query.trim().chars().count() == 1);+ let grouped = grouped(picker);if !bottom_up {for vi in 0..picker.visible.len() {let group = picker.rows[picker.visible[vi].0].group.as_deref().filter(|_| grouped);@@ -638,26 +829,29 @@ pub fn list_from(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, det}if let Some(title) = pending { titles.push((lines.len(), title)); lines.push(None) }}+ (lines, titles)+}++/// [picker]'s scroll (the first line shown of [n]) keeping the cursor's row in view — and, top+/// down, its heading with it — unless the wheel put the list where it is.+fn scroll_to_cursor(picker: &mut Picker, lines: &[Option<usize>], titles: &[(usize, String)], n: usize, bottom_up: bool) {let at_line = lines.iter().position(|l| *l == Some(picker.cursor)).unwrap_or(0);- // (The cursor's heading comes into view with it.)let top = if !bottom_up && at_line >= 1 && titles.iter().any(|(i, _)| *i + 1 == at_line) { at_line - 1 } else { at_line };- // (Scrolled by the wheel: the list stays where it was put, the cursor wherever it is.)if !picker.free_scroll {if top < picker.scroll { picker.scroll = top }if at_line >= picker.scroll + n { picker.scroll = at_line + 1 - n }}picker.scroll = picker.scroll.min(lines.len().saturating_sub(n));- for (slot, line) in lines.iter().enumerate().skip(picker.scroll).take(n).map(|(i, l)| (i - picker.scroll, (i, *l))) {- let y = if bottom_up { r.bottom() - 1 - slot as u16 } else { r.y + slot as u16 };- let (li, Some(vi)) = line else {- if let Some((_, title)) = titles.iter().find(|(i, _)| *i == line.0) { put(buf, r.x + 2, y, r.width.saturating_sub(2), title, c.muted.add_modifier(Modifier::BOLD)); }- continue;- };- let _ = li;+}++impl PanelList<'_> {+ /// Row [vi] of [picker] on [line]: the cursor's in the chosen style across the line.+ fn row(&self, buf: &mut Buffer, picker: &Picker, vi: usize, line: Rect) {+ let (c, details, r, y) = (self.chrome, self.details, line, line.y);let row = &picker.rows[picker.visible[vi].0];let here = vi == picker.cursor;let style = if here { c.selected } else { c.base };- if here { for x in r.x..r.right() { if let Some(cell) = buf.cell_mut((x, y)) { cell.set_style(style); } } }+ if here { Block::new().style(style).render(line, buf) }put(buf, r.x, y, 1, if here { "›" } else { " " }, if here { c.selected } else { c.accent });// Marked with Tab (several at once): a dot beside the pointer.if picker.marked.contains(&row.id) { put(buf, r.x + 1, y, 1, "•", if here { c.selected } else { c.accent }); }@@ -688,10 +882,7 @@ pub fn list_from(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, detif !said.is_empty() { put(buf, at, y, end - at, &format!(" · {said}"), quiet); }}if right_w > 0 { put(buf, r.right().saturating_sub(right_w + 2), y, right_w, right_text, if here { style } else { c.muted }); }- row_at.push((y, vi));}- // (No scrollbar: the list follows the cursor, the wheel scrolls it.)- picker.row_at = row_at;}// ── the preview: a small hn with the whole look applied ─────────────────────────────@@ -1016,6 +1207,318 @@ fn preview_bar(buf: &mut Buffer, bar: Rect, left: bool, pal: &theme::PanePaletteline(buf, &mut y, &[(" └─ ", Style::default().fg(pal.muted)), ("?", Style::default().fg(theme::paint(theme::ATTENTION))), (" 0:claude", Style::default().fg(fg).add_modifier(Modifier::BOLD))], Some(row));}+/// The panel's lines and the panel as they were drawn by hand, cell by cell (2026-10-08), kept so+/// the ratatui widgets that replaced them can be shown to draw the very same buffer. Copied as+/// they were; the names here shadow the widgets' module's.+#[cfg(test)]+pub(crate) mod oracle {+ use super::*;++ /// The chromes the widgets are checked in: a dark theme, a light one, and NO_COLOR, without+ /// touching the environment. (The caller holds `colours_lock`.)+ pub fn chromes() -> Vec<Chrome> {+ let mut out = Vec::new();+ for (bg, fg) in [("#1e1e2e", "#cdd6f4"), ("#fafafa", "#383a42")] {+ crate::term_out::set_theme_colours(Some((bg.into(), fg.into())));+ out.push(chrome_with(false));+ }+ crate::term_out::set_theme_colours(None);+ out.push(chrome_with(true));+ out+ }++ /// A blank buffer and one already written over, so a widget that touches a cell the old+ /// drawing left alone shows.+ pub fn grounds(area: Rect) -> [Buffer; 2] {+ let mut dirty = Buffer::empty(area);+ for p in area.positions() { dirty[p].set_symbol("x").set_style(Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::ITALIC)); }+ [Buffer::empty(area), dirty]+ }++ /// A query wider than any line it is drawn in.+ pub const LONG: &str = "/home/dev/harnesses/worktrees/autonomous-harness/hn-007/tui/src/settings.rs";++ /// Fill [r] with the panel's surface — no border: the surface against the backdrop is the edge.+ pub fn fill(buf: &mut Buffer, r: Rect, base: Style) {+ crate::term_out::clear_extras(r);+ for y in r.y..r.bottom() { for x in r.x..r.right() { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(base); } } }+ }++ /// [text] at (x, y) in at most [width] columns, cut with an ellipsis. Returns the columns used.+ pub fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) -> u16 {+ if width == 0 { return 0 }+ let limit = width as usize;+ let cut = text.width() > limit;+ let (mut out, mut used) = (String::new(), 0);+ for ch in text.chars().filter(|c| !c.is_control()) {+ let w = ch.width().unwrap_or(0);+ if used + w > limit - usize::from(cut) { break }+ out.push(ch);+ used += w;+ }+ if cut { out.push('…'); used += 1 }+ buf.set_stringn(x, y, out, limit, style);+ used as u16+ }++ /// Dim every cell of [area] under the panel, keeping what is drawn there visible.+ pub fn backdrop(buf: &mut Buffer, area: Rect, style: Style) {+ crate::term_out::clear_extras(area);+ for y in area.y..area.bottom() { for x in area.x..area.right() { if let Some(c) = buf.cell_mut((x, y)) { c.set_style(style); } } }+ }++ /// The list as it was drawn by hand (2026-10-08), [super::list_from]'s oracle.+ pub fn list_from(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, details: bool, bottom_up: bool) {+ picker.list_area.set(r);+ let mut row_at = Vec::new();+ let n = r.height as usize;+ if n == 0 { picker.row_at = row_at; return }+ if picker.visible.is_empty() {+ let mut empty = if picker.empty.is_empty() || !picker.query.is_empty() { "Nothing matches".to_string() } else { picker.empty.clone() };+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ if picker.shell_panel && total == 0 {+ if picker.busy.is_some() { empty.clear() } else if !picker.empty.is_empty() { empty = picker.empty.clone() }+ }+ if !empty.is_empty() { put(buf, r.x + 2, if bottom_up { r.bottom() - 1 } else { r.y }, r.width.saturating_sub(2), &empty, c.muted); }+ picker.row_at = row_at;+ return;+ }+ let mut lines: Vec<Option<usize>> = Vec::new();+ let mut titles: Vec<(usize, String)> = Vec::new();+ let mut last: Option<&str> = None;+ let grouped = grouped(picker);+ if !bottom_up {+ for vi in 0..picker.visible.len() {+ let group = picker.rows[picker.visible[vi].0].group.as_deref().filter(|_| grouped);+ if group.is_some() && group != last {+ if !lines.is_empty() { lines.push(None) }+ titles.push((lines.len(), group.unwrap_or_default().to_string()));+ lines.push(None);+ }+ last = group;+ lines.push(Some(vi));+ }+ } else {+ let mut pending: Option<String> = None;+ for vi in 0..picker.visible.len() {+ let group = picker.rows[picker.visible[vi].0].group.as_deref().filter(|_| grouped);+ if group != last {+ if let Some(title) = pending.take() { titles.push((lines.len(), title)); lines.push(None); lines.push(None) }+ pending = group.map(str::to_string);+ }+ last = group;+ lines.push(Some(vi));+ }+ if let Some(title) = pending { titles.push((lines.len(), title)); lines.push(None) }+ }+ let at_line = lines.iter().position(|l| *l == Some(picker.cursor)).unwrap_or(0);+ let top = if !bottom_up && at_line >= 1 && titles.iter().any(|(i, _)| *i + 1 == at_line) { at_line - 1 } else { at_line };+ if !picker.free_scroll {+ if top < picker.scroll { picker.scroll = top }+ if at_line >= picker.scroll + n { picker.scroll = at_line + 1 - n }+ }+ picker.scroll = picker.scroll.min(lines.len().saturating_sub(n));+ for (slot, line) in lines.iter().enumerate().skip(picker.scroll).take(n).map(|(i, l)| (i - picker.scroll, (i, *l))) {+ let y = if bottom_up { r.bottom() - 1 - slot as u16 } else { r.y + slot as u16 };+ let (_, Some(vi)) = line else {+ if let Some((_, title)) = titles.iter().find(|(i, _)| *i == line.0) { put(buf, r.x + 2, y, r.width.saturating_sub(2), title, c.muted.add_modifier(Modifier::BOLD)); }+ continue;+ };+ let row = &picker.rows[picker.visible[vi].0];+ let here = vi == picker.cursor;+ let style = if here { c.selected } else { c.base };+ if here { for x in r.x..r.right() { if let Some(cell) = buf.cell_mut((x, y)) { cell.set_style(style); } } }+ put(buf, r.x, y, 1, if here { "›" } else { " " }, if here { c.selected } else { c.accent });+ if picker.marked.contains(&row.id) { put(buf, r.x + 1, y, 1, "•", if here { c.selected } else { c.accent }); }+ let mut at = r.x + 2;+ for span in &row.lead {+ let s = if here { style.patch(Style::default().fg(span.style.fg.unwrap_or(Color::Reset))) } else { c.base.patch(span.style) };+ at += put(buf, at, y, r.right().saturating_sub(at), &span.content, s);+ }+ let right_text = row.right_at(r.width as usize);+ let right_w = (right_text.width() as u16).min(if picker.right_half { r.width / 2 } else { r.width / 3 });+ let end = r.right().saturating_sub(if right_w > 0 { right_w + 3 } else { 2 });+ let hint: String = if details { row.detail.iter().map(|s| s.content.as_ref()).collect() } else { String::new() };+ let hx = at + 28;+ let with_hint = !hint.is_empty() && hx + 8 < end;+ at += put(buf, at, y, if with_hint { 26 } else { end.saturating_sub(at) }, &row.label, style);+ let quiet = if here { style.remove_modifier(Modifier::BOLD) } else { c.muted };+ if with_hint { put(buf, hx.max(at + 2), y, end - hx.max(at + 2), &hint, quiet); }+ else if !details && at + 10 < end {+ let said: String = row.detail.iter().map(|s| s.content.as_ref()).collect();+ if !said.is_empty() { put(buf, at, y, end - at, &format!(" · {said}"), quiet); }+ }+ if right_w > 0 { put(buf, r.right().saturating_sub(right_w + 2), y, right_w, right_text, if here { style } else { c.muted }); }+ row_at.push((y, vi));+ }+ picker.row_at = row_at;+ }++ pub fn query_line(buf: &mut Buffer, picker: &Picker, x: u16, y: u16, w: u16, ghost: &str, c: &Chrome) -> (Position, u16) {+ put(buf, x, y, 2, "›", c.accent);+ let room = w.saturating_sub(2);+ picker.prompt_at.set((y, x + 2));+ if picker.query.is_empty() {+ picker.xoffset.set(0);+ return (Position::new((x + 2).min(x + w), y), put(buf, x + 2, y, room, &whole_parts(ghost, room), c.muted));+ }+ let chars: Vec<char> = picker.query.chars().collect();+ let at = picker.qcursor.min(chars.len());+ let width = |s: &[char]| s.iter().map(|ch| ch.width().unwrap_or(0)).sum::<usize>();+ // (The cursor's own cell is in the room too: what is before it takes at most room - 1.)+ let mut from = if width(&chars) < room as usize { 0 } else { picker.xoffset.get().min(at) };+ while from < at && width(&chars[from..at]) >= room as usize { from += 1 }+ picker.xoffset.set(from);+ let text = ratatui::text::Line::from(ratatui::text::Span::styled(chars[from..].iter().collect::<String>(), c.base));+ let used = (text.width() as u16).min(room);+ ratatui::widgets::Widget::render(&text, Rect::new(x + 2, y, room, 1), buf);+ (Position::new((x + 2 + width(&chars[from..at]) as u16).min(x + w), y), used)+ }++ pub fn count_rule(buf: &mut Buffer, shown: usize, total: usize, marked: Option<usize>, x: u16, y: u16, w: u16, c: &Chrome) {+ let count = match marked { Some(m) => format!("{shown}/{total} ({m})"), None => format!("{shown}/{total}") };+ let cw = put(buf, x, y, w, &count, c.muted);+ for cx in x + cw + 1..x + w { put(buf, cx, y, 1, "─", c.muted.remove_modifier(Modifier::BOLD)); }+ }++ pub fn keys_line(buf: &mut Buffer, keys: &[(&str, &str)], x: u16, y: u16, w: u16, c: &Chrome) {+ let (mut kx, right) = (x, x + w);+ for (i, (k, what)) in keys.iter().enumerate() {+ if i > 0 { kx += put(buf, kx, y, right.saturating_sub(kx), " · ", c.muted); }+ kx += put(buf, kx, y, right.saturating_sub(kx), k, c.base.add_modifier(Modifier::BOLD));+ kx += put(buf, kx, y, right.saturating_sub(kx), &format!(" {what}"), c.muted);+ if kx >= right { break }+ }+ }++ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker: &mut Picker) -> (Option<Position>, Option<Rect>) {+ // ── machines & devices ── (the same panel, laid out by devices.rs: Add phone's QR code takes+ // the panel's whole height, and each view draws its own right side)+ if let PickerKind::Devices(view) = kind { return (crate::devices::draw(buf, app, body, *view, picker), None) }+ if matches!(kind, PickerKind::Account) { return (crate::account::draw(buf, app, body, picker), None) }+ let c = chrome();+ backdrop(buf, body, c.backdrop);+ if body.width < 24 || body.height < 8 {+ put(buf, body.x, body.y, body.width, &format!("{} · resize or Esc", title(app, kind, picker)), c.base);+ return (None, None);+ }+ // (A palette as tall as all its rows, not the ones a search leaves, so it stays put as you type;+ // Commands' search reaches every tmux command, so theirs is the most a palette takes.)+ let all = if matches!(kind, PickerKind::Commands) { u16::MAX } else { picker.rows.len().min(u16::MAX as usize) as u16 };+ let r = area(body, kind.size(), all);+ fill(buf, r, c.base);+ picker.screen_area.set(r);+ let (x, right) = (r.x + 2, r.right().saturating_sub(2));+ let inner_w = right.saturating_sub(x);++ // Title: where you are, and how to leave.+ let mut at = x + put(buf, x, r.y + 1, inner_w, &title(app, kind, picker), c.base.add_modifier(Modifier::BOLD));+ if let Some(section) = picker.theme_in.as_deref() {+ at += put(buf, at, r.y + 1, right.saturating_sub(at), " › ", c.muted);+ at += put(buf, at, r.y + 1, right.saturating_sub(at), section_title(section), c.accent);+ }+ // What the list says of itself (a count, "searching…"), before the way out — with a spinner+ // while it waits on something (a read, a model moving), so a still panel is not a stuck one.+ let working = picker.busy.clone().or_else(|| if matches!(kind, PickerKind::Models) { crate::models::working(app) } else { None });+ let status = match working { Some(w) => format!("{} {w}", theme::spinner(app.tick)), None => picker.status.clone() };+ if !status.is_empty() {+ let w = (status.width() as u16).min(right.saturating_sub(at + 8));+ put(buf, right.saturating_sub(w + 6), r.y + 1, w, &status, c.muted);+ }+ put(buf, right.saturating_sub(3), r.y + 1, 3, "esc", c.muted);++ // The query: at the top of the menus (as the New Harness chooser has its own); at the bottom+ // of the launcher's lists, fzf's way, its keys and its count over it (below).+ let launcher = crate::modal::is_launcher(kind);+ let qy = if launcher { r.bottom().saturating_sub(2) } else { r.y + 3 };+ let hint = if launcher { format!("Search {}", title(app, kind, picker).to_lowercase()) } else { picker.placeholder.clone() };+ let (cursor, qw) = query_line(buf, picker, x, qy, inner_w, &hint, &c);+ // (On the tab row the keys are not the query's: no text cursor.)+ let cursor = Some(cursor).filter(|_| !picker.on_tabs);++ if launcher {+ // After the query: the tabs it switches between, the one you are in marked — lit while the+ // tab row has the keys (↓ past the list's last row).+ let here = crate::picker::scope_of(&picker.query);+ let mut sx = x + 2 + qw + 3;+ for (ch, name) in crate::modal::LAUNCHER_TABS {+ let text = ch.map(|ch| format!("{ch} {name}")).unwrap_or_else(|| name.to_string());+ // (The one you are in in brackets — seen in any theme, colour or none.)+ let text = if here == *ch { format!("[{text}]") } else { text };+ if sx + text.width() as u16 > right { break }+ let style = match (here == *ch, picker.on_tabs) { (true, true) => c.selected.add_modifier(Modifier::BOLD), (true, false) => c.base.add_modifier(Modifier::BOLD | Modifier::UNDERLINED), _ => c.muted };+ sx += put(buf, sx, qy, right.saturating_sub(sx), &text, style) + 3;+ }+ // Over it: how many rows match of how many (and how many marked), a rule after.+ count_rule(buf, picker.visible.len(), picker.rows.len(), Some(picker.marked.len()), x, qy - 1, inner_w, &c);+ // Over that: this list's keys, `key what` · `key what`, the keys bold (the tab row's own,+ // while it has the keys).+ let tab_keys = [("← →", "switch"), ("↑", "list"), ("type", "to search")];+ keys_line(buf, if picker.on_tabs { &tab_keys[..] } else { &picker.hints[..] }, x, qy - 2, inner_w, &c);+ }++ // The list, and beside it the preview when there is room for both.+ // (Without a keys row, the list and the preview reach down to the panel's last rows; the+ // launcher's reach down to its keys.)+ let (top, bottom) = if launcher { (r.y + 3, r.bottom().saturating_sub(5)) } else { (r.y + 5, r.bottom().saturating_sub(if keyed(kind) { 3 } else { 1 })) };+ let rows = bottom.saturating_sub(top) as usize;+ // (Commands need no preview: the list takes the width, a row's hint beside its name. A list+ // that is the whole answer — output, messages, keys — has none either.)+ // (Keybinds are keys, not a look: no preview; the list takes the width, a key beside each.)+ let settings = matches!(kind, PickerKind::Theme);+ // (A palette is a list only.)+ let side = inner_w >= 64 && kind.size() == PanelSize::Large && (settings || (picker.preview && !matches!(kind, PickerKind::Commands | PickerKind::Theme)));+ // (A list's preview gets at least half: a harness's screen, a machine's, a model's facts —+ // the list room for a row's name and what it says, a harness's doing.)+ // (Models: a model's name, its size and speed, and its word side by side, as the desktop's rows.)+ let widest = if matches!(kind, PickerKind::Models) { 72 } else { 56 };+ let list_w = if !side { inner_w } else if settings { (inner_w * 2 / 5).clamp(28, 40) } else { (inner_w / 2).clamp(30, widest) };+ list_from(buf, picker, Rect::new(x, top, list_w, rows as u16), &c, !side, !top_down(kind));+ picker.preview_area.set(None);+ picker.bar.set(None);+ let mut shown = None;+ if side {+ let px = x + list_w + 3;+ // (The settings' preview is the page's picture, from the query line down; a list's is+ // beside its rows, under the query and the scopes, which keep the whole width.)+ let from = if settings { r.y + 3 } else { top };+ let pr = Rect::new(px, from, right.saturating_sub(px), bottom.saturating_sub(from));+ if settings {+ let look = Look::of(app).with(picker.theme_in.as_ref().and(picker.current_id()).as_deref());+ preview(buf, pr, &look, &c);+ } else {+ // A thin rule between the list and its preview, in the panel's muted colour.+ for y in pr.y..pr.bottom() { put(buf, px - 2, y, 1, "│", c.muted.remove_modifier(Modifier::BOLD)); }+ picker.preview_area.set(Some((pr, 'r')));+ shown = Some(pr);+ }+ }++ // The footer: what was just said, else — in the menus (Commands, Appearance) — their keys. The+ // other lists say nothing there: their room is the list's and the preview's.+ // (The launcher's: in place of its keys, for the moment it is said.)+ let fy = r.bottom().saturating_sub(if launcher { 4 } else if keyed(kind) { 2 } else { 1 });+ let flash = picker.flash.as_ref().filter(|(_, at)| at.elapsed().as_secs() < 3).map(|(t, _)| t.clone());+ let keys = match kind {+ PickerKind::Commands if in_tmux(picker) => Some("↑↓ move enter run type to search esc back"),+ PickerKind::Commands => Some("↑↓ move enter run type to search esc close"),+ PickerKind::Theme if picker.theme_in.is_some() => Some("↑↓ move enter apply ← back esc back"),+ PickerKind::Theme if picker.from_commands => Some("↑↓ move → open type to search esc back"),+ PickerKind::Theme => Some("↑↓ move → open type to search esc close"),+ // ── keys ──+ PickerKind::Keybinds if picker.from_commands => Some("↑↓ move enter change type to search esc back"),+ PickerKind::Keybinds => Some("↑↓ move enter change type to search esc close"),+ _ => None,+ };+ match (flash, keys) {+ (Some(text), _) => { put(buf, x, fy, inner_w, &" ".repeat(inner_w as usize), c.base); put(buf, x, fy, inner_w, &text, c.accent); }+ (None, Some(keys)) => { put(buf, x, fy, inner_w, keys, c.muted); }+ (None, None) => {}+ }+ (cursor, shown)+ }+}+#[cfg(test)]mod tests {use super::*;@@ -1044,6 +1547,17 @@ mod tests {p}+ /// The query line and count rule widgets at (x, y), [w] wide, as the tests below draw them.+ fn query_line(buf: &mut Buffer, picker: &Picker, x: u16, y: u16, w: u16, ghost: &str, c: &Chrome) -> (Position, u16) {+ let mut q = QueryLine::new(picker, ghost, c);+ q.render(Rect::new(x, y, w, 1), buf);+ (q.cursor, q.used)+ }++ fn count_rule(buf: &mut Buffer, shown: usize, total: usize, marked: Option<usize>, x: u16, y: u16, w: u16, c: &Chrome) {+ CountRule { shown, total, marked, chrome: c }.render(Rect::new(x, y, w, 1), buf);+ }+/// The panel stays where it is, the same size, whether it shows the sections or one section's/// options — and draws at every size without a panic.#[test]@@ -1249,4 +1763,399 @@ mod tests {assert_eq!(Look::of(&app).with(Some("window_active:filled")).window_active, "filled");assert!(row(&filled, 19).contains("0:claude") && !row(&filled, 19).contains("0:claude*"), "{}", text(&filled));}++ fn launcher_buffer(query: &str, on_tabs: bool) -> (Buffer, Rect, Option<Position>) {+ let app = app((100, 30));+ let body = Rect::new(0, 0, 100, 29);+ let kind = PickerKind::Open { filter: modal::Filter::All, machine: None, project: None };+ let mut p = Picker::new("harnesses", "");+ p.hints = vec![("↑↓", "move"), ("enter", "open")];+ p.set_rows(vec![crate::picker::Row::new("a", "alpha"), crate::picker::Row::new("b", "beta"), crate::picker::Row::new("c", "alpine")]);+ if !query.is_empty() { p.set_query(query); }+ p.marked = vec!["a".into()];+ p.on_tabs = on_tabs;+ let mut buf = Buffer::empty(body);+ let (cursor, _) = draw(&mut buf, &app, body, &kind, &mut p);+ (buf, p.screen_area.get(), cursor)+ }++ /// The launcher's rows from the list's tail to the query, and the styles of its query, count,+ /// rule and keys: what `draw` drew inline before those lines became shared pieces.+ #[test]+ fn the_launcher_keeps_its_rows_and_styles() {+ let _l = crate::term_out::colours_lock();+ let c = chrome();+ let fg = |s: Style| s.fg.unwrap_or(Color::Reset);+ let rule = |count: &str| format!(" {count} {}", "─".repeat(86 - count.width() - 1));+ let query = |typed: &str, more: &str| format!(" › {typed} [harnesses] > commands @ machines # projects : models{more}");+ let keys = |s: &str| format!(" {s}");+ let (alpine, beta, alpha) = (" alpine".to_string(), " beta".to_string(), " ›•alpha".to_string());+ let cases = [+ ("", false, [alpine.clone(), beta.clone(), alpha.clone(), String::new(), keys("↑↓ move · enter open"), rule("3/3 (1)"), query("Search harnesses", "")]),+ ("al", false, [String::new(), alpine.clone(), alpha.clone(), String::new(), keys("↑↓ move · enter open"), rule("2/3 (1)"), query("al", " * store")]),+ ("", true, [alpine, beta, alpha, String::new(), keys("← → switch · ↑ list · type to search"), rule("3/3 (1)"), query("Search harnesses", "")]),+ ];+ for (typed, on_tabs, want) in cases {+ let (buf, r, _) = launcher_buffer(typed, on_tabs);+ let row = |y: u16| (r.x..r.right()).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>().trim_end().to_string();+ let q = r.bottom() - 2;+ let title = row(r.y + 1);+ assert!(title.starts_with(" Harnesses ") && title.ends_with(" esc"), "{title}");+ let rows: Vec<String> = (q - 6..=q).map(row).collect();+ assert_eq!(rows.iter().map(|r| r.replace('│', "").trim_end().to_string()).collect::<Vec<_>>(), want.to_vec(), "{typed:?} tabs={on_tabs}");+ let cell = |y: u16, x: u16| buf[(r.x + x, y)].clone();+ // the prompt in accent; the count and its rule muted; a key bold, its word muted+ assert_eq!((cell(q, 2).symbol().to_string(), cell(q, 2).fg), ("›".to_string(), fg(c.accent)));+ assert_eq!(cell(q - 1, 2).fg, fg(c.muted));+ assert_eq!((cell(q - 1, 12).symbol().to_string(), cell(q - 1, 12).fg), ("─".to_string(), fg(c.muted)));+ assert!(!cell(q - 1, 12).modifier.contains(Modifier::BOLD));+ assert_eq!(cell(q - 2, 2).fg, fg(c.base));+ assert!(cell(q - 2, 2).modifier.contains(Modifier::BOLD));+ assert_eq!(cell(q - 2, 5).fg, fg(c.muted));+ }+ }++ #[test]+ fn the_launcher_draws_keys_count_and_query_in_three_rows() {+ let _l = crate::term_out::colours_lock();+ let app = app((100, 30));+ let body = Rect::new(0, 0, 100, 29);+ let kind = PickerKind::Open { filter: modal::Filter::All, machine: None, project: None };+ let mut p = Picker::new("harnesses", "");+ p.hints = vec![("↑↓", "move"), ("enter", "open")];+ p.set_rows(vec![crate::picker::Row::new("a", "alpha"), crate::picker::Row::new("b", "beta")]);+ let mut buf = Buffer::empty(body);+ let (cursor, _) = draw(&mut buf, &app, body, &kind, &mut p);+ let r = p.screen_area.get();+ let qy = r.bottom() - 2;+ let row = |y: u16| (r.x..r.right()).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>();+ assert!(row(qy).contains('›'), "{}", row(qy));+ assert!(row(qy - 1).trim_start().starts_with("2/2 (0) ─"), "{}", row(qy - 1));+ assert!(row(qy - 2).contains("↑↓ move · enter open"), "{}", row(qy - 2));+ assert_eq!(cursor, Some(Position::new(r.x + 2 + 2, qy)));+ }++ #[test]+ fn the_count_rule_without_a_marked_count() {+ let _l = crate::term_out::colours_lock();+ let c = chrome();+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));+ count_rule(&mut buf, 3, 5, None, 2, 0, 16, &c);+ let line: String = (0..20).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert_eq!(line, format!(" 3/5 {} ", "─".repeat(12)));+ assert_eq!(buf[(6, 0)].fg, c.muted.fg.unwrap_or(Color::Reset));+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));+ count_rule(&mut buf, 3, 5, Some(1), 2, 0, 16, &c);+ let line: String = (0..20).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(line.starts_with(" 3/5 (1) ─"), "{line}");+ }++ #[test]+ fn the_query_line_is_the_panels() {+ let _l = crate::term_out::colours_lock();+ let c = chrome();+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 3));+ let mut p = Picker::new("", "");+ p.query = "gpt".into(); p.qcursor = 3;+ let (at, used) = query_line(&mut buf, &p, 0, 0, 40, "@ computer", &c);+ assert_eq!(buf[(0, 0)].symbol(), "›");+ assert_eq!(buf[(0, 0)].fg, c.accent.fg.unwrap_or(Color::Reset));+ assert_eq!((buf[(2, 0)].symbol(), at, used), ("g", Position::new(5, 0), 3));+ p.query.clear(); p.qcursor = 0;+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 3));+ query_line(&mut buf, &p, 0, 0, 40, "@ computer", &c);+ assert_eq!(buf[(2, 0)].fg, c.muted.fg.unwrap_or(Color::Reset), "the ghost is muted");+ // whole scopes only, never a scope cut in half+ let mut buf = Buffer::empty(Rect::new(0, 0, 20, 1));+ query_line(&mut buf, &p, 0, 0, 20, "@ computer : project % model", &c);+ let line: String = (0..20).map(|x| buf[(x, 0)].symbol().to_string()).collect();+ assert!(line.contains("@ computer") && !line.contains("proj") && !line.contains('…'), "{line}");+ }++ #[test]+ fn a_long_query_scrolls_to_keep_its_cursor_in_view() {+ let c = chrome_with(true);+ let mut p = Picker::new("", "");+ p.query = "/home/dev/harnesses/worktrees/autonomous-harness/hn-007/tui/src".into();+ p.qcursor = p.query.chars().count();+ let draw = |p: &Picker| {+ let mut buf = Buffer::empty(Rect::new(0, 0, 40, 1));+ let (at, _) = query_line(&mut buf, p, 0, 0, 40, "", &c);+ (at, (0..40).map(|x| buf[(x, 0)].symbol().to_string()).collect::<String>())+ };+ let (at, line) = draw(&p);+ assert!(line.trim_end().ends_with("hn-007/tui/src"), "the last typed text: {line}");+ assert_eq!(at.x as usize, line.trim_end().width(), "the cursor right after it: {line}");+ assert!(at.x < 40);+ p.qcursor = 0;+ let (at, line) = draw(&p);+ assert!(line.starts_with("› /home/dev/harnesses"), "home shows the start: {line}");+ assert_eq!(at, Position::new(2, 0));+ }++ #[test]+ fn list_lines_counts_what_list_draws() {+ let mut p = Picker::new("", "");+ use crate::picker::Row;+ p.set_rows(vec![Row::new("a", "alpha").group("One"), Row::new("b", "beta").group("One"), Row::new("c", "gamma").group("Two")]);+ // One, alpha, beta, (blank), Two, gamma+ assert_eq!(list_lines(&p), 6);+ let mut buf = Buffer::empty(Rect::new(0, 0, 30, 10));+ list(&mut buf, &mut p, Rect::new(0, 0, 30, 10), &chrome_with(true), false);+ let drawn = (0..10).rposition(|y| (0..30).any(|x| buf[(x, y)].symbol() != " ")).unwrap() + 1;+ assert_eq!(list_lines(&p), drawn);+ p.query = "ga".into();+ p.refilter();+ assert_eq!(list_lines(&p), p.visible.len(), "while typing: the matches, untitled");+ }++ /// Only the shell composer keeps its empty message under a query: the command panel's lists+ /// (Projects, Models …) with no rows still say "Nothing matches" once something is typed.+ #[test]+ fn an_empty_list_under_a_query_says_nothing_matches_except_in_the_shell_composer() {+ let draw = |p: &mut Picker| { let mut buf = Buffer::empty(Rect::new(0, 0, 40, 4)); list(&mut buf, p, Rect::new(0, 0, 40, 4), &chrome_with(true), false); text(&buf) };+ for empty in ["No projects yet.", "Loading its models…"] {+ let mut p = Picker::new("", "");+ p.empty = empty.into();+ assert!(draw(&mut p).contains(empty), "{empty}");+ p.query = "foo".into();+ p.refilter();+ let shown = draw(&mut p);+ assert!(shown.contains("Nothing matches") && !shown.contains(empty), "{empty}: {shown}");+ p.shell_panel = true;+ assert!(draw(&mut p).contains(empty), "the composer says why: {empty}");+ p.busy = Some("loading".into());+ assert_eq!(draw(&mut p).trim(), "", "a loading composer's list is blank");+ }+ }++ // ── the lines as ratatui widgets draw what the hand-drawn ones drew (`oracle`) ──+ use oracle::{chromes, grounds, LONG};++ /// `put` as a `Span` writes the cells, styles and width the hand-drawn one did: wide+ /// characters, a combining mark in its grapheme, control characters, cut text, every width+ /// and an edge of the buffer.+ #[test]+ fn put_as_a_span_draws_what_set_stringn_did() {+ let texts = ["", "›", "New Harness", "日本語のクエリ", "e\u{301}cole · café", "tab\there\nnewline", "🙂 emoji wide", LONG];+ let styles = [Style::default(), Style::default().fg(Color::Rgb(1, 2, 3)).add_modifier(Modifier::BOLD), Style::default().bg(Color::Indexed(236)).add_modifier(Modifier::REVERSED)];+ let area = Rect::new(0, 0, 40, 2);+ for ground in grounds(area) { for text in texts { for style in styles { for x in [0u16, 3, 30, 39] { for width in 0..=42u16 {+ let (mut old, mut new) = (ground.clone(), ground.clone());+ let was = oracle::put(&mut old, x, 1, width, text, style);+ assert_eq!(put(&mut new, x, 1, width, text, style), was, "{text:?} at {x} in {width}");+ assert_eq!(old, new, "{text:?} at {x} in {width}");+ } } } } }+ }++ #[test]+ fn backdrop_as_a_block_dims_what_it_did() {+ let _l = crate::term_out::colours_lock();+ for c in chromes() { for ground in grounds(Rect::new(0, 0, 12, 6)) { for r in [Rect::new(0, 0, 12, 6), Rect::new(2, 1, 5, 3), Rect::new(10, 4, 8, 8), Rect::default()] {+ let (mut old, mut new) = (ground.clone(), ground.clone());+ oracle::backdrop(&mut old, r, c.backdrop);+ backdrop(&mut new, r, c.backdrop);+ assert_eq!(old, new, "{r:?}");+ } } }+ }++ /// The pickers the list is checked with, by [kind] (each built afresh: a picker is not+ /// `Clone`): plain rows; grouped rows with leads, hints, right columns (a long one, a narrow+ /// form, a wide-character one) and marks; the right column given half; a query that ungroups+ /// them; an empty list that says why; the composer's, saying nothing while it loads.+ const LIST_PICKERS: usize = 6;+ fn list_picker(kind: usize) -> (&'static str, Picker) {+ let mut p = Picker::new("", "");+ let grouped = || {+ let mut rows = Vec::new();+ for (g, group) in ["Harnesses", "Projects", "Machines"].iter().enumerate() {+ for i in 0..6 {+ let mut r = crate::picker::Row::new(format!("{g}:{i}"), format!("{group} item {i} with a longer name than most"));+ r.group = Some(group.to_string());+ r.lead = vec![Span::styled("● ", Style::default().fg(Color::Green)), Span::raw("cx ")];+ r.detail = vec![Span::raw(format!("what it is doing now, step {i}"))];+ r.right = match i % 3 { 0 => "autonomous-harness · studio · 3m".into(), 1 => "2h".into(), _ => String::new() };+ if i == 2 { r.right_narrow = Some("1d".into()) }+ if i == 4 { r.right = "大きな機械".into() }+ rows.push(r);+ }+ }+ rows+ };+ let what = match kind {+ 0 => { p.set_rows((0..30).map(|i| crate::picker::Row::new(format!("r{i}"), format!("row {i}"))).collect()); "plain" }+ 1 => { p.set_rows(grouped()); p.marked = vec!["0:1".into(), "1:3".into()]; "grouped" }+ 2 => { p.set_rows(grouped()); p.right_half = true; "right half" }+ 3 => { p.set_rows(grouped()); p.query = "item".into(); p.refilter(); "queried" }+ 4 => { p.empty = "No harnesses yet".into(); p.set_rows(Vec::new()); "empty" }+ _ => { p.set_rows(Vec::new()); p.shell_panel = true; p.busy = Some("loading".into()); "composer loading" }+ };+ (what, p)+ }++ /// The list as a `StatefulWidget` draws, scrolls and keeps its rows for the mouse as the+ /// hand-drawn one did: every picker above, top down and bottom up, with and without hints,+ /// the cursor at its first, a middle and its last row, scrolled by the wheel or following the+ /// cursor, in sizes down to nothing, in a dark and a light theme and NO_COLOR.+ #[test]+ fn the_panel_list_widget_draws_what_the_hand_drawn_list_did() {+ let _l = crate::term_out::colours_lock();+ for c in chromes() { for kind in 0..LIST_PICKERS { for bottom_up in [false, true] { for details in [false, true] {+ let last = list_picker(kind).1.visible.len().saturating_sub(1);+ for cursor in [0, last / 2, last] { for free in [false, true] { for (w, h) in [(0, 0), (4, 3), (20, 1), (30, 8), (60, 12), (90, 40)] {+ let area = Rect::new(2, 1, w, h);+ for ground in grounds(Rect::new(0, 0, w + 4, h + 2)) {+ let ((what, mut po), (_, mut pn)) = (list_picker(kind), list_picker(kind));+ for p in [&mut po, &mut pn] { p.cursor = cursor; p.free_scroll = free; p.scroll = if free { 3 } else { 0 } }+ let (mut old, mut new) = (ground.clone(), ground.clone());+ oracle::list_from(&mut old, &mut po, area, &c, details, bottom_up);+ list_from(&mut new, &mut pn, area, &c, details, bottom_up);+ let at = format!("{what} bottom_up {bottom_up} details {details} cursor {cursor} free {free} at {w}x{h}");+ assert_eq!(old, new, "{at}");+ assert_eq!((pn.scroll, &pn.row_at, pn.list_area.get()), (po.scroll, &po.row_at, po.list_area.get()), "{at}");+ }+ } } }+ } } } }+ }++ #[test]+ fn the_query_line_widget_draws_what_the_hand_drawn_one_did() {+ let _l = crate::term_out::colours_lock();+ let ghosts = ["Search agents @ computer : project % model & agent", "Search harnesses on every machine you have connected", ""];+ let queries = ["gpt", "日本語のクエリ", LONG];+ for c in chromes() { for w in 1..=160u16 {+ let area = Rect::new(3, 1, w, 1);+ for ground in grounds(Rect::new(0, 0, w + 6, 3)) {+ let check = |p: &Picker, ghost: &str, old: &mut Buffer, new: &mut Buffer, what: &str| {+ let before = p.xoffset.get();+ let was = oracle::query_line(old, p, area.x, area.y, area.width, ghost, &c);+ let (xoffset, prompt_at) = (p.xoffset.get(), p.prompt_at.get());+ p.xoffset.set(before);+ p.prompt_at.set((0, 0));+ let mut q = QueryLine::new(p, ghost, &c);+ q.render(area, new);+ assert_eq!((q.cursor, q.used), was, "{what} at {w}");+ assert_eq!((p.xoffset.get(), p.prompt_at.get()), (xoffset, prompt_at), "{what} at {w}");+ assert_eq!(old, new, "{what} at {w}");+ };+ for ghost in ghosts {+ let p = Picker::new("", "");+ check(&p, ghost, &mut ground.clone(), &mut ground.clone(), &format!("ghost {ghost:?}"));+ }+ for query in queries {+ let mut p = Picker::new("", "");+ p.query = query.into();+ let n = query.chars().count();+ // A cursor moved along the query frame by frame: its scroll carries over.+ for at in [n, 0, n / 2, n, 1, n] {+ p.qcursor = at;+ check(&p, "@ computer", &mut ground.clone(), &mut ground.clone(), &format!("{query:?} cursor {at}"));+ }+ }+ }+ } }+ }++ #[test]+ fn the_count_rule_widget_draws_what_the_hand_drawn_one_did() {+ let _l = crate::term_out::colours_lock();+ for c in chromes() { for w in 1..=160u16 {+ let area = Rect::new(2, 1, w, 1);+ for ground in grounds(Rect::new(0, 0, w + 4, 3)) {+ for (shown, total, marked) in [(0, 0, None), (3, 5, None), (3, 5, Some(1)), (1234, 56789, Some(12))] {+ let (mut old, mut new) = (ground.clone(), ground.clone());+ oracle::count_rule(&mut old, shown, total, marked, area.x, area.y, area.width, &c);+ CountRule { shown, total, marked, chrome: &c }.render(area, &mut new);+ assert_eq!(old, new, "{shown}/{total} {marked:?} at {w}");+ }+ }+ } }+ }++ #[test]+ fn the_keys_line_widget_draws_what_the_hand_drawn_one_did() {+ let _l = crate::term_out::colours_lock();+ let sets: [&[(&str, &str)]; 4] = [+ &[("↑↓", "move"), ("enter", "choose"), ("esc", "back")],+ &[("← →", "switch"), ("↑", "list"), ("type", "to search")],+ &[("enter", "choose"), ("esc", "back")],+ &[],+ ];+ for c in chromes() { for w in 1..=160u16 {+ let area = Rect::new(2, 1, w, 1);+ for ground in grounds(Rect::new(0, 0, w + 4, 3)) {+ for keys in sets {+ let (mut old, mut new) = (ground.clone(), ground.clone());+ oracle::keys_line(&mut old, keys, area.x, area.y, area.width, &c);+ KeysLine { keys, chrome: &c }.render(area, &mut new);+ assert_eq!(old, new, "{keys:?} at {w}");+ }+ }+ } }+ }++ #[test]+ fn the_surface_widget_fills_as_fill_did() {+ let _l = crate::term_out::colours_lock();+ for c in chromes() {+ for ground in grounds(Rect::new(0, 0, 30, 6)) {+ let (mut old, mut new) = (ground.clone(), ground.clone());+ oracle::fill(&mut old, Rect::new(2, 1, 20, 4), c.base);+ Surface(c.base).render(Rect::new(2, 1, 20, 4), &mut new);+ assert_eq!(old, new);+ // (A surface reaching past the buffer is cut at its edge, as fill's was.)+ let (mut old, mut new) = (ground.clone(), ground);+ oracle::fill(&mut old, Rect::new(20, 3, 20, 4), c.base);+ fill(&mut new, Rect::new(20, 3, 20, 4), c.base);+ assert_eq!(old, new);+ }+ }+ }++ /// The command panel (the launcher's lists, with their tabs, and the menus) drawn whole with+ /// the widgets is the panel the hand-drawn lines drew, in a dark and a light theme.+ #[test]+ fn the_command_panel_draws_what_it_did_with_the_hand_drawn_lines() {+ let _l = crate::term_out::colours_lock();+ // (The spinner still, so the two draws a moment apart show the same frame.)+ theme::begin_animation_frame(false);+ let app = app((200, 42));+ let rows = || (0..30).map(|i| crate::picker::Row::new(format!("r{i}"), format!("row {i}")).detail(vec![ratatui::text::Span::raw("a detail")]).right("C-b x").group(if i < 10 { "One" } else { "Two" })).collect::<Vec<_>>();+ let kinds = [+ PickerKind::Palette,+ PickerKind::Open { filter: modal::Filter::All, machine: None, project: None },+ PickerKind::Commands,+ PickerKind::Keybinds,+ PickerKind::Theme,+ ];+ for (bg, fg) in [("#1e1e2e", "#cdd6f4"), ("#fafafa", "#383a42")] {+ crate::term_out::set_theme_colours(Some((bg.into(), fg.into())));+ for kind in &kinds { for (w, h) in [(24, 8), (30, 12), (40, 24), (64, 20), (96, 30), (160, 41), (200, 41)] {+ for (query, tabs, flash) in [("", false, false), ("ro", false, false), (LONG, false, false), ("", true, false), ("ro", false, true)] {+ let body = Rect::new(0, 0, w, h);+ let picker = || {+ let mut p = Picker::new("t", "Search commands");+ p.hints = vec![("↑↓", "move"), ("enter", "open"), ("ctrl-x", "close it"), ("tab", "mark")];+ p.set_rows(rows());+ p.query = query.into();+ p.qcursor = query.chars().count();+ p.refilter();+ p.on_tabs = tabs;+ p.marked = vec!["r1".into()];+ if flash { p.flash = Some(("Copied".into(), std::time::Instant::now())) }+ p+ };+ let (mut a, mut b) = (picker(), picker());+ let (mut old, mut new) = (Buffer::empty(body), Buffer::empty(body));+ let was = oracle::draw(&mut old, &app, body, kind, &mut a);+ let now = draw(&mut new, &app, body, kind, &mut b);+ let what = format!("{kind:?} {w}x{h} {query:?} tabs {tabs} flash {flash}");+ assert_eq!(was, now, "{what}");+ assert_eq!((a.xoffset.get(), a.prompt_at.get(), &a.row_at), (b.xoffset.get(), b.prompt_at.get(), &b.row_at), "{what}");+ assert!(old == new, "{what}: the cells that differ, as drawn now: {:?}", old.diff(&new));+ }+ } }+ }+ crate::term_out::set_theme_colours(None);+ }}diff --git a/tui/src/shell_composer.rs b/tui/src/shell_composer.rsindex 57f63710a..aa74a9bf1 100644--- a/tui/src/shell_composer.rs+++ b/tui/src/shell_composer.rs@@ -514,7 +514,7 @@ pub fn run(args: &[String]) -> std::io::Result<i32> {};let mut launch = Launch::parse(agent, &args[1..]).map_err(std::io::Error::other)?;launch.cwd = std::env::current_dir()?.to_string_lossy().into_owned();- let plan = crate::shell_picker::exchange("compose-launch", &serde_json::to_value(&launch)?)?;+ let plan = crate::shell_picker::exchange("compose-launch", &serde_json::to_value(&launch)?, launch.host.as_deref().unwrap_or("this computer"))?;if plan["attached"] == true {if let Some(message) = plan["message"].as_str().filter(|s| !s.is_empty()) {eprintln!("{message}");diff --git a/tui/src/shell_context.rs b/tui/src/shell_context.rsindex d0fe653eb..d0cbae82a 100644--- a/tui/src/shell_context.rs+++ b/tui/src/shell_context.rs@@ -130,6 +130,29 @@ pub fn status(app: &App, pane: Option<u64>) -> String {.chars().filter(|c| !c.is_control()).collect::<String>().replace('#', "##")}+/// The TUI's look as a shell picker draws it (see `shell_picker::Look`): colours of the chosen+/// theme, else the terminal's answer (empty until it answers: the picker keeps its default);+/// `lists` is "fzf" when the user chose fzf's lists, by `@hn-lists fzf` or fzf options of their own.+fn look_value() -> serde_json::Value { look_value_with(&crate::theme::default_opts()) }+/// [look_value] with the fzf options given, not read from the environment.+fn look_value_with(fzf_opts: &[String]) -> serde_json::Value {+ let (background, foreground) = crate::term_out::terminal_colours().unwrap_or_default();+ let accent = crate::term_out::accent_override()+ .or_else(|| crate::term_out::native_accent().map(|[r, g, b]| format!("#{r:02x}{g:02x}{b:02x}")))+ .unwrap_or_default();+ let fzf = crate::settings::fzf_lists() || !crate::shell_picker::composer_panel(fzf_opts);+ json!(crate::shell_picker::Look { background, foreground, accent, lists: if fzf { "fzf" } else { "" }.into() })+}++/// The look a new shell starts with, as `HN_LOOK` for its first picker frame.+fn look_arg() -> String { format!("--look={}", look_value()) }++/// Separate the `--look=` argument from the others.+fn split_look(args: &[String]) -> (Vec<String>, Option<String>) {+ let look = args.iter().find_map(|a| a.strip_prefix("--look=")).map(String::from);+ (args.iter().filter(|a| !a.starts_with("--look=")).cloned().collect(), look)+}+pub fn bootstrap(token: &str, cli: Option<&str>, local: bool) -> Vec<String> {// The core receives only literal argv. Shell setup runs in the native helper after the PTY opens.let mut argv = if let Some(bin) = local.then(|| std::env::current_exe().ok()).flatten() {@@ -137,11 +160,29 @@ pub fn bootstrap(token: &str, cli: Option<&str>, local: bool) -> Vec<String> {} else { vec![cli.unwrap_or("harness").into(), "tui".into()] };argv.extend(["--shell-init".into(), token.into()]);if let Some(cli) = cli { argv.push(cli.into()); }+ // Only this build's own binary is known to take it; a remote's older hn would refuse the argument.+ if local { argv.push(look_arg()); }argv}/// A connected shell uses the service's durable receipt, never an agent_create command string.-pub async fn open_shell(link: &crate::daemon::Link, mut payload: serde_json::Value) -> Result<serde_json::Value, crate::daemon::RpcError> {+/// A folder that is gone on that computer (CWD_NOT_FOUND): the shell starts at its home instead.+pub async fn open_shell(link: &crate::daemon::Link, payload: serde_json::Value) -> Result<serde_json::Value, crate::daemon::RpcError> {+ let gone = |code: &str| code == "CWD_NOT_FOUND";+ let asked = payload["cwd"].as_str().is_some_and(|c| !c.is_empty());+ match open_shell_once(link, payload.clone()).await {+ // (A receipt says why it failed as `failure.code`; a refusal as `error`.)+ Ok(reply) if asked && [&reply["error"], &reply["failure"]["code"]].iter().any(|c| c.as_str().is_some_and(gone)) => {},+ Err(e) if asked && gone(&e.code) => {},+ other => return other,+ }+ let mut home = payload;+ home["cwd"] = json!("");+ home["creationId"] = json!(uuid::Uuid::new_v4().to_string());+ open_shell_once(link, home).await+}++async fn open_shell_once(link: &crate::daemon::Link, mut payload: serde_json::Value) -> Result<serde_json::Value, crate::daemon::RpcError> {if payload["cwd"].as_str().is_none_or(str::is_empty) {let folder = link.rpc("fs_list_dir", json!({"path":""}), Duration::from_secs(20)).await?;let path = folder["path"].as_str().ok_or_else(|| crate::daemon::RpcError::new("CWD_NOT_FOUND", "That computer's home folder is unavailable."))?;@@ -157,6 +198,13 @@ pub async fn open_shell(link: &crate::daemon::Link, mut payload: serde_json::Val}}+/// The script a new shell runs first: its context, the picker, and (when given) the TUI's look.+fn init_script(token: &str, picker: &str, cli: &str, look: Option<&str>) -> String {+ let look = look.map(|l| format!("export HN_LOOK={}\n", quote(l))).unwrap_or_default();+ format!("export _HN_CONTEXT={}\nexport _HN_PICKER={}\nexport _HN_CLI={}\n{look}{}", quote(token), quote(picker), quote(cli),+ include_str!("shell_bootstrap.sh").replace("@INTEGRATION@", include_str!("shell_integration.sh")))+}+pub fn initialize(args: &[String]) -> std::io::Result<()> {use std::os::unix::process::CommandExt;let Some(token) = args.first().filter(|v| uuid::Uuid::parse_str(v).is_ok()) else {@@ -164,12 +212,10 @@ pub fn initialize(args: &[String]) -> std::io::Result<()> {};let pick_agent = args.last().is_some_and(|arg| arg == "--pick-agent");let args = if pick_agent { &args[..args.len()-1] } else { args };+ let (args, look) = split_look(args);if args.len()>2 { return Err(std::io::Error::other("Invalid shell initialization arguments.")) }- let helpers = include_str!("shell_integration.sh");let picker = std::env::current_exe()?;- let script = format!("export _HN_CONTEXT={}\nexport _HN_PICKER={}\nexport _HN_CLI={}\n{}", quote(token),- quote(&picker.to_string_lossy()), quote(args.get(1).map(String::as_str).unwrap_or("harness")),- include_str!("shell_bootstrap.sh").replace("@INTEGRATION@", helpers));+ let script = init_script(token, &picker.to_string_lossy(), args.get(1).map(String::as_str).unwrap_or("harness"), look.as_deref());let mut command = std::process::Command::new("/bin/sh");command.args(["-c", &script]);if pick_agent { command.env("_HN_START_PICKER", "1"); }@@ -372,6 +418,12 @@ fn scan(carry: &mut Vec<u8>, bytes: &[u8], pane: u64) -> Vec<Request> {fn reply(app: &mut App, request: &Request, code: u8, text: &str) {reply_data(app, request, code, text, None);}+/// A picker's catalog reply, carrying how the TUI looks now. An `unchanged` one carries it too:+/// a theme change leaves a catalog's revision alone.+fn catalog_reply(app: &mut App, request: &Request, mut data: serde_json::Value) {+ if data.is_object() { data["look"] = look_value(); }+ reply_data(app, request, 0, "", Some(data));+}fn reply_data(app: &mut App, request: &Request, code: u8, text: &str, data: Option<serde_json::Value>) {let data = data.map(std::sync::Arc::new);app.shell_context.replies.push_back(Reply { request: request.clone(), code, text: text.into(), data: data.clone(), at: Instant::now() });@@ -687,7 +739,7 @@ fn inline_list(app: &mut App, request: Request) {let revision = hash.finish().to_string();if args["revision"].as_str() == Some(revision.as_str()) { data = json!({"unchanged":true}); }data["revision"] = json!(revision);- reply_data(app, &request, 0, "", Some(data));+ catalog_reply(app, &request, data);}fn load_routes(app: &mut App, request: Request) {@@ -847,7 +899,10 @@ pub fn tick(app: &mut App) {if app.shell_context.pending.as_ref().is_some_and(|r| r.verb != "compose-launch" && !r.verb.ends_with("-inline")) && !matches!(app.modal, Some(Modal::Picker { kind:PickerKind::ShellContext, .. })) {cancel(app);}- if app.shell_context.pending.as_ref().is_some_and(|r| r.at.elapsed() > Duration::from_secs(if r.verb == "compose-launch" { 180 } else { 100 })) {+ // A line-editor request is kept 5 s past the shell's own wait for that action+ // (shell_integration.sh `_hn_attempts`), so the shell always gives up first.+ let limit = |verb: &str| match verb { "compose-launch" => 180, "host-inline" => 105, "session-inline" => 185, "model-inline" => 65, _ => 100 };+ if app.shell_context.pending.as_ref().is_some_and(|r| r.at.elapsed() > Duration::from_secs(limit(&r.verb))) {finish(app, 1, "The request timed out. Your shell is unchanged.");}}@@ -1254,6 +1309,71 @@ mod tests {assert_eq!(app.panes.len(),1);}#[tokio::test]+ async fn catalog_replies_carry_the_tuis_theme() {+ let _l = crate::term_out::colours_lock();+ let _restore = LookGuard;+ crate::term_out::set_theme_colours(Some(("#101010".into(), "#eeeeee".into())));+ crate::term_out::set_accent_override(Some("#ff0000".into()));+ crate::settings::set_fzf_lists(true);+ let mut app = app();+ let token = prepare(&mut app,None,false); bind(&mut app,&token,"local","shell");+ output(&mut app,1,&request(&token,"list-host",r#"{"query":"","revision":""}"#));+ let data = app.shell_context.replies.back().unwrap().data.as_ref().unwrap();+ assert_eq!(data["look"]["accent"],"#ff0000");+ assert_eq!(data["look"]["background"],"#101010");+ assert_eq!(data["look"]["foreground"],"#eeeeee");+ assert_eq!(data["look"]["lists"],"fzf");+ let revision = data["revision"].as_str().unwrap().to_string();+ crate::settings::set_fzf_lists(false);+ output(&mut app,1,&request(&token,"list-host",&json!({"query":"","revision":revision}).to_string()));+ let data = app.shell_context.replies.back().unwrap().data.as_ref().unwrap();+ assert_eq!(data["unchanged"],true);+ assert_eq!(data["look"]["accent"],"#ff0000","an unchanged reply still says the theme");+ // A reply that is no catalog (a plan, an acknowledgement) carries no look.+ let plan = request(&token,"model-inline","0");+ output(&mut app,1,&plan);+ assert!(app.shell_context.replies.back().unwrap().data.as_ref().is_none_or(|d| d.get("look").is_none()));+ }+ /// Puts hn's process-wide colours and list style back, even when an assertion fails.+ struct LookGuard;+ impl Drop for LookGuard {+ fn drop(&mut self) {+ crate::term_out::set_theme_colours(None); crate::term_out::set_accent_override(None);+ crate::settings::set_fzf_lists(false);+ }+ }+ #[test]+ fn the_looks_lists_follow_the_choice_not_the_developers_environment() {+ let _l = crate::term_out::colours_lock();+ let _restore = LookGuard;+ let words = |s: &str| s.split(' ').map(String::from).collect::<Vec<_>>();+ assert_eq!(look_value_with(&[])["lists"], "");+ assert_eq!(look_value_with(&words("--layout=reverse --border"))["lists"], "fzf");+ crate::settings::set_fzf_lists(true);+ assert_eq!(look_value_with(&[])["lists"], "fzf", "@hn-lists fzf");+ }+ #[test]+ fn a_new_shell_starts_with_the_tuis_look_in_its_environment() {+ let script = init_script("tok","/bin/hn","harness",Some(r##"{"background":"#101010","accent":"it's"}"##));+ assert!(script.starts_with("export _HN_CONTEXT='tok'\n"));+ assert!(script.contains(r##"export HN_LOOK='{"background":"#101010","accent":"it'\''s"}'"##),"{script}");+ assert!(!init_script("tok","/bin/hn","harness",None).contains("HN_LOOK"));+ }+ #[test]+ fn the_look_travels_in_the_shell_start_arguments() {+ let _l = crate::term_out::colours_lock();+ let _restore = LookGuard;+ crate::term_out::set_theme_colours(Some(("#101010".into(),"#eeeeee".into())));+ let argv = bootstrap("tok",Some("cli"),true);+ let remote = bootstrap("tok",Some("cli"),false);+ crate::term_out::set_theme_colours(None);+ assert!(argv.iter().any(|a| a.starts_with("--look={") && a.contains("#101010")),"{argv:?}");+ assert!(!remote.iter().any(|a| a.starts_with("--look=")),"a remote's older hn would refuse it");+ let (args, look) = split_look(&argv[2..]);+ assert_eq!(args, ["tok".to_string(),"cli".to_string()]);+ assert!(look.unwrap().contains("#eeeeee"));+ }+ #[tokio::test]async fn inline_model_selection_uses_stable_ids_and_retry_does_not_repeat_it() {let mut app=app();let token=prepare(&mut app,None,false);bind(&mut app,&token,"local","shell");@@ -1304,6 +1424,34 @@ mod tests {assert_eq!(app.shell_context.replies.back().unwrap().code,1);}+ #[tokio::test]+ async fn an_inline_request_the_shell_gave_up_on_is_dropped_and_frees_the_picker() {+ let mut app=app();+ let token=prepare(&mut app,None,false);bind(&mut app,&token,"local","shell");+ let id=uuid::Uuid::new_v4().to_string();+ let waiting=|verb:&str,age:u64|Some(Request{token:token.clone(),id:uuid::Uuid::new_v4().to_string(),pane:1,verb:verb.into(),query:"Gone".into(),at:Instant::now()-Duration::from_secs(age)});+ // the shell waits as long as the TUI's own budget for each action; the TUI+ // keeps the request 5 s longer than that+ for (verb,limit) in [("host-inline",100),("session-inline",180),("model-inline",60)] {+ app.shell_context.pending=waiting(verb,limit+2);+ tick(&mut app);assert!(app.shell_context.pending.is_some(),"{verb} outlives the shell's {limit} s wait");+ app.shell_context.pending=waiting(verb,limit+6);+ tick(&mut app);+ assert!(app.shell_context.pending.is_none(),"{verb} expires 5 s after the shell gives up");+ assert_eq!(app.shell_context.replies.back().unwrap().code,1);+ }+ let pending=|age:u64|Some(Request{token:token.clone(),id:id.clone(),pane:1,verb:"host-inline".into(),query:"Gone".into(),at:Instant::now()-Duration::from_secs(age)});+ // a later request is served, not refused with "close the current picker first"+ output(&mut app,1,&request(&token,"model-inline","default"));+ assert_eq!(app.shell_context.replies.back().unwrap().code,0);+ // a cancel for a waiting -inline request frees the picker at once+ app.shell_context.pending=pending(1);+ output(&mut app,1,format!("\x1b]633;hn;{token};{id};cancel;\x07").as_bytes());+ assert!(app.shell_context.pending.is_none());+ output(&mut app,1,&request(&token,"model-inline","default"));+ assert_eq!(app.shell_context.replies.back().unwrap().code,0);+ }+#[tokio::test]async fn inline_cancel_and_invalid_session_return_to_the_same_shell() {let mut app=app();diff --git a/tui/src/shell_context/composition.rs b/tui/src/shell_context/composition.rsindex 345b30ab3..133ff2b64 100644--- a/tui/src/shell_context/composition.rs+++ b/tui/src/shell_context/composition.rs@@ -64,17 +64,11 @@ fn data(app: &mut App, request: &Request, rows: Vec<Row>, notice: String) {// therefore produce a different response for each query.items.revision = format!("{}:{}:{}", catalog.revision, catalog.scan_revision, args["query"].as_str().unwrap_or(""));if args["revision"].as_str() == Some(items.revision.as_str()) {- return reply_data(- app,- request,- 0,- "",- Some(json!({"unchanged":true,"revision":items.revision})),- );+ return catalog_reply(app, request, json!({"unchanged":true,"revision":items.revision}));}}}- reply_data(app, request, 0, "", serde_json::to_value(items).ok());+ if let Ok(data) = serde_json::to_value(items) { catalog_reply(app, request, data); }}fn folder_items(picker: &mut Picker, query: &str) -> crate::shell_picker::Items {diff --git a/tui/src/shell_integration.sh b/tui/src/shell_integration.shindex 215762740..ec9f41724 100644--- a/tui/src/shell_integration.sh+++ b/tui/src/shell_integration.sh@@ -2,45 +2,125 @@_hn_request() (exec 4<>/dev/tty[ -t 4 ] || { printf '%s\n' 'Run this command at an interactive Harness prompt.' >&2; exit 1; }+ # Ctrl-C cancels at any moment; before the request has an id there is+ # nothing to cancel yet.+ _hn_id='' _hn_stop='' _hn_drawn=''+ # The progress line's rows go before anything else is said, so the screen+ # shows only the prompt (and any message) again, on the row it started from.+ _hn_erase() {+ [ -z "$_hn_drawn" ] || printf '\r\033[2K\033[1A\033[2K\033[1A' >&4+ _hn_drawn=''+ }+ _hn_cancel() {+ [ -z "$_hn_id" ] || printf '\033]633;hn;%s;%s;cancel;\007' "$_HN_CONTEXT" "$_hn_id" >&4+ _hn_erase+ [ "$1" != 130 ] || printf '%s\n' 'Cancelled.' >&2+ exit "$1"+ }+ # A helper that Ctrl-C stopped (zsh only notes the signal) failed because the+ # user cancelled: say so, not that the request failed.+ _hn_fail() {+ [ -z "$_hn_stop" ] || _hn_cancel "$_hn_stop"+ _hn_erase+ [ -z "${1-}" ] || printf '%s\n' "$1" >&2+ exit 1+ }+ # zsh runs a trap inside its signal handler, even halfway through a builtin's+ # write. Exiting from there forks the EXIT trap's rm while the write holds the+ # stdio lock; the child waits on that lock forever and the shell freezes. So+ # zsh only notes the signal and the loop cancels; its read returns at once.+ # Bash acts in the trap: its read would wait out the timeout, and 3.2's takes+ # whole seconds only, so noting the signal could keep Ctrl-C waiting a second.+ # Bash 4.3+ runs the trap between commands. Older bash (macOS's 3.2) runs it+ # from the signal handler, but only while read waits, reading byte by byte+ # with read(2): no write is in progress there. Only a Ctrl-C that lands just+ # as an arriving reply grows read's buffer could meet a busy allocator, a+ # window of microseconds once per reply.+ if [ -n "${ZSH_VERSION-}" ]; then+ trap '_hn_stop=130' INT; trap '_hn_stop=143' TERM HUP+ else+ trap '_hn_cancel 130' INT; trap '_hn_cancel 143' TERM HUP+ fi+ _hn_who=''+ case "$1" in+ host-inline)+ _hn_who=${2-}; _hn_who=${_hn_who//[[:cntrl:]]/}+ case "$_hn_who" in+ -|local) _hn_who='This computer'; _hn_what='Opening a shell on this computer…' ;;+ *) _hn_what="Opening a shell on ${_hn_who:-the computer}…" ;;+ esac ;;+ model-inline) _hn_what='Switching model…' ;;+ session-inline) _hn_what='Opening session…' ;;+ *) _hn_what='' ;;+ esac+ # Drawn first, before any helper process starts, so a silent computer never+ # looks like a frozen shell, even on a busy machine. With wrapping off, a long+ # name in a narrow pane still takes one row.+ if [ -n "$_hn_what" ]; then+ printf '\n\033[?7l%s Ctrl-C to cancel\033[?7h\r\n' "$_hn_what" >&4+ _hn_drawn=1+ fi+ [ -z "$_hn_stop" ] || _hn_cancel "$_hn_stop" # cancelled already: start no helper# zsh subshells inherit the same RANDOM state. Use fresh OS randomness so# successive commands cannot accidentally reuse a completed request id._hn_nonce=$(od -An -N16 -tx1 /dev/urandom | tr -d ' \r\n')- [ "${#_hn_nonce}" = 32 ] || { printf '%s\n' 'Could not create a shell request.' >&2; exit 1; }+ [ "${#_hn_nonce}" = 32 ] || _hn_fail 'Could not create a shell request.'_hn_id="$$-$_hn_nonce"_hn_dir="$HOME/.harness/shell-requests/$_HN_CONTEXT"umask 077- mkdir -p -- "$_hn_dir" || exit 1+ mkdir -p -- "$_hn_dir" || _hn_fail_hn_fifo="$_hn_dir/$_hn_id"- mkfifo -- "$_hn_fifo" || exit 1+ mkfifo -- "$_hn_fifo" || _hn_failtrap 'rm -f -- "$_hn_fifo"; rmdir -- "$_hn_dir" 2>/dev/null || true' EXIT- trap 'printf "\\033]633;hn;%s;%s;cancel;\\007" "$_HN_CONTEXT" "$_hn_id" >&4; exit 130' INT- trap 'printf "\\033]633;hn;%s;%s;cancel;\\007" "$_HN_CONTEXT" "$_hn_id" >&4; exit 143' TERM HUP- exec 3<>"$_hn_fifo" || exit 1+ exec 3<>"$_hn_fifo" || _hn_fail_hn_query=$(printf '%s' "${2-}" | base64 | tr -d '\r\n')# A freshly reattached stream may miss its first output event. Retry the same# request id; the client deduplicates it and never repeats the action._hn_attempt=0- _hn_attempts=120- [ "$1" != picker-ready ] || _hn_attempts=5- while [ "$_hn_attempt" -lt "$_hn_attempts" ]; do+ # Called from a line-editor widget, a request says what it waits for and gives+ # up after the TUI's own budget for that action (the TUI drops it 5 s later).+ case "$1" in+ host-inline) _hn_attempts=100 ;;+ session-inline) _hn_attempts=180 ;;+ model-inline) _hn_attempts=60 ;;+ picker-ready) _hn_attempts=5 ;;+ *) _hn_attempts=120 ;;+ esac+ # The reply to this request ends it with the TUI's code and data.+ _hn_answer() {+ case "$_hn_reply" in "HN:$_hn_id:"*) ;; *) return 1 ;; esac+ _hn_reply=${_hn_reply#"HN:$_hn_id:"}+ _hn_code=${_hn_reply%%:*}+ _hn_data=${_hn_reply#*:}+ _hn_erase+ if [ "$_hn_code" = 0 ]; then+ printf '%s' "$_hn_data" | base64 -d+ exit 0+ fi+ [ -z "$_hn_data" ] || { printf '%s' "$_hn_data" | base64 -d >&2; printf '\n' >&2; }+ exit 1+ }+ while [ -z "$_hn_stop" ] && [ "$_hn_attempt" -lt "$_hn_attempts" ]; do_hn_attempt=$((_hn_attempt + 1))printf '\033]633;hn;%s;%s;%s;%s\007' "$_HN_CONTEXT" "$_hn_id" "$1" "$_hn_query" >&4+ [ -z "$_hn_stop" ] || breakIFS= read -r -t 1 _hn_reply <&3 || continue- case "$_hn_reply" in- "HN:$_hn_id:"*)- _hn_reply=${_hn_reply#"HN:$_hn_id:"}- _hn_code=${_hn_reply%%:*}- _hn_data=${_hn_reply#*:}- if [ "$_hn_code" = 0 ]; then- printf '%s' "$_hn_data" | base64 -d- exit 0- fi- [ -z "$_hn_data" ] || { printf '%s' "$_hn_data" | base64 -d >&2; printf '\n' >&2; }- exit 1- ;;- esac+ _hn_answer || :done- printf '%s\n' 'Harness did not answer. Your shell is still available; try again.' >&2+ [ -z "$_hn_stop" ] || _hn_cancel "$_hn_stop"+ # Given up: the TUI drops the request. An answer it sent before it saw that+ # is already on its way, so take one last look before saying none came.+ # Bash 3.2's read -t takes whole seconds only.+ printf '\033]633;hn;%s;%s;cancel;\007' "$_HN_CONTEXT" "$_hn_id" >&4+ if [ -n "${ZSH_VERSION-}" ] || [ "${BASH_VERSINFO[0]}" -ge 4 ]; then _hn_last=0.5; else _hn_last=1; fi+ IFS= read -r -t "$_hn_last" _hn_reply <&3 && _hn_answer+ [ -z "$_hn_stop" ] || _hn_cancel "$_hn_stop"+ _hn_erase+ case "$1" in+ *-inline)+ printf '%s did not answer. Your line is unchanged; try again.\n' "${_hn_who:-Harness}" >&2 ;;+ *) printf '%s\n' 'Harness did not answer. Your shell is still available; try again.' >&2 ;;+ esacexit 1)_hn_pick() {@@ -200,7 +280,7 @@ _hn_choose() {esac}_hn_picker_widget() {- local _hn_message _hn_choice _hn_rest _hn_cursor _hn_line _hn_kind _hn_value _hn_nl='+ local _hn_message _hn_choice _hn_rest _hn_cursor _hn_line _hn_kind _hn_value _hn_saved_int _hn_nl=''if [ -n "${ZSH_VERSION-}" ]; then_hn_choice=$(_HN_PICKER_WIDGET=1 _hn_pick compose "$BUFFER" "$CURSOR" "$@") || { zle reset-prompt; return 0; }@@ -230,10 +310,18 @@ _hn_picker_widget() {fireturn 0fi+ # Ctrl-C reaches this shell too. _hn_request cancels its own request; the+ # widget must not abort with it, or zsh throws the line away.+ # zsh's localtraps puts the user's INT trap back (localoptions keeps the+ # option itself to this widget); bash needs it saved by hand.+ if [ -n "${ZSH_VERSION-}" ]; then setopt localoptions localtraps; trap ':' INT; else _hn_saved_int=$(trap -p INT); trap '' INT; ficase "$_hn_kind" inhost|model) _hn_message=$(_hn_request "$_hn_kind-inline" "$_hn_value" 2>&1) || : ;;sessions) _hn_message=$(_hn_request session-inline "$_hn_value" 2>&1) || : ;;esac+ if [ -n "${BASH_VERSION-}" ]; then+ if [ -n "$_hn_saved_int" ]; then eval "$_hn_saved_int"; else trap - INT; fi+ fiif [ -n "$_hn_message" ]; thenif [ -n "${ZSH_VERSION-}" ]; then# The finder moved the physical cursor while ZLE retained its owndiff --git a/tui/src/shell_picker.rs b/tui/src/shell_picker.rsindex 91fde768a..d8ed2ebbb 100644--- a/tui/src/shell_picker.rs+++ b/tui/src/shell_picker.rs@@ -1,6 +1,7 @@//! A height-limited finder running in the shell's own PTY, like fzf --height.//! No alternate screen, application modal, shell evaluation, or extra executable.use std::fs::{File, OpenOptions};+use std::collections::BTreeSet;use std::io::{self, Read, Write};use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt};use std::path::PathBuf;@@ -34,6 +35,34 @@ pub struct Items {pub folder: Option<String>,/// Canonical computer for the draft, including an implicit current computer.pub machine: Option<String>,+ /// How the TUI looks now; every reply says it, `unchanged` ones too.+ pub look: Option<Look>,+}+/// The TUI's look, for the picker to draw in: `#rrggbb` colours (empty: the terminal's own), the+/// accent as `@hn-accent` takes it, and `lists` = "fzf" when the user chose fzf-styled lists.+#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+pub struct Look { pub background: String, pub foreground: String, pub accent: String, pub lists: String }++/// `look.lists` = "fzf": the composer keeps the fzf frame (the user's `@hn-lists fzf`, or fzf+/// options of their own in the TUI's environment).+static LISTS_FZF: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);++/// Draw with [look] from now on, through the setters the TUI's own chrome uses. True when+/// anything changed.+pub fn apply_look(look: &Look) -> bool {+ let colours=(!look.background.is_empty() && !look.foreground.is_empty()).then(||(look.background.clone(),look.foreground.clone()));+ let before=crate::term_out::accent_override();+ let mut changed=crate::term_out::set_theme_colours(colours);+ crate::term_out::set_accent_override((!look.accent.is_empty()).then(||look.accent.clone()));+ changed|=crate::term_out::accent_override()!=before;+ changed|=LISTS_FZF.swap(look.lists=="fzf",std::sync::atomic::Ordering::Relaxed)!=(look.lists=="fzf");+ changed+}++/// The look the TUI exported as `HN_LOOK` into this shell, for the first frame. True when it applied.+fn apply_env_look(json:Option<&str>)->bool {+ json.and_then(|j|serde_json::from_str::<Look>(j).ok()).is_some_and(|look|{apply_look(&look);true})}impl Items {pub fn from_picker(picker: &Picker) -> Self {@@ -174,7 +203,57 @@ impl Drop for Request {}fn clean(s: &str) -> String { s.chars().filter(|c| !c.is_control()).collect() }-pub fn exchange(verb:&str,value:&serde_json::Value)->io::Result<serde_json::Value> {+/// `failed` is the number of failures in a row while the last request failed.+/// A failure is kept apart from the server's status, so an error that happens+/// to end in "…" never reads as loading; while a retry is due, the list spins.+fn is_loading(items_loaded:bool,status:&str,failed:Option<u8>)->bool {+ match failed {+ Some(failures)=>retry_after(failures).is_some(),+ None=>!items_loaded || status.ends_with('…'),+ }+}+/// A failure's message stays readable: beside the spinner while a retry is due,+/// in the list once the retries are spent. A finished list with a notice (a+/// failed directory read, a catalog warning) shows it instead of looking empty.+fn paint_list(next:&mut Buffer,area:Rect,picker:&mut Picker,loading:bool,failure:Option<&str>,lines:Vec<Line<'static>>,bottom:bool)->Position {+ let previous_empty=std::mem::take(&mut picker.empty);+ let previous_flash=picker.flash.clone();+ match failure {+ Some(message) if loading=>picker.flash=Some((message.into(),Instant::now())),+ Some(message)=>picker.empty=message.into(),+ None if !loading && !picker.status.is_empty()=>picker.empty=picker.status.clone(),+ None=>{},+ }+ let at=paint_inline(next,area,picker,loading,lines,bottom);+ picker.empty=previous_empty;picker.flash=previous_flash;at+}+/// The line under a launch that waits for its computer: only once the wait is+/// long enough to notice (an instant local launch draws nothing), and one row+/// that fits the pane, since a wrapped line would add a row at every frame.+fn wait_line(elapsed:Duration,waiting:&str,cols:u16)->Option<String> {+ const FRAMES:[&str;8]=crate::theme::SPINNER;+ if elapsed<Duration::from_millis(150) {return None}+ let who=match clean(waiting).as_str() {"local"|"-"=>"this computer".to_string(),name=>name.to_string()};+ let line=format!("{} Starting on {who}… Ctrl-C to cancel",FRAMES[(elapsed.as_millis()/100) as usize%FRAMES.len()]);+ // The last column is left free: some terminals wrap on writing it.+ Some(crate::ui::clip(&line,usize::from(cols.saturating_sub(1))))+}+fn tty_cols(tty:&File)->u16 {+ use std::os::fd::AsRawFd;+ let mut size:libc::winsize=unsafe{std::mem::zeroed()};+ if unsafe{libc::ioctl(tty.as_raw_fd(),libc::TIOCGWINSZ,&mut size)}==0 && size.ws_col>0 {size.ws_col} else {80}+}+fn frame_due(loading:bool,last:Instant,now:Instant)->bool { loading && now.duration_since(last)>=Duration::from_millis(120) }+// A failed list request is retried a few times, then left showing its message.+fn retry_after(failures:u8)->Option<Duration> { (failures<=3).then(||Duration::from_secs(2)) }+fn paint_inline(next:&mut Buffer,area:Rect,picker:&mut Picker,loading:bool,lines:Vec<Line<'static>>,bottom:bool)->Position {+ // `inline_fzf` spins only for a busy picker; mark it for this paint alone.+ let busy=std::mem::replace(&mut picker.busy,loading.then(||"loading".to_string()));+ let at=crate::ui::inline_fzf(next,area,picker,loading,lines,bottom);+ picker.busy=busy;at+}+/// `waiting` names the computer; the line turns a spinner until the answer comes.+pub fn exchange(verb:&str,value:&serde_json::Value,waiting:&str)->io::Result<serde_json::Value> {use std::sync::atomic::{AtomicBool,Ordering};static INTERRUPTED:AtomicBool=AtomicBool::new(false);extern "C" fn interrupted(_:libc::c_int) {INTERRUPTED.store(true,Ordering::Relaxed);}@@ -184,14 +263,30 @@ pub fn exchange(verb:&str,value:&serde_json::Value)->io::Result<serde_json::Valulet _signal=Signal(unsafe{libc::signal(libc::SIGINT,interrupted as *const () as libc::sighandler_t)});let mut out=OpenOptions::new().read(true).write(true).open("/dev/tty")?;let mut request=Request::new(&mut out,verb,&value.to_string())?;- loop {+ let begun=Instant::now();+ let mut shown=usize::MAX;+ let result=loop {if INTERRUPTED.load(Ordering::Relaxed) {- write!(out,"\x1b]633;hn;{};{};cancel;\x07",request.token,request.id)?;out.flush()?;- return Err(io::Error::new(io::ErrorKind::Interrupted,"Launch cancelled."))+ let cancelled=write!(out,"\x1b]633;hn;{};{};cancel;\x07",request.token,request.id).and_then(|_|out.flush());+ break cancelled.and_then(|_|Err(io::Error::new(io::ErrorKind::Interrupted,"Launch cancelled.")))+ }+ match request.poll_value(&mut out) {+ Ok(Some(value))=>break Ok(value),+ Ok(None)=>{},+ Err(e)=>break Err(e),+ }+ let frame=(begun.elapsed().as_millis()/100) as usize;+ // The width is read each frame, so a pane resized meanwhile still gets one row.+ if frame!=shown && let Some(line)=wait_line(begun.elapsed(),waiting,tty_cols(&out)) {+ shown=frame;+ let _=write!(out,"\r\x1b[2K{line}");+ let _=out.flush();}- if let Some(value)=request.poll_value(&mut out)? { return Ok(value) }std::thread::sleep(Duration::from_millis(20));- }+ };+ // The wait line is gone before the shell prints anything of its own.+ if shown!=usize::MAX {let _=write!(out,"\r\x1b[2K");let _=out.flush();}+ result}fn dimensions(rows: u16, origin: u16, picker: &Picker) -> (u16, u16) {let height = crate::ui::fzf_rows(rows, theme::fzf_opts().height.unwrap_or(theme::Height {@@ -239,11 +334,13 @@ fn tty_position(out: &File) -> io::Result<(u16,u16)> {struct Screen {out: File, top: u16, height: u16, cols: u16, raw: bool,widget: bool, anchor_x: u16, previous: Option<Buffer>,+ /// The row an erase waits at for the next draw, which writes it inside its synchronized update.+ erase: Option<u16>,}impl Screen {fn new(out: File, picker: &Picker) -> io::Result<Self> {terminal::enable_raw_mode()?;- let mut screen=Self {out,top:0,height:0,cols:0,raw:true,widget:false,anchor_x:0,previous:None};+ let mut screen=Self {out,top:0,height:0,cols:0,raw:true,widget:false,anchor_x:0,previous:None,erase:None};let (cols, rows)=terminal::size().unwrap_or((80,24));// cursor::position retries reader errors indefinitely. Initialize the// event source first so an unusable input descriptor returns to the shell.@@ -268,7 +365,9 @@ impl Screen {// Resizing can bring old rows back from the terminal's reflow buffer,// beyond today's picker height. Clearing only the current rectangle// leaves those old borders behind (especially with Bash/Readline).- if self.height>0 {write!(self.out,"\x1b[{};1H\x1b[J",self.top+1)?;}+ // The erase waits for the redraw, inside its synchronized update: written now, the+ // terminal would show the picker blank until the redraw comes.+ if self.height>0 {self.erase=Some(self.erase.map_or(self.top,|t|t.min(self.top)));}Ok(())}fn resize(&mut self,cols:u16,rows:u16,picker:&Picker)->io::Result<()> {@@ -276,20 +375,14 @@ impl Screen {(self.top,self.height)=dimensions(rows,self.top,picker);self.cols=cols;self.clear()}- fn draw(&mut self,picker:&mut Picker,items:Option<&Items>,preview_id:Option<&str>)->io::Result<()> {+ fn draw(&mut self,picker:&mut Picker,items:Option<&Items>,preview_id:Option<&str>,loading:bool,failure:Option<&str>)->io::Result<()> {let area=self.area();let mut next=Buffer::empty(area);let valid=items.filter(|v| v.preview_id.as_deref()==preview_id && preview_id.is_some());let lines=valid.map(|v|v.preview.iter().map(|s|Line::raw(clean(s))).collect()).unwrap_or_default();let bottom=valid.is_some_and(|v|v.preview_bottom);- let loading=items.is_none() || picker.status.ends_with('…');- // Loading uses the usual spinner. A failed directory read or catalog- // warning must remain visible instead of looking like an endless load.- let previous_empty=std::mem::take(&mut picker.empty);- if !loading && !picker.status.is_empty() {picker.empty=picker.status.clone();}- let cursor=crate::ui::inline_fzf(&mut next,area,picker,loading,lines,bottom);- picker.empty=previous_empty;- let bytes=render_diff(self.previous.as_ref(),&next,cursor)?;+ let cursor=paint_list(&mut next,area,picker,loading,failure,lines,bottom);+ let bytes=render_diff(self.previous.as_ref(),&next,cursor,self.erase.take())?;self.out.write_all(&bytes)?;self.out.flush()?;self.previous=Some(next);@@ -297,12 +390,43 @@ impl Screen {}}-fn render_diff(previous:Option<&Buffer>,next:&Buffer,at:Position)->io::Result<Vec<u8>> {+/// [erase]: the row a clear erases from to the screen's end, first thing in the update.+fn render_diff(previous:Option<&Buffer>,next:&Buffer,at:Position,erase:Option<u16>)->io::Result<Vec<u8>> {let blank=Buffer::empty(next.area);let previous=previous.filter(|p|p.area==next.area).unwrap_or(&blank);let mut bytes=b"\x1b[?2026h\x1b[?7l\x1b[?25l".to_vec();+ if let Some(top)=erase {write!(bytes,"\x1b[{};1H\x1b[J",top+1)?;}let mut backend=CrosstermBackend::new(&mut bytes);- backend.draw(previous.diff(next).into_iter())?;+ let cells=previous.diff(next);+ // A row that holds (or held) a cluster the terminal may count otherwise is written whole and+ // its rest erased, as the main renderer does: a cell-by-cell update there leaves a stale character.+ let held=|buf:&Buffer,y:u16|(next.area.x..next.area.right()).any(|x|crate::term_out::risky(buf[(x,y)].symbol()));+ let whole:BTreeSet<u16>=cells.iter().map(|c|c.1).collect::<BTreeSet<_>>().into_iter()+ .filter(|y|held(next,*y)||held(previous,*y)).collect();+ backend.draw(cells.into_iter().filter(|c|!whole.contains(&c.1)))?;+ let width=|c:&ratatui::buffer::Cell|unicode_width::UnicodeWidthStr::width(c.symbol()).max(1) as u16;+ for y in whole {+ // Every cell up to its last that is not blank (the erase takes the blanks after it); the+ // area is the terminal's full width, so the erase reaches nothing of anyone else's.+ let end=(next.area.x..next.area.right()).rev().find(|x|next[(*x,y)]!=ratatui::buffer::Cell::EMPTY)+ .map_or(next.area.x,|x|x+width(&next[(x,y)]));+ let mut row=Vec::new();+ let mut x=next.area.x;+ while x<end { row.push((x,y,&next[(x,y)])); x+=width(&next[(x,y)]); }+ // Each draw places its first cell: after a cluster the terminal may have counted+ // otherwise, the next cell goes where hn counts it.+ let mut placed=true;+ for run in row.split_inclusive(|c|crate::term_out::risky(c.2.symbol())) {+ backend.draw(run.iter().copied())?;+ placed=!run.last().is_some_and(|c|crate::term_out::risky(c.2.symbol()));+ }+ // A row that reaches the last column needs no erase (the cursor waiting there would take+ // that column's cell with it).+ if end<next.area.right() {+ if !placed||row.is_empty() {write!(backend,"\x1b[{};{}H",y+1,end+1)?;}+ write!(backend,"\x1b[K")?;+ }+ }backend.set_cursor_position(at)?;write!(bytes,"\x1b[0m\x1b[?25h\x1b[?7h\x1b[?2026l")?;Ok(bytes)@@ -312,7 +436,9 @@ impl Drop for Screen {if let Ok(token)=std::env::var("_HN_CONTEXT") {let _=write!(self.out,"\x1b]633;hn;{};{};close-picker;\x07",token,uuid::Uuid::new_v4());}- let _=self.clear();+ // No redraw follows: the picker's rows are erased at once.+ let top=self.erase.take().map_or(self.top,|t|t.min(self.top));+ if self.height>0 {let _=write!(self.out,"\x1b[{};1H\x1b[J",top+1);}let y=if self.widget {self.top.saturating_sub(1)} else {self.top};let x=if self.widget {self.anchor_x.min(self.cols.saturating_sub(1))} else {0};if self.height>0 {let _=write!(self.out,"\x1b[0m\x1b[?2004l\x1b[{};{}H\x1b[?25h",y+1,x+1);}@@ -465,6 +591,7 @@ pub fn run(args:&[String])->io::Result<i32> {let composing=source=="compose";let unified=source=="choose";if uuid::Uuid::parse_str(&std::env::var("_HN_CONTEXT").unwrap_or_default()).is_err() {return Err(io::Error::other("Open this picker from a Harness shell."))}+ apply_env_look(std::env::var("HN_LOOK").ok().as_deref());let mut picker=Picker::new("","");picker.query=if automatic {draft.as_ref().unwrap().initial()} else if source=="compose" {String::new()} else {clean(args.get(1).map(String::as_str).unwrap_or("")).chars().take(128).collect()};picker.qend();let unified=unified || source=="compose";@@ -485,6 +612,10 @@ pub fn run(args:&[String])->io::Result<i32> {let mut due=Instant::now();let mut last_id=None;let mut dirty=true;+ let mut last_draw=Instant::now();+ let mut failures=0u8;+ // The last request's error, apart from the server's own status line.+ let mut failure:Option<String>=None;loop {let current=picker.current_id();if current!=last_id {@@ -493,9 +624,11 @@ pub fn run(args:&[String])->io::Result<i32> {// brief settle, so a held arrow doesn't launch a preview for every row.if picker.preview {due=Instant::now()+Duration::from_millis(35);}}- if dirty {+ // A visible spinner turns on its own; an idle picker draws nothing.+ let loading=is_loading(items.is_some(),&picker.status,failure.is_some().then_some(failures));+ if dirty || frame_due(loading,last_draw,Instant::now()) {theme::begin_animation_frame(true);- screen.draw(&mut picker,items.as_ref(),last_id.as_deref())?;dirty=false;+ screen.draw(&mut picker,items.as_ref(),last_id.as_deref(),loading,failure.as_deref())?;dirty=false;last_draw=Instant::now();}if request.is_none() && Instant::now()>=due {requested_preview=if picker.preview {picker.current_id()} else {None};@@ -510,7 +643,26 @@ pub fn run(args:&[String])->io::Result<i32> {last_query=picker.query.clone();}if let Some(r)=&mut request {- if let Some(mut value)=r.poll(&mut screen.out)? {+ let polled=r.poll(&mut screen.out);+ if let Err(e)=&polled {+ // "Office is offline", "Harness did not answer": say it in the list+ // and retry a few times, instead of ending the picker unseen.+ failures=failures.saturating_add(1);+ failure=Some(e.to_string());+ if items.is_none() {items=Some(Items::default());}+ request=None;dirty=true;+ due=Instant::now()+retry_after(failures).unwrap_or(Duration::from_secs(86400));+ } else if let Some(mut value)=polled? {+ failures=0;+ if failure.take().is_some() {dirty=true;}+ // Before `unchanged`: a theme change does not change a catalog's revision.+ if let Some(look)=&value.look {+ let panel=panel_now(&theme::default_opts());+ if apply_look(look) {+ dirty=true;+ if composing && panel!=panel_now(&theme::default_opts()) {compose_scope(&mut picker,kind);}+ }+ }if !value.unchanged {// Older preview servers omit this optional field. The request// still supplies the exact id; never associate it with today's cursor.@@ -556,7 +708,7 @@ pub fn run(args:&[String])->io::Result<i32> {}}if old_query!=picker.query {- due=Instant::now()+Duration::from_millis(150);+ due=Instant::now()+Duration::from_millis(150);failures=0;if let Some(action)=crate::input::finder_binding(&mut picker,"change",if theme::fzf().reverse {-1}else{1}) {end=action;}if composing && kind=="folder" && folder_parts(old_query.strip_prefix(':').unwrap_or(&old_query)).0!=folder_parts(picker.query.strip_prefix(':').unwrap_or(&picker.query)).0 {// A late reply from the old folder must never be selectable in@@ -656,9 +808,24 @@ fn composer_kind(query:&str,agents:bool)->&'static str {_=>if agents {"agent"} else {"sessions"},}}-fn compose_scope(picker:&mut Picker,kind:&str) {+/// Whether the composer takes the command panel's look: it does unless the user drew their lists+/// themselves with `--layout`/`--border`/`--info`/`--color` (or their short forms) in their fzf+/// options.+pub(crate) fn composer_panel(opts:&[String])->bool {+ const OWN:[&str;10]=["--layout","--reverse","+r","--border","--no-border","--info","--inline-info","--no-info","--color","--style"];+ !opts.iter().any(|v|OWN.contains(&v.split('=').next().unwrap_or(v)))+}+/// [composer_panel] for these options, and the TUI's look says the user did not choose fzf's lists.+fn panel_now(opts:&[String])->bool { composer_panel(opts) && !LISTS_FZF.load(std::sync::atomic::Ordering::Relaxed) }+fn compose_scope(picker:&mut Picker,kind:&str) { compose_scope_with(picker,kind,panel_now(&theme::default_opts())) }+/// [compose_scope] with the look decided by the caller (`panel`), not by the environment.+fn compose_scope_with(picker:&mut Picker,kind:&str,panel:bool) {picker.title=match kind {"agent"=>"Agent","host"=>"Computer","folder"=>"Project","model"=>"Model",_=>"Compose"}.into();- picker.placeholder=match kind {"sessions"=>"Search sessions","agent"=>"Search agents","part"=>"@ computer : project % model",_=>"Search"}.into();+ picker.placeholder=match kind {+ "sessions"=>"Search sessions @ computer : project % model & agent",+ "agent"=>"Search agents @ computer : project % model & agent",+ "part"=>"@ computer : project % model",_=>"Search"}.into();+ picker.shell_panel=kind!="sessions" && panel;picker.prefixed=!["part","sessions"].contains(&kind) && picker.query.starts_with(['&','@',':','%']);picker.scope_prefix=match kind {"agent"=>Some('&'),"model"=>Some('%'),_=>None};picker.preview=kind=="sessions";@@ -667,6 +834,64 @@ fn compose_scope(picker:&mut Picker,kind:&str) {#[cfg(test)]mod tests {use super::*;+ use ratatui::style::{Color,Modifier};+ fn look(bg:&str,fg:&str,accent:&str,lists:&str)->Look {+ Look{background:bg.into(),foreground:fg.into(),accent:accent.into(),lists:lists.into()}+ }+ fn reset_look() {+ crate::term_out::set_theme_colours(None);crate::term_out::set_accent_override(None);apply_look(&look("","","",""));+ }+ #[test]+ fn a_replys_look_changes_the_pickers_chrome() {+ let _l=crate::term_out::colours_lock();+ assert!(apply_look(&look("#ffffff","#111111","#ff0000","")));+ assert_eq!(theme::accent(),Color::Rgb(255,0,0));+ assert_eq!(crate::term_out::terminal_colours(),Some(("#ffffff".into(),"#111111".into())));+ assert!(!apply_look(&look("#ffffff","#111111","#ff0000","")),"the same look changes nothing");+ // An indexed accent is kept in the form `@hn-accent` takes.+ assert!(apply_look(&look("#ffffff","#111111","colour33","")));+ assert_eq!(theme::accent(),Color::Indexed(33));+ // No colours in the look: the picker is back to the terminal's own.+ assert!(apply_look(&look("","","","")));+ assert_eq!(crate::term_out::accent_override(),None);+ assert!(!crate::term_out::theme_chosen());+ reset_look();+ }+ #[test]+ fn a_replys_look_does_not_bring_colours_back_under_no_color() {+ let _l=crate::term_out::colours_lock();+ apply_look(&look("#ffffff","#111111","#ff0000","fzf"));+ let chrome=crate::settings::chrome_with(true);+ reset_look();+ assert_eq!(chrome.base,ratatui::style::Style::default());+ assert_eq!(chrome.accent,ratatui::style::Style::default().add_modifier(Modifier::BOLD));+ assert_eq!(chrome.selected,ratatui::style::Style::default().add_modifier(Modifier::REVERSED));+ }+ #[test]+ fn the_looks_lists_decide_whether_the_composer_keeps_the_fzf_frame() {+ let _l=crate::term_out::colours_lock();+ assert!(panel_now(&[]));+ assert!(apply_look(&look("","","","fzf")));+ assert!(!panel_now(&[]));+ let mut picker=Picker::new("","");+ compose_scope(&mut picker,"model");+ assert!(!picker.shell_panel);+ assert!(apply_look(&look("","","","")));+ assert!(panel_now(&[]));+ reset_look();+ }+ #[test]+ fn the_first_frame_uses_the_look_the_tui_exported() {+ let _l=crate::term_out::colours_lock();+ let json=r##"{"background":"#101010","foreground":"#eeeeee","accent":"#00ff00","lists":"fzf"}"##;+ assert!(apply_env_look(Some(json)));+ assert_eq!(theme::accent(),Color::Rgb(0,255,0));+ assert!(!panel_now(&[]));+ reset_look();+ assert!(!apply_env_look(Some("not json")),"a broken look is ignored");+ assert!(!apply_env_look(None));+ reset_look();+ }#[test]fn machine_identity_preserves_folders_for_current_computer_and_aliases() {let row=Row::new("M2","M2").extra("local-id");@@ -767,6 +992,118 @@ mod tests {picker.clear_query();assert_eq!(picker.query,prefix.to_string());picker.backspace(false);assert!(picker.query.is_empty());}}+ fn composer_picker(labels:&[&str])->Picker {+ let mut p=Picker::new("","");+ p.query="%gpt".into();p.qend();+ compose_scope_with(&mut p,"model",true);+ p.set_rows(labels.iter().map(|l|Row::new(*l,*l).detail(vec![ratatui::text::Span::raw("OpenAI")])).collect());+ p+ }+ fn row_text(buf:&Buffer,y:u16,w:u16)->String { (0..w).map(|x|buf[(x,y)].symbol().to_string()).collect() }+ #[test]+ fn the_composer_is_drawn_like_the_command_panel() {+ let _l=crate::term_out::colours_lock();+ let c=crate::settings::chrome();+ let mut picker=composer_picker(&["gpt-6-astra","gpt-6-astra-fast"]);+ assert!(picker.shell_panel);+ let area=Rect::new(0,0,60,6);+ let mut buf=Buffer::empty(area);+ crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],false);+ let row=|y:u16|row_text(&buf,y,60);+ assert!(!row(0).contains('╭') && !row(0).contains('│'),"no border: {}",row(0));+ assert!(row(0).trim_start().starts_with("› %gpt"),"{}",row(0));+ assert!(row(1).starts_with(" 2/2 ─"),"{}",row(1));+ assert!(row(5).contains("↑↓ move") && row(5).contains("esc back"),"{}",row(5));+ let sel=(0..60).find(|x|buf[(*x,2)].symbol()=="g").unwrap();+ // (Under NO_COLOR the chosen row has no band, only a modifier.)+ assert_eq!(buf[(sel,2)].bg,c.selected.bg.unwrap_or(Color::Reset),"the chosen row on the panel's lifted band");+ assert!(buf[(sel,2)].modifier.contains(c.selected.add_modifier));+ if let Some(bg)=c.selected.bg {+ assert!(buf[(sel,2)].modifier.contains(Modifier::BOLD));+ assert_ne!(buf[(sel,3)].bg,bg);+ } else {+ assert!(!buf[(sel,3)].modifier.contains(c.selected.add_modifier));+ }+ }+ #[test]+ fn the_ghost_shows_whole_scopes_and_the_panel_survives_tiny_areas() {+ let _l=crate::term_out::colours_lock();+ let mut picker=Picker::new("","");+ compose_scope_with(&mut picker,"agent",true);+ picker.set_rows(vec![Row::new("claude","Claude Code")]);+ assert_eq!(picker.placeholder,"Search agents @ computer : project % model & agent");+ for w in [1,8,23,24,30,60,140] { for h in 1..12 {+ let area=Rect::new(0,0,w,h);+ let mut buf=Buffer::empty(area);+ let at=crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],false);+ assert!(area.contains(at),"{w}x{h}: {at:?}");+ let first=row_text(&buf,0,w);+ assert!(!first.contains("Search agents1"),"{w}x{h}: {first}");+ } }+ let area=Rect::new(0,0,140,6);+ let mut buf=Buffer::empty(area);+ crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],false);+ let first=row_text(&buf,0,140);+ for scope in ["@ computer",": project","% model","& agent"] {assert!(first.contains(scope),"{scope}: {first}");}+ let area=Rect::new(0,0,40,6);+ let mut buf=Buffer::empty(area);+ crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],false);+ let first=row_text(&buf,0,40);+ assert!(first.contains("@ computer") && !first.contains("% model") && !first.contains('…'),"whole scopes only: {first}");+ }+ #[test]+ fn the_panel_spins_in_the_rule_while_loading_and_the_sessions_list_keeps_fzfs_frame() {+ let _l=crate::term_out::colours_lock();+ let mut picker=composer_picker(&["gpt-6-astra"]);+ picker.status="Searching models…".into();+ let area=Rect::new(0,0,60,6);+ let mut buf=Buffer::empty(area);+ paint_inline(&mut buf,area,&mut picker,true,vec![],false);+ let rule=row_text(&buf,1,60);+ assert!(rule.contains("Searching models…") && rule.contains("1/1"),"{rule}");+ assert!(picker.busy.is_none());+ let mut sessions=Picker::new("","");+ compose_scope_with(&mut sessions,"sessions",true);+ assert!(!sessions.shell_panel);+ }+ #[test]+ fn the_users_own_fzf_look_keeps_the_fzf_frame() {+ let words=|s:&str|s.split(' ').map(String::from).collect::<Vec<_>>();+ assert!(composer_panel(&[]));+ assert!(composer_panel(&words("--height=40% --multi")));+ for opts in ["--layout=reverse","--border=rounded","--info=inline","--color=light","--reverse","--no-border","--style=full"] {+ assert!(!composer_panel(&words(opts)),"{opts}");+ }+ }+ #[test]+ fn opting_out_of_the_panel_draws_the_fzf_frame() {+ let mut picker=Picker::new("","");+ configure(&mut picker,false);+ compose_scope_with(&mut picker,"model",false);+ picker.set_rows(vec![Row::new("gpt","gpt-6-astra")]);+ assert!(!picker.shell_panel);+ let area=Rect::new(0,0,60,8);+ let mut buf=Buffer::empty(area);+ crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],false);+ assert!((0..8).any(|y|row_text(&buf,y,60).contains('╭')),"the fzf frame");+ theme::fzf_reset();+ }+ #[test]+ fn a_composer_low_in_the_pane_opens_upward_like_the_launcher() {+ let _l=crate::term_out::colours_lock();+ let mut picker=composer_picker(&["gpt-6-astra","gpt-6-astra-fast"]);+ let area=Rect::new(0,0,60,6);+ let mut buf=Buffer::empty(area);+ let at=crate::ui::inline_fzf(&mut buf,area,&mut picker,false,vec![],true);+ let row=|y:u16|row_text(&buf,y,60);+ assert!(row(5).trim_start().starts_with("› %gpt"),"query at the bottom: {}",row(5));+ assert_eq!(at.y,5);+ assert!(row(4).starts_with(" 2/2 ─"),"{}",row(4));+ assert!(row(3).contains("↑↓ move") && row(3).contains("esc back"),"{}",row(3));+ assert!(row(2).contains("gpt-6-astra") && !row(2).contains("fast"),"first row nearest the query: {}",row(2));+ assert!(row(1).contains("gpt-6-astra-fast"),"{}",row(1));+ assert!(!row(0).contains("gpt"),"{}",row(0));+ }#[test]fn scope_characters_filter_only_the_unified_picker_and_can_be_removed() {let mut picker=Picker::new("","");@@ -808,6 +1145,75 @@ mod tests {}}#[test]+ fn frames_are_due_only_while_loading() {+ let t=Instant::now();+ assert!(frame_due(true,t,t+Duration::from_millis(150)));+ assert!(!frame_due(true,t,t+Duration::from_millis(50)));+ assert!(!frame_due(false,t,t+Duration::from_secs(5)),"an idle picker draws nothing");+ assert!(is_loading(false,"",None) && is_loading(true,"Searching folders…",None) && !is_loading(true,"Office is offline",None));+ }+ #[test]+ fn a_failed_request_says_why_while_retrying_and_after() {+ let area=Rect::new(0,0,60,12);+ let text=|buf:&Buffer|buf.content().iter().map(|c|c.symbol()).collect::<String>();+ // An error that ends in "…" is still an error: once the retries are+ // spent it stops spinning. During the 2 s retry gaps the spinner turns.+ let message="Office went to sleep…";+ // The fzf frame and the composer's panel both say it, a typed query too.+ for (panel,query) in [(false,""),(true,""),(true,"gpt")] {+ for (failures,spins) in [(1,true),(3,true),(4,false)] {+ let mut picker=Picker::new("","");configure(&mut picker,false);+ if panel {compose_scope_with(&mut picker,"model",true);}+ picker.query=query.into();picker.qend();+ let empty=picker.empty.clone();+ let loading=is_loading(true,&picker.status,Some(failures));+ assert_eq!(loading,spins,"{failures}");+ let mut buf=Buffer::empty(area);+ theme::begin_animation_frame(true);+ paint_list(&mut buf,area,&mut picker,loading,Some(message),vec![],false);+ assert_eq!(theme::needs_animation_frame(),spins,"{panel} {failures}");+ assert!(text(&buf).contains(message),"{panel} {query:?} {failures}: the message is not shown");+ // While it retries, the list under the message is blank, as the fzf frame's is.+ assert!(!text(&buf).contains("Nothing matches"),"{panel} {query:?} {failures}");+ assert!(picker.flash.is_none() && picker.empty==empty,"the message is not left on the picker");+ }+ }+ theme::fzf_reset();+ }+ #[test]+ fn the_launch_wait_line_is_one_row_and_waits_before_it_shows() {+ use unicode_width::UnicodeWidthStr;+ let at=Duration::from_millis;+ assert_eq!(wait_line(at(100),"Office",80),None,"an instant launch draws nothing");+ assert_eq!(wait_line(at(200),"Office",80).as_deref(),Some(format!("{} Starting on Office… Ctrl-C to cancel", crate::theme::SPINNER[2]).as_str()));+ for name in ["local","-"] {assert!(wait_line(at(200),name,80).unwrap().contains("Starting on this computer…"),"{name}");}+ // A long (CJK) name in a narrow pane stays on one row: a wrapped line+ // would add a row at every frame, and the final erase clears only one.+ for cols in [0,1,2,10,20,39] {+ let line=wait_line(at(300),"日本語のとても長いコンピューター名",cols).unwrap();+ assert!(line.width()<=usize::from(cols.saturating_sub(1)),"{cols}: {line}");+ }+ }+ #[test]+ fn a_failed_list_request_retries_three_times_then_stays_put() {+ assert_eq!(retry_after(1),Some(Duration::from_secs(2)));+ assert_eq!(retry_after(3),Some(Duration::from_secs(2)));+ assert_eq!(retry_after(4),None,"never an endless retry loop");+ }+ #[test]+ fn a_loading_inline_picker_spins_and_a_loaded_one_does_not() {+ let area=Rect::new(0,0,60,12);+ for loading in [true,false,true] {+ let mut picker=Picker::new("","");configure(&mut picker,false);+ let mut buf=Buffer::empty(area);+ theme::begin_animation_frame(true);+ paint_inline(&mut buf,area,&mut picker,loading,vec![],false);+ assert_eq!(theme::needs_animation_frame(),loading);+ assert!(picker.busy.is_none(),"the busy mark is not left on the picker");+ }+ theme::fzf_reset();+ }+ #[test]fn inline_renderer_survives_tiny_resizes_and_preserves_its_query() {let mut picker=Picker::new("","");configure(&mut picker,true);@@ -830,18 +1236,76 @@ mod tests {let area=Rect::new(0,4,120,18);let mut first=Buffer::empty(area);let at=crate::ui::inline_fzf(&mut first,area,&mut picker,false,vec![],false);- let full=render_diff(None,&first,at).unwrap();- let idle=render_diff(Some(&first),&first,at).unwrap();+ let full=render_diff(None,&first,at,None).unwrap();+ let idle=render_diff(Some(&first),&first,at,None).unwrap();assert!(idle.len()<100&&idle.len()*10<full.len(),"full={} idle={}",full.len(),idle.len());picker.move_by(1);let mut next=Buffer::empty(area);let at=crate::ui::inline_fzf(&mut next,area,&mut picker,false,vec![],false);- let moved=render_diff(Some(&first),&next,at).unwrap();- assert!(!moved.windows(4).any(|w|w==b"\x1b[2K"),"navigation erased a row");+ let moved=render_diff(Some(&first),&next,at,None).unwrap();+ assert!(!moved.windows(3).any(|w|w==b"\x1b[K")&&!moved.windows(4).any(|w|w==b"\x1b[2K"),"navigation erased a row");assert!(moved.len()<full.len()/2,"full={} move={}",full.len(),moved.len());theme::fzf_reset();}#[test]+ fn a_row_with_a_risky_symbol_is_written_whole_then_its_rest_erased() {+ use ratatui::style::Style;+ let area=Rect::new(0,4,20,3);+ let mut first=Buffer::empty(area);+ first.set_string(0,4,"plain",Style::default());+ first.set_string(0,5,"go ⚡ now",Style::default());+ let mut next=first.clone();+ next.set_string(8,5,"x",Style::default()); // a one-cell change on the risky row+ next.set_string(8,4,"y",Style::default()); // and on a plain row+ let bytes=render_diff(Some(&first),&next,Position::new(0,4),None).unwrap();+ let s=String::from_utf8_lossy(&bytes);+ assert!(!s.contains("\x1b[2K"),"a row is never erased before its text: {s:?}");+ // Row 5 (screen row 6) from its first column; the cell after ⚡ placed where hn counts it.+ let row=s.find("\x1b[6;1Hgo ⚡").unwrap_or_else(||panic!("row 5 written whole: {s:?}"));+ let after=s[row..].find("\x1b[6;6H nox").unwrap_or_else(||panic!("placed after the risky symbol: {s:?}"));+ assert_eq!(s.matches("\x1b[K").count(),1,"only the risky row is erased: {s:?}");+ assert!(s.find("\x1b[K").unwrap()>row+after,"its rest erased after its text: {s:?}");+ assert!(s.contains("\x1b[5;9Hy"),"the plain row stays a cell-by-cell update: {s:?}");+ // A terminal holding a longer, stale row 5: nothing of it survives.+ let mut pane=crate::pane::Pane::new(1,"m","a",20,8);+ pane.feed("\x1b[6;1Hgo ⚡ now STALE".as_bytes());+ pane.feed(&bytes);+ use alacritty_terminal::index::{Column,Line};+ let text:String=(0..16).filter(|x|*x!=4).map(|x|pane.term.grid()[Line(5)][Column(x)].c).collect();+ assert_eq!(text,"go ⚡ nox ","{s:?}");+ }+ #[test]+ fn a_ctrl_l_or_resize_redraw_erases_inside_its_synchronized_update() {+ let path=std::env::temp_dir().join(format!("hn-picker-screen-{}-{}",std::process::id(),uuid::Uuid::new_v4()));+ let out=OpenOptions::new().create_new(true).read(true).write(true).open(&path).unwrap();+ let mut screen=Screen{out,top:4,height:6,cols:40,raw:false,widget:false,anchor_x:0,previous:None,erase:None};+ let mut picker=Picker::new("","");+ picker.set_rows(vec![Row::new("1","one"),Row::new("2","two")]);+ // (No items yet: loading.)+ screen.draw(&mut picker,None,None,true,None).unwrap();+ let first=std::fs::read(&path).unwrap().len();+ // Ctrl-L: nothing is written until the redraw, which erases inside its own update.+ screen.clear().unwrap();+ assert_eq!(std::fs::read(&path).unwrap().len(),first,"the erase waits for the redraw");+ screen.draw(&mut picker,None,None,true,None).unwrap();+ // A resize: erased from the higher of the old and the new top.+ screen.resize(40,8,&picker).unwrap();+ let top=screen.top.min(4);+ screen.draw(&mut picker,None,None,true,None).unwrap();+ let bytes=std::fs::read(&path).unwrap();+ drop(screen);+ let _=std::fs::remove_file(&path);+ let s=String::from_utf8_lossy(&bytes[first..]);+ let frames:Vec<&str>=s.split_inclusive("\x1b[?2026l").collect();+ assert_eq!(frames.len(),2,"{s:?}");+ for f in &frames {+ assert!(f.starts_with("\x1b[?2026h")&&f.ends_with("\x1b[?2026l"),"{s:?}");+ assert_eq!(f.matches("\x1b[J").count(),1,"one erase, inside the update: {s:?}");+ }+ assert!(frames[0].contains("\x1b[5;1H\x1b[J"),"{s:?}");+ assert!(frames[1].contains(&format!("\x1b[{};1H\x1b[J",top+1)),"{s:?}");+ }+ #[test]fn paste_is_inserted_at_the_query_cursor_and_fzf_editing_keys_work() {let mut picker=Picker::new("","");picker.set_rows(vec![Row::new("1","日本 café suffix")]);diff --git a/tui/src/term_out.rs b/tui/src/term_out.rsindex 8c6356181..5ba23d2b5 100644--- a/tui/src/term_out.rs+++ b/tui/src/term_out.rs@@ -30,6 +30,15 @@ pub struct TmuxBackend<W: Write> {/// silent, as tmux is — a terminal's or an outer tmux's activity mark stays clear).cursor_at: Option<Position>,cursor_shown: Option<bool>,+ /// How many cells the last frame wrote (0 for one that wrote nothing): a large one is a+ /// burst the settle rewrite follows.+ last_cells: usize,+ /// The terminal's size as a test gives it (else the terminal is asked).+ size_known: Option<Size>,+ /// The rows written cell by cell (or owed) since the last settle rewrite, and the rows that+ /// rewrite writes whole in the next frame.+ touched: std::collections::BTreeSet<u16>,+ rewrite: std::collections::BTreeSet<u16>,}/// Whether a frame is wrapped in synchronized output (?2026): yes, unless `HARNESS_TUI_SYNC=off`@@ -41,7 +50,7 @@ fn sync_wanted(setting: &str) -> bool {/// A cluster whose width terminals may count otherwise than hn does: several code points (a/// base and its marks, ZWJ emoji, a keycap, VS16), or a script whose vowels some count as/// spacing and some as combining (Thai, Lao, Tibetan, Myanmar, Khmer).-fn risky(symbol: &str) -> bool {+pub(crate) fn risky(symbol: &str) -> bool {let mut n = 0;for c in symbol.chars() {n += 1;@@ -134,6 +143,10 @@ pub fn set_extra(x: u16, y: u16, extra: Extra) {if let Ok(mut f) = FRAME.lock() { if let Some(f) = f.as_mut() { f.extras.insert((x, y), extra); } }}+/// A full repaint rewrites rows over what the terminal holds, unless its size changed: then the+/// terminal reflowed its own cells and only an erase leaves no text outside the new rows.+pub fn repaint_is_soft(drawn: Size, now: Size) -> bool { drawn == now }+/// An overlay owns its cells; pane metadata underneath must not bleed through it.pub fn clear_extras(area: ratatui::layout::Rect) {if let Ok(mut frame) = FRAME.lock() { if let Some(frame) = frame.as_mut() {@@ -169,12 +182,31 @@ impl<W: Write> TmuxBackend<W> {Self { sync_ok, ..Self::with_sync(writer) }}- fn with_sync(writer: W) -> Self { Self { inner: CrosstermBackend::new(writer), shadow: Vec::new(), extra_shadow: Default::default(), syncing: false, sync_ok: true, soft: false, force_whole: false, cursor_at: None, cursor_shown: None } }+ fn with_sync(writer: W) -> Self { Self { inner: CrosstermBackend::new(writer), shadow: Vec::new(), extra_shadow: Default::default(), syncing: false, sync_ok: true, soft: false, force_whole: false, cursor_at: None, cursor_shown: None, last_cells: 0, size_known: None, touched: Default::default(), rewrite: Default::default() } }++ fn screen_size(&self) -> Option<Size> { self.size_known.or_else(|| self.inner.size().ok()) }- /// The next `clear()` does not erase the screen: every row is written again, each erased and- /// rewritten in the same write, so a stale cell goes but the screen is never seen blank.+ /// The next `clear()` does not erase the screen: every row is written again, its text and then+ /// the rest of it erased, so a stale cell goes but the screen is never seen blank.pub fn soft_clear_next(&mut self) { self.soft = true }+ /// The cells the last frame wrote.+ pub fn last_cells(&self) -> usize { self.last_cells }++ /// Rows the next settle rewrite writes too (where an overlay was).+ pub fn owe_rows(&mut self, rows: impl IntoIterator<Item = u16>) { self.touched.extend(rows) }++ /// The settle rewrite: the next frame writes whole every row touched since the last one (and+ /// nothing when none was: an idle hn stays silent).+ pub fn settle_next(&mut self) { let touched = std::mem::take(&mut self.touched); self.rewrite.extend(touched) }++ /// Opens the frame's synchronized update (once); `flush` closes it. A clear belongs inside it,+ /// so the terminal shows the erase and the redraw together, never the blank between them.+ fn begin_sync(&mut self) -> io::Result<()> {+ if self.sync_ok && !self.syncing { self.inner.write_all(b"\x1b[?2026h")?; self.syncing = true }+ Ok(())+ }+fn row_risky(&self, y: u16) -> bool { self.shadow.get(y as usize).map(|r| r.iter().any(|c| risky(c.symbol()))).unwrap_or(false) }fn remember(&mut self, x: u16, y: u16, cell: &Cell) {@@ -240,13 +272,51 @@ pub fn ask_terminal() {let _ = out.flush();}-/// The terminal's colours 1-7 as it answered OSC 4 (`#rrggbb`), where it did.-static PALETTE: std::sync::RwLock<[Option<[u8; 3]>; 8]> = std::sync::RwLock::new([None; 8]);+/// What hn draws with that the terminal answered or the look chose: one for the whole process —+/// and in tests each test thread's own, as the fzf look is (theme.rs): tests run side by side, and+/// each draws with the colours it set, not with what another set meanwhile.+struct Kept<T: 'static> {+ #[cfg(not(test))]+ shared: std::sync::RwLock<T>,+ #[cfg(test)]+ local: &'static std::thread::LocalKey<std::cell::RefCell<T>>,+}++impl<T: Clone> Kept<T> {+ fn get(&self) -> T {+ #[cfg(not(test))]+ { self.shared.read().unwrap_or_else(|e| e.into_inner()).clone() }+ #[cfg(test)]+ { self.local.with(|c| c.borrow().clone()) }+ }++ fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {+ #[cfg(not(test))]+ { f(&mut self.shared.write().unwrap_or_else(|e| e.into_inner())) }+ #[cfg(test)]+ { self.local.with(|c| f(&mut c.borrow_mut())) }+ }+}++/// A [Kept] named [$name] of type [$t], starting as [$init].+macro_rules! kept {+ ($name:ident, $local:ident, $t:ty, $init:expr) => {+ #[cfg(test)]+ thread_local! { static $local: std::cell::RefCell<$t> = const { std::cell::RefCell::new($init) }; }+ #[cfg(not(test))]+ static $name: Kept<$t> = Kept { shared: std::sync::RwLock::new($init) };+ #[cfg(test)]+ static $name: Kept<$t> = Kept { local: &$local };+ };+}++// The terminal's colours 1-7 as it answered OSC 4 (`#rrggbb`), where it did.+kept!(PALETTE, PALETTE_HERE, [Option<[u8; 3]>; 8], [None; 8]);/// Record an OSC 4 answer for colour [n] (1-7 are kept; the rest are not asked).pub fn set_palette_colour(n: u8, colour: Option<String>) {let Some((r, g, b)) = colour.as_deref().and_then(hex_rgb) else { return };- if (1..8).contains(&n) { if let Ok(mut p) = PALETTE.write() { p[n as usize] = Some([r, g, b]) } }+ if (1..8).contains(&n) { PALETTE.update(|p| p[n as usize] = Some([r, g, b])) }}/// The accent the terminal's own theme gives, when it answered its colours and its background:@@ -254,7 +324,7 @@ pub fn set_palette_colour(n: u8, colour: Option<String>) {pub fn native_accent() -> Option<[u8; 3]> {let (bg, _) = native_terminal_colours()?;let (r, g, b) = hex_rgb(&bg)?;- let p = PALETTE.read().ok()?;+ let p = PALETTE.get();let colours: Vec<(usize, [u8; 3])> = (1..8).filter_map(|i| p[i].map(|c| (i, c))).collect();// (Most of them, or it is not the terminal's palette speaking.)if colours.len() < 5 { return None }@@ -288,7 +358,7 @@ pub fn set_colours(n: u32) { COLOURS.store(n, std::sync::atomic::Ordering::Relax/// these are asked directly and answer reliably; the daemon uses them to paint agent panes.#[derive(Clone)]struct TerminalColours { bg: String, fg: String, foreground_reported: bool }-static TERMINAL_FG_BG: std::sync::RwLock<Option<TerminalColours>> = std::sync::RwLock::new(None);+kept!(TERMINAL_FG_BG, TERMINAL_FG_BG_HERE, Option<TerminalColours>, None);fn hex_rgb(hex: &str) -> Option<(u8, u8, u8)> {let h = hex.trim_start_matches('#');@@ -308,20 +378,21 @@ fn companion_fg(bg: &str) -> String {/// A theme chosen in the settings (`@hn-theme`) stands in for them: hn's chrome, and the panes the/// daemon paints, take the theme's background and foreground.pub fn terminal_colours() -> Option<(String, String)> {- if let Some(theme) = THEME_COLOURS.read().ok().and_then(|g| g.clone()) { return Some(theme) }- TERMINAL_FG_BG.read().ok()?.as_ref().map(|c| (c.bg.clone(), c.fg.clone()))+ if let Some(theme) = THEME_COLOURS.get() { return Some(theme) }+ native_terminal_colours()}/// The terminal's own answer, whatever theme is chosen (the settings' "Terminal default").pub fn native_terminal_colours() -> Option<(String, String)> {- TERMINAL_FG_BG.read().ok()?.as_ref().map(|c| (c.bg.clone(), c.fg.clone()))+ TERMINAL_FG_BG.get().map(|c| (c.bg, c.fg))}-/// The chosen theme's (background, foreground) as `#rrggbb`; None: the terminal's own.-static THEME_COLOURS: std::sync::RwLock<Option<(String, String)>> = std::sync::RwLock::new(None);+// The chosen theme's (background, foreground) as `#rrggbb`; None: the terminal's own.+kept!(THEME_COLOURS, THEME_COLOURS_HERE, Option<(String, String)>, None);-/// Tests that set hn's colours (a theme, an accent) or read them back hold this, one at a time:-/// the colours are one for the whole process, and tests run side by side.+/// Tests that set hn's colours (a theme, an accent) or read them back held this, one at a time,+/// when the colours were one for the whole test process; they are each test thread's own now+/// ([Kept]), so it only orders those tests.#[cfg(test)]pub fn colours_lock() -> std::sync::MutexGuard<'static, ()> {static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());@@ -329,26 +400,23 @@ pub fn colours_lock() -> std::sync::MutexGuard<'static, ()> {}/// Whether a theme's colours stand in for the terminal's now.-pub fn theme_chosen() -> bool { THEME_COLOURS.read().ok().is_some_and(|g| g.is_some()) }+pub fn theme_chosen() -> bool { THEME_COLOURS.get().is_some() }/// Draw with a theme's colours (or, None, the terminal's again). True when that changed them.pub fn set_theme_colours(colours: Option<(String, String)>) -> bool {- let Ok(mut g) = THEME_COLOURS.write() else { return false };- let changed = *g != colours;- *g = colours;- changed+ THEME_COLOURS.update(|g| { let changed = *g != colours; *g = colours; changed })}-/// The `[look]` accent (`@hn-accent`, a `#rrggbb`) to draw hn's chrome with, when the look names-/// one. Kept separate from the terminal palette because an accent is a choice, not a terminal-/// answer; `theme::accent()` consults it first and falls back to the derived teal.-static ACCENT_OVERRIDE: std::sync::RwLock<Option<String>> = std::sync::RwLock::new(None);+// The `[look]` accent (`@hn-accent`, a `#rrggbb`) to draw hn's chrome with, when the look names+// one. Kept separate from the terminal palette because an accent is a choice, not a terminal+// answer; `theme::accent()` consults it first and falls back to the derived teal.+kept!(ACCENT_OVERRIDE, ACCENT_OVERRIDE_HERE, Option<String>, None);pub fn set_accent_override(hex: Option<String>) {- if let Ok(mut g) = ACCENT_OVERRIDE.write() { *g = hex.map(normalise_hex_short) }+ ACCENT_OVERRIDE.update(|g| *g = hex.map(normalise_hex_short))}-pub fn accent_override() -> Option<String> { ACCENT_OVERRIDE.read().ok()?.clone() }+pub fn accent_override() -> Option<String> { ACCENT_OVERRIDE.get() }/// Accept `#rgb` too (shorthand) by expanding it to `#rrggbb`, the form hn parses.fn normalise_hex_short(hex: String) -> String {@@ -373,9 +441,7 @@ mod accent_override_tests {/// Record an OSC 10/11 answer. A half left blank keeps the other (a terminal may answer bg only);/// a missing foreground is chosen for contrast on the background.pub fn set_terminal_colours(bg: Option<String>, fg: Option<String>) {- if let Ok(mut guard) = TERMINAL_FG_BG.write() {- *guard = updated_terminal_colours(guard.as_ref(), bg, fg);- }+ TERMINAL_FG_BG.update(|kept| *kept = updated_terminal_colours(kept.as_ref(), bg, fg));}fn updated_terminal_colours(existing: Option<&TerminalColours>, bg: Option<String>, fg: Option<String>) -> Option<TerminalColours> {@@ -551,24 +617,34 @@ impl<W: Write> Backend for TmuxBackend<W> {self.extra_shadow = extras;// Nothing changed: nothing written.let all = std::mem::take(&mut self.force_whole);- if cells.is_empty() && !all { return Ok(()) }+ let rewrite = std::mem::take(&mut self.rewrite);+ self.last_cells = cells.len();+ if cells.is_empty() && !all && rewrite.is_empty() { return Ok(()) }+ // An input method or the terminal itself may have moved the cursor since the last frame:+ // the first cell of a frame that writes is placed by a CUP, never assumed.+ self.cursor_at = None;// A row that holds (or held) a cluster the terminal may count otherwise is written again// whole from its first column, as fzf writes a line: a cell-by-cell update there would// leave a stale character where the two counts part (a Thai vowel beside a keycap).let touched: std::collections::BTreeSet<u16> = cells.iter().map(|c| c.1).collect();let was: std::collections::HashSet<u16> = touched.iter().copied().filter(|y| self.row_risky(*y)).collect();for (x, y, c) in &cells { self.remember(*x, *y, c) }- let mut whole: std::collections::BTreeSet<u16> = touched.into_iter().filter(|y| was.contains(y) || self.row_risky(*y)).collect();- // A soft clear: every row of the screen (the terminal's height; else the rows known).+ let mut whole: std::collections::BTreeSet<u16> = touched.iter().copied().filter(|y| was.contains(y) || self.row_risky(*y)).collect();+ // A soft clear: every row of the screen (the terminal's height; else the rows known). A+ // settle rewrite: the rows touched since the last one.if all {- let rows = self.inner.size().map(|s| s.height as usize).unwrap_or(self.shadow.len()).max(self.shadow.len());+ let rows = self.screen_size().map(|s| s.height as usize).unwrap_or(self.shadow.len()).max(self.shadow.len());whole.extend((0..rows).map(|y| y as u16));}+ whole.extend(rewrite);+ // The rows written cell by cell are the next settle rewrite's.+ self.touched.extend(touched.into_iter().filter(|y| !whole.contains(y)));// A single-cell update fits in the writer's one buffered flush; synchronizing it// adds sixteen bytes to an ordinary one-byte echo without hiding any redraw.- if self.sync_ok && !self.syncing && (cells.len() > 1 || !whole.is_empty()) { self.inner.write_all(b"\x1b[?2026h")?; self.syncing = true }+ if cells.len() > 1 || !whole.is_empty() { self.begin_sync()? }let (usstyle, links) = frame.map(|f| (f.usstyle, f.links)).unwrap_or((false, false));let extra_at = |x: u16, y: u16| frame.and_then(|f| f.extras.get(&(x, y)));+ let cols = if whole.is_empty() { None } else { self.screen_size().map(|s| s.width as usize) };// CrosstermBackend writes through to its writer.let w = &mut self.inner;let mut pen = Pen::new();@@ -580,28 +656,35 @@ impl<W: Write> Backend for TmuxBackend<W> {let width = unicode_width::UnicodeWidthStr::width(cell.symbol()).max(1) as u16;self.cursor_at = Some(Position::new(x.saturating_add(width), *y));}+ // A row written whole: its text from the first column, then the rest of the row erased —+ // never erased first, which a terminal without ?2026 would show blank for a moment.+ let blank = Cell::default();+ let width = |c: &Cell| unicode_width::UnicodeWidthStr::width(c.symbol()).max(1);for y in whole {// A row of a soft clear with nothing on it is still erased: a stale cell may be there.- let Some(row) = self.shadow.get(y as usize) else {- if all { write!(w, "\x1b[{};1H", y + 1)?; pen.reset(w)?; w.write_all(b"\x1b[2K")?; self.cursor_at = None }- continue- };+ let row = match self.shadow.get(y as usize) { Some(row) => row.as_slice(), None if all => &[], None => continue };+ // (Blank cells at its end are the erase's.)+ let end = row.iter().enumerate().rev().find(|(x, c)| **c != blank || extra_at(*x as u16, y).is_some())+ .map_or(0, |(x, c)| x + width(c));write!(w, "\x1b[{};1H", y + 1)?;- self.cursor_at = Some(Position::new(0, y));- pen.reset(w)?;- w.write_all(b"\x1b[2K")?;let (mut skip, mut placed) = (0usize, true);- for (x, cell) in row.iter().enumerate() {+ for (x, cell) in row[..end].iter().enumerate() {if skip > 0 { skip -= 1; continue }// After a cluster the terminal may have counted otherwise, the next cell goes// where hn counts it.if !placed { write!(w, "\x1b[{};{}H", y + 1, x + 1)?; }pen.put(w, cell, extra_at(x as u16, y), usstyle, links)?;- let width = unicode_width::UnicodeWidthStr::width(cell.symbol()).max(1);- skip = width - 1;+ skip = width(cell) - 1;placed = !risky(cell.symbol());- self.cursor_at = placed.then(|| Position::new((x + width) as u16, y));}+ // A row that reaches the last column needs no erase (and the cursor waiting there+ // would take that column's cell with it).+ if cols.is_none_or(|c| end < c) {+ if !placed { write!(w, "\x1b[{};{}H", y + 1, end + 1)?; placed = true }+ pen.reset(w)?;+ w.write_all(b"\x1b[K")?;+ }+ self.cursor_at = placed.then(|| Position::new(end as u16, y));}// SGR 0 restores all three colours and attributes in one command; when they// are already default, a plain-text echo has nothing to restore.@@ -619,13 +702,18 @@ impl<W: Write> Backend for TmuxBackend<W> {self.cursor_at = Some(p);self.inner.set_cursor_position(p)}- fn clear(&mut self) -> io::Result<()> { self.shadow.clear(); self.extra_shadow.clear(); self.cursor_at = None; self.cursor_shown = None; self.inner.clear() }+ fn clear(&mut self) -> io::Result<()> { self.shadow.clear(); self.extra_shadow.clear(); self.touched.clear(); self.rewrite.clear(); self.cursor_at = None; self.cursor_shown = None; self.inner.clear() }fn clear_region(&mut self, clear_type: ClearType) -> io::Result<()> {if matches!(clear_type, ClearType::All) {+ // Hard or soft, the draw that follows is the same update; `flush` closes it.+ self.begin_sync()?;self.shadow.clear();self.extra_shadow.clear();+ // Every row is written again: no settle rewrite is owed for what came before.+ self.touched.clear();+ self.rewrite.clear();// A soft clear forgets what was written but erases nothing: the draw that follows writes- // every row, each erased and rewritten at once, so the screen is never seen blank.+ // every row, each its text and then the rest erased, so the screen is never seen blank.if std::mem::take(&mut self.soft) { self.cursor_at = None; self.force_whole = true; return Ok(()) }}self.inner.clear_region(clear_type)@@ -661,6 +749,186 @@ mod tests {assert_eq!(pane.term.grid()[Line(0)][Column(2)].c, 'b', "b lands where hn drew it");}+ #[test]+ fn a_frame_knows_how_many_cells_it_wrote() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let mut c = Cell::default();+ c.set_char('a');+ backend.draw([(0u16, 0u16, &c), (1, 0, &c), (2, 0, &c)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ assert_eq!(backend.last_cells(), 3);+ backend.draw(std::iter::empty()).unwrap();+ assert_eq!(backend.last_cells(), 0, "a frame with no change wrote none");+ }++ #[test]+ fn a_repaint_is_soft_unless_the_size_changed() {+ assert!(repaint_is_soft(Size::new(80, 24), Size::new(80, 24)));+ assert!(!repaint_is_soft(Size::new(80, 24), Size::new(100, 24)));+ assert!(!repaint_is_soft(Size::new(80, 24), Size::new(80, 20)));+ }++ #[test]+ fn a_soft_clear_writes_each_row_once_inside_one_update_and_never_erases_first() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(10, 3));+ let mut cells = Vec::new();+ for y in 0..3u16 { let mut c = Cell::default(); c.set_char('x'); cells.push((0u16, y, c)) }+ backend.draw(cells.iter().map(|(x, y, c)| (*x, *y, c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ backend.draw(cells.iter().map(|(x, y, c)| (*x, *y, c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(!s.contains("\x1b[2J") && !s.contains("\x1b[2K"), "{s:?}");+ // Each row's text, then the rest of the row erased: never a blank row mid-write.+ for y in 1..=3 { assert_eq!(s.matches(&format!("\x1b[{y};1Hx\x1b[K")).count(), 1, "row {y}: {s:?}") }+ assert_eq!(s.matches("\x1b[?2026h").count(), 2, "one update per frame: {s:?}");+ assert_eq!(s.matches("\x1b[?2026l").count(), 2, "{s:?}");+ // The soft frame's update opens before its first row is written.+ let after_first = &s[s.find("\x1b[?2026l").unwrap()..];+ assert!(after_first.find("\x1b[?2026h").unwrap() < after_first.find("\x1b[1;1Hx").unwrap(), "{s:?}");+ }++ /// Cells for [text] from column 0 of row [y], each at the column its width puts it.+ fn text_at(backend: &mut TmuxBackend<&mut Vec<u8>>, y: u16, text: &str) {+ use unicode_segmentation::UnicodeSegmentation;+ let mut cells = Vec::new();+ let mut x = 0u16;+ for g in text.graphemes(true) {+ let mut c = Cell::default();+ c.set_symbol(g);+ cells.push((x, y, c));+ x += unicode_width::UnicodeWidthStr::width(g).max(1) as u16;+ }+ backend.draw(cells.iter().map(|(x, y, c)| (*x, *y, c))).unwrap();+ Backend::flush(backend).unwrap();+ }++ #[test]+ fn a_whole_row_writes_its_text_and_then_erases_the_rest() {+ use alacritty_terminal::index::{Column, Line};+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(20, 2));+ text_at(&mut backend, 0, "abcdefgh");+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ text_at(&mut backend, 0, "ab");+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(!s.contains("\x1b[2K"), "{s:?}");+ assert!(s.contains("\x1b[1;1Hab\x1b[K"), "the text first, then the rest of the row: {s:?}");+ assert!(s.contains("\x1b[2;1H\x1b[K"), "an empty row is still erased: {s:?}");+ let mut pane = crate::pane::Pane::new(1, "m", "a", 20, 2);+ pane.feed(&written);+ let row: String = (0..8).map(|x| pane.term.grid()[Line(0)][Column(x)].c).collect();+ assert_eq!(row, "ab ", "no cell of the longer row survives");+ }++ #[test]+ fn a_whole_row_that_reaches_the_right_edge_is_not_erased_after_it() {+ // The cursor waits on the last column after printing there: an erase then takes that cell.+ use alacritty_terminal::index::{Column, Line};+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(4, 1));+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ text_at(&mut backend, 0, "abcd");+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(!s.contains("\x1b[K") && !s.contains("\x1b[2K"), "{s:?}");+ let mut pane = crate::pane::Pane::new(1, "m", "a", 4, 1);+ pane.feed(&written);+ assert_eq!(pane.term.grid()[Line(0)][Column(3)].c, 'd', "{s:?}");+ }++ #[test]+ fn a_risky_row_is_written_whole_text_first_and_placed_after_each_risky_symbol() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(20, 2));+ text_at(&mut backend, 0, "go⚡ now");+ text_at(&mut backend, 1, "ab⚡");+ // One cell changes on each row: both rows hold a risky symbol, so both are written whole.+ let mut x = Cell::default();+ x.set_char('x');+ backend.draw([(5u16, 0u16, &x), (0, 1, &x)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ let last = &s[s.rfind("\x1b[?2026h").unwrap()..];+ assert!(!last.contains("\x1b[2K"), "{last:?}");+ assert!(last.contains("\x1b[1;1Hgo⚡\x1b[1;5H xow\x1b[K"), "the cell after ⚡ placed by hn, the erase after the text: {last:?}");+ // A row that ends on a risky symbol: the erase starts where hn counts the row's end.+ assert!(last.contains("\x1b[2;1Hxb⚡\x1b[2;5H\x1b[K"), "{last:?}");+ }++ #[test]+ fn a_settle_rewrite_writes_only_the_rows_touched_since_the_last_one() {+ use alacritty_terminal::index::{Column, Line};+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(10, 4));+ text_at(&mut backend, 0, "ab");+ text_at(&mut backend, 2, "cd");+ backend.settle_next();+ backend.draw(std::iter::empty()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // Nothing touched since: the next one writes nothing (an idle hn stays silent).+ backend.settle_next();+ backend.draw(std::iter::empty()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ let settle = &s[s.rfind("\x1b[?2026h").unwrap()..];+ assert_eq!(settle, "\x1b[?2026h\x1b[1;1Hab\x1b[K\x1b[3;1Hcd\x1b[K\x1b[?2026l", "rows 1 and 3, not the screen: {s:?}");+ // A cell the terminal kept wrongly on a touched row is gone after it.+ let mut pane = crate::pane::Pane::new(1, "m", "a", 10, 4);+ pane.feed(b"\x1b[1;6HX");+ pane.feed(&written);+ assert_eq!(pane.term.grid()[Line(0)][Column(5)].c, ' ');+ }++ #[test]+ fn a_settle_rewrite_takes_the_rows_an_overlay_left_and_none_a_repaint_wrote() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.size_known = Some(Size::new(10, 4));+ for y in 0..3 { text_at(&mut backend, y, "xy") }+ backend.settle_next();+ backend.draw(std::iter::empty()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // One row changes, and an overlay that covered row 2 is gone.+ text_at(&mut backend, 0, "ab");+ backend.owe_rows(1..2);+ backend.settle_next();+ backend.draw(std::iter::empty()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // A row changes, then a repaint writes every row: nothing is owed after it.+ text_at(&mut backend, 2, "cd");+ backend.soft_clear_next();+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ let (mut a, mut b) = (Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ backend.settle_next();+ backend.draw(std::iter::empty()).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ let frames: Vec<&str> = s.split("\x1b[?2026h").collect();+ let second = frames.iter().find(|f| f.starts_with("\x1b[1;1Hab\x1b[K")).unwrap_or_else(|| panic!("{s:?}"));+ assert!(second.starts_with("\x1b[1;1Hab\x1b[K\x1b[2;1Hxy\x1b[K\x1b[?2026l"), "the changed row and the overlay's, not row 3: {s:?}");+ assert!(frames.last().unwrap().contains("\x1b[4;1H\x1b[K"), "the repaint is the last frame written: {s:?}");+ }+#[test]fn a_soft_clear_writes_every_row_over_the_screen_without_erasing_it() {use alacritty_terminal::index::{Column, Line};@@ -689,6 +957,45 @@ mod tests {assert_eq!(pane.term.grid()[Line(0)][Column(5)].c, ' ', "the stale cell was erased by its row being written again");}+ fn two_cells(backend: &mut TmuxBackend<&mut Vec<u8>>) {+ let (mut a, mut b) = (Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ }++ #[test]+ fn a_hard_clear_is_inside_the_frames_synchronized_update() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ // What `Terminal::clear` asks of the backend, then the frame that follows it.+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ let clear = s.find("\x1b[2J").expect("a hard clear");+ let open = s[..clear].rfind("\x1b[?2026h").expect("opened before the clear");+ assert!(s[..clear].rfind("\x1b[?2026l").map_or(true, |close| close < open), "no close between open and clear: {s:?}");+ assert!(s[clear..].contains("\x1b[?2026l"), "closed after the redraw: {s:?}");+ assert_eq!(s.matches("\x1b[?2026h").count(), s.matches("\x1b[?2026l").count(), "balanced: {s:?}");+ assert_eq!(s[clear..].matches("\x1b[?2026h").count(), 0, "the frame joins the clear's update, it does not open another: {s:?}");+ }++ #[test]+ fn a_hard_clear_without_synchronized_output_writes_no_2026() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ backend.sync_ok = false;+ Backend::clear_region(&mut backend, ClearType::All).unwrap();+ two_cells(&mut backend);+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(s.contains("\x1b[2J") && !s.contains("2026"), "{s:?}");+ }+#[test]fn synchronized_output_is_on_unless_turned_off() {assert!(sync_wanted(""));@@ -739,7 +1046,7 @@ mod tests {Backend::flush(&mut backend).unwrap();drop(backend);let bytes = written.as_slice();- assert!(bytes.len() <= 7, "one echoed key wrote {} bytes including its initial cursor", bytes.len());+ assert!(bytes.len() <= 13, "one echoed key wrote {} bytes: its initial cursor, the frame's own CUP and the char", bytes.len());let mut pane = crate::pane::Pane::new(1, "m", "a", 20, 4);pane.feed(bytes);use alacritty_terminal::index::{Column, Line, Point};@@ -747,6 +1054,46 @@ mod tests {assert_eq!(pane.term.grid().cursor.point, Point::new(Line(1), Column(3)));}+ #[test]+ fn each_frame_places_the_cursor_itself() {+ let mut written = Vec::new();+ let mut backend = TmuxBackend::with_sync(&mut written);+ let (mut a, mut b, mut c) = (Cell::default(), Cell::default(), Cell::default());+ a.set_char('a'); b.set_char('b'); c.set_char('c');+ backend.draw([(0u16, 0u16, &a), (1, 0, &b)].into_iter()).unwrap();+ Backend::flush(&mut backend).unwrap();+ // The next frame changes only the cell right after the cursor hn left (column 2).+ backend.draw(std::iter::once((2u16, 0u16, &c))).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let s = String::from_utf8_lossy(&written);+ assert!(s.contains("\x1b[1;3H"), "the second frame moved the cursor first: {s:?}");+ }++ #[test]+ fn an_idle_frame_writes_nothing_after_a_frame_with_cells() {+ // As ratatui calls the backend for a frame: draw, place the cursor, flush. A frame with+ // nothing changed writes nothing, not even a cursor move.+ let mut a = Cell::default();+ a.set_char('a');+ let at = Position::new(1, 0);+ let (mut one, mut two) = (Vec::new(), Vec::new());+ let mut backend = TmuxBackend::with_sync(&mut one);+ backend.draw(std::iter::once((0u16, 0u16, &a))).unwrap();+ backend.set_cursor_position(at).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ let mut backend = TmuxBackend::with_sync(&mut two);+ backend.draw(std::iter::once((0u16, 0u16, &a))).unwrap();+ backend.set_cursor_position(at).unwrap();+ Backend::flush(&mut backend).unwrap();+ backend.draw(std::iter::empty()).unwrap();+ backend.set_cursor_position(at).unwrap();+ Backend::flush(&mut backend).unwrap();+ drop(backend);+ assert_eq!(String::from_utf8_lossy(&one), String::from_utf8_lossy(&two));+ }+#[test]fn styled_frame_restores_colours_before_plain_echo() {let mut written = Vec::new();diff --git a/tui/src/theme.rs b/tui/src/theme.rsindex edd5e3df3..767cc5b0e 100644--- a/tui/src/theme.rs+++ b/tui/src/theme.rs@@ -537,7 +537,7 @@ fn pane_palette_for(native: Option<(Color, Color)>) -> PanePalette {/// fzf's colours — its dark256 default, or what `--color=light|16|bw` in `$FZF_DEFAULT_OPTS` asks/// for (and bw under NO_COLOR), so a list here looks like fzf does on this terminal.#[derive(Clone)]-pub struct Fzf { pub reverse: bool, pub unicode: bool, pub pointer_char: String, pub marker_char: String, pub marker_multi: [String; 3], pub prompt_text: String, pub bg_plus: Color, pub hl: Color, pub prompt: Color, pub bw: bool, pub pal: fzfcolor::Palette }+pub struct Fzf { pub reverse: bool, pub unicode: bool, pub pointer_char: String, pub marker_char: String, pub marker_multi: [String; 3], pub prompt_text: String, pub hl: Color, pub prompt: Color, pub pal: fzfcolor::Palette }impl Fzf {/// The border (and --border's glyphs) and the scrollbar: each its own slot.@@ -689,7 +689,7 @@ fn fzf_base() -> &'static Fzf {marker_char,// (Its first line only, as fzf's firstLine keeps it.)prompt_text: prompt.map(|p| p.split('\n').next().unwrap_or("").to_string()).unwrap_or_else(|| "> ".into()),- bg_plus: pal.current.style().bg.unwrap_or(Color::Reset), hl: fg(pal.matched), prompt: fg(pal.prompt), bw: !pal.colored, pal,+ hl: fg(pal.matched), prompt: fg(pal.prompt), pal,}})}@@ -1352,11 +1352,14 @@ pub fn animation_frame() -> usize {(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis() / 100).unwrap_or(0)) as usize}+/// hn's spinner, everywhere one turns (working dots, connecting cards, a list loading, a launch+/// waiting): three dots chasing round all four rows of a braille cell, so it turns about the+/// cell's middle. (fzf's ⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏ keep to the top three rows: it sat high in the cell.)+pub const SPINNER: [&str; 8] = ["⠋", "⠙", "⠸", "⢰", "⣠", "⣄", "⡆", "⠇"];+/// A spinner frame for things in motion (working dots, connecting cards).pub fn spinner(_tick: u64) -> &'static str {- // fzf's frames, in its order.- const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];- FRAMES[animation_frame() % FRAMES.len()]+ SPINNER[animation_frame() % SPINNER.len()]}#[cfg(test)]@@ -1453,6 +1456,7 @@ mod palette_tests {/// of it disagrees with the theme.#[test]fn palette_follows_the_terminal_answer() {+ let _colours = crate::term_out::colours_lock();crate::term_out::set_terminal_colours(Some("#201f26".into()), Some("#f5f5f5".into()));let (bg, fg, light) = palette();assert_eq!(bg, Color::Rgb(0x20, 0x1f, 0x26), "dark bg must map to the terminal's rgb");diff --git a/tui/src/tree.rs b/tui/src/tree.rsindex d6a0e4d78..25be55083 100644--- a/tui/src/tree.rs+++ b/tui/src/tree.rs@@ -1273,7 +1273,7 @@ fn display_menu(app: &mut App, t: &Tree, pane: u64, x: u32, y: u32, outside: boolet mut y = y;if x + w > sx { x = sx - w }if y + h > sy { y = sy - h }- app.modal = Some(Modal::Menu(crate::modal::Menu { title, items, choice: None, x: x as u16, y: y as u16, width, stay_open: false, no_mouse: false, mouse: None, tree: Some((pane, line)), complete: None, responsive: None }));+ app.modal = Some(Modal::Menu(crate::modal::Menu { title, items, choice: None, x: x as u16, y: y as u16, width, stay_open: false, no_mouse: false, mouse: None, tree: Some((pane, line)), complete: None, responsive: None, buttons: None }));}/// mode_tree_menu_callback and window_tree_menu: the menu's line made current, its item's keydiff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 28dbbd630..3b80c7a13 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -10,7 +10,9 @@ use alacritty_terminal::vte::ansi::{Color as AColor, NamedColor};use ratatui::buffer::Buffer;use ratatui::layout::{Position, Rect};use ratatui::style::{Color, Modifier, Style};+use ratatui::symbols::border;use ratatui::text::{Line, Span};+use ratatui::widgets::{Block, Clear, StatefulWidget, Widget};use ratatui::Frame;use unicode_width::UnicodeWidthStr;@@ -189,6 +191,7 @@ fn box_set(lines: &str) -> (&'static str, &'static str, &'static str, &'static spub fn draw(frame: &mut Frame, app: &mut App) {crate::workspace_controls::begin_frame(app);+ crate::pane_drag::let_go_if_gone(app);theme::begin_animation_frame(app.options.animations());app.renumber();// automatic-rename as of this frame: a pane that went into a mode ([tmux]) or out of one is@@ -232,6 +235,7 @@ pub fn draw(frame: &mut Frame, app: &mut App) {// The status bar down a side, and the tabs over the panes beside it.crate::bar::draw(buf, app);if let Some(Modal::DisplayPanes { .. }) = &app.modal { display_panes(buf, app) }+ crate::pane_drag::draw(buf, app);let search_busy = app.said_due.is_some() || app.said_pending > 0;let msg_style = app.message_style();if let Some(Modal::Picker { kind, mut picker }) = app.modal.take_if(|m| matches!(m, Modal::Picker { kind, .. } if crate::settings::is_panel(kind))) {@@ -287,16 +291,43 @@ pub fn draw(frame: &mut Frame, app: &mut App) {}// (Not under @hn-look tmux unless @hn-hint-time asks for it: tmux shows nothing after the prefix.)let hints = !(app.options.tmux_look() && app.options.get("@hn-hint-time", "", None).is_none());- if hints && app.prefix && app.prefix_at.map(|t| t.elapsed() >= Duration::from_millis(app.keymap.hint_ms)).unwrap_or(false) { which_key(buf, app, body) }+ let hinted = if hints && app.prefix && app.prefix_at.map(|t| t.elapsed() >= Duration::from_millis(app.keymap.hint_ms)).unwrap_or(false) { which_key(buf, app, body) } else { None };// `set -g status off`: no status line — a prompt or a message still borrows the last row.let hidden = app.status_lines() == 0;- let speaking = matches!(app.modal, Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. })) || app.toast.as_ref().map(|(_, _, at)| at.elapsed() < Duration::from_millis(app.toast_ms())).unwrap_or(false);+ let speaking = matches!(&app.modal, Some(Modal::Prompt(p)) if !p.dialog()) || matches!(app.modal, Some(Modal::Confirm { .. })) || app.toast.as_ref().map(|(_, _, at)| at.elapsed() < Duration::from_millis(app.toast_ms())).unwrap_or(false);if !hidden || speaking { if let Some(pos) = status_line(buf, app, status) { cursor = Some(pos) } }crate::os_welcome::draw_dock(buf, app);// A menu is tmux's overlay: over the status line too, where it is kept on the screen.if let Some(Modal::Menu(m)) = &app.modal { menu(buf, app, m) }if let Some(Modal::NewHarness(form)) = &mut app.modal { cursor = crate::new_harness::draw(buf, body, form); }+ if let Some(pos) = draw_prompt(buf, app) { cursor = Some(pos) }+ app.overlay_drawn = overlay_area(app, area, body, status, hinted);if let Some(pos) = cursor { frame.set_cursor_position(pos) }+ crate::devices::cancel_unfit(app);+}++/// Where this frame drew an overlay, for the settle rewrite: one that is gone or no longer covers+/// the cells it did may have left some kept wrongly (see `app::settle_due`). [hints]: the prefix's+/// key hints, when drawn.+fn overlay_area(app: &App, screen: Rect, body: Rect, status: Rect, hints: Option<Rect>) -> Option<Rect> {+ let spoken = app.toast.as_ref().is_some_and(|(_, _, at)| at.elapsed() < Duration::from_millis(app.toast_ms()));+ let area = match &app.modal {+ Some(Modal::Picker { picker, .. }) => Some(picker.screen_area.get()),+ // (Drawn clipped to the screen: a box placed past its edge. A confirmation's box is two rows+ // taller, for its blank row and its buttons.)+ Some(Modal::Menu(m)) if m.buttons.is_some() => Some(crate::workspace_menu::dialog_box(m).intersection(screen)),+ Some(Modal::Menu(m)) => Some(Rect::new(m.x, m.y, m.width + 4, m.items.len() as u16 + 2).intersection(screen)),+ Some(Modal::NewHarness(form)) => Some(form.drawn_area()),+ Some(Modal::Popup { x, y, width, height, .. }) => Some(Rect::new(*x, *y, *width, *height).intersection(screen)),+ // (hn's own questions are dialogs over the panes; tmux's prompts take the status line.)+ Some(Modal::Prompt(p)) if p.dialog() => prompt_layout(app).map(|(r, _)| r),+ Some(Modal::Prompt(_)) | Some(Modal::Confirm { .. }) => Some(status),+ Some(Modal::DisplayPanes { .. }) => Some(body),+ Some(Modal::Copy { .. }) | None if spoken => Some(status),+ Some(Modal::Copy { .. }) | None => None,+ };+ let area = area.filter(|r| r.width > 0 && r.height > 0);+ match (area, hints.filter(|r| r.width > 0 && r.height > 0)) { (Some(a), Some(h)) => Some(a.union(h)), (a, h) => a.or(h) }}/// tmux's menu (menu_draw_cb, screen_write_menu, screen_write_box): a box width + 4 wide at its@@ -305,23 +336,29 @@ pub fn draw(frame: &mut Frame, app: &mut App) {/// dim when disabled — its key right-aligned as (k); '' a rule across, joined to the sides.fn menu(buf: &mut Buffer, app: &App, m: &crate::modal::Menu) {let opt = |name: &str, default: &str| Some(app.style_spec(name, app.active, app.focused())).filter(|s| !s.is_empty()).unwrap_or_else(|| default.to_string());+ let lines = opt("menu-border-lines", "single");+ // A menu with buttons is a dialog: its box takes the command panel's surface so the box and+ // its buttons match; the vertical menus keep menu-style.+ if let Some(b) = &m.buttons {+ let c = crate::settings::chrome();+ // (An overlay: the window behind it dimmed, as every question is asked.)+ let over = app.body();+ return confirmation(m, &b.row, &lines, &c).render_over(over, crate::workspace_menu::dialog_box(m), buf);+ }let base = Style::default();// tmux's menu_set_style keeps colours, clearing attributes for each menu pair.let plain = |mut st: Style| { st.add_modifier = Modifier::empty(); st.sub_modifier = Modifier::empty(); st };let style = plain(crate::draw::style_over(&opt("menu-style", "default"), base));let selected = plain(crate::draw::style_over(&opt("menu-selected-style", "bg=yellow,fg=black"), base));let border = plain(crate::draw::style_over(&opt("menu-border-style", "default"), style));- let lines = opt("menu-border-lines", "single");- let (tl, tr, bl, br, hz, vt, lj, rj) = box_set(&lines);+ let (.., hz, _, lj, rj) = box_set(&lines);let (w, h) = (m.width + 4, m.items.len() as u16 + 2);let (x0, y0) = (m.x, m.y);- crate::term_out::clear_extras(Rect::new(x0, y0, w, h));- let put = |buf: &mut Buffer, x: u16, y: u16, s: &str, st: Style| { if let Some(c) = buf.cell_mut((x, y)) { c.set_symbol(s); c.set_style(st); } };- for y in y0..y0 + h { for x in x0..x0 + w { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(style); } } }- let (x1, y1) = (x0 + w - 1, y0 + h - 1);- for x in x0 + 1..x1 { put(buf, x, y0, hz, border); put(buf, x, y1, hz, border) }- for y in y0 + 1..y1 { put(buf, x0, y, vt, border); put(buf, x1, y, vt, border) }- put(buf, x0, y0, tl, border); put(buf, x1, y0, tr, border); put(buf, x0, y1, bl, border); put(buf, x1, y1, br, border);+ let area = Rect::new(x0, y0, w, h);+ crate::term_out::clear_extras(area);+ // The box: cleared, in menu-style, its border in menu-border-lines and menu-border-style.+ Clear.render(area, buf);+ Block::bordered().border_set(dialog_border(&lines)).border_style(border).style(style).render(area, buf);let draw_at = |buf: &mut Buffer, x: u16, y: u16, text: &str, st: Style, avail: u16| {for (i, cell) in crate::draw::format_draw_over(text, st, avail).into_iter().enumerate() {if let Some((ch, cs)) = cell { if let Some(c) = buf.cell_mut((x + i as u16, y)) { c.set_symbol(if ch.is_empty() { " " } else { &ch }); c.set_style(cs); } }@@ -331,24 +368,85 @@ fn menu(buf: &mut Buffer, app: &App, m: &crate::modal::Menu) {for (i, it) in m.items.iter().enumerate() {let y = y0 + 1 + i as u16;if it.separator {- put(buf, x0, y, lj, border);- for x in x0 + 1..x1 { put(buf, x, y, hz, border) }- put(buf, x1, y, rj, border);+ // A rule across, joined to the sides.+ Line::from_iter([Span::styled(lj, border), Span::styled(hz.repeat(w.saturating_sub(2) as usize), border), Span::styled(rj, border)]).render(Rect::new(x0, y, w, 1), buf);continue;}// screen_write_menu: the row padded first, then a disabled item's words drawn dim.let pad = if m.choice == Some(i) && !it.disabled { selected } else { style };- for x in x0 + 1..x0 + 1 + m.width + 2 { put(buf, x, y, " ", pad) }+ Block::new().style(pad).render(Rect::new(x0 + 1, y, m.width + 2, 1), buf);let st = if it.disabled { style.add_modifier(Modifier::DIM) } else { pad };- let text = if it.key.is_empty() { it.label.clone() } else { format!("{}#[default] #[align=right]({})", it.label, it.key) };- draw_at(buf, x0 + 2, y, &text, st, m.width);+ draw_at(buf, x0 + 2, y, &menu_text(it), st, m.width);}}+/// An item's words, its key right-aligned as (k).+fn menu_text(it: &crate::modal::MenuItem) -> String {+ if it.key.is_empty() { it.label.clone() } else { format!("{}#[default] #[align=right]({})", it.label, it.key) }+}++/// menu-border-lines as a ratatui border set, for the dialogs drawn as `Block`s.+pub fn dialog_border(lines: &str) -> border::Set<'static> {+ let (tl, tr, bl, br, hz, vt, ..) = box_set(lines);+ border::Set { top_left: tl, top_right: tr, bottom_left: bl, bottom_right: br, vertical_left: vt, vertical_right: vt, horizontal_top: hz, horizontal_bottom: hz }+}++/// One of hn's own questions (Rename Tab, Rename Harness, Send, Broadcast, Answer, Message) as the+/// shared `Dialog` in the middle of the panes, in menu-border-lines: its line of context, the+/// input and its buttons. None where the buttons, or the input, cannot fit.+pub fn prompt_dialog<'a>(app: &App, p: &'a crate::modal::Prompt, row: &'a crate::buttons::Row, c: &'a crate::settings::Chrome) -> Option<(Rect, crate::dialog::Dialog<'a>)> {+ let over = app.body();+ let room = over.width.saturating_sub(4);+ if row.buttons_width() > room { return None }+ let lines = Some(app.style_spec("menu-border-lines", app.active, app.focused())).filter(|s| !s.is_empty()).unwrap_or_else(|| "single".into());+ let body = if p.body.is_empty() { Vec::new() } else { crate::dialog::wrap(&p.body, room.min(crate::dialog::INPUT_W), c.base) };+ let mut d = crate::dialog::Dialog::new(&p.title, body, row, c);+ d.border = dialog_border(&lines);+ d.input = Some(crate::dialog::Input { label: &p.field, value: &p.value, caret: p.cursor, select: None, secret: p.secret, focused: !p.buttons, width: crate::dialog::INPUT_W });+ if !d.fit(over.height) { return None }+ Some((d.place(over), d))+}++/// The open question's box and the parts inside it (for drawing and clicks alike).+pub fn prompt_layout(app: &App) -> Option<(Rect, crate::dialog::Areas)> {+ let Some(Modal::Prompt(p)) = &app.modal else { return None };+ if !p.dialog() { return None }+ let (row, c) = (p.row(), crate::settings::chrome());+ let (r, d) = prompt_dialog(app, p, &row, &c)?;+ Some((r, d.areas(r)))+}++/// Draws the open question, if it is one of hn's dialogs: where its caret is. One with no room+/// to be drawn is cancelled, never kept invisible to answer keys.+fn draw_prompt(buf: &mut Buffer, app: &mut App) -> Option<Position> {+ let Some(Modal::Prompt(p)) = &app.modal else { return None };+ if !p.dialog() { return None }+ let (row, c) = (p.row(), crate::settings::chrome());+ let Some((r, d)) = prompt_dialog(app, p, &row, &c) else {+ app.modal = None;+ app.back_to_list = None;+ app.say(crate::workspace_menu::TOO_SMALL_TO_ANSWER, theme::WARN);+ return None;+ };+ crate::term_out::clear_extras(r);+ d.render_over(app.body(), r, buf);+ d.cursor(r)+}++/// A confirmation (a menu with buttons: Close Tab, Stop Harness) as the shared `Dialog`: in+/// menu-border-lines, its tmux-format title and notes as `Line`s. Its notes are never chosen or+/// dimmed: the buttons have the keys and the mouse.+fn confirmation<'a>(m: &crate::modal::Menu, row: &'a crate::buttons::Row, lines: &str, c: &'a crate::settings::Chrome) -> crate::dialog::Dialog<'a> {+ let border = dialog_border(lines);+ let title = if m.title.is_empty() { Line::default() } else { crate::draw::format_line(&m.title, c.muted, m.width, (border.horizontal_top, c.muted)) };+ let body = m.items.iter().map(|it| crate::draw::format_line(&menu_text(it), c.base, m.width, (" ", c.base))).collect();+ crate::dialog::Dialog { title, border, ..crate::dialog::Dialog::new("", body, row, c) }+}+/// A pause after the prefix: every key that can come next, from the live table (your binds too),/// in a box over the bottom of the window — tmux's keys, with the hint zellij users praise.-fn which_key(buf: &mut Buffer, app: &App, body: Rect) {- if body.width < 16 || body.height < 4 { return }+fn which_key(buf: &mut Buffer, app: &App, body: Rect) -> Option<Rect> {+ if body.width < 16 || body.height < 4 { return None }let mut items: Vec<(String, String)> = Vec::new();let mut digits = false;for b in &app.keymap.prefix_table {@@ -377,13 +475,12 @@ fn which_key(buf: &mut Buffer, app: &App, body: Rect) {let panel = Style::default().bg(pal.surface);let border = Style::default().fg(pal.border).bg(pal.surface);crate::term_out::clear_extras(area);- for y in area.y..area.y + area.height { for x in area.x..area.x + area.width { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(panel); } } }- for x in area.x..area.x + area.width { buf.set_string(x, area.y, "─", border); buf.set_string(x, area.y + area.height - 1, "─", border) }- for y in area.y..area.y + area.height { buf.set_string(area.x, y, "│", border); buf.set_string(area.x + area.width - 1, y, "│", border) }- buf.set_string(area.x, area.y, "┌", border); buf.set_string(area.x + area.width - 1, area.y, "┐", border);- buf.set_string(area.x, area.y + area.height - 1, "└", border); buf.set_string(area.x + area.width - 1, area.y + area.height - 1, "┘", border);+ // The box: cleared, on the surface, bordered, the prefix's name over its top rule from its+ // third column (a `Block`'s title starts by the corner: one more of the rule first).let title = format!(" {} ", crate::keys::name(&app.keymap.prefix));- buf.set_string(area.x + 2, area.y, &title, Style::default().fg(pal.foreground).bg(pal.surface).add_modifier(Modifier::BOLD));+ let title = Line::from_iter([Span::styled("─", border), Span::styled(title, Style::default().fg(pal.foreground).bg(pal.surface).add_modifier(Modifier::BOLD))]);+ Clear.render(area, buf);+ Block::bordered().border_style(border).style(panel).title(title).render(area, buf);let inner_rows = area.height.saturating_sub(2) as usize;// Column-major, like ls: read down, then across.let fits = cols * inner_rows.max(1);@@ -402,6 +499,7 @@ fn which_key(buf: &mut Buffer, app: &App, body: Rect) {let room = col_w - key_w - 3;buf.set_stringn(x + key_w as u16 + 1, y, clip(what, room), room, Style::default().fg(pal.foreground).bg(pal.surface));}+ Some(area)}@@ -505,7 +603,9 @@ fn pane_chrome(buf: &mut Buffer, app: &App) {let marker = if app.marked == Some(*id) { "◆" } else { " " };if title.width > 0 { if let Some(cell) = buf.cell_mut((title.x, title.y)) { cell.set_symbol(marker).set_style(style); } }let text = Rect::new(title.x + 1.min(title.width), title.y, title.width.saturating_sub(2), 1);- title_line(buf, app, *id, text, style);+ let name = title_line(buf, app, *id, text, style);+ // (The whole header row drags the pane, but for its name only where it is a divider.)+ crate::workspace_controls::name_span_on_divider(app, *id, name);}}@@ -533,7 +633,9 @@ fn borders(buf: &mut Buffer, app: &App, body: Rect) {let style = border_style(app, t.active);let (x, y) = (body.x + t.x as u16, body.y + t.y as u16);for (k, g) in t.fill.iter().enumerate() { if let Some(cell) = buf.cell_mut((x + k as u16, y)) { cell.set_symbol(g).set_style(style); } }- title_line(buf, app, t.pane, Rect::new(x, y, t.width as u16, 1), style);+ let name = title_line(buf, app, t.pane, Rect::new(x, y, t.width as u16, 1), style);+ // (Only the name drags the pane: the line after it is the divider, which resizes.)+ crate::workspace_controls::name_span(app, t.pane, name);}}@@ -565,15 +667,18 @@ fn border_style(app: &App, active: bool) -> Style {/// name, its state symbol, and as far as the pane is wide, its project and branch), drawn as/// screen_redraw_make_pane_status draws it — format_draw over the border, so #[align=right],/// #[align=centre] and #[fill] place it as tmux does, the border showing wherever the format-/// writes nothing.-fn title_line(buf: &mut Buffer, app: &App, id: u64, area: Rect, style: Style) {- if area.width == 0 { return }+/// writes nothing. Returns how many leading cells the format drew (the name).+fn title_line(buf: &mut Buffer, app: &App, id: u64, area: Rect, style: Style) -> u16 {+ if area.width == 0 { return 0 }let area = crate::workspace_controls::title(buf, app, id, area, style);- let Some(fmt) = app.options.get("pane-border-format", &app.tab().id, Some(id)) else { return };+ let Some(fmt) = app.options.get("pane-border-format", &app.tab().id, Some(id)) else { return 0 };let expanded = crate::format::expand(app, &fmt, app.active, Some(id), true);- for (i, cell) in crate::draw::format_draw_over(&expanded, style, area.width).into_iter().enumerate() {+ let cells = crate::draw::format_draw_over(&expanded, style, area.width);+ let drawn = cells.iter().position(|c| c.is_none()).unwrap_or(cells.len()) as u16;+ for (i, cell) in cells.into_iter().enumerate() {if let Some((ch, cs)) = cell { if let Some(c) = buf.cell_mut((area.x + i as u16, area.y)) { c.set_symbol(if ch.is_empty() { " " } else { &ch }); c.set_style(cs); } }}+ drawn}// ── box panes ──@@ -614,6 +719,8 @@ fn boxes(buf: &mut Buffer, app: &App) {let cells = crate::draw::format_draw_over(&expanded, words, t.width);// ` title `: a blank after the words where the line would run on.let end = cells.iter().position(|c| c.is_none()).unwrap_or(cells.len());+ // (The whole header row drags the pane, but for its name only where it is a divider.)+ crate::workspace_controls::name_span_on_divider(app, id, end as u16);for (i, cell) in cells.into_iter().enumerate() {if let Some((ch, cs)) = cell { if let Some(c) = buf.cell_mut((t.x + i as u16, t.y)) { c.set_symbol(if ch.is_empty() { " " } else { &ch }); c.set_style(cs); } }}@@ -697,7 +804,7 @@ mod os_welcome_tests {for action in ["Install Harness", "Try without installing", "Wi-Fi", "Super+b"] {assert!(!text.contains(action), "ordinary hn must not offer {action}: {text}");}- assert!(text.contains("Task") || text.contains("What task should"), "{text}");+ assert!(text.contains("Task") || text.contains("What should it do?"), "{text}");} else if live {assert!(text.contains("Enter Install Harness"), "{text}");assert!(text.contains("t Try without installing"), "{text}");@@ -772,7 +879,8 @@ fn status_line(buf: &mut Buffer, app: &mut App, rect: Rect) -> Option<Position>// (A prompt's completion menu keeps the prompt on the status line under it.)let under_menu = match &app.modal { Some(Modal::Menu(m)) => m.complete.as_ref().map(|c| &c.prompt), _ => None };let prompt_like: Option<(String, String, usize, String, bool)> = match (&app.modal, under_menu) {- (_, Some(p)) | (Some(Modal::Prompt(p)), _) => {+ // (hn's own questions are dialogs over the panes: the status line stays.)+ (_, Some(p)) | (Some(Modal::Prompt(p)), _) if !p.dialog() => {let shown: String = if p.secret { "*".repeat(p.value.chars().count()) } else { p.value.clone() };Some((p.label.clone(), shown, p.cursor, p.hint.clone(), p.vi_normal))}@@ -1465,7 +1573,7 @@ fn fzf_in_frame(buf: &mut Buffer, frame: FzfFrame, picker: &mut Picker, kind: &P// --ghost: yours, cut at the edge as fzf cuts it.pbuf.set_stringn(ia.x + pw, prompt_y, ghost, q_room, pal.ghost.style());typed_w = ghost.width().min(q_room) as u16;- shift = typed_w as i32;+ shift = typed_w as i32 + 2;} else if picker.query.is_empty() && !picker.placeholder.is_empty() {// The placeholder (fzf's --ghost), whole scopes only, leaving an inline count its place.let room = if mode.starts_with("inline") { q_room.saturating_sub(16) } else { q_room };@@ -1473,7 +1581,7 @@ fn fzf_in_frame(buf: &mut Buffer, frame: FzfFrame, picker: &mut Picker, kind: &Pfor part in picker.placeholder.split(" ") { if text.width() + part.width() + 3 > room { break } if !text.is_empty() { text.push_str(" ") } text.push_str(part) }pbuf.set_stringn(ia.x + pw, prompt_y, &text, q_room, pal.ghost.style());typed_w = text.width() as u16;- if !text.is_empty() { shift = typed_w as i32 }+ if !text.is_empty() { shift = typed_w as i32 + 2 }}let cursor = Position::new(ia.x + pw + before_w as u16, prompt_y);picker.prompt_at.set((prompt_y, ia.x + pw));@@ -1493,10 +1601,10 @@ fn fzf_in_frame(buf: &mut Buffer, frame: FzfFrame, picker: &mut Picker, kind: &P// spins in the spinner's pair where fzf's does, and gives an info prefix that pair too.let (info_style, sep_style, spin_style) = (pal.info.style(), pal.separator.style(), pal.spinner.style());let reading = picker.busy.is_some() || matches!(kind, PickerKind::Open { .. }) && search_busy;- // fzf's makeSpinner (ASCII under --no-unicode).- const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];+ // hn's spinner, as everywhere else (fzf's makeSpinner keeps to a cell's top rows); ASCII under+ // --no-unicode, as fzf's.const ASCII_SPINNER: [&str; 8] = ["-", "\\", "|", "/", "-", "\\", "|", "/"];- let frames: &[&str] = if theme::fzf().unicode { &SPINNER } else { &ASCII_SPINNER };+ let frames: &[&str] = if theme::fzf().unicode { &theme::SPINNER } else { &ASCII_SPINNER };let spinner = frames[if reading { theme::animation_frame() % frames.len() } else { 0 }];let w = ia.width as i32;let put = |pbuf: &mut Buffer, x: i32, y: u16, s: &str, st: Style| { if x >= 0 && x < w && !s.is_empty() { pbuf.set_stringn(ia.x + x as u16, y, s, (w - x) as usize, st); } };@@ -2515,6 +2623,7 @@ fn preview_text(buf: &mut Buffer, picker: &Picker, pb: &PreviewBox, text: Vec<Li/// The shell owns a reserved region below its prompt. Draw the very same finder/// there, without applying --height a second time or accessing application state.pub(crate) fn inline_fzf(buf: &mut Buffer, area: Rect, picker: &mut Picker, busy: bool, text: Vec<Line<'static>>, bottom_up: bool) -> Position {+ if picker.shell_panel { return inline_panel(buf, area, picker, busy, bottom_up) }let kind = PickerKind::ShellContext;let frame = fzf_frame_at(area);let inner = frame.inner;@@ -2536,6 +2645,180 @@ pub(crate) fn inline_fzf(buf: &mut Buffer, area: Rect, picker: &mut Picker, busyat}+/// [InlinePanel] in the theme's chrome; where the text cursor goes.+fn inline_panel(buf: &mut Buffer, area: Rect, picker: &mut Picker, busy: bool, upward: bool) -> Position {+ let c = crate::settings::chrome();+ let mut panel = InlinePanel { busy, upward, chrome: &c, cursor: Position::default() };+ (&mut panel).render(area, buf, picker);+ panel.cursor+}++/// The shell composer, drawn with the command panel's own pieces (`settings::chrome()` and its+/// query line, count rule, rows and keys line) in the reserved region, no border. Top-down, or+/// [upward] (a composer low in its pane) mirrored as the launcher's lists are: the query at the+/// bottom, its count over it, the keys over that, the rows going up from there. Rendered by+/// reference, it leaves the query's text cursor in [cursor].+pub(crate) struct InlinePanel<'a> {+ pub busy: bool,+ pub upward: bool,+ pub chrome: &'a crate::settings::Chrome,+ pub cursor: Position,+}++impl StatefulWidget for &mut InlinePanel<'_> {+ type State = Picker;+ fn render(self, area: Rect, buf: &mut Buffer, picker: &mut Picker) {+ use crate::settings::{CountRule, KeysLine, QueryLine, Surface};+ use ratatui::layout::{Constraint::{Fill, Length}, Layout, Margin};+ let c = self.chrome;+ Surface(c.base).render(area, buf);+ let ghost = picker.placeholder.clone();+ let inside = |p: Position| Position::new(p.x.min(area.right().saturating_sub(1)), p.y);+ // Too small for the list: the query alone, as the panel's own too-small notice keeps its title.+ if area.height < 4 || area.width < 24 {+ let mut query = QueryLine::new(picker, &ghost, c);+ query.render(Rect { height: 1, ..area }, buf);+ self.cursor = inside(query.cursor);+ return;+ }+ let inner = area.inner(Margin::new(1, 0));+ let [query, rule, list, keys] = if self.upward {+ let [list, keys, rule, query] = Layout::vertical([Fill(1), Length(1), Length(1), Length(1)]).areas(inner);+ [query, rule, list, keys]+ } else {+ Layout::vertical([Length(1), Length(1), Fill(1), Length(1)]).areas(inner)+ };+ let mut line = QueryLine::new(picker, &ghost, c);+ line.render(query, buf);+ self.cursor = inside(line.cursor);+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ // While it waits on something the rule ends in the usual spinner (and what is being waited for).+ // A flash (a failed request being retried) says itself there in the status's place, as the fzf+ // frame's info line does.+ let said = picker.flash.as_ref().map_or(picker.status.as_str(), |f| f.0.as_str());+ let wait = if self.busy {+ Some(if said.is_empty() { theme::spinner(0).to_string() } else { format!("{} {}", theme::spinner(0), said) })+ } else { picker.flash.as_ref().map(|f| f.0.clone()) };+ // (The wait after the rule, a column apart, in at most half the line.)+ let room = wait.as_ref().map_or(0, |t| (t.width() as u16 + 1).min(rule.width / 2));+ let [count, waiting] = Layout::horizontal([Fill(1), Length(room)]).areas(rule);+ CountRule { shown: picker.visible.len(), total, marked: None, chrome: c }.render(count, buf);+ if let Some(t) = wait {+ let [_, said] = Layout::horizontal([Length(1), Fill(1)]).areas(waiting);+ Span::styled(crate::settings::fit(&t, said.width).0, c.muted).render(said, buf);+ }+ crate::settings::list_from(buf, picker, list, c, true, self.upward);+ KeysLine { keys: &[("↑↓", "move"), ("enter", "choose"), ("esc", "back")], chrome: c }.render(keys, buf);+ }+}++/// The shell composer as it was drawn by hand (2026-10-08), its chrome passed in, kept so the+/// widget that replaced it can be shown to draw the very same buffer.+#[cfg(test)]+pub(crate) mod oracle {+ use super::*;++ pub fn inline_panel(buf: &mut Buffer, area: Rect, picker: &mut Picker, busy: bool, upward: bool, c: &crate::settings::Chrome) -> Position {+ crate::settings::oracle::fill(buf, area, c.base);+ let ghost = picker.placeholder.clone();+ let inside = |p: Position| Position::new(p.x.min(area.right().saturating_sub(1)), p.y);+ // Too small for the list: the query alone, as the panel's own too-small notice keeps its title.+ if area.height < 4 || area.width < 24 {+ let (at, _) = crate::settings::oracle::query_line(buf, picker, area.x, area.y, area.width, &ghost, c);+ return inside(at);+ }+ let (x, w) = (area.x + 1, area.width - 2);+ let (qy, ry, ky, list) = if upward {+ (area.bottom() - 1, area.bottom() - 2, area.bottom() - 3, Rect::new(x, area.y, w, area.height - 3))+ } else {+ (area.y, area.y + 1, area.bottom() - 1, Rect::new(x, area.y + 2, w, area.height - 3))+ };+ let (at, _) = crate::settings::oracle::query_line(buf, picker, x, qy, w, &ghost, c);+ let total = picker.total_rows.unwrap_or_else(|| picker.rows.iter().filter(|r| !r.disabled).count());+ // While it waits on something the rule ends in the usual spinner (and what is being waited for).+ // A flash (a failed request being retried) says itself there in the status's place, as the fzf+ // frame's info line does.+ let said = picker.flash.as_ref().map_or(picker.status.as_str(), |f| f.0.as_str());+ let wait = if busy {+ Some(if said.is_empty() { theme::spinner(0).to_string() } else { format!("{} {}", theme::spinner(0), said) })+ } else { picker.flash.as_ref().map(|f| f.0.clone()) };+ let room = wait.as_ref().map_or(0, |t| (t.width() as u16 + 1).min(w / 2));+ crate::settings::oracle::count_rule(buf, picker.visible.len(), total, None, x, ry, w - room, c);+ if let Some(t) = wait { crate::settings::oracle::put(buf, x + w - room + 1, ry, room.saturating_sub(1), &t, c.muted); }+ crate::settings::list_from(buf, picker, list, c, true, upward);+ crate::settings::oracle::keys_line(buf, &[("↑↓", "move"), ("enter", "choose"), ("esc", "back")], x, ky, w, c);+ inside(at)+ }+}++#[cfg(test)]+mod inline_panel_tests {+ use super::*;+ use crate::picker::Row;+ use crate::settings::oracle::{chromes, grounds, LONG};++ /// A composer's picker: a short catalog in two groups, [query] typed (its cursor at [at]).+ fn composer(query: &str, at: usize) -> Picker {+ let mut p = Picker::new("", "Search agents @ computer : project % model & agent");+ p.shell_panel = true;+ p.set_rows((0..14).map(|i| Row::new(format!("m{i}"), format!("gpt-6-{i}")).detail(vec![Span::raw("OpenAI")]).group(if i < 5 { "Recent" } else { "All" })).collect());+ p.query = query.into();+ p.refilter();+ p.qcursor = at;+ p+ }++ /// The shell composer drawn with the InlinePanel widget is the composer the hand-drawn one+ /// drew: down and upward, every width up to 160, waiting or failed or not, in a dark theme, a+ /// light one and NO_COLOR.+ #[test]+ fn the_shell_composer_widget_draws_what_the_hand_drawn_one_did() {+ let _l = crate::term_out::colours_lock();+ // (The spinner still, so the two draws a moment apart show the same frame.)+ theme::begin_animation_frame(false);+ let n = LONG.chars().count();+ // (query, its cursor, busy, the status, a flash, the catalog's own total)+ let cases: [(&str, usize, bool, &str, Option<&str>, Option<usize>); 8] = [+ ("", 0, false, "", None, None),+ ("gpt", 3, false, "", None, None),+ (LONG, n, false, "", None, None),+ (LONG, 0, false, "", None, None),+ ("", 0, true, "", None, None),+ ("gp", 2, true, "Searching models…", None, Some(40)),+ ("gp", 2, false, "", Some("Could not list models: the daemon is not running"), None),+ ("zzz", 3, false, "", None, Some(0)),+ ];+ // (Every width the line widgets are checked at is too slow here: the too-small ones, the+ // edge at 24, and wider ones in steps.)+ let widths = [1, 2, 8, 23, 24, 25, 30, 40, 47, 64, 80, 96, 120, 159, 160];+ for c in chromes() { for upward in [false, true] { for w in widths { for h in [1, 3, 4, 5, 8, 12] {+ let area = Rect::new(2, 1, w, h);+ // (Over cells already written: the panel clears what it covers and touches nothing else.)+ let [_, ground] = grounds(Rect::new(0, 0, w + 4, h + 2));+ {+ for (query, at, busy, status, flash, total) in cases {+ let make = || {+ let mut p = composer(query, at);+ p.status = status.into();+ p.flash = flash.map(|f| (f.to_string(), Instant::now()));+ p.total_rows = total;+ p+ };+ let (mut a, mut b) = (make(), make());+ let (mut old, mut new) = (ground.clone(), ground.clone());+ let was = oracle::inline_panel(&mut old, area, &mut a, busy, upward, &c);+ let mut panel = InlinePanel { busy, upward, chrome: &c, cursor: Position::default() };+ (&mut panel).render(area, &mut new, &mut b);+ let what = format!("{w}x{h} upward {upward} {query:?} at {at} busy {busy} {status:?} {flash:?}");+ assert_eq!(was, panel.cursor, "{what}");+ assert_eq!((a.xoffset.get(), a.prompt_at.get(), &a.row_at), (b.xoffset.get(), b.prompt_at.get(), &b.row_at), "{what}");+ assert!(old == new, "{what}: the cells that differ, as drawn now: {:?}", old.diff(&new));+ }+ }+ } } } }+ }+}+/// A pane's terminal, drawn into a preview box: its bottom, where the work is.fn preview_grid(buf: &mut Buffer, pane: &Pane, area: Rect, scroll: u16) {let content = pane.term.renderable_content();@@ -2709,7 +2992,7 @@ fn clock(buf: &mut Buffer, app: &App, rect: Rect) {}-fn clip(text: &str, cols: usize) -> String {+pub(crate) fn clip(text: &str, cols: usize) -> String {if text.width() <= cols { return text.to_string() }if cols == 0 { return String::new() }let mut out = String::new();@@ -3208,6 +3491,73 @@ mod theme_render_tests {assert_eq!(picker.screen_area.get(), at, "back in the palette's place");}+ /// A panel whose rows drop from 10 to 2 is smaller in the next frame: the cells it covered+ /// before are owed one settle rewrite; the same panel again, or a bigger one, owes none.+ #[test]+ fn a_panel_that_shrinks_or_closes_owes_one_settle_rewrite() {+ let t0 = std::time::Instant::now();+ let mut app = app();+ let open = |app: &mut App, n: usize| {+ let mut picker = Picker::new("layout", "");+ picker.set_rows((0..n).map(|i| crate::picker::Row::new(&format!("r{i}"), &format!("row {i}"))).collect());+ app.modal = Some(Modal::Picker { kind: PickerKind::Layout, picker });+ };+ assert_eq!(app.overlay_drawn, None);+ open(&mut app, 10);+ screen(&mut app);+ let ten = app.overlay_drawn.expect("a panel was drawn");+ open(&mut app, 10);+ screen(&mut app);+ assert_eq!(crate::app::settle_due(Some(ten), app.overlay_drawn, 5, None, t0), None, "the same panel");+ open(&mut app, 2);+ screen(&mut app);+ let two = app.overlay_drawn.expect("a panel was drawn");+ assert!(two.height < ten.height, "{two:?} {ten:?}");+ assert_eq!(crate::app::settle_due(Some(ten), Some(two), 5, None, t0), Some(t0), "10 rows down to 2");+ assert_eq!(crate::app::settle_due(Some(two), Some(ten), 5, None, t0), None, "2 up to 10 covers what it did");+ app.modal = None;+ screen(&mut app);+ assert_eq!(app.overlay_drawn, None);+ assert_eq!(crate::app::settle_due(Some(two), app.overlay_drawn, 5, None, t0), Some(t0), "closed");+ }++ /// The rect kept for the settle rewrite is where the frame drew: a menu or popup placed past+ /// the screen's edge is clipped to it, as drawn; the prefix's key hints are an overlay too.+ #[test]+ fn the_overlay_rect_is_on_the_screen_and_takes_in_the_key_hints() {+ let mut app = app();+ let whole = Rect::new(0, 0, 150, 42);+ let items = (0..3).map(|i| modal::MenuItem { label: format!("item {i}"), key: String::new(), command: String::new(), disabled: false, separator: false }).collect();+ app.modal = Some(Modal::Menu(modal::Menu { title: "m".into(), items, choice: None, x: 140, y: 40, width: 20, stay_open: false, no_mouse: false, mouse: None, tree: None, complete: None, responsive: None, buttons: None }));+ screen(&mut app);+ assert_eq!(app.overlay_drawn, Some(Rect::new(140, 40, 10, 2)), "the menu, clipped to the screen");+ // A confirmation's box is two rows taller than a menu's (its blank row and buttons); hn's+ // own question is a dialog over the panes, not the status line.+ let button = |label: &str| crate::buttons::Button { label: label.into(), key: None };+ let row = crate::buttons::Row { buttons: vec![button("Cancel"), button("Stop")], chosen: 0, hint: String::new() };+ assert!(crate::workspace_menu::open_buttons(&mut app, "Close Tab", vec![crate::workspace_menu::note("Working")], row, vec!["x".into(), "y".into()]));+ screen(&mut app);+ let Some(Modal::Menu(m)) = &app.modal else { panic!("the confirmation") };+ assert_eq!(app.overlay_drawn, Some(crate::workspace_menu::dialog_box(m)));+ app.modal = None;+ crate::input::run(&mut app, "rename-tab");+ screen(&mut app);+ assert_eq!(app.overlay_drawn, prompt_layout(&app).map(|(r, _)| r));+ assert!(app.overlay_drawn.is_some_and(|r| r.y < app.body().bottom()), "over the panes");+ app.modal = None;+ app.modal = Some(Modal::Popup { pane: 999, x: 130, y: 35, width: 40, height: 20, border: true, title: String::new(), look: Default::default() });+ screen(&mut app);+ assert_eq!(app.overlay_drawn, Some(Rect::new(130, 35, 20, 7)), "the popup, clipped to the screen");+ assert!(app.overlay_drawn.is_some_and(|r| r.intersection(whole) == r));+ app.modal = None;+ app.prefix = true;+ app.prefix_at = Some(std::time::Instant::now() - Duration::from_secs(5));+ let s = screen(&mut app);+ let hints = app.overlay_drawn.unwrap_or_else(|| panic!("the key hints are an overlay:\n{s}"));+ let body = app.body();+ assert_eq!((hints.x, hints.width, hints.bottom()), (body.x, body.width, body.bottom()), "{hints:?} {body:?}");+ }+// ── tabs ──/// The launcher's tab row: ↓ past the list's last row goes onto it; there ←/→ open the next@@ -3407,6 +3757,29 @@ mod theme_render_tests {key(&mut app, KeyCode::Esc);assert!(app.modal.is_none());}++ /// Close Tab / Stop Harness end in one row, `[ Cancel ] [ Stop ]`, the way out first.+ #[test]+ fn a_confirmation_draws_its_buttons_on_one_row_and_keys_choose() {+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+ let mut app = app();+ let button = |label: &str, key| crate::buttons::Button { label: label.into(), key };+ let row = crate::buttons::Row { buttons: vec![button("Cancel", None), button("Stop", Some('s'))], chosen: 0, hint: "s stop · esc cancel".into() };+ assert!(crate::workspace_menu::open_buttons(&mut app, "Close Tab · zsh", vec![crate::workspace_menu::note("Stop? Saved history will remain.")],+ row, vec!["close-harness -x x".into(), "close-harness -y x".into()]));+ let s = screen(&mut app);+ let lines: Vec<&str> = s.lines().collect();+ let at = lines.iter().position(|l| l.contains("[ Cancel ]")).unwrap_or_else(|| panic!("no button row:\n{s}"));+ let line = lines[at];+ assert!(line.contains("[ Stop ]") && line.find("[ Cancel ]") < line.find("[ Stop ]"), "{line}");+ assert!(!line.contains("esc cancel"), "the hint is not on the buttons' row: {line}");+ assert!(!lines[at + 1].contains("esc cancel") && lines[at + 2].contains("esc cancel"), "a blank row, then the hint as the box's last line:\n{s}");+ let key = |app: &mut App, code| crate::input::modal_key(app, KeyEvent::new(code, KeyModifiers::NONE));+ key(&mut app, KeyCode::Right);+ assert!(matches!(app.modal, Some(Modal::Menu(_))), "moving keeps the menu");+ key(&mut app, KeyCode::Enter);+ assert!(app.modal.is_none());+ }}#[cfg(test)]@@ -3447,3 +3820,468 @@ mod which_key_tests {}}}++/// tmux's menu and the prefix's key hints as they were drawn cell by cell (2026-10-08), before+/// their boxes were `Block`s, and the checks that the `Block`s draw the very same buffers.+#[cfg(test)]+mod box_oracle_tests {+ use super::*;+ use crate::app::App;++ fn old_menu(buf: &mut Buffer, app: &App, m: &crate::modal::Menu) {+ let opt = |name: &str, default: &str| Some(app.style_spec(name, app.active, app.focused())).filter(|s| !s.is_empty()).unwrap_or_else(|| default.to_string());+ let lines = opt("menu-border-lines", "single");+ let base = Style::default();+ let plain = |mut st: Style| { st.add_modifier = Modifier::empty(); st.sub_modifier = Modifier::empty(); st };+ let style = plain(crate::draw::style_over(&opt("menu-style", "default"), base));+ let selected = plain(crate::draw::style_over(&opt("menu-selected-style", "bg=yellow,fg=black"), base));+ let border = plain(crate::draw::style_over(&opt("menu-border-style", "default"), style));+ let (tl, tr, bl, br, hz, vt, lj, rj) = box_set(&lines);+ let (w, h) = (m.width + 4, m.items.len() as u16 + 2);+ let (x0, y0) = (m.x, m.y);+ let put = |buf: &mut Buffer, x: u16, y: u16, s: &str, st: Style| { if let Some(c) = buf.cell_mut((x, y)) { c.set_symbol(s); c.set_style(st); } };+ for y in y0..y0 + h { for x in x0..x0 + w { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(style); } } }+ let (x1, y1) = (x0 + w - 1, y0 + h - 1);+ for x in x0 + 1..x1 { put(buf, x, y0, hz, border); put(buf, x, y1, hz, border) }+ for y in y0 + 1..y1 { put(buf, x0, y, vt, border); put(buf, x1, y, vt, border) }+ put(buf, x0, y0, tl, border); put(buf, x1, y0, tr, border); put(buf, x0, y1, bl, border); put(buf, x1, y1, br, border);+ let draw_at = |buf: &mut Buffer, x: u16, y: u16, text: &str, st: Style, avail: u16| {+ for (i, cell) in crate::draw::format_draw_over(text, st, avail).into_iter().enumerate() {+ if let Some((ch, cs)) = cell { if let Some(c) = buf.cell_mut((x + i as u16, y)) { c.set_symbol(if ch.is_empty() { " " } else { &ch }); c.set_style(cs); } }+ }+ };+ if !m.title.is_empty() { draw_at(buf, x0 + 2, y0, &m.title, border, w.saturating_sub(4)) }+ for (i, it) in m.items.iter().enumerate() {+ let y = y0 + 1 + i as u16;+ if it.separator {+ put(buf, x0, y, lj, border);+ for x in x0 + 1..x1 { put(buf, x, y, hz, border) }+ put(buf, x1, y, rj, border);+ continue;+ }+ let pad = if m.choice == Some(i) && !it.disabled { selected } else { style };+ for x in x0 + 1..x0 + 1 + m.width + 2 { put(buf, x, y, " ", pad) }+ let st = if it.disabled { style.add_modifier(Modifier::DIM) } else { pad };+ draw_at(buf, x0 + 2, y, &menu_text(it), st, m.width);+ }+ }++ /// The key hints as they were drawn, box and items.+ fn old_which_key(buf: &mut Buffer, app: &App, body: Rect) -> Option<Rect> {+ if body.width < 16 || body.height < 4 { return None }+ let mut items: Vec<(String, String)> = Vec::new();+ let mut digits = false;+ for b in &app.keymap.prefix_table {+ let key = crate::keys::name(&b.chord);+ if b.command.starts_with("select-window -t ") && key.len() == 1 && key.chars().all(|c| c.is_ascii_digit()) { digits = true; continue }+ let what = if b.note.is_empty() { b.command.clone() } else { b.note.clone() };+ items.push((key, what));+ }+ if digits { items.insert(0, ("0-9".into(), "Select window 0 to 9".into())) }+ const FIRST: &[&str] = &["c", "N", "n", "p", "l", "0-9", "w", "s", "d", "%", "\"", "x", "z", "o", ";", "[", "]", ":", "?", "&", ",", "$", "!", "q", "t", "{", "}", "Space"];+ items.sort_by_key(|(k, _)| FIRST.iter().position(|f| f == k).unwrap_or(FIRST.len()));+ let key_w = items.iter().map(|(k, _)| k.width()).max().unwrap_or(1).min(8);+ let col_w: usize = key_w + if body.width >= 150 { 44 } else { 32 };+ let cols = ((body.width as usize).saturating_sub(4) / col_w).max(1);+ let col_w = ((body.width as usize).saturating_sub(4) / cols).max(col_w);+ let rows_needed = items.len().div_ceil(cols);+ let height = (rows_needed as u16 + 2).min((body.height / 3).max(4)).min(body.height);+ let area = Rect::new(body.x, body.y + body.height - height, body.width, height);+ let pal = theme::pane_palette();+ let panel = Style::default().bg(pal.surface);+ let border = Style::default().fg(pal.border).bg(pal.surface);+ for y in area.y..area.y + area.height { for x in area.x..area.x + area.width { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(panel); } } }+ for x in area.x..area.x + area.width { buf.set_string(x, area.y, "─", border); buf.set_string(x, area.y + area.height - 1, "─", border) }+ for y in area.y..area.y + area.height { buf.set_string(area.x, y, "│", border); buf.set_string(area.x + area.width - 1, y, "│", border) }+ buf.set_string(area.x, area.y, "┌", border); buf.set_string(area.x + area.width - 1, area.y, "┐", border);+ buf.set_string(area.x, area.y + area.height - 1, "└", border); buf.set_string(area.x + area.width - 1, area.y + area.height - 1, "┘", border);+ let title = format!(" {} ", crate::keys::name(&app.keymap.prefix));+ buf.set_string(area.x + 2, area.y, &title, Style::default().fg(pal.foreground).bg(pal.surface).add_modifier(Modifier::BOLD));+ let inner_rows = area.height.saturating_sub(2) as usize;+ let fits = cols * inner_rows.max(1);+ if items.len() > fits && fits > 0 {+ let more = format!(" +{} more — {} ? ", items.len() - fits + 1, crate::keys::name(&app.keymap.prefix));+ let mx = (area.x + area.width).saturating_sub(more.width() as u16 + 2);+ buf.set_string(mx, area.y + area.height - 1, &more, Style::default().fg(pal.muted).bg(pal.surface).add_modifier(Modifier::DIM));+ }+ for (i, (key, what)) in items.iter().enumerate() {+ let (col, row) = (i / inner_rows.max(1), i % inner_rows.max(1));+ if col >= cols || (items.len() > fits && i + 1 >= fits) { break }+ let x = area.x + 2 + (col * col_w) as u16;+ let y = area.y + 1 + row as u16;+ buf.set_string(x, y, format!("{key:>key_w$}"), Style::default().fg(theme::accent()).bg(pal.surface).add_modifier(Modifier::BOLD));+ let room = col_w - key_w - 3;+ buf.set_stringn(x + key_w as u16 + 1, y, clip(what, room), room, Style::default().fg(pal.foreground).bg(pal.surface));+ }+ Some(area)+ }++ fn app(size: (u16, u16)) -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ App::new(19789, sink, size)+ }++ /// A screen already written over, so a cell the old drawing left alone shows.+ fn ground(area: Rect) -> Buffer {+ let mut buf = Buffer::empty(area);+ for p in area.positions() { buf[p].set_symbol("x").set_style(Style::default().fg(Color::Red).bg(Color::Blue).add_modifier(Modifier::ITALIC)); }+ buf+ }++ /// tmux's menu box as a `Block` draws what it did: items, keys, a disabled note, rules, the+ /// chosen row and none, a `#[…]` title, in each menu-border-lines and with styles set, at the+ /// screen's corner and in its middle.+ #[test]+ fn the_menu_box_as_a_block_draws_what_it_did() {+ let item = |label: &str, key: &str| crate::modal::MenuItem { label: label.into(), key: key.into(), command: "x".into(), disabled: false, separator: false };+ let items = vec![+ item("New window", "c"), item("Split #[bold]right", "%"),+ crate::modal::MenuItem { separator: true, ..item("", "") },+ crate::modal::MenuItem { disabled: true, ..item("Nothing to paste", "") },+ item("日本語の項目", ""), item("Kill", "X"),+ ];+ let screen = Rect::new(0, 0, 60, 14);+ for lines in ["single", "double", "heavy", "simple", "rounded", "padded", "none"] {+ for styled in [false, true] {+ let mut app = app((60, 14));+ let g = crate::options::SetFlags { global: true, ..Default::default() };+ app.options.set("menu-border-lines", Some(lines), &g, "", 0).unwrap();+ if styled {+ app.options.set("menu-style", Some("bg=colour236,fg=colour250"), &g, "", 0).unwrap();+ app.options.set("menu-border-style", Some("fg=colour39"), &g, "", 0).unwrap();+ app.options.set("menu-selected-style", Some("bg=colour24,fg=white,bold"), &g, "", 0).unwrap();+ }+ for (x, y) in [(0, 0), (17, 3)] { for choice in [None, Some(0), Some(3), Some(5)] { for title in ["", "Pane", "#[fg=red]Tab #1 ## (x)"] {+ let m = crate::modal::Menu { title: title.into(), items: items.clone(), choice, x, y, width: 24, stay_open: false, no_mouse: false, mouse: None, tree: None, complete: None, responsive: None, buttons: None };+ let (mut old, mut new) = (ground(screen), ground(screen));+ old_menu(&mut old, &app, &m);+ menu(&mut new, &app, &m);+ assert_eq!(new, old, "{lines} styled {styled} at ({x}, {y}) choice {choice:?} title {title:?}");+ } } }+ }+ }+ }++ /// The key hints' box as a `Block` draws what it did, at every size it is drawn in, under its+ /// items.+ #[test]+ fn the_key_hints_box_as_a_block_draws_what_it_did() {+ let _colours = crate::term_out::colours_lock();+ let app = app((150, 42));+ for (w, h) in [(16, 4), (40, 10), (80, 24), (150, 42), (200, 60)] {+ let body = Rect::new(0, 0, w, h);+ let (mut old, mut new) = (ground(body), ground(body));+ let was = old_which_key(&mut old, &app, body);+ assert_eq!(which_key(&mut new, &app, body), was, "{w}x{h}");+ assert_eq!(new, old, "{w}x{h}");+ }+ }+}++#[cfg(test)]+mod confirm_box_tests {+ use super::*;+ use crate::app::App;+ use crate::buttons::{oracle as row_oracle, Button, Row};+ use crate::modal::Menu;+ use crate::settings::Chrome;++ /// The confirmation box as it was drawn by hand, cell by cell (menu() with buttons), before it+ /// was a ratatui Block: what it must still look like.+ fn old_confirm(buf: &mut Buffer, m: &Menu, lines: &str, c: &Chrome) {+ let (tl, tr, bl, br, hz, vt, lj, rj) = box_set(lines);+ let (style, border) = (c.base, c.muted);+ let (w, h) = (m.width + 4, m.items.len() as u16 + 2 + 2);+ let (x0, y0) = (m.x, m.y);+ let put = |buf: &mut Buffer, x: u16, y: u16, s: &str, st: Style| { if let Some(c) = buf.cell_mut((x, y)) { c.set_symbol(s); c.set_style(st); } };+ for y in y0..y0 + h { for x in x0..x0 + w { if let Some(c) = buf.cell_mut((x, y)) { c.reset(); c.set_style(style); } } }+ let (x1, y1) = (x0 + w - 1, y0 + h - 1);+ for x in x0 + 1..x1 { put(buf, x, y0, hz, border); put(buf, x, y1, hz, border) }+ for y in y0 + 1..y1 { put(buf, x0, y, vt, border); put(buf, x1, y, vt, border) }+ put(buf, x0, y0, tl, border); put(buf, x1, y0, tr, border); put(buf, x0, y1, bl, border); put(buf, x1, y1, br, border);+ let draw_at = |buf: &mut Buffer, x: u16, y: u16, text: &str, st: Style, avail: u16| {+ for (i, cell) in crate::draw::format_draw_over(text, st, avail).into_iter().enumerate() {+ if let Some((ch, cs)) = cell { if let Some(c) = buf.cell_mut((x + i as u16, y)) { c.set_symbol(if ch.is_empty() { " " } else { &ch }); c.set_style(cs); } }+ }+ };+ if !m.title.is_empty() { draw_at(buf, x0 + 2, y0, &m.title, border, w.saturating_sub(4)) }+ for (i, it) in m.items.iter().enumerate() {+ let y = y0 + 1 + i as u16;+ if it.separator {+ put(buf, x0, y, lj, border);+ for x in x0 + 1..x1 { put(buf, x, y, hz, border) }+ put(buf, x1, y, rj, border);+ continue;+ }+ // (A confirmation's notes are never chosen: its buttons have the keys and the mouse.)+ for x in x0 + 1..x0 + 1 + m.width + 2 { put(buf, x, y, " ", style) }+ let text = if it.key.is_empty() { it.label.clone() } else { format!("{}#[default] #[align=right]({})", it.label, it.key) };+ draw_at(buf, x0 + 2, y, &text, style, m.width);+ }+ let b = m.buttons.as_ref().unwrap();+ row_oracle::draw(&b.row, buf, x0 + 2, x0 + 2 + m.width, y0 + 1 + m.items.len() as u16 + 1, c);+ }++ /// The box as drawn now: the shared Dialog.+ fn drawn(buf: &mut Buffer, m: &Menu, lines: &str, c: &Chrome) {+ let row = &m.buttons.as_ref().unwrap().row;+ (&confirmation(m, row, lines, c)).render(crate::workspace_menu::dialog_box(m), buf)+ }++ /// What a terminal shows: a cell hidden behind a wide character is never sent (ratatui's diff+ /// and term_out's rows both skip it), so it is blanked here. (The only difference a wide+ /// title makes: the Block's title `Span` resets that cell, the old loop wrote a styled blank.)+ fn shown(mut buf: Buffer) -> Buffer {+ let a = buf.area;+ for y in a.top()..a.bottom() {+ let mut x = a.left();+ while x < a.right() {+ let w = buf[(x, y)].symbol().width().max(1) as u16;+ for hidden in x + 1..(x + w).min(a.right()) { buf[(hidden, y)].reset() }+ x += w;+ }+ }+ buf+ }++ fn dialog(size: (u16, u16), lines: &str, title: &str, notes: &[&str], row: Row) -> (App, Menu) {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, size);+ let g = crate::options::SetFlags { global: true, ..Default::default() };+ app.options.set("menu-border-lines", Some(lines), &g, "", 0).unwrap();+ let actions = row.buttons.iter().map(|b| format!("set -g @clicked {}", b.label)).collect();+ let notes = notes.iter().map(|n| crate::workspace_menu::note(n)).collect();+ assert!(crate::workspace_menu::open_buttons(&mut app, title, notes, row, actions), "{title} at {size:?}");+ let Some(Modal::Menu(m)) = &app.modal else { panic!("no dialog") };+ let m = m.clone();+ assert_eq!(m.choice, None, "a confirmation's notes are never chosen");+ (app, m)+ }++ /// The Close Tab box (and a failed stop's, and ones with wide or `#` titles) draws exactly as+ /// before it was a Block with a Paragraph and the row widget: every cell of an 80×24 and a+ /// 40×12 screen, in each menu-border-lines, a dark and a light theme and NO_COLOR. (Rows with+ /// no keys hint: the hint left the buttons' row for the box's last line on purpose, tested in+ /// `a_confirmation_draws_its_buttons_on_one_row_and_keys_choose`.)+ #[test]+ fn the_confirmation_box_draws_as_the_old_one() {+ let b = |label: &str, key| Button { label: label.into(), key };+ let stop = Row { buttons: vec![b("Cancel", None), b("Stop", Some('s'))], chosen: 0, hint: String::new() };+ let back = Row { buttons: vec![b("Back", None)], chosen: 0, hint: String::new() };+ // (menu() and the direct draw each read hn's colours: no other test may change them between.)+ let _colours = crate::term_out::colours_lock();+ let cases: [(&str, Vec<&str>, Row, bool); 4] = [+ ("Close Tab · zsh", vec!["Working · zsh", "The terminal and its running commands will end."], stop.clone(), true),+ ("Stop Harness · build", vec!["1 stopped. The session or connection changed. Check it before trying again."], back, true),+ ("Close Tab · #1 ## (x)", vec!["Idle · #1"], Row { chosen: 1, ..stop.clone() }, true),+ ("关闭标签 · 终端", vec!["正在运行 · 终端", "终端及其命令将结束。"], stop, false), // see `shown`+ ];+ for c in row_oracle::chromes() {+ for size in [(80, 24), (40, 12)] {+ for lines in ["single", "double", "heavy", "simple", "rounded", "padded", "none"] {+ for (title, notes, row, exact) in &cases {+ let (app, m) = dialog(size, lines, title, notes, row.clone());+ let screen = Rect::new(0, 0, size.0, size.1);+ let (mut old, mut new) = (row_oracle::canvas(screen), row_oracle::canvas(screen));+ old_confirm(&mut old, &m, lines, &c);+ drawn(&mut new, &m, lines, &c);+ if *exact { assert_eq!(new, old, "{title} at {size:?} in {lines}") }+ else { assert_eq!(shown(new), shown(old), "{title} at {size:?} in {lines}") }+ // menu() draws a menu with buttons as this box, in menu-border-lines, as an+ // overlay: the window behind it dimmed with the panel's backdrop.+ let (mut routed, mut direct) = (row_oracle::canvas(screen), row_oracle::canvas(screen));+ menu(&mut routed, &app, &m);+ crate::settings::backdrop(&mut direct, app.body(), crate::settings::chrome().backdrop);+ drawn(&mut direct, &m, lines, &crate::settings::chrome());+ assert_eq!(routed, direct, "{title} at {size:?} in {lines}");+ }+ }+ }+ }+ }+}++#[cfg(test)]+mod prompt_dialog_tests {+ use super::*;+ use crate::app::App;+ use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};+ use ratatui::backend::Backend;++ fn app(size: (u16, u16)) -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19789, sink, size);+ app.fleet.local_id = "local".into();+ app+ }++ /// The screen as text, and where the terminal's cursor was put.+ fn screen(app: &mut App) -> (String, Option<Position>) {+ let (w, h) = app.size;+ let mut term = ratatui::Terminal::new(ratatui::backend::TestBackend::new(w, h)).unwrap();+ term.draw(|f| { draw(f, app); }).unwrap();+ let at = term.backend_mut().get_cursor_position().ok();+ let buf = term.backend().buffer().clone();+ ((0..h).map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect::<String>()).collect::<Vec<_>>().join("\n"), at)+ }++ fn press(app: &mut App, code: KeyCode) { crate::input::handle(app, Event::Key(KeyEvent::new(code, KeyModifiers::NONE))) }+ fn typed(app: &mut App, text: &str) { for ch in text.chars() { press(app, KeyCode::Char(ch)) } }+ fn click(app: &mut App, at: Position) {+ crate::input::handle(app, Event::Mouse(MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: at.x, row: at.y, modifiers: KeyModifiers::NONE }));+ }+ fn open(app: &App) -> Option<&crate::modal::Prompt> { match &app.modal { Some(Modal::Prompt(p)) => Some(p), _ => None } }++ /// Rename… from the tab's menu: a dialog titled with the tab, its name in the input with the+ /// caret at its end, `[ Cancel ] [ Rename ]` — not tmux's `(rename-tab)` on the status line.+ #[test]+ fn rename_tab_is_a_dialog_with_the_name_in_its_input() {+ let mut app = app((120, 30));+ app.mouse = true;+ let name = app.tab().name.clone();+ crate::input::run(&mut app, "rename-tab");+ let (s, cursor) = screen(&mut app);+ assert!(s.contains(&format!("┌─Rename Tab · {name}")) && s.contains("Tab name") && s.contains("[ Cancel ] [ Rename ]"), "{s}");+ assert!(s.contains(&format!("│{name}")), "the name in the input:\n{s}");+ assert!(!s.contains("(rename-tab)"), "not on the status line:\n{s}");+ let (r, a) = prompt_layout(&app).expect("fits");+ let field = Rect::new(a.input.unwrap().x + 1, a.input.unwrap().y + 1, a.input.unwrap().width - 2, 1);+ assert_eq!(cursor, Some(Position::new(field.x + name.chars().count() as u16, field.y)), "the caret after the name");+ assert!(r.y > 0 && r.bottom() < 29, "over the panes");+ // The caret edits where it is; Enter renames.+ press(&mut app, KeyCode::Home);+ typed(&mut app, "my ");+ press(&mut app, KeyCode::Enter);+ assert!(app.modal.is_none());+ assert_eq!(app.tab().name, format!("my {name}"));+ }++ /// ↓ takes the keys from the input to the buttons, ↑ and ↓ move between them, and ↑ from+ /// Cancel's row… goes back up to the input.+ #[test]+ fn the_arrows_go_down_to_the_buttons_and_back_up() {+ let mut app = app((120, 30));+ crate::input::run(&mut app, "rename-tab");+ press(&mut app, KeyCode::Down);+ assert!(open(&app).is_some_and(|p| p.buttons && p.chosen == 1), "↓: on the buttons, Rename chosen");+ press(&mut app, KeyCode::Left);+ assert!(open(&app).is_some_and(|p| p.chosen == 0), "← → between them");+ press(&mut app, KeyCode::Up);+ assert!(open(&app).is_some_and(|p| !p.buttons), "↑: the input again");+ }++ #[test]+ fn esc_and_cancel_change_nothing_and_tab_moves_the_keys_to_the_buttons() {+ let mut app = app((120, 30));+ app.mouse = true;+ let name = app.tab().name.clone();+ crate::input::run(&mut app, "rename-tab");+ typed(&mut app, "x");+ press(&mut app, KeyCode::Esc);+ assert!(app.modal.is_none() && app.tab().name == name, "Esc");+ // status-keys vi is the status line's: Esc still cancels a dialog.+ crate::commands::execute(&mut app, "set -g status-keys vi");+ crate::input::run(&mut app, "rename-tab");+ press(&mut app, KeyCode::Esc);+ assert!(app.modal.is_none(), "Esc under status-keys vi");+ crate::input::run(&mut app, "rename-tab");+ typed(&mut app, "x");+ press(&mut app, KeyCode::Tab);+ assert!(open(&app).is_some_and(|p| p.buttons && p.chosen == 1), "Rename chosen");+ press(&mut app, KeyCode::Left);+ assert_eq!(open(&app).map(|p| p.chosen), Some(0), "← → between the buttons");+ // A letter is typed, and the input has the keys again.+ typed(&mut app, "y");+ assert!(open(&app).is_some_and(|p| !p.buttons && p.value == format!("{name}xy")));+ press(&mut app, KeyCode::Tab);+ press(&mut app, KeyCode::Enter);+ assert!(app.modal.is_none() && app.tab().name == name, "Enter on [ Cancel ]");+ }++ #[test]+ fn the_mouse_answers_with_a_button_and_cancels_outside() {+ let mut app = app((120, 30));+ app.mouse = true;+ let name = app.tab().name.clone();+ crate::input::run(&mut app, "rename-tab");+ typed(&mut app, "2");+ screen(&mut app);+ let (r, a) = prompt_layout(&app).expect("fits");+ let buttons = { let p = open(&app).unwrap(); p.row().areas(a.row) };+ press(&mut app, KeyCode::Tab);+ click(&mut app, Position::new(a.input.unwrap().x + 2, a.input.unwrap().y + 1));+ assert!(open(&app).is_some_and(|p| !p.buttons), "a click on the input gives it the keys");+ click(&mut app, Position::new(r.x + 1, r.y + 1));+ assert!(open(&app).is_some(), "the box's own rule does nothing");+ click(&mut app, Position::new(buttons[1].x + 1, buttons[1].y));+ assert!(app.modal.is_none() && app.tab().name == format!("{name}2"), "[ Rename ]");+ crate::input::run(&mut app, "rename-tab");+ typed(&mut app, "3");+ click(&mut app, Position::new(buttons[0].x + 1, buttons[0].y));+ assert!(app.modal.is_none() && app.tab().name == format!("{name}2"), "[ Cancel ]");+ crate::input::run(&mut app, "rename-tab");+ typed(&mut app, "3");+ click(&mut app, Position::new(0, 0));+ assert!(app.modal.is_none() && app.tab().name == format!("{name}2"), "outside");+ }++ #[test]+ fn a_paste_goes_in_at_the_caret() {+ let mut app = app((120, 30));+ crate::input::run(&mut app, "send");+ typed(&mut app, "fix tests");+ for _ in 0..5 { press(&mut app, KeyCode::Left) }+ press(&mut app, KeyCode::Tab);+ crate::input::handle(&mut app, Event::Paste("the\nnew ".into()));+ assert!(open(&app).is_some_and(|p| p.value == "fix the new tests" && p.cursor == 12 && !p.buttons), "{:?}", open(&app).map(|p| (&p.value, p.cursor)));+ }++ /// Send, Broadcast, Rename Harness, Message and Answer are the same dialog with their own+ /// title, line, label and action.+ #[test]+ fn hn_s_other_questions_are_dialogs_with_their_own_action() {+ let mut app = app((120, 30));+ crate::input::run(&mut app, "send");+ let (s, _) = screen(&mut app);+ // (Its line wrapped to the input's width.)+ for want in ["┌─Send to Harness", "Harness picks the harness that fits best;", "confirm.", "What should be done?", "[ Cancel ] [ Send ]"] { assert!(s.contains(want), "{want}:\n{s}") }+ press(&mut app, KeyCode::Esc);+ let kinds = [+ (crate::modal::PromptKind::Broadcast, "Broadcast"),+ (crate::modal::PromptKind::RenameHarness { machine: "m".into(), agent: "a".into() }, "Rename"),+ (crate::modal::PromptKind::Message { machine: "m".into(), agent: "a".into() }, "Send"),+ (crate::modal::PromptKind::Answer { machine: "m".into(), agent: "a".into(), request: "r".into() }, "Answer"),+ ];+ for (kind, action) in kinds {+ let mut p = crate::modal::Prompt::status(kind, "", "");+ (p.title, p.field) = ("Title".into(), "Field".into());+ app.modal = Some(Modal::Prompt(p));+ let (s, _) = screen(&mut app);+ assert!(s.contains("┌─Title") && s.contains(&format!("[ Cancel ] [ {action} ]")), "{action}:\n{s}");+ }+ }++ /// tmux's own prompts (C-b , and every command-prompt, choose-tree's) stay on the status line.+ #[test]+ fn tmux_s_command_prompt_keeps_the_status_line() {+ let mut app = app((120, 30));+ crate::commands::execute(&mut app, "command-prompt -I zsh -p (rename-window) \"rename-window '%%'\"");+ assert!(open(&app).is_some_and(|p| !p.dialog()));+ let (s, _) = screen(&mut app);+ assert!(s.lines().last().unwrap().starts_with("(rename-window) zsh"), "{s}");+ assert!(!s.contains("┌─"), "no dialog:\n{s}");+ assert!(prompt_layout(&app).is_none());+ }++ #[test]+ fn a_dialog_that_cannot_fit_is_cancelled() {+ let mut app = app((20, 6));+ let name = app.tab().name.clone();+ crate::input::run(&mut app, "rename-tab");+ screen(&mut app);+ assert!(app.modal.is_none(), "an invisible question must not keep answering keys");+ assert_eq!(app.toast.as_ref().map(|t| t.0.as_str()), Some("Make the terminal larger to answer this"));+ press(&mut app, KeyCode::Enter);+ assert_eq!(app.tab().name, name);+ }+}diff --git a/tui/src/workspace_controls.rs b/tui/src/workspace_controls.rsindex 437f08a8d..12880615e 100644--- a/tui/src/workspace_controls.rs+++ b/tui/src/workspace_controls.rs@@ -3,23 +3,55 @@use std::cell::RefCell;use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};-use ratatui::{buffer::Buffer, layout::Rect, style::{Modifier, Style}};+use ratatui::{buffer::Buffer, layout::Rect, style::{Modifier, Style}, text::Span, widgets::Widget};use unicode_width::UnicodeWidthStr;use crate::{app::App, draw::RangeKind, theme, workspace_menu as menu};#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Action { New, Menu, Account, Header(u64), PaneMenu(u64), Close(u64) }+pub enum Action { New, Menu, Account, Header(u64), PaneMenu(u64) }++/// The menu's glyph — at a pane's title, in the status line and the side bar: three dots up and+/// down, centred in the cell, drawn bold so it does not read thin. (A braille `⠇` is as big as the+/// spinner's dots but sits in the cell's top three of four rows.)+pub const MENU_GLYPH: &str = "⋮";+/// The pane title's control: the glyph with a blank each side. (No close button: the menu has+/// Close / Stop Harness.)+const MENU_COLS: u16 = 3;#[derive(Default)]pub struct State {pub hits: RefCell<Vec<(Rect, Action)>>,/// The release of a UI click belongs to that control, even if it opened or dismissed a modal.pub pressed: Option<MouseButton>,+ /// The title cells a pane drag starts from (the line look: only the name; its line resizes).+ pub grips: RefCell<Vec<(Rect, u64)>>,+ pub grab: Option<Grab>,target: Option<MenuTarget>,workspace_open: bool,}+/// A pane held by its title. Its release belongs to the header press, as any control's does.+pub struct Grab {+ pub pane: u64,+ from: (u16, u16),+ /// true once the pointer moved 2 cells: a drag, no longer a click+ pub live: bool,+ pub drop: crate::pane_drag::Drop,+}++impl Grab {+ /// Whether the pointer at (x, y) makes it a drag: 2 cells from the press along either axis+ /// (a one-cell diagonal wobble is still a click).+ pub fn moved(&self, x: u16, y: u16) -> bool { self.live || x.abs_diff(self.from.0).max(y.abs_diff(self.from.1)) >= 2 }+}++#[cfg(test)]+impl Grab {+ /// A drag already under way, over [drop].+ pub fn live_for_test(pane: u64, drop: crate::pane_drag::Drop) -> Grab { Grab { pane, from: (0, 0), live: true, drop } }+}+struct MenuTarget {token: String,window: String,@@ -28,9 +60,9 @@ struct MenuTarget {connection: Option<u64>,}-pub fn begin_frame(app: &App) { app.controls.hits.borrow_mut().clear(); }+pub fn begin_frame(app: &App) { app.controls.hits.borrow_mut().clear(); app.controls.grips.borrow_mut().clear(); }-fn enabled(app: &App) -> bool { app.mouse && !app.headless && !app.options.tmux_look() && !app.read_only() }+pub(crate) fn enabled(app: &App) -> bool { app.mouse && !app.headless && !app.options.tmux_look() && !app.read_only() }pub fn register(app: &App, rect: Rect, action: Action) {if rect.width > 0 && rect.height > 0 { app.controls.hits.borrow_mut().push((rect, action)); }@@ -39,23 +71,43 @@ pub fn register(app: &App, rect: Rect, action: Action) {pub fn title_reserve(app: &App, window: usize, pane: u64, width: u16) -> u16 {let tab = app.tabs.get(window).map(|t| t.id.as_str()).unwrap_or("");if !enabled(app) || !app.mouse || width < 20 || app.options.has_window_override("pane-border-format", tab, pane) { return 0 }- // (No agent or model label: the … menu changes both.)- 6+ // (No agent or model label: the menu changes both.)+ MENU_COLS}/// Return the title's remaining space. The controls never add a row or resize a terminal.+/// (A pane narrower than 20 columns has no controls, so no grip either: it is not dragged.)pub fn title(buf: &mut Buffer, app: &App, pane: u64, rect: Rect, style: Style) -> Rect {let reserve = title_reserve(app, app.active, pane, rect.width);if reserve == 0 { return rect }register(app, rect, Action::Header(pane));+ app.controls.grips.borrow_mut().push((Rect::new(rect.x, rect.y, rect.width - reserve, 1), pane));let quiet = style.remove_modifier(Modifier::BOLD | Modifier::DIM).fg(theme::paint(theme::pane_palette().muted));- let x = rect.right() - 6;- buf.set_stringn(x, rect.y, " … × ", 6, quiet);- register(app, Rect::new(x, rect.y, 3, 1), Action::PaneMenu(pane));- register(app, Rect::new(x + 3, rect.y, 3, 1), Action::Close(pane));+ let menu = Rect::new(rect.right() - reserve, rect.y, reserve, 1);+ Span::styled(format!(" {MENU_GLYPH} "), quiet.add_modifier(Modifier::BOLD)).render(menu, buf);+ register(app, menu, Action::PaneMenu(pane));Rect::new(rect.x, rect.y, rect.width - reserve, rect.height)}+/// The line look's title is the divider: only its first [width] cells (the name) drag the pane.+/// (Your own pane-border-format: one that starts with #[align=…] draws no leading cells, so no+/// grip; one that fills the whole line makes all of it a grip.)+pub fn name_span(app: &App, pane: u64, width: u16) {+ let mut grips = app.controls.grips.borrow_mut();+ let Some(i) = grips.iter().position(|(_, p)| *p == pane) else { return };+ if width == 0 { grips.remove(i); } else { grips[i].0.width = width.min(grips[i].0.width); }+}++/// The box and surface looks' header row drags the pane, except where it lies on a divider (the+/// lower pane's with titles on top, the upper one's below): there only its name does, as in the+/// line look, and the rest of the row resizes.+pub fn name_span_on_divider(app: &App, pane: u64, width: u16) {+ let Some(r) = app.controls.grips.borrow().iter().find(|(_, p)| *p == pane).map(|(r, _)| *r) else { return };+ // (The window's own bottom edge, the last pane's title below it, divides nothing.)+ let below = r.y.checked_sub(app.body().y).is_some_and(|y| app.visible_layout_geoms().iter().any(|(_, g)| g.y > y as u32));+ if below && (r.x..r.right()).all(|x| crate::mouse::over_resize_border(app, x, r.y)) { name_span(app, pane, width) }+}+/// tmux's status renderer carries these ranges through clipping and alignment. A customized/// status format keeps ownership of every cell unless it opts in with #{hn_controls}.pub fn status(app: &App) -> String {@@ -64,7 +116,7 @@ pub fn status(app: &App) -> String {if app.account.status == crate::account::Status::SignedOut {parts.push("#[range=user|hn-account]Sign in#[norange]".to_string());}- parts.extend(["#[range=user|hn-new]+#[norange]", "#[range=user|hn-menu]…#[norange]"].map(str::to_string));+ parts.extend(["#[range=user|hn-new]+#[norange]".to_string(), format!("#[range=user|hn-menu]#[bold]{MENU_GLYPH}#[nobold]#[norange]")]);parts.join(" ")}@@ -72,12 +124,13 @@ pub fn status(app: &App) -> String {pub fn side_actions(buf: &mut Buffer, app: &App, rect: Rect, style: Style, account: bool) {if !enabled(app) { return }let items: Vec<(&str, Action)> = if account { vec![(crate::account::label(app), Action::Account)] }- else { vec![("+", Action::New), ("…", Action::Menu)] };+ else { vec![("+", Action::New), (MENU_GLYPH, Action::Menu)] };let total: u16 = items.iter().map(|(label, _)| label.width() as u16).sum::<u16>() + items.len().saturating_sub(1) as u16 * 2;if total > rect.width { return }let mut x = rect.right() - total;for (label, action) in items {let width = label.width() as u16;+ let style = if label == MENU_GLYPH { style.add_modifier(Modifier::BOLD) } else { style };buf.set_stringn(x, rect.y, label, width as usize, style);register(app, Rect::new(x, rect.y, width, 1), action);x += width + 2;@@ -98,7 +151,6 @@ pub fn activate(app: &mut App, action: Action, at: Option<(u16, u16)>) {Action::Account => crate::account::open(app),Action::Header(pane) => { select_pane(app, pane); }Action::PaneMenu(pane) => pane_menu(app, pane, at),- Action::Close(pane) => crate::session_close::pane(app, pane),}}@@ -122,9 +174,16 @@ pub fn begin_press(app: &mut App, button: MouseButton) {pub fn finish_press(app: &mut App, mouse: &MouseEvent) -> bool {let Some(button) = app.controls.pressed else { return false };match mouse.kind {- MouseEventKind::Up(up) if up == button => { app.controls.pressed = None; true }- MouseEventKind::Drag(drag) if drag == button => true,- MouseEventKind::Down(_) => { app.controls.pressed = None; false }+ MouseEventKind::Up(up) if up == button => {+ app.controls.pressed = None;+ if let Some(grab) = app.controls.grab.take() {+ // (The zone drawn while it moved goes with it.)+ if grab.live { app.redraw_all = true; crate::pane_drag::release(app, grab.pane, grab.drop) }+ }+ true+ }+ MouseEventKind::Drag(drag) if drag == button => { crate::pane_drag::follow(app, mouse.column, mouse.row); true }+ MouseEventKind::Down(_) => { app.controls.pressed = None; crate::pane_drag::cancel(app); false }_ => false,}}@@ -139,7 +198,7 @@ pub fn mouse(app: &mut App, mouse: &MouseEvent) -> bool {let at = Some((mouse.column, mouse.row.saturating_add(1)));// A title is a border in line layouts and a pane's first row in boxed layouts.// Either explicit binding takes precedence over the added header controls.- let places: &[&str] = if matches!(action, Some(Action::Header(_) | Action::PaneMenu(_) | Action::Close(_))) { &["Border", "Pane"] } else { &["Status"] };+ let places: &[&str] = if matches!(action, Some(Action::Header(_) | Action::PaneMenu(_))) { &["Border", "Pane"] } else { &["Status"] };if let MouseEventKind::Down(button @ (MouseButton::Left | MouseButton::Right)) = mouse.kind {let defaults = crate::keys::Keymap::tmux_defaults();for place in places {@@ -149,19 +208,33 @@ pub fn mouse(app: &mut App, mouse: &MouseEvent) -> bool {}match mouse.kind {MouseEventKind::Down(MouseButton::Left) => if let Some(action) = action {+ // The title's words drag the pane; the rest of a divider title still resizes (tmux's binding).+ let grip = match action {+ Action::Header(pane) => app.controls.grips.borrow().iter().any(|(r, p)| *p == pane && inside(r)).then_some(pane),+ _ => None,+ };if let Action::Header(pane) = action {- if crate::mouse::over_resize_border(app, mouse.column, mouse.row) {+ if grip.is_none() && crate::mouse::over_resize_border(app, mouse.column, mouse.row) {select_pane(app, pane);return false;}}begin_press(app, MouseButton::Left);activate(app, action, at);+ if let Some(pane) = grip.filter(|_| !app.tab().zoomed) {+ app.controls.grab = Some(Grab { pane, from: (mouse.column, mouse.row), live: false, drop: crate::pane_drag::Drop::Nothing });+ }return true;},MouseEventKind::Down(MouseButton::Right) => {- let pane = match action { Some(Action::Header(p) | Action::PaneMenu(p) | Action::Close(p)) => Some(p), _ => None };+ let pane = match action { Some(Action::Header(p) | Action::PaneMenu(p)) => Some(p), _ => None };if let Some(pane) = pane { begin_press(app, MouseButton::Right); pane_menu(app, pane, at); return true; }+ // A machine's heading in the side bar: what can be done on it.+ if let Some(crate::bar::Hit::Machine(machine, _)) = crate::bar::hit_at(app, mouse.column, mouse.row) {+ begin_press(app, MouseButton::Right);+ crate::machine_menu::open(app, &machine, at);+ return true;+ }let tab = crate::bar::hit_at(app, mouse.column, mouse.row).and_then(|hit| match hit { crate::bar::Hit::Window(i) => Some(i), _ => None }).or_else(|| {let top = if app.status_top { 0 } else { app.size.1.saturating_sub(app.status_lines()) };app.status_ranges.iter().find_map(|(row, hit)| {@@ -251,12 +324,9 @@ pub fn pane_menu(app: &mut App, pane: u64, at: Option<(u16, u16)>) {let Some(tab) = app.tabs.iter().position(|t| t.panes().contains(&pane)) else { return };let Some(token) = capture(app, tab, Some(pane)) else { return };let item = |label: &str, key: &str, verb: &str| menu::item(label, key, format!("pane-control {token} {verb}"));- let close = app.panes.get(&pane).map(|p| {- let view_only = app.fleet.machine(&p.machine_id).is_some_and(|m| m.shared)- || app.fleet.agent(&p.machine_id, &p.agent_id).is_some_and(|a| a.status == "stopped" || a.dsh_id == "autonomous/harness-monitor");- if view_only { "Close pane" }- else if crate::session_close::managed_pane(app, pane) { "Stop Harness" } else { "Close terminal" }- }).unwrap_or("Close pane");+ // (What the title's close button did, the last item: "Close pane" for every pane — a harness's+ // stop is said in the question it asks, Stop Harness.)+ let close = "Close pane";let mut model = item("Change model…", "m", "models");model.disabled = !crate::models::pane_supports(app, pane);let mut agent = item("Change agent…", "a", "agent");@@ -304,7 +374,7 @@ pub fn run(app: &mut App, token: &str, verb: &str) {}#[cfg(test)]-mod tests {+pub(crate) mod tests {use super::*;use crossterm::event::{Event, KeyModifiers};use serde_json::json;@@ -341,7 +411,7 @@ mod tests {}}- fn app(width: u16) -> App {+ pub(crate) fn app(width: u16) -> App {let (sink, _) = tokio::sync::mpsc::unbounded_channel();let mut app = App::new(19799, sink, (width, 32));app.handed_over = true;@@ -368,7 +438,7 @@ mod tests {app}- fn render(app: &mut App) -> Buffer {+ pub(crate) fn render(app: &mut App) -> Buffer {let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(app.size.0, app.size.1)).unwrap();terminal.draw(|f| crate::ui::draw(f, app)).unwrap();terminal.backend().buffer().clone()@@ -384,6 +454,245 @@ mod tests {app.controls.hits.borrow().iter().find(|(_, action)| *action == wanted).unwrap_or_else(|| panic!("missing {wanted:?}")).0}+ fn send(app: &mut App, kind: MouseEventKind, x: u16, y: u16) {+ crate::input::handle(app, Event::Mouse(MouseEvent { kind, column: x, row: y, modifiers: KeyModifiers::NONE }));+ }++ fn grip(app: &App, pane: u64) -> Rect {+ app.controls.grips.borrow().iter().find(|(_, p)| *p == pane).unwrap_or_else(|| panic!("no grip for {pane}")).0+ }++ fn live(app: &App) -> bool { app.controls.grab.as_ref().is_some_and(|g| g.live) }++ #[tokio::test]+ async fn the_drop_zone_follows_the_pointer_and_the_frame_after_release_has_none() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes();+ render(&mut app);+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ let (cx, cy) = (r2.x + r2.width / 2, r2.y + r2.height / 2);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), cx, cy);+ let during = render(&mut app);+ let row: String = (r2.x..r2.right()).map(|x| during[(x, cy)].symbol()).collect();+ assert!(row.contains("swap with Task 2"), "{row}");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), cx, cy);+ assert!(app.redraw_all, "the release repaints the screen once");+ assert_eq!(app.tabs[0].panes(), vec![2, 1], "the drop swapped them");+ assert_eq!(app.tabs[0].focus, Some(1), "the held pane keeps the focus");+ // the same drop, never dragged: the frame it draws, with no zone+ let mut swapped = self::app(120);+ swapped.tabs.truncate(1);+ swapped.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ swapped.fit_panes();+ crate::pane_drag::release(&mut swapped, 1, crate::pane_drag::Drop::Swap(2));+ assert_eq!(render(&mut app), render(&mut swapped), "the frame after the release has no zone");+ }++ #[tokio::test]+ async fn a_header_drag_of_two_cells_becomes_a_pane_drag_and_a_short_one_stays_a_click() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 2, g.y); // 1 cell: still a click+ assert!(!live(&app));+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 4, g.y + 3); // 2 or more cells+ assert!(live(&app));+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ let (cx, cy) = (r2.x + r2.width / 2, r2.y + r2.height / 2);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), cx, cy);+ assert_eq!(app.controls.grab.as_ref().unwrap().drop, crate::pane_drag::Drop::Swap(2));+ send(&mut app, MouseEventKind::Up(MouseButton::Left), cx, cy);+ assert!(app.controls.grab.is_none() && app.controls.pressed.is_none());+ assert_eq!(app.tabs[0].panes(), vec![2, 1], "the drop swapped them");+ render(&mut app);+ // a press and release that never moved 2 cells runs nothing+ let order = app.tabs[0].panes();+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Up(MouseButton::Left), g.x + 1, g.y);+ assert_eq!(app.tabs[0].panes(), order);+ }++ #[tokio::test]+ async fn the_line_looks_divider_still_resizes_and_only_the_name_drags_the_pane() {+ for name_drag in [false, true] {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Vertical);+ app.options.set("@hn-border", Some("line"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes(); render(&mut app);+ let title = hit(&app, Action::Header(2));+ let name = grip(&app, 2);+ assert!(name.width > 0 && name.right() < title.right() - 6, "the grip is the name, not the whole line");+ let before = app.tab().root.as_ref().unwrap().to_tmux();+ let x = if name_drag { name.x + 1 } else { name.right() + 1 };+ send(&mut app, MouseEventKind::Down(MouseButton::Left), x, title.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), x, title.y + 3);+ assert_eq!(live(&app), name_drag, "name_drag={name_drag}");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), x, title.y + 3);+ let after = app.tab().root.as_ref().unwrap().to_tmux();+ // the divider part resizes as before; the name part never resizes+ assert_eq!(after != before, !name_drag, "name_drag={name_drag}");+ }+ }++ /// Pane 1 over pane 2, 100 wide, in [look] (`@hn-border box` or `@hn-focus surface`), the+ /// titles on [status] (pane-border-status top or bottom).+ fn stacked(look: (&str, &str), status: &str) -> App {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Vertical);+ let global = crate::options::SetFlags { global: true, ..Default::default() };+ app.options.set(look.0, Some(look.1), &global, "", 0).unwrap();+ app.options.set("pane-border-status", Some(status), &global, "", 0).unwrap();+ app.fit_panes(); render(&mut app);+ app+ }++ #[tokio::test]+ async fn a_box_or_surface_title_on_a_divider_drags_the_pane_by_its_name_and_resizes_elsewhere() {+ for look in [("@hn-border", "box"), ("@hn-focus", "surface")] {+ for status in ["top", "bottom"] {+ // the title on the divider: the lower pane's when titles are on top, the upper one's below+ let (pane, other) = if status == "top" { (2, 1) } else { (1, 2) };+ let probe = stacked(look, status);+ let (title, name) = (hit(&probe, Action::Header(pane)), grip(&probe, pane));+ assert!(name.width > 0 && name.right() < title.right() - MENU_COLS, "{look:?} {status}: the grip is the name, not the whole row");+ let away = (hit(&probe, Action::Header(other)), grip(&probe, other));+ assert_eq!(away.1.width, away.0.width - MENU_COLS, "{look:?} {status}: a title on no divider drags from its whole row");+ let controls = [hit(&probe, Action::PaneMenu(pane))];+ let before = probe.tab().root.as_ref().unwrap().to_tmux();+ // 3 rows into its own pane, from each cell of the row+ let to = if status == "top" { title.y + 3 } else { title.y - 3 };+ for x in 0..probe.size.0 {+ let mut app = stacked(look, status);+ for (kind, y) in [(MouseEventKind::Down(MouseButton::Left), title.y), (MouseEventKind::Drag(MouseButton::Left), to), (MouseEventKind::Up(MouseButton::Left), to)] {+ send(&mut app, kind, x, y);+ }+ let resized = app.tab().root.as_ref().unwrap().to_tmux() != before;+ let at = ratatui::layout::Position { x, y: title.y };+ let kept = name.contains(at) || controls.iter().any(|r| r.contains(at));+ assert_eq!(resized, !kept, "{look:?} {status}: cell {x} of the divider title");+ }+ }+ }+ }++ #[tokio::test]+ async fn a_one_cell_diagonal_wobble_on_a_stacked_title_changes_nothing() {+ for dx in [1i32, -1] {+ let mut app = stacked(("@hn-border", "box"), "top");+ let name = grip(&app, 2);+ let (order, layout) = (app.tabs[0].panes(), app.tab().root.as_ref().unwrap().to_tmux());+ let (x, y) = (name.x + 1, name.y);+ let wobble = ((x as i32 + dx) as u16, y - 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), x, y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), wobble.0, wobble.1);+ assert!(!live(&app), "one cell each way is still a click (dx={dx})");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), wobble.0, wobble.1);+ assert_eq!((app.tabs[0].panes(), app.tab().root.as_ref().unwrap().to_tmux()), (order, layout), "dx={dx}");+ }+ }++ #[tokio::test]+ async fn a_right_button_or_modifier_held_drag_on_a_grip_is_never_a_pane_drag() {+ for (button, modifiers) in [(MouseButton::Right, KeyModifiers::NONE), (MouseButton::Left, KeyModifiers::ALT), (MouseButton::Left, KeyModifiers::CONTROL)] {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let (g, order) = (grip(&app, 1), app.tabs[0].panes());+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ let (cx, cy) = (r2.x + r2.width / 2, r2.y + r2.height / 2);+ for (kind, x, y) in [(MouseEventKind::Down(button), g.x + 1, g.y), (MouseEventKind::Drag(button), g.x + 1, g.y + 3),+ (MouseEventKind::Drag(button), cx, cy), (MouseEventKind::Up(button), cx, cy)] {+ crate::input::handle(&mut app, Event::Mouse(MouseEvent { kind, column: x, row: y, modifiers }));+ assert!(!live(&app), "{button:?} {modifiers:?}");+ }+ assert_eq!(app.tabs[0].panes(), order, "{button:?} {modifiers:?}");+ }+ }++ #[tokio::test]+ async fn a_held_pane_that_is_gone_is_let_go() {+ let mut app = app(100); // window 1: pane 1; window 2: pane 2+ render(&mut app);+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 1, g.y + 3);+ assert!(live(&app));+ // its window empties mid-drag: the release may never reach the header press+ app.close_pane(1);+ render(&mut app);+ assert!(app.controls.grab.is_none(), "the next frame lets go of a pane that is gone");+ app.controls.grab = Some(Grab::live_for_test(1, crate::pane_drag::Drop::Swap(2)));+ crate::pane_drag::follow(&mut app, 5, 5);+ assert!(app.controls.grab.is_none(), "so does the next move");+ }++ #[tokio::test]+ async fn escape_during_a_pane_drag_cancels_it_and_the_release_runs_nothing() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let order = app.tabs[0].panes();+ let g = grip(&app, 1);+ let r2 = app.rects.iter().find(|(id, _)| *id == 2).unwrap().1;+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 1, g.y + 3);+ assert!(live(&app));+ let typed = app.panes[&1].queued.len();+ crate::input::handle(&mut app, Event::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Esc, KeyModifiers::NONE)));+ assert!(app.controls.grab.is_none());+ assert_eq!(app.panes[&1].queued.len(), typed, "a visible drag uses the Escape up");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), r2.x + 5, r2.y + 5);+ assert_eq!(app.tabs[0].panes(), order);+ }++ #[tokio::test]+ async fn escape_during_an_unmoved_press_lets_go_and_still_reaches_the_program() {+ let mut app = app(120);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.fit_panes(); render(&mut app);+ let g = grip(&app, 1);+ send(&mut app, MouseEventKind::Down(MouseButton::Left), g.x + 1, g.y);+ assert!(app.controls.grab.is_some() && !live(&app));+ let typed = app.panes[&1].queued.len();+ crate::input::handle(&mut app, Event::Key(crossterm::event::KeyEvent::new(crossterm::event::KeyCode::Esc, KeyModifiers::NONE)));+ assert!(app.panes[&1].queued.len() > typed, "the Escape reaches the program");+ assert!(app.controls.grab.is_none());+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), g.x + 1, g.y + 3);+ assert!(!live(&app), "a let-go press does not become a drag");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), g.x + 1, g.y + 3);+ }++ #[tokio::test]+ async fn the_surface_looks_whole_header_row_drags_the_pane() {+ let mut app = app(100);+ app.tabs.truncate(1);+ app.tabs[0].root.as_mut().unwrap().split(1, 2, crate::layout::Dir::Horizontal);+ app.options.set("@hn-focus", Some("surface"), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();+ app.fit_panes();+ let buf = render(&mut app);+ let title = hit(&app, Action::Header(1));+ // the blank part of the header, right of the name and left of the … × controls+ let x = title.right() - 8;+ assert_eq!(buf[(x, title.y)].symbol(), " ", "this test needs a blank header cell right of the name");+ send(&mut app, MouseEventKind::Down(MouseButton::Left), x, title.y);+ send(&mut app, MouseEventKind::Drag(MouseButton::Left), x - 4, title.y + 3);+ assert!(live(&app), "the surface look drags from the whole header row");+ send(&mut app, MouseEventKind::Up(MouseButton::Left), x - 4, title.y + 3);+ }+#[tokio::test]async fn ui_controls_end_pending_terminal_clicks_before_focus_moves() {for control in ["terminal", "header", "dialog", "sidebar"] {@@ -440,11 +749,13 @@ mod tests {app.options.set("@hn-border", Some("line"), &crate::options::SetFlags { global:true, ..Default::default() }, "", 0).unwrap();app.fit_panes(); render(&mut app);let title = hit(&app, Action::Header(2));+ // (The line right of the name: the name itself drags the pane.)+ let col = grip(&app, 2).right() + 1;let before = app.tab().root.as_ref().unwrap().to_tmux();if !controls { app.controls.hits.borrow_mut().clear(); }for (kind, row) in [(MouseEventKind::Down(MouseButton::Left), title.y),(MouseEventKind::Drag(MouseButton::Left), title.y + 3), (MouseEventKind::Up(MouseButton::Left), title.y + 3)] {- crate::input::handle(&mut app, Event::Mouse(MouseEvent { kind, column:title.x + 3, row, modifiers:KeyModifiers::NONE }));+ crate::input::handle(&mut app, Event::Mouse(MouseEvent { kind, column:col, row, modifiers:KeyModifiers::NONE }));}let after = app.tab().root.as_ref().unwrap().to_tmux();assert_ne!(after, before, "plain title must keep its resize drag (controls={controls}, top={top})");@@ -460,7 +771,7 @@ mod tests {let mut app = app(100);crate::commands::execute(&mut app, &format!("bind-key -n {key} 'set -g @header-click custom'"));render(&mut app);- let control = hit(&app, Action::Close(1));+ let control = hit(&app, Action::PaneMenu(1));click(&mut app, button, control.x + 1, control.y);assert_eq!(app.options.get("@header-click", "", None).as_deref(), Some("custom"));assert!(app.session_close.sent.is_empty(), "custom binding owns the click");@@ -475,13 +786,14 @@ mod tests {app.options.set(name, Some(value), &crate::options::SetFlags { global: true, ..Default::default() }, "", 0).unwrap();app.fit_panes();let buf = render(&mut app);- let at = hit(&app, Action::Close(1));+ let at = hit(&app, Action::PaneMenu(1));let body = app.rects.iter().find(|(id, _)| *id == 1).map(|(_, r)| app.content_of(app.tab(), *r)).unwrap();assert_eq!(at.intersection(body).area(), 0, "controls must not steal a terminal cell");- assert!((at.x..at.right()).any(|x| buf[(x, at.y)].symbol() == "×"));+ let row: String = (at.x..at.right()).map(|x| buf[(x, at.y)].symbol()).collect();+ assert_eq!(row, format!(" {MENU_GLYPH} "), "the menu's three dots, no close button");+ assert!(!(0..app.size.0).any(|x| buf[(x, at.y)].symbol() == "×"), "no close button on the title");click(&mut app, MouseButton::Left, at.x + 1, at.y);- assert_eq!(app.session_close.sent.last().unwrap().1["agentId"], "a1");- assert!(matches!(app.modal, Some(crate::modal::Modal::Menu(_))), "mouseup must not activate the new close dialog");+ assert!(matches!(&app.modal, Some(crate::modal::Modal::Menu(m)) if m.items.iter().any(|i| i.key == "x")), "the pane menu, its close item on x");app.modal = None;}}@@ -531,7 +843,7 @@ mod tests {assert!(app.home_visible());let buf = render(&mut app);let text: String = buf.content().iter().map(|c| c.symbol()).collect();- assert!(text.contains("New Harness") && text.contains("What task should this agent work on?") && text.contains("New Terminal"));+ assert!(text.contains("New Harness") && text.contains("What should it do?") && text.contains("New Terminal"));assert!(!text.contains("machines connected"));}}diff --git a/tui/src/workspace_menu.rs b/tui/src/workspace_menu.rsindex b8a4c4c0d..2fd4fcdbf 100644--- a/tui/src/workspace_menu.rs+++ b/tui/src/workspace_menu.rs@@ -3,10 +3,16 @@use crate::app::App;use crate::modal::{Menu, MenuItem, Modal};+use ratatui::layout::Rect;use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};+/// A confirmation's button row and the command each button runs; button 0 is the way out, so+/// `actions[0]` is also what Esc runs.#[derive(Clone, Debug)]-pub struct Layout { items: Vec<MenuItem>, anchor: Option<(u16, u16)> }+pub struct Buttons { pub row: crate::buttons::Row, pub actions: Vec<String> }++#[derive(Clone, Debug)]+pub struct Layout { items: Vec<MenuItem>, anchor: Option<(u16, u16)>, buttons: Option<Buttons> }/// Labels from a machine or conversation are text, not tmux format instructions.pub fn literal(text: &str) -> String {@@ -23,36 +29,79 @@ pub fn note(label: &str) -> MenuItem {/// The menu stays inside the terminal. Callers with long lists use a picker instead.pub fn open(app: &mut App, title: &str, items: Vec<MenuItem>, at: Option<(u16, u16)>, choice: Option<usize>) -> bool {- let layout = Layout { items:items.clone(), anchor:at };+ let layout = Layout { items:items.clone(), anchor:at, buttons:None };let mut menu = Menu { title:literal(title), items, choice, x:0, y:0, width:0,- stay_open:true, no_mouse:false, mouse:None, tree:None, complete:None, responsive:Some(Box::new(layout)) };+ stay_open:true, no_mouse:false, mouse:None, tree:None, complete:None, responsive:Some(Box::new(layout)), buttons:None };if !fit(&mut menu, app.size) { app.say("Make the terminal larger to show this menu", crate::theme::WARN); return false }app.toast = None;app.modal = Some(Modal::Menu(menu));true}+/// A confirmation: [notes] over one row of [row]'s buttons, `actions[i]` the command button i runs.+pub fn open_buttons(app: &mut App, title: &str, notes: Vec<MenuItem>, row: crate::buttons::Row, actions: Vec<String>) -> bool {+ let buttons = Buttons { row, actions };+ let layout = Layout { items:notes.clone(), anchor:None, buttons:Some(buttons.clone()) };+ let mut menu = Menu { title:literal(title), items:notes, choice:None, x:0, y:0, width:0,+ stay_open:true, no_mouse:false, mouse:None, tree:None, complete:None, responsive:Some(Box::new(layout)), buttons:Some(buttons) };+ if !fit(&mut menu, app.size) { app.say(TOO_SMALL_TO_ANSWER, crate::theme::WARN); return false }+ app.toast = None;+ app.modal = Some(Modal::Menu(menu));+ true+}++/// What a question too big for the terminal says, as every dialog says it.+pub const TOO_SMALL_TO_ANSWER: &str = "Make the terminal larger to answer this";++/// A confirmation's parts as a `dialog::Dialog` lays them out: the keys hint's last line when its+/// row kept one.+pub fn dialog_parts(m: &Menu) -> crate::dialog::Parts {+ crate::dialog::Parts { hint: m.buttons.as_ref().is_some_and(|b| !b.row.hint.is_empty()), ..Default::default() }+}++/// A confirmation's box (a `dialog::Dialog`): its notes, a blank row, the buttons' row and the+/// keys hint's line inside the border. The drawing and the mouse both lay it out with+/// `dialog::areas` and [dialog_parts].+pub fn dialog_box(m: &Menu) -> Rect { Rect::new(m.x, m.y, m.width + 4, m.items.len() as u16 + 4 + 2 * u16::from(dialog_parts(m).hint)) }+fn fit(menu: &mut Menu, size: (u16, u16)) -> bool {+ // A resize keeps the button the keys were on.+ if let (Some(layout), Some(shown)) = (&mut menu.responsive, &menu.buttons) {+ if let Some(own) = &mut layout.buttons { own.row.chosen = shown.row.chosen }+ }let Some(layout) = &menu.responsive else { return true };let actions = layout.items.iter().filter(|i| !(i.disabled && i.command.is_empty() && !i.separator)).count();- if size.0 < 12 || size.1 < actions as u16 + 2 { return false }+ // The blank line, the buttons' row and the hint's line. The hint gives way first, where+ // either the rows or the columns run out; buttons that still do not fit are refused, never+ // overlapped.+ let mut buttons = layout.buttons.clone();+ let extra = |b: &Option<Buttons>| b.as_ref().map_or(0, |b| 2 + 2 * u16::from(!b.row.hint.is_empty()));+ if size.1 < actions as u16 + 2 + extra(&buttons) { if let Some(b) = &mut buttons { b.row.hint.clear() } }+ if size.0 < 12 || size.1 < actions as u16 + 2 + extra(&buttons) { return false }let choice = menu.choice.and_then(|at| menu.items.get(at)).and_then(|chosen| layout.items.iter().position(|i|!i.disabled && !i.separator && i.command == chosen.command && i.key == chosen.key));let width = layout.items.iter().map(|i| crate::draw::format_width(&i.label) as usize + if i.key.is_empty() { 0 } else { i.key.width() + 3 })- .chain([crate::draw::format_width(&menu.title) as usize]).max().unwrap_or(1).min(size.0.saturating_sub(4) as usize) as u16;- let (items, choice) = wrap_notes(layout.items.clone(), choice, width as usize, size.1.saturating_sub(2) as usize);- let height = items.len() as u16 + 2;+ .chain([crate::draw::format_width(&menu.title) as usize])+ .chain(buttons.iter().map(|b| b.row.width() as usize)).max().unwrap_or(1).min(size.0.saturating_sub(4) as usize) as u16;+ if let Some(b) = &mut buttons { if b.row.width() > width { b.row.hint.clear() } }+ if buttons.as_ref().is_some_and(|b| b.row.buttons_width() > width) { return false }+ let (items, choice) = wrap_notes(layout.items.clone(), choice, width as usize, size.1.saturating_sub(2 + extra(&buttons)) as usize);+ let height = items.len() as u16 + 2 + extra(&buttons);let (x, y) = layout.anchor.unwrap_or(((size.0 - width - 4) / 2, (size.1 - height) / 2));menu.x = x.min(size.0 - width - 4); menu.y = y.min(size.1 - height);- menu.width = width; menu.items = items; menu.choice = choice;+ menu.width = width; menu.items = items; menu.choice = choice; menu.buttons = buttons;true}pub fn resize(app: &mut App) {if let Some(Modal::Menu(menu)) = &mut app.modal {if !fit(menu, app.size) {+ // A confirmation going away is a cancel: what it was asking about must not stay pending.+ let cancel = menu.buttons.as_ref().and_then(|b| b.actions.first().cloned());app.modal = None;- app.say("Make the terminal larger to show this menu", crate::theme::WARN);+ let asked = cancel.is_some();+ if let Some(command) = cancel { crate::commands::execute(app, &command) }+ app.say(if asked { TOO_SMALL_TO_ANSWER } else { "Make the terminal larger to show this menu" }, crate::theme::WARN);}}}@@ -77,7 +126,7 @@ fn wrap_notes(items: Vec<MenuItem>, choice: Option<usize>, width: usize, height:(rows, selected)}-fn wrap(text: &str, width: usize) -> Vec<String> {+pub(crate) fn wrap(text: &str, width: usize) -> Vec<String> {let width = width.max(1); let mut lines = Vec::new(); let mut line = String::new(); let mut used = 0;for word in text.split_whitespace() {if !line.is_empty() && used + 1 + word.width() > width { lines.push(std::mem::take(&mut line)); used = 0; }@@ -128,4 +177,41 @@ mod tests {assert_eq!(rows.len(), 4); assert_eq!(rows[choice.unwrap()].command, "cancel");assert_eq!(rows.last().unwrap().command, "stop");}++ fn confirm(hint: &str) -> crate::buttons::Row {+ let button = |label: &str, key| crate::buttons::Button { label: label.into(), key };+ crate::buttons::Row { buttons: vec![button("Cancel", None), button("Stop", Some('s'))], chosen: 0, hint: hint.into() }+ }++ #[test]+ fn buttons_widen_the_box_drop_the_hint_first_and_never_overlap() {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19799, tx, (100, 20));+ assert!(open_buttons(&mut app, "Hi", vec![note("Stop?")], confirm(crate::buttons::KEYS), vec!["x".into(), "y".into()]));+ let Some(Modal::Menu(menu)) = &mut app.modal else { panic!("closed") };+ assert!(menu.width >= confirm(crate::buttons::KEYS).width(), "the box holds the hint's line and the buttons");+ assert_eq!(dialog_box(menu).height, menu.items.len() as u16 + 6, "notes, a blank, the buttons, a blank, the hint: the last line");+ assert_eq!(menu.items.len(), 1);+ menu.buttons.as_mut().unwrap().row.chosen = 1;+ app.size = (26, 20); resize(&mut app); // 22 columns of room: buttons need 20, the hint 38+ let Some(Modal::Menu(menu)) = &app.modal else { panic!("closed") };+ let b = menu.buttons.as_ref().unwrap();+ assert!(b.row.hint.is_empty(), "the hint goes first");+ assert_eq!(dialog_box(menu).height, menu.items.len() as u16 + 4, "no hint, no line for it");+ assert_eq!(b.row.chosen, 1, "a resize keeps the chosen button");+ assert!(menu.width >= b.row.buttons_width());+ app.size = (20, 20); resize(&mut app); // 16 columns: the buttons cannot fit+ assert!(app.modal.is_none(), "refused, never overlapped");+ assert!(!open_buttons(&mut app, "Hi", vec![note("Stop?")], confirm(""), vec!["x".into(), "y".into()]));+ }++ #[test]+ fn a_confirmation_removed_by_a_resize_runs_its_cancel_action() {+ let (tx, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19799, tx, (100, 20));+ assert!(open_buttons(&mut app, "Hi", vec![note("Stop?")], confirm(""), vec!["set -g @clicked cancel".into(), "set -g @clicked stop".into()]));+ app.size = (20, 20); resize(&mut app);+ assert!(app.modal.is_none());+ assert_eq!(app.options.get("@clicked", "", None).as_deref(), Some("cancel"));+ }}diff --git a/tui/tests/composer-machine.py b/tui/tests/composer-machine.pyindex 8552716a2..61e648cd2 100644--- a/tui/tests/composer-machine.py+++ b/tui/tests/composer-machine.py@@ -32,6 +32,7 @@ class Shell:def __init__(self, root, shell):self.root, self.data, self.wire = root, b'', b''self.requests, self.answered = [], set()+ self.delayed, self.launches, self.allow_launch = [], [], Falseself.snapshot = root / 'snapshot'self.done = root / 'done'# Test-only observation/loading widgets preserve the exact Readline/ZLE@@ -67,7 +68,24 @@ bind -x '"\\C-x\\C-b": _test_snapshot'def send(self, text):os.write(self.fd, text.encode() if isinstance(text, str) else text)+ def answer(self, request_id, catalog):+ path = self.root / '.harness/shell-requests' / TOKEN / request_id+ data = path.with_suffix('.json')+ try:+ if not path.exists():+ return # the user changed scope before this reply+ data.write_text(json.dumps(catalog))+ data.chmod(0o600)+ fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK)+ os.write(fd, ('HN:' + request_id + ':0:\n').encode())+ os.close(fd)+ except OSError:+ if path.exists():+ raise+def pump(self):+ for item in [d for d in self.delayed if d[0] <= time.monotonic()]:+ self.delayed.remove(item); self.answer(item[1], item[2])if not select.select([self.fd], [], [], .02)[0]:returnchunk = os.read(self.fd, 65536)@@ -87,17 +105,23 @@ bind -x '"\\C-x\\C-b": _test_snapshot'verb = match[3].decode()if verb == 'close-picker':continue+ if verb == 'compose-launch' and self.allow_launch:+ # Never answered: Enter on a slow computer waits, and nothing starts.+ self.launches.append(json.loads(base64.b64decode(match[4])))+ continueassert verb in ('list-compose', 'list-sessions'), ('completion launched or switched the shell', verb, base64.b64decode(match[4]))args = json.loads(base64.b64decode(match[4]))args.setdefault('kind', 'sessions')self.requests.append((verb, args))host = args.get('compose', {}).get('host')- machine = 'remote-id' if host in ('Office', 'office', 'remote-id') else 'local-id'+ machine = ('remote-id' if host in ('Office', 'office', 'remote-id')+ else 'slow-id' if host in ('Slow', 'slow', 'slow-id') else 'local-id')kind = args['kind']if kind == 'host':- rows = [dict(id='M2', label='M2', extra='local-id'), dict(id='Office', label='Office', extra='remote-id')]+ rows = [dict(id='M2', label='M2', extra='local-id'), dict(id='Office', label='Office', extra='remote-id'),+ dict(id='Slow', label='Slow', extra='slow-id')]elif kind == 'folder':- path = '~/office-project' if machine == 'remote-id' else '~/mac-project'+ path = {'remote-id': '~/office-project', 'slow-id': '~/slow-project'}.get(machine, '~/mac-project')rows = [dict(id=path, label=path)]elif kind == 'agent':rows = [dict(id='codex', label='Codex'), dict(id='claude', label='Claude Code')]@@ -106,19 +130,11 @@ bind -x '"\\C-x\\C-b": _test_snapshot'else:raise AssertionError(('unexpected completion scope', kind))catalog = dict(rows=rows, machine=machine, folder='~')- path = self.root / '.harness/shell-requests' / TOKEN / request_id- data = path.with_suffix('.json')- try:- if not path.exists():- continue # the user changed scope before this reply- data.write_text(json.dumps(catalog))- data.chmod(0o600)- fd = os.open(path, os.O_WRONLY | os.O_NONBLOCK)- os.write(fd, ('HN:' + request_id + ':0:\n').encode())- os.close(fd)- except OSError:- if path.exists():- raise+ if machine == 'slow-id' and kind == 'folder':+ # The picker re-sends the same id every second; self.answered queues it once.+ self.delayed.append((time.monotonic() + 8, request_id, catalog))+ continue+ self.answer(request_id, catalog)def wait(self, predicate, label, seconds=6):end = time.monotonic() + seconds@@ -216,6 +232,39 @@ def check(shell):assert words[0] == 'codex' and '%gpt' in words, wordsif original.startswith('claude'):assert words == ['claude', '--prompt', ':literal', '@Office', '--', '@literal', ':literal'], words+ # Enter on a computer that has not answered says what it waits for, within 1 s.+ # (Both Slow journeys run before failing, so one red run shows both causes.)+ problems = []+ assert not s.launches, 'an earlier journey started an agent'+ s.load('claude @Slow '); s.data = b''; s.wire = b''+ s.allow_launch = True # only this check may reach compose-launch+ s.send('\r')+ end = time.monotonic() + 1+ while time.monotonic() < end and 'Starting on Slow… Ctrl-C to cancel' not in s.data.decode('utf-8', 'ignore'):+ s.pump()+ if 'Starting on Slow… Ctrl-C to cancel' not in s.data.decode('utf-8', 'ignore'):+ problems.append(('Enter on claude @Slow drew no "Starting on Slow… Ctrl-C to cancel" within 1 s', s.data[-500:]))+ s.send('\x03'); s.wait(lambda: b'READY> ' in s.data[-200:], 'Ctrl-C after Enter on Slow')+ # The wait line is erased (its one row cleared) before the prompt comes back.+ after = s.data.rsplit('Starting on Slow… Ctrl-C to cancel'.encode(), 1)[-1]+ if b'\r\x1b[2K' not in after.split(b'READY> ', 1)[0]:+ problems.append(('the wait line was not erased after Ctrl-C', after[-500:]))+ s.allow_launch = False+ if not (len(s.launches) == 1 and s.launches[0].get('host') == 'Slow'):+ problems.append(('Enter did not ask for exactly one launch on Slow', s.launches))++ # A computer whose folders take 8 s: the spinner keeps turning with no key pressed.+ s.load('codex '); n = s.count(); start = len(s.requests)+ s.host('Slow'); s.scope('folder', start, 'Slow')+ s.data = b''+ end = time.monotonic() + 2+ while time.monotonic() < end:+ s.pump()+ glyphs = set(re.findall('[⠋⠙⠸⢰⣠⣄⡆⠇]', s.data.decode('utf-8', 'ignore')))+ if len(glyphs) < 2:+ problems.append(('the spinner did not turn', glyphs, s.data[-500:]))+ s.send('\x1b'); s.wait(lambda: s.count() == n + 1, 'cancel slow folders')+ assert not problems, problemsassert b'No such widget' not in s.data, 'automatic completion displayed a missing ZLE widget error'print('PASS', shell, 'Ctrl-N agent -> folder -> different machine -> remote folder; same-machine aliases; Unicode; folder-first; native literals; Escape/Ctrl-C/backspace; no launch', flush=True)finally:diff --git a/tui/tests/fresh-user.py b/tui/tests/fresh-user.pyindex 007ee00ee..e45ee1968 100644--- a/tui/tests/fresh-user.py+++ b/tui/tests/fresh-user.py@@ -181,10 +181,10 @@ class User:def closed():return pane not in self.native('list-panes', '-s', '-F', '#{pane_id}').splitlines()self.keys('C-b', 'x')- self.check(lambda: closed() or '(s)' in self.screen() or 'kill-pane' in self.screen(),+ self.check(lambda: closed() or '[ Stop ]' in self.screen() or 'kill-pane' in self.screen(),'Stop completes or offers confirmation')if not closed():- self.keys('s' if '(s)' in self.screen() else 'y')+ self.keys('s' if '[ Stop ]' in self.screen() else 'y')self.check(closed, 'Confirmed Stop removes its pane', 60)def status(self):diff --git a/tui/tests/layout-sync.py b/tui/tests/layout-sync.pyindex 7725deada..3cd061ef7 100644--- a/tui/tests/layout-sync.py+++ b/tui/tests/layout-sync.py@@ -295,8 +295,22 @@ def scenario(mode, port, read_only=False):# The shared identities, not the saved tmux IDs, decide placement.start(peer=True)wait(lambda: names(peer=True) == desk_names(), 'reopened client follows shared order')+ # A pane dropped on another's bottom quarter (join-pane -v): the open peer stacks them too.+ (source, upper), (target, lower) = [r[:2] for r in placed()[:2]]++ def stacked(peer=False):+ cells = {r[1]: (int(r[2]), int(r[3])) for r in placed(peer)}+ a, b = cells.get(upper), cells.get(lower)+ return bool(a and b) and a[0] == b[0] and a[1] > b[1]++ def order(peer=False):+ return [r.split('|')[1] for r in hn('list-panes', '-F', '#{pane_id}|#{pane_title}', peer=peer).splitlines()]+ hn('join-pane', '-v', '-s', source, '-t', target)+ wait(stacked, 'join-pane stacks the dropped pane below its target')+ wait(lambda: order() == desk_names(), 'join-pane publishes pane order')+ wait(lambda: stacked(peer=True) and order(peer=True) == desk_names(), 'the peer shows the joined layout')hn('kill-server', peer=True, ok=False)- print('PASS normal: fresh client agrees with desktop after reorder', flush=True)+ print('PASS normal: fresh client agrees with desktop after reorder, and follows a join-pane', flush=True)# The reported case: a two-pane window, with the desktop serializing only# presets/sizes and dropping hn's native geometry a few seconds later.diff --git a/tui/tests/new-harness.py b/tui/tests/new-harness.pyindex 185282e2e..f12f6361a 100644--- a/tui/tests/new-harness.py+++ b/tui/tests/new-harness.py@@ -62,8 +62,8 @@ def form_screen():def settle_ui():# Wait for chooser content to redraw, not just tmux send-keys returning,# before taking mouse coordinates.- # The panels are borderless; crop around the centered form and right-hand chooser- # so animated working panes around them cannot keep the fixture unsettled.+ # The panels are borderless; crop around the centered form (its choosers drop down+ # inside it) so animated working panes around it cannot keep the fixture unsettled.previous, changed = None, time.monotonic()deadline = changed + 3while time.monotonic() < deadline:@@ -71,17 +71,8 @@ def settle_ui():# Once the form/chooser closes, live panes are allowed to keep changing.if not any('›' in line for line in lines):return- width = max(map(len, lines), default=0)- height = len(lines) - 1 # hn's bottom status lineleft, top, form_w, form_h = form_bounds(lines)- side = width - (left + form_w) - 4 >= 32signature = tuple(line[left:left+form_w] for line in lines[top:top+form_h])- child_left = left + form_w + 2- header = lines[top+2][child_left+2:].lstrip() if top + 2 < len(lines) else ''- if side and (header.startswith('›') or header.startswith('Task (optional)')):- child_right = child_left + min(60, width - left - form_w - 4)- bottom = min(height - 1, top + 22)- signature += tuple(line[child_left:child_right] for line in lines[top:bottom])if signature != previous:previous, changed = signature, time.monotonic()elif time.monotonic() - changed >= .15:@@ -204,13 +195,16 @@ try:field('Project'); type_text('m2 webapp'); keys('Enter'); shows('webapp @ local')assert create_count() == before, 'searching projects across machines only changes the draft'print('PASS New Harness: short local machine name and remote folders after a large local history', flush=True)- # Moving over a field previews its choices beside the stationary form.- keys('Down', 'Tab'); shows('Search agents and harnesses')- assert field_position('Task') == anchor, 'a preview must not move or hide the form'- assert any(line.find('Search agents and harnesses') > anchor[0] + 50 for line in screen().splitlines())+ # Moving over a field drops nothing down; entering it drops its chooser under it, in the form.+ keys('Down', 'Tab')+ # (Wait for the redraw that moved the pointer to Agent before reading what it shows.)+ wait(lambda: re.search(r'›\s+(Agent|Harness)\s', form_screen()), 'Tab reaches Agent')+ assert 'Search agents' not in screen(), 'arrowing over a field shows no chooser'keys('Right'); shows('Search agents and harnesses')+ assert 'Search agents and harnesses' in form_screen(), 'the chooser drops down inside the form'assert field_position('Task') == anchor, 'entering a chooser keeps the form visible'- assert 'Blender' in screen(), 'the agent chooser lists the harnesses'+ # (The dropdown shows a dozen rows; the harnesses follow the agents.)+ keys('PageDown', 'PageDown'); assert 'Blender' in screen(), 'the agent chooser lists the harnesses'snapshot('new-harness-agent')type_text('codex'); keys('Escape')shows('Approvals'); keys('Right'); shows('Search agents and harnesses')@@ -273,14 +267,14 @@ try:assert 'codexHome' not in request, requestprint('PASS New Harness: machine-scoped profiles and explicit model routes', flush=True)- # Blender asks for its coding agent next in the same side chooser.+ # Blender asks for its coding agent next in the same chooser.new_form(); field('Agent|Harness'); type_text('Blender'); keys('Enter'); shows('Choose a coding agent'); type_text('codex'); keys('Enter'); shows('Blender · Codex')submit(before + 6)assert state()['created'][-1]['dsh'] == 'example/blender'new_form()before_terminal = placement()previous_agents = {a['id'] for a in state()['agents']}- field('Harness'); type_text('Terminal'); shows('No matches')+ field('Harness'); type_text('Terminal'); shows('Nothing matches')keys('Escape', 'Escape', 'C-b', 'T')wait(lambda: create_count() == before + 7 and not form_visible(), 'Terminal shortcut opens a shell immediately')snapshot('new-harness-terminal')diff --git a/tui/tests/pane-ui.py b/tui/tests/pane-ui.pyindex 8ccca5ad8..a5ab971a8 100644--- a/tui/tests/pane-ui.py+++ b/tui/tests/pane-ui.py@@ -215,7 +215,8 @@ try:other = next(w for w in hn('list-windows', '-F', '#{window_id}').splitlines() if w != current)hn('select-window', '-t', other)previous = value(hn('show', '-gwv', 'window-status-format'), current)- assert previous.startswith(label + '-'), (previous, label)+ # (No `-` for the window used before: tmux's last-window flag says nothing hn's tabs need.)+ assert previous.startswith(label) and not previous[len(label):].startswith('-'), (previous, label)hn('select-window', '-t', current)assert 'reverse' not in value('#{fleet}')assert 'reverse' not in value('#{tree_mode_format}')@@ -303,7 +304,7 @@ try:x, y, w = map(int, value('#{pane_left} #{pane_top} #{pane_width}', second).split())def waiting_heading():return tmux('capture-pane', '-p', '-t', 'test').splitlines()[y - 1][x:x + w].strip()- wait(lambda: re.search(r'\(2\) \?\s+…\s+×$', waiting_heading()), 'long pane names retain their suffix and waiting indicator before the mouse controls')+ wait(lambda: re.search(r'\(2\) \?\s+⋮$', waiting_heading()), 'long pane names retain their suffix and waiting indicator before the menu control')assert '…' in waiting_heading()assert value('#{pane_title}', second) == long_title, 'raw pane title must remain unchanged'hn('select-pane', '-t', second, '-T', original_title)@@ -335,7 +336,7 @@ try:def context_before_controls():heading = tmux('capture-pane', '-p', '-t', 'test').splitlines()[y - 1][x:x + w].rstrip()suffix = heading.partition(branch_context)[2]- return branch_context in heading and bool(re.fullmatch(r'\s+…\s+×', suffix))+ return branch_context in heading and bool(re.fullmatch(r'\s+⋮', suffix))wait(context_before_controls, 'machine, project, branch and PR align beside the right-hand controls')snapshot('panes-zoomed' if target == first else 'panes-remote-zoomed')keys('C-b', 'z')diff --git a/tui/tests/repaint.py b/tui/tests/repaint.pyindex ca45c4527..afeef1874 100644--- a/tui/tests/repaint.py+++ b/tui/tests/repaint.py@@ -1,5 +1,6 @@#!/usr/bin/env python3-"""Animation, timed UI and idle-input checks in an isolated real terminal.+"""Animation, timed UI and idle-input checks in an isolated real terminal, then the+byte stream hn writes (?2026 pairs, soft and hard clears, the settle rewrite, idle).Run after a release build. HARNESS_TUI_BIN can select a frozen comparison build.Only a private HOME, named hn/tmux sockets, and a guarded mock port are used.@@ -9,6 +10,7 @@ from pathlib import Pathimport reimport shleximport shutil+import signalimport socketimport subprocessimport tempfile@@ -29,6 +31,7 @@ ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(TERM='xterm-256color', SHELL='/bin/sh', HARNESS_TUI_DESK='off',HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', HARNESS_TUI_ASK_TERMINAL='off',HARNESS_TUI_KITTY_KEYS='off')+VERIFY = BASE / 'verify.log'CONF = BASE / 'tmux.conf'CONF.write_text('set -g @hn-new-window shell\nset -g automatic-rename off\nset -g status-right "REPAINT_IDLE"\n''set -g set-titles-string "REPAINT_TITLE"\n')@@ -82,7 +85,7 @@ def changes(read, seconds=1.3):def spinner():- match = re.search(r'REPAINT_ANIM=([⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏])', screen())+ match = re.search(r'REPAINT_ANIM=([⠋⠙⠸⢰⣠⣄⡆⠇])', screen())return match[1] if match else None@@ -91,10 +94,168 @@ def clock():return match[0] if match else None+RAW = BASE / 'raw.bin'+SYNC = re.compile(rb'\x1b\[\?2026([hl])')+CLEAR, ERASE_ROW = b'\x1b[2J', b'\x1b[2K'+ROW_START, CUP = re.compile(rb'\x1b\[(\d+);1H'), re.compile(rb'\x1b\[(\d+);(\d+)H')+++def mark():+ """A position in what hn has written so far (the outer pane's raw output)."""+ return RAW.stat().st_size if RAW.exists() else 0+++def written(since, until=None):+ with RAW.open('rb') as f:+ f.seek(since)+ return f.read() if until is None else f.read(until - since)+++def updates(data):+ """The synchronized updates in [data]: the bytes between each ?2026h and its ?2026l.++ Asserts the pairs are balanced, never nested, that every hard clear is inside one, and that no+ row is erased before its text is written (a row written whole is its text, then \\e[K).+ """+ assert ERASE_ROW not in data, 'a row erased before its text'+ found, open_at, last = [], None, 0+ for m in SYNC.finditer(data):+ if m[1] == b'h':+ assert open_at is None, '?2026h inside an open update'+ assert CLEAR not in data[last:m.start()], 'a hard clear outside a synchronized update'+ open_at = m.end()+ else:+ assert open_at is not None, '?2026l with no update open'+ found.append(data[open_at:m.start()])+ open_at = None+ last = m.end()+ assert open_at is None, 'an update left open'+ assert CLEAR not in data[last:], 'a hard clear outside a synchronized update'+ return found+++def row_starts(update):+ """The rows (1-based) [update] writes from their first column."""+ return {int(m[1]) for m in ROW_START.finditer(update)}+++def cup_rows(data):+ """The rows (1-based) [data] places the cursor on: every row a frame writes a cell in."""+ return {int(m[1]) for m in CUP.finditer(data)}+++def settle_rewrite(data, rows, label):+ """[data] is a change, then its settle rewrite (the last update): the rows the change touched,+ each written from its first column — never the whole screen, never a hard clear."""+ found = updates(data)+ assert len(found) >= 2, f'{label}: no settle rewrite after the change ({len(found)} updates)'+ settle = found[-1]+ rewritten = row_starts(settle)+ touched = cup_rows(data[:data.rfind(b'\x1b[?2026h')])+ assert rewritten, f'{label}: the settle rewrite wrote no row'+ assert rewritten <= touched, f'{label}: rows {sorted(rewritten - touched)} rewritten that the change did not touch'+ assert len(rewritten) < rows, f'{label}: the whole screen was rewritten'+ assert not hard_clears(data) and not soft_repaints(data, rows), f'{label}: repainted'+ return sorted(rewritten)+++def soft_repaints(data, rows):+ """Updates that write every row from its first column, and do not erase the screen: a soft repaint."""+ return [u for u in updates(data) if row_starts(u) >= set(range(1, rows + 1)) and CLEAR not in u]+++def hard_clears(data):+ return [u for u in updates(data) if CLEAR in u]+++def settled(quiet=.8, within=8):+ """Wait until hn has written nothing for [quiet] seconds: an idle hn writes no bytes."""+ end = time.monotonic() + within+ while time.monotonic() < end:+ at = mark()+ time.sleep(quiet)+ if mark() == at:+ return+ raise AssertionError('hn keeps writing while idle:\n' + screen())+++def keys(*args):+ outer('send-keys', '-t', 'view', *args)+++def size():+ return [int(n) for n in outer('display-message', '-p', '-t', 'view', '#{window_width} #{window_height}').split()]+++def resize(width, height):+ outer('resize-window', '-t', 'view', '-x', str(width), '-y', str(height))+ wait(lambda: size() == [width, height], 'outer resize')+++def tui_pid():+ tui = ' '.join(COMMAND)+ listing = subprocess.run(['ps', '-axo', 'pid=,ppid=,command='], text=True, capture_output=True).stdout+ found = [l.split(None, 2) for l in listing.splitlines() if l.strip().endswith(tui)]+ pids = [int(pid) for pid, _, _ in found if not any(ppid == pid for _, ppid, _ in found)] # the child of the shell+ assert len(pids) == 1, ('the TUI process', found)+ return pids[0]+++def check_replay():+ """HARNESS_TUI_VERIFY replays every byte into a reference terminal: SIGUSR2 and a frame+ log its screen against what hn drew; no cell may differ, here or in any earlier frame."""+ os.kill(tui_pid(), signal.SIGUSR2)+ keys('-H', '1b', '5b', '49') # the dump is taken at the next frame; focus-in asks for one+ wait(lambda: VERIFY.exists() and re.search(r'### .* dump: SIGUSR2 .* 0 cells differ', VERIFY.read_text()),+ 'the replayed screen was not dumped')+ bad = re.findall(r'(?:===|###) .* [1-9][0-9]* cells differ', VERIFY.read_text())+ assert not bad, bad+++def start_session(*extra):+ """A fresh hn in the outer terminal (with [extra] env), its output copied to raw.bin."""+ run(COMMAND + ['kill-server'], ok=False)+ run(OUTER + ['kill-server'], ok=False)+ RAW.unlink(missing_ok=True)+ VERIFY.unlink(missing_ok=True)+ launch = ['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in ENV.items()], *extra, *COMMAND]+ outer('new-session', '-d', '-s', 'view', '-x', '120', '-y', '32', shlex.join(launch))+ wait(lambda: 'Mock terminal' in screen(), 'frame of the fresh session')+ outer('pipe-pane', '-t', 'view', f'cat >> {RAW}')+ keys('C-g') # the startup notice+ settled()+++def complete(data):+ """[data] without an update still being written (the pipe can end between its halves)."""+ cut = data.rfind(b'\x1b[?2026h')+ return data[:cut] if cut >= 0 and SYNC.search(data, cut + 8) is None else data+++def burst(act, seen=lambda data: len(data) > 0):+ """Run [act]; wait for the bytes it causes ([seen] of the whole updates written so far),+ then for hn to go quiet, so a second, unwanted repaint would show; return the bytes."""+ return burst_after(act, seen)[0]+++def burst_after(act, seen):+ """As burst, with the seconds from the key (delivered) to the first sight of [seen]."""+ at = mark()+ act()+ begun = time.monotonic()+ wait(lambda: seen(complete(written(at))), 'the expected bytes were not written')+ took = time.monotonic() - begun+ settled()+ return written(at), took++mock = Nonestarted = Falsetry:with socket.socket() as probe:+ # As the mock sets it: a port in TIME_WAIT from the last run is free, a live listener is not.+ probe.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)probe.bind(('127.0.0.1', PORT))with (BASE / 'mock.log').open('w') as log:mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)],@@ -170,6 +331,93 @@ try:== f'{width} {height}', 'resize')wait(lambda: 'REPAINT_INPUT_READY' in screen(), 'content after resize')print('PASS repaint: input after idle and recovery from a one-cell terminal', flush=True)++ # The byte stream: what a fresh hn (verifying its output) writes, as the terminal receives it.+ start_session(f'HARNESS_TUI_VERIFY={VERIFY}')+ rows = size()[1]+ soft = lambda data: len(soft_repaints(data, rows)) >= 1+ hard = lambda data: len(hard_clears(data)) >= 1++ def one_soft(data, label):+ assert len(soft_repaints(data, rows)) == 1, f'{label}: {len(soft_repaints(data, rows))} soft repaints, {len(updates(data))} updates'+ assert len(updates(data)) == 1, f'{label}: more than one update'+ assert not hard_clears(data), f'{label}: a hard clear'++ def no_repaint(data, label):+ assert data and not soft_repaints(data, rows) and not hard_clears(data), f'{label}: repainted'++ at = mark()+ time.sleep(1.2)+ assert mark() == at, 'an idle hn wrote bytes'+ print('PASS repaint: an idle hn writes no bytes', flush=True)++ # Focus-in repaints softly, once; so does Ctrl-L in a picker (the command panel).+ one_soft(burst(lambda: keys('-H', '1b', '5b', '49'), soft), 'focus-in')+ keys('C-b', 'Enter')+ wait(lambda: 'Commands' in screen(), 'command panel opens')+ settled()+ one_soft(burst(lambda: keys('C-l'), soft), 'Ctrl-L')++ # (Two requests in one loop pass giving one repaint is decided inside hn's loop, which the+ # input thread's timing keeps a terminal from reproducing: `redraw_all` is one flag the loop+ # takes once per pass, and each check above asserts one update per request.)+ print('PASS repaint: focus-in and Ctrl-L repaint softly, once each', flush=True)++ # Closing the command panel: one settle rewrite of the rows it touched, within 400 ms of the+ # key (plus what delivering a key costs, measured here), not at once, and never again by itself.+ started_at = time.monotonic()+ for _ in range(3): outer('display-message', '-p', 'x')+ overhead = (time.monotonic() - started_at) / 3 + .05 # a tmux call, and wait()'s poll step+ data, took = burst_after(lambda: keys('Escape'), lambda d: len(updates(d)) >= 2)+ rewritten = settle_rewrite(data, rows, 'command panel close')+ assert len(updates(data)) == 2, f'command panel close: {len(updates(data))} updates, not the close and one settle'+ assert .1 <= took <= .4 + overhead, f'the settle rewrite came {took:.3f}s after the key (overhead allowed {overhead:.3f})'+ assert 'Commands' not in screen()+ print(f'PASS repaint: the command panel closes with one settle rewrite of {len(rewritten)} rows ({took:.2f}s), then silence', flush=True)++ # New Harness: opening and typing do not repaint; closing settles once.+ hn('workspace-menu', 'new-harness')+ wait(lambda: 'New Harness' in screen(), 'New Harness opens')+ settled()+ no_repaint(burst(lambda: keys('-l', 'repaint check text')), 'typing in New Harness')+ no_repaint(burst(lambda: keys(*['BSpace'] * 20)), '20 backspaces')+ data = burst(lambda: keys('Escape'), lambda d: len(updates(d)) >= 2)+ settle_rewrite(data, rows, 'New Harness close')+ assert 'New Harness' not in screen()+ print('PASS repaint: New Harness open, typing and 20 backspaces, close', flush=True)++ # Streaming output: lines the mock echoes back scroll the pane, a burst of cells written one by+ # one; once it rests, only the rows it wrote are rewritten — not the whole screen.+ text = ''.join(f'REPAINT_STREAM {i:02d} ' + 'x' * 60 + '\r' for i in range(40))+ data = burst(lambda: keys('-l', text), lambda d: len(updates(d)) >= 2)+ rewritten = settle_rewrite(data, rows, 'streaming output')+ assert 'REPAINT_STREAM 39' in screen()+ print(f'PASS repaint: streaming output settles with a rewrite of the {len(rewritten)} rows it wrote', flush=True)++ # A real size change hard-clears, inside its update.+ for width, height in [(100, 30), (120, 32)]:+ data = burst(lambda: resize(width, height), hard)+ assert len(hard_clears(data)) == 1, f'resize to {width}x{height}: {len(hard_clears(data))} hard clears'+ print('PASS repaint: a resize hard-clears inside one synchronized update', flush=True)++ # Over the whole run: balanced, never nested, every clear inside a pair; no stale cell.+ updates(written(0))+ check_replay()+ print('PASS repaint: pairs balanced, no hard clear outside one, replayed screen matches', flush=True)++ # Without synchronized output: no ?2026 at all, the screen is still right.+ start_session(f'HARNESS_TUI_VERIFY={VERIFY}', 'HARNESS_TUI_SYNC=off')+ data = burst(lambda: keys('C-b', 'Enter'))+ wait(lambda: 'Commands' in screen(), 'panel')+ data += burst(lambda: keys('Escape'))+ assert CLEAR not in data, 'opening and closing a panel erased the whole screen'+ for width, height in [(100, 30), (120, 32)]:+ data += burst(lambda: resize(width, height), lambda d: CLEAR in d) # the size changed: a hard clear+ assert b'2026' not in data, 'HARNESS_TUI_SYNC=off still wrote ?2026'+ assert 'Commands' not in screen() and 'Mock terminal' in screen()+ check_replay()+ assert b'2026' not in written(0)+ print('PASS repaint: HARNESS_TUI_SYNC=off writes no ?2026 and the screen is correct', flush=True)finally:if started:run(COMMAND + ['kill-server'], ok=False)diff --git a/tui/tests/shell-first.py b/tui/tests/shell-first.pyindex 163fb04d4..b0c52455a 100644--- a/tui/tests/shell-first.py+++ b/tui/tests/shell-first.py@@ -161,14 +161,21 @@ def screen(): return tm('capture-pane','-p','-t','test',check=False)def finder_text():pane=hn('capture-pane','-p',check=False)start=pane.find('╭')- return pane[start:pane.find('╰',start)] if start>=0 else ''+ if start>=0: return pane[start:pane.find('╰',start)]+ # The composer has no box: its `›` query line, an `n/m ───` rule, the rows, then the keys line.+ lines=pane.splitlines()+ for i,line in enumerate(lines[:-1]):+ if '›' in line and re.match(r'\s*\d+/\d+\b',lines[i+1]):+ end=next((j for j in range(i+2,len(lines)) if 'esc back' in lines[j]),len(lines)-1)+ return '\n'.join(lines[i:end+1])+ return ''def finder_ready():return re.search(r'\d+/\d+',finder_text())def browsing(directory):# A recursive result already contains its descendants' names. Those names# alone do not prove Tab was handled or the destination's list was loaded.query=':~/'+directory.relative_to(BASE).as_posix()+'/'- return '> '+query+' ' in finder_text()+ return '› '+query+' ' in finder_text()def prompt_ready():lines=[line.strip() for line in hn('capture-pane','-p',check=False).splitlines() if line.strip()]return bool(lines) and lines[-1]=='SHELL_READY>'@@ -258,7 +265,7 @@ try:tm('send-keys','-t','test','-l','cd')# The temporary root name can also fuzzy-match "cd". The desired code# directory must rank first and open; the match count need not be one.- wait(lambda:finder_ready() and '> :cd ' in finder_text() and '~/project ü %/code' in finder_text() and re.search(r'\b[1-9]\d*/\d+',finder_text()),'fuzzy folder search without full spelling')+ wait(lambda:finder_ready() and '› :cd ' in finder_text() and '~/project ü %/code' in finder_text() and re.search(r'\b[1-9]\d*/\d+',finder_text()),'fuzzy folder search without full spelling')keys('Tab')wait(lambda:browsing(PROJECT/'code') and 'cool-project/' in finder_text() and 'client 日本/' in finder_text(),'Tab browses code')tm('send-keys','-t','test','-l','clpj')@@ -286,7 +293,7 @@ try:tm('send-keys','-t','test','-l','claude :')wait(finder_ready,'relative path folder picker')tm('send-keys','-t','test','-l','code/')- wait(lambda:'> :code/ ' in finder_text() and 'cool-project/' in finder_text() and 'client 日本/' in finder_text(),'relative code/ resolves against shell cwd')+ wait(lambda:'› :code/ ' in finder_text() and 'cool-project/' in finder_text() and 'client 日本/' in finder_text(),'relative code/ resolves against shell cwd')tm('send-keys','-t','test','-l','missing/')wait(lambda:finder_ready() and ('unavailable' in finder_text() or 'Could not read' in finder_text()),'missing folder explains failure')assert re.search(r'\b0/0\b',finder_text()),screen()@@ -306,9 +313,9 @@ try:if os.environ.get('HN_SHELL_TEST_GUI')=='1':def click_text(text):lines=screen().splitlines()- for y,line in ([(len(lines)-1,lines[-1])] if text in ('+','…') else enumerate(lines)):+ for y,line in ([(len(lines)-1,lines[-1])] if text in ('+','⋮') else enumerate(lines)):if text in line:- x=line.index(' '+text+' ')+2 if text in ('+','…') else line.index(text)+ x=line.index(' '+text+' ')+2 if text in ('+','⋮') else line.index(text)tm('send-keys','-t','test','-l',f'\x1b[<0;{x+1};{y+1}M\x1b[<0;{x+1};{y+1}m')returnraise AssertionError(('missing clickable text',text,screen()))@@ -317,10 +324,10 @@ try:wait(lambda:'New Harness' in screen() and 'Task' in screen(),'footer + opens GUI composer')assert pane_count()==1 and hn('display-message','-p','#{window_id}').strip()==original_windowkeys('Escape');wait(prompt_ready,'GUI composer cancels back to original shell')- click_text('…');wait(lambda:'New Harness' in screen() and 'New Tab' in screen(),'workspace mouse menu')+ click_text('⋮');wait(lambda:'New Harness' in screen() and 'New Tab' in screen(),'workspace mouse menu')click_text('New Harness');wait(lambda:'Task' in screen(),'menu New Harness opens GUI')keys('Escape');wait(prompt_ready,'menu composer cancels')- click_text('…');wait(lambda:'New Tab' in screen(),'workspace menu reopened')+ click_text('⋮');wait(lambda:'New Tab' in screen(),'workspace menu reopened')click_text('New Tab');wait(lambda:'New Harness' in screen() and 'Task' in screen() and 'machines connected' in screen(),'mouse New Tab opens welcome composer')gui_window=hn('display-message','-p','#{window_id}').strip()assert gui_window!=original_window@@ -331,7 +338,8 @@ try:start_window=hn('display-message','-p','#{window_id}').strip()keys('C-b','c')wait(lambda:finder_ready() and 'Claude Code' in screen(),'new keyboard tab opens agent picker',30)- assert 'Search agents' in screen() and '> &' not in screen(),screen()+ assert 'Search agents' in screen() and '› &' not in screen(),screen()+ for scope in ['@ computer',': project','% model','& agent']: assert scope in screen(),(scope,screen())tm('send-keys','-t','test','-l','cld')wait(lambda:finder_ready() and 'Claude Code' in screen() and re.search(r'\b1/\d+',screen()),'plain fuzzy agent search')keys('Enter')@@ -379,7 +387,7 @@ try:tm('send-keys','-t','test','-l',prefix)wait(lambda:finder_ready() and expected in finder_text(),'automatic '+prefix+' selector')keys('BSpace')- wait(lambda:not finder_ready() and '╭' not in hn('capture-pane','-p'),'erasing '+prefix+' closes suggestions instead of switching lists')+ wait(lambda:not finder_ready(),'erasing '+prefix+' closes suggestions instead of switching lists')assert 'Search sessions' not in hn('capture-pane','-p') and 'Search agents' not in hn('capture-pane','-p')assert not (BASE/'fixture-agent.json').exists(),'deleting a selector launched the agent'# Print the draft as data to inspect every argument; no agent runs.@@ -406,24 +414,24 @@ try:keys('C-n');wait(lambda:finder_ready() and 'Claude Code' in screen(),'Ctrl-N opens agents directly after folder')tm('send-keys','-t','test','-l','clau')wait(lambda:finder_ready() and 'Claude Code' in screen(),'Ctrl-N agent filter')- keys('Enter');wait(lambda:'SHELL_READY> claude' in hn('capture-pane','-p') and '╭' not in hn('capture-pane','-p'),'agent inserted into draft')+ keys('Enter');wait(lambda:'SHELL_READY> claude' in hn('capture-pane','-p') and not finder_ready(),'agent inserted into draft')assert not (BASE/'fixture-agent.json').exists(),'selection launched agent'tm('send-keys','-t','test','-l','%');wait(finder_ready,'automatic model list');tm('send-keys','-t','test','-l','son')wait(lambda:finder_ready() and 'sonnet' in screen(),'native model autocomplete')- keys('Enter');wait(lambda:'%sonnet' in hn('capture-pane','-p') and '╭' not in hn('capture-pane','-p'),'model inserted after folder')+ keys('Enter');wait(lambda:'%sonnet' in hn('capture-pane','-p') and not finder_ready(),'model inserted after folder')tm('send-keys','-t','test','-l','@')wait(finder_ready,'automatic computer list')- keys('Escape');wait(lambda:'╭' not in hn('capture-pane','-p'),'automatic computer choice cancelled')+ keys('Escape');wait(lambda:not finder_ready(),'automatic computer choice cancelled')keys('BSpace')tm('send-keys','-t','test','-l',':')wait(lambda:finder_ready() and 'project ü' in screen(),'folder list')tm('send-keys','-t','test','-l','project ü')- keys('Enter');wait(lambda:'╭' not in hn('capture-pane','-p') and 'project ü' in screen(),'folder inserted and quoted')+ keys('Enter');wait(lambda:not finder_ready() and 'project ü' in screen(),'folder inserted and quoted')assert not (BASE/'fixture-agent.json').exists()keys('C-p');wait(finder_ready,'continue composing');keys('Escape')- wait(lambda:'╭' not in hn('capture-pane','-p'),'composer cancellation')+ wait(lambda:not finder_ready(),'composer cancellation')keys('C-n');wait(lambda:finder_ready() and 'Claude Code' in screen(),'Ctrl-N reopens agents in composed draft');keys('Escape')- wait(lambda:'╭' not in hn('capture-pane','-p'),'Ctrl-N cancellation preserves composed draft')+ wait(lambda:not finder_ready(),'Ctrl-N cancellation preserves composed draft')assert not (BASE/'fixture-agent.json').exists()keys('Enter')else:@@ -583,7 +591,7 @@ try:wait(lambda:'Use agent default' in screen(),'model scope in shared finder')assert 'SHORTCUT_DRAFT_LRIGHT' not in screen(),'opening the finder executed the draft'keys('Enter')- wait(lambda:'SHELL_READY> '+draft in hn('capture-pane','-p') and '╭' not in hn('capture-pane','-p'),'model selection preserves draft')+ wait(lambda:'SHELL_READY> '+draft in hn('capture-pane','-p') and not finder_ready(),'model selection preserves draft')tm('send-keys','-t','test','-l','M');keys('Enter')wait(lambda:'SHORTCUT_DRAFT_LMRIGHT' in screen(),'model selection preserves cursor')# Simulate a terminal reporting Cmd-P via the Kitty protocol, not a claim@@ -594,7 +602,7 @@ try:tm('send-keys','-t','test','-l','@')wait(lambda:'this computer' in screen(),'computer scope in shared finder')keys('Enter')- wait(lambda:"SHELL_READY> printf 'CMD_PICKER_" in hn('capture-pane','-p') and '╭' not in hn('capture-pane','-p'),'computer selection preserves draft')+ wait(lambda:"SHELL_READY> printf 'CMD_PICKER_" in hn('capture-pane','-p') and not finder_ready(),'computer selection preserves draft')assert 'CMD_PICKER_OK' not in screen()keys('Enter');wait(lambda:'CMD_PICKER_OK' in screen(),'computer shortcut returns usable draft')keys('C-p');wait(finder_ready,'scope-switch cancellation')diff --git a/tui/tests/shell-integration.py b/tui/tests/shell-integration.pyindex f4ecc8533..9bad0331c 100644--- a/tui/tests/shell-integration.py+++ b/tui/tests/shell-integration.py@@ -18,6 +18,9 @@ import urllib.parseROOT = Path(__file__).resolve().parents[1]TOKEN = '8c73ea55-683a-4207-a9aa-ab8a9e813bea'REQUEST = re.compile(rb'\x1b\]633;hn;([^;]+);([^;]+);([^;]+);([^\x07]*)\x07')+PICKED = b'\x1b]633;picked\x07'+# Removes the progress line's two rows and returns to the row it started on.+ERASE = b'\r\x1b[2K\x1b[1A\x1b[2K\x1b[1A'AGENTS = ('codex', 'claude', 'cursor-agent', 'opencode', 'pi', 'hermes', 'cmd', 'devin', 'muse', 'amp', 'kilo', 'grok', 'agy', 'copilot')class Shell:@@ -31,8 +34,14 @@ class Shell:path.write_text('#!/usr/bin/env python3\nimport os,sys,json\nwith open(os.environ["CALLS"],"a") as f: f.write(json.dumps(sys.argv)+"\\n")\n')path.chmod(0o755)picker=binpath/'native-picker'- picker.write_text('#!/bin/sh\n[ -f "$HOME/picker-choice" ] || exit 130\ncat "$HOME/picker-choice"\n')+ # With picker-mark, it also marks on the terminal the moment the choice is made.+ picker.write_text('#!/bin/sh\n[ -f "$HOME/picker-choice" ] || exit 130\n'+ '[ ! -f "$HOME/picker-mark" ] || printf \'\\033]633;picked\\007\' >&2\ncat "$HOME/picker-choice"\n')picker.chmod(0o755)+ # With slow-od, making a request id takes a while (a busy machine).+ od=binpath/'od'+ od.write_text('#!/bin/sh\n[ ! -f "$HOME/slow-od" ] || sleep 3\nexec /usr/bin/od "$@"\n')+ od.chmod(0o755)for rc in ('.zshenv', '.zprofile', '.zshrc', '.zlogin', '.bashrc'):text = f"printf '%s\\n' '{rc}' >> \"$STARTUP\"\n"if rc in ('.zshrc', '.bashrc'):@@ -52,6 +61,11 @@ class Shell:bootstrap = (ROOT / 'src/shell_bootstrap.sh').read_text().replace('@INTEGRATION@', (ROOT / 'src/shell_integration.sh').read_text())self.pid, self.fd = pty.fork()if not self.pid:+ # A terminal (tmux too) starts its shell with default signals. A runner+ # started with `&` ignores SIGINT, and a shell can never trap a signal+ # ignored on entry, so Ctrl-C could not cancel anything.+ signal.signal(signal.SIGINT, signal.SIG_DFL)+ signal.signal(signal.SIGQUIT, signal.SIG_DFL)os.chdir(root)env = {k:v for k,v in os.environ.items() if k in ('LANG','LC_ALL','TZ')}env.update(HOME=str(root), SHELL=shell, PATH=str(binpath)+':/usr/bin:/bin:/usr/sbin:/sbin', _HN_CLI=str(binpath/'harness'),@@ -110,7 +124,8 @@ class Shell:os.close(self.fd)with tempfile.TemporaryDirectory(prefix='hn-shell-test-') as tmp:- for shell in ('/bin/zsh',os.environ.get('HN_SHELL_TEST_BASH','/bin/bash')):+ # An empty HN_SHELL_TEST_ZSH skips zsh (a machine with only a bash 5).+ for shell in filter(None,(os.environ.get('HN_SHELL_TEST_ZSH','/bin/zsh'),os.environ.get('HN_SHELL_TEST_BASH','/bin/bash'))):for custom in (False,True):root=Path(tmp)/(Path(shell).name+str(custom)); root.mkdir()print('starting',shell,custom,flush=True)@@ -139,6 +154,89 @@ with tempfile.TemporaryDirectory(prefix='hn-shell-test-') as tmp:s.read_until(b'READY> ')s.send('M\r')s.result(b'DRAFT_LMRIGHT')+ # A computer that never answers: the widget says at once what it waits+ # for, Ctrl-C gives the prompt back with the line unchanged, and the+ # next pick is served.+ # The wait starts once the choice is made, not while the picker starts.+ (root/'picker-choice').write_text('host\nGone\n')+ (root/'picker-mark').touch()+ s.send("printf 'GONE_%s\\n' LRIGHT")+ s.send('\x02'*5+'\x10')+ seen=s.read_until(PICKED).split(PICKED,1)[1]+ t0=time.monotonic()+ (root/'picker-mark').unlink()+ if not REQUEST.search(seen): seen+=s.read_until(REQUEST)+ first=REQUEST.search(seen)+ assert first[3]==b'host-inline' and base64.b64decode(first[4])==b'Gone'+ progress='Opening a shell on Gone… Ctrl-C to cancel'.encode()+ if progress not in seen: seen+=s.read_until(progress,seconds=1)+ assert time.monotonic()-t0<1,'the progress line came too late'+ time.sleep(.3) # nobody answers: the line must stay as it is meanwhile+ s.send('\x03')+ t0=time.monotonic()+ said=s.read_until(b'READY> ',seconds=1)+ assert time.monotonic()-t0<1,'Ctrl-C did not give the prompt back within 1 s'+ assert re.search(rb'633;hn;'+TOKEN.encode()+b';'+re.escape(first[2])+b';cancel;',said),'the request was not cancelled'+ # The rows the progress line added are gone again: only the prompt is left.+ assert ERASE in said.split(b'cancel;',1)[1],('the progress line was left behind',said)+ s.send('M\r')+ s.result(b'GONE_LMRIGHT') # the line is exactly what it was+ # Right after it, another choice is served (the TUI freed the picker),+ # and the progress line names this computer as such.+ (root/'picker-choice').write_text('host\nlocal\n')+ s.send('\x10')+ seen=s.read_until(REQUEST)+ match=REQUEST.search(seen)+ assert match[3]==b'host-inline' and match[2]!=first[2]+ if b'Ctrl-C to cancel' not in seen: seen+=s.read_until(b'Ctrl-C to cancel')+ assert 'Opening a shell on this computer… Ctrl-C to cancel'.encode() in seen,seen+ s.reply(match); done=s.read_until(b'READY> ')+ assert ERASE in done,('the progress line was left behind',done)+ if shell.endswith('zsh'):+ # The widget's localtraps ends with it: a user function's trap still holds after it.+ s.send("[[ -o localtraps ]] && printf 'LT_%s\\n' ON || printf 'LT_%s\\n' OFF\r")+ said=s.read_until(LT:=re.compile(rb'[\r\n]LT_(ON|OFF)\r?\n'))+ assert LT.search(said)[1]==b'OFF',('LOCAL_TRAPS leaked into the shell',said)+ if b'READY> ' not in said[LT.search(said).end():]: s.read_until(b'READY> ')+ # The widget keeps its saved trap to itself.+ s.send("[ -z \"${_hn_saved_int+x}\" ] && printf 'SV_%s\\n' CLEAN || printf 'SV_%s\\n' LEAKED\r")+ said=s.read_until(SV:=re.compile(rb'[\r\n]SV_(CLEAN|LEAKED)\r?\n'))+ assert SV.search(said)[1]==b'CLEAN',('the widget left _hn_saved_int behind',said)+ if b'READY> ' not in said[SV.search(said).end():]: s.read_until(b'READY> ')+ # Ctrl-C while the request is still being made says Cancelled, not a failure.+ (root/'slow-od').touch()+ (root/'picker-choice').write_text('host\nGone\n')+ s.send('\x10')+ s.read_until(b'Ctrl-C to cancel')+ time.sleep(.3) # od is running now+ s.send('\x03')+ said=s.read_until(b'Cancelled.',seconds=2)+ assert b'Could not create' not in said,said+ # zsh draws the prompt before its message; bash after it.+ if shell.endswith('bash') and b'READY> ' not in said.split(b'Cancelled.',1)[1]: s.read_until(b'READY> ')+ (root/'slow-od').unlink()+ if not custom:+ # An answer that comes just as the shell gives up is used, not+ # reported as missing. (picker-ready gives up after 5 s.)+ s.send("_hn_request picker-ready; printf 'RC_%s\\n' $?\r")+ late=REQUEST.search(s.read_until(REQUEST))+ assert late[3]==b'picker-ready'+ s.read_until(re.compile(rb'633;hn;'+TOKEN.encode()+b';'+re.escape(late[2])+b';cancel;'),seconds=8)+ s.reply(late,'JUST_IN_TIME\n')+ said=s.read_until(RC:=re.compile(rb'[\r\n]RC_(\d+)\r?\n'),seconds=3)+ assert b'JUST_IN_TIME' in said and RC.search(said)[1]==b'0' and b'did not answer' not in said,said+ if b'READY> ' not in said[RC.search(said).end():]: s.read_until(b'READY> ')+ # The widget's own Ctrl-C guard must not drop the user's INT trap.+ s.send("trap 'echo MINE' INT\r"); s.read_until(b'READY> ')+ s.send('\x10')+ match=REQUEST.search(s.read_until(REQUEST))+ s.reply(match); s.read_until(b'READY> ')+ show='trap' if shell.endswith('zsh') else 'trap -p INT'+ s.send("printf 'TRAP_%s\\n' BEGIN; "+show+"; printf 'TRAP_%s\\n' END\r")+ kept=s.read_until(re.compile(rb'\nTRAP_END'))+ assert b'echo MINE' in kept.split(b'TRAP_BEGIN',2)[-1],('the INT trap was lost',kept)+ if b'READY> ' not in kept.rsplit(b'TRAP_END',1)[1]: s.read_until(b'READY> ')+ s.send("trap - INT\r"); s.read_until(b'READY> ')(root/'picker-choice').unlink()(root/'picker-choice').write_text('sessions\nexternal:local:missing\n')s.send('\x10')diff --git a/tui/tests/welcome-composer.py b/tui/tests/welcome-composer.pyindex 61ac3e5fa..9eedd1162 100644--- a/tui/tests/welcome-composer.py+++ b/tui/tests/welcome-composer.py@@ -90,7 +90,7 @@ try:wait(lambda:'studio' in screen(),'local fixture connected')hn('workspace-menu','new-tab'); shows('New Terminal'); shows('Recent harnesses')shows('gpu-box shell') # Terminals remain recent harnesses, as in production.- shows('What task should this agent work on?')+ shows('What should it do?')snapshot('welcome-empty')initial_header=header()assert initial_header.index('OpenCode') < initial_header.index(LOCAL_LABEL) < initial_header.rfind('[ '), initial_header@@ -102,11 +102,13 @@ try:choose_machine('gpu-box'); assert '[ gpu-box ▾ ]' in header(),header()click('New Folder'); shows('Search projects')snapshot('welcome-project-picker')- # A side picker leaves the recent list visible. Check the picker column,- # not unrelated local projects in that background list.+ # The picker drops down over the recent list. Check its own rows (query line+ # to keys line), not unrelated local projects in that background list.project_lines=screen().splitlines()- picker_x=next(line.index('Search projects') for line in project_lines if 'Search projects' in line)- projects='\n'.join(line[picker_x:] for line in project_lines)+ top=next(y for y,line in enumerate(project_lines) if 'Search projects' in line)+ bottom=next(y for y in range(top,len(project_lines)) if 'esc back' in project_lines[y])+ picker_x=project_lines[top].index('Search projects')+ projects='\n'.join(line[picker_x:picker_x+60] for line in project_lines[top:bottom+1])assert 'ml-lab' in projects and 'billing' not in projects, 'projects must belong to the selected computer'type_text('ml-lab'); keys('Enter'); shows('[ ml-lab ▾ ]'); shows(task)choose_machine('studio'); assert header()==initial_header,(header(),initial_header)@@ -161,7 +163,7 @@ try:count=len(created()); click('New Terminal'); shows('dev@gpu-box')assert len(created())==count, 'New Terminal must not launch the chosen coding agent'print('PASS keyboard traversal, All action, wide/narrow/light rendering, preserved task, New Terminal',flush=True)- hn('workspace-menu','new-tab'); shows('What task should this agent work on?')+ hn('workspace-menu','new-tab'); shows('What should it do?')task="what's 1+1"type_text(task); keys('Enter')assert len(created())==count, 'first task Enter only highlights New Harness'diff --git a/tui/tests/welcome.py b/tui/tests/welcome.pyindex ef9055b00..e143d9a33 100644--- a/tui/tests/welcome.py+++ b/tui/tests/welcome.py@@ -125,7 +125,7 @@ def created(): return [p for p in state().get('created', []) if p['engine'] != 'def window(): return hn('display', '-p', '#{window_id}')def new_tab():hn('workspace-menu', 'new-tab')- shows('What task should this agent work on?')+ shows('What should it do?')def initial_gui():wait(lambda: hn('display', '-p', '#{window_panes}', ok=False) == '1', 'initial shell ready')shell = window()@@ -213,7 +213,9 @@ try:snapshot('new-window-draft')print('PASS welcome: immediate first task, duplicate prevention, delayed placement and independent drafts', flush=True)- keys('Down'); shows('Search agents')+ # Down reaches Agent (no chooser until it is entered: → opens it, Esc closes it there).+ keys('Down', 'Right'); shows('Search agents')+ keys('Escape'); wait(lambda: 'Search agents' not in screen(), 'Esc closes the chooser on Agent')keys('Up'); type_text('!'); shows('second window draft!')keys('BSpace')wait(lambda: 'second window draft!' not in screen(), 'Backspace edits the task after returning from Agent')@@ -285,7 +287,7 @@ try:new_tab()type_text('Keep this task away from the terminal')click('Agent'); type_text('Terminal')- shows('No matches')+ shows('Nothing matches')keys('Escape')click('New Terminal'); shows('Mock terminal (mock)')assert len(created()) == count + 1, 'New Terminal never starts a coding agent'diff --git a/tui/tests/workspace-controls.py b/tui/tests/workspace-controls.pyindex 6a8050a66..09c06879c 100644--- a/tui/tests/workspace-controls.py+++ b/tui/tests/workspace-controls.py@@ -183,13 +183,24 @@ def painted_workspace(alpha, beta):for name, (x, y, w) in positions)+MENU = '⋮'++def pane_menu_item(item, row):- """The first pane's … in title row [row], then [item]: the agent and the model change there."""- click_text('…', row=row)+ """The first pane's menu (⋮) in title row [row], then [item]: the agent and the model change there."""+ click_text(MENU, row=row)shown(item)click_text(item)+def close_from_menu(row, occurrence=0):+ """A pane's menu (⋮) in title row [row], then its close item (x): Stop Harness or Close. The+ title has no close button."""+ click_text(MENU, occurrence=occurrence, row=row)+ shown('Move to new tab')+ keys('x')++def alpha_agent_picker():wait(lambda: any('Change agent' in line and 'Alpha task' in line for line in screen().splitlines()),'the visible agent picker belongs to Alpha')@@ -220,11 +231,19 @@ def machine_prompt_journey():shown('•' * len('fixture pasted password'))assert 'fixture pasted password' not in screen()+ def dialog(title, action):+ # The question is asked in its own box; the panel's search line stays the search.+ shown('┌─' + title)+ shown('[ Cancel ] [ ' + action + ' ]')+ assert 'Search machines, links and steps' in screen()+hn('devices')shown('Set password…')click_text('Set password…')shown('New remote password')+ dialog('Set Remote Password', 'Continue')paste_password()+ assert '│' + '•' * len('fixture pasted password') in screen(), 'the password is typed into the dialog input'# A list click used to become Enter and accept the unfinished password.click_text('Refresh links')shown('New remote password')@@ -234,6 +253,7 @@ def machine_prompt_journey():paste_password()click_text('Continue')shown("Set this computer's remote password?")+ dialog('Set Remote Password', 'Yes')assert not actions()snapshot('machine-password-confirmation')click_text('Cancel')@@ -245,7 +265,7 @@ def machine_prompt_journey():click_text('Continue')paste_password()click_text('Continue')- click_text(' Yes ')+ click_text('[ Yes ]')wait(lambda: actions() == ['set'], 'one explicitly confirmed password write')shown('Clear password…')click_text('Clear password…')@@ -254,8 +274,9 @@ def machine_prompt_journey():tmux('resize-window', '-t', 'test', '-x', str(cols), '-y', str(rows))wait(lambda: value('#{client_width}x#{client_height}') == f'{cols}x{rows}', 'client follows terminal resize')shown('Prevent new links')- shown(' Cancel ')- shown(' Yes ')+ shown('┌─Clear Remote Password')+ shown('[ Cancel ]')+ shown('[ Yes ]')snapshot(f'machine-confirmation-{cols}x{rows}')click_text('Cancel')assert actions() == ['set']@@ -357,9 +378,9 @@ def mirror_journey(command, source):replacement_agent = next(a['id'] for a in api()['agents'][api()['local']] if a['engine'] == 'claude' and a['name'] == source and a['status'] != 'stopped')api({'action': 'activity', 'agent': replacement_agent, 'activity': 'working'})before_stop = len(requests('agent_close'))- click_text('×', row=0)+ close_from_menu(row=0)shown('Stop? Saved history will remain.')- click_text('(s)')+ click_text('[ Stop ]')wait(lambda: original_pane not in hn('list-panes', '-s', '-t', 'mirror-review', '-F', '#{pane_id}').splitlines(), 'confirmed Stop closes the owning session view')wait(lambda: source not in tmux('capture-pane', '-p', '-t', 'test:0').splitlines()[0], 'owner no longer shows the stopped harness')stop_calls = [r['payload']['mode'] for r in requests('agent_close')[before_stop:] if r['payload']['agentId'] == replacement_agent]@@ -389,18 +410,26 @@ def overlay_dismiss_journey(alpha):print('PASS workspace: overlay dismissal and pane actions consume the complete mouse click', flush=True)-def title_drag_journey(alpha, beta):+def title_drag_journey(alpha, beta, look='line'):original = value('#{window_layout}')border = hn('show', '-gv', '@hn-border', ok=False)- hn('set', '-g', '@hn-border', 'line')+ hn('set', '-g', '@hn-border', look)hn('select-layout', 'even-vertical')x, top = map(int, value('#{pane_left} #{pane_top}', beta).split())- wait(lambda: 'Beta task' in screen().splitlines()[top - 1], 'lower title is painted at its divider')+ # The line look's title is the divider row above the pane; the box look's frame, with the title+ # in it, sits on that same row.+ corner = {'line': '─', 'box': '┌'}[look]+ wait(lambda: 'Beta task' in screen().splitlines()[top - 1] and corner in screen().splitlines()[top - 1],+ f'lower {look} title is painted at its divider')before = len(api()['inputs'])+ # The line right of the name (the name itself drags the pane).+ line = screen().splitlines()[top - 1]+ col = next(c for c in range(line.index('Beta task') + len('Beta task') + 1, x + int(value('#{pane_width}', beta)) - 7)+ if line[c] == '─')for code, row, ending in [(0, top - 1, 'M'), (32, top + 1, 'M'), (0, top + 1, 'm')]:- raw = f'\x1b[<{code};{x + 5};{row + 1}{ending}'.encode()+ raw = f'\x1b[<{code};{col + 1};{row + 1}{ending}'.encode()tmux('send-keys', '-H', '-t', TARGET, *[f'{b:02x}' for b in raw])- wait(lambda: int(value('#{pane_top}', beta)) == top + 2, 'dragging the plain title resizes its divider')+ wait(lambda: int(value('#{pane_top}', beta)) == top + 2, f'dragging the {look} title beside its name resizes its divider')assert len(api()['inputs']) == before, 'title drag must not reach the terminal program'hn('select-layout', original)if border:@@ -410,7 +439,122 @@ def title_drag_journey(alpha, beta):hn('select-pane', '-t', alpha)wait(lambda: value('#{window_layout}') == original, 'restore layout after title drag')wait(lambda: painted_workspace(alpha, beta), 'restored layout paints both pane titles')- print('PASS workspace: plain title divider drags retain tmux resize behavior', flush=True)+ print(f'PASS workspace: {"plain" if look == "line" else look} title divider drags retain tmux resize behavior', flush=True)+++def pane_drag_journey(alpha, beta):+ original = value('#{window_layout}')+ border = hn('show', '-gv', '@hn-border', ok=False)+ hn('set', '-g', '@hn-border', 'box')+ hn('select-pane', '-t', alpha)++ def box(pane):+ return tuple(map(int, value('#{pane_left} #{pane_top} #{pane_width} #{pane_height}', pane).split()))++ def name_cell(pane, name):+ # The name in the pane's header, above its first row (the box frame adds one), once painted there.+ x, y, w, _ = box(pane)+ lines = screen().splitlines()+ for row in range(y - 1, max(y - 4, -1), -1):+ index = lines[row].find(name) if row < len(lines) else -1+ if index >= 0 and x - 1 <= width(lines[row][:index]) <= x + w:+ return width(lines[row][:index]) + 2, row+ return None++ def held(pane, name):+ wait(lambda: name_cell(pane, name), f'{name} title is painted over its pane')+ return name_cell(pane, name)++ def drag(start, end):+ (sx, sy), (ex, ey) = start, end+ for code, x, y, ending in [(0, sx, sy, 'M'), (32, sx + 2, sy + 1, 'M'), (32, ex, ey, 'M'), (0, ex, ey, 'm')]:+ raw = f'\x1b[<{code};{x + 1};{y + 1}{ending}'.encode()+ tmux('send-keys', '-H', '-t', TARGET, *[f'{b:02x}' for b in raw])++ def ids(*target):+ return hn('list-panes', *target, '-F', '#{pane_id}').splitlines()++ before = len(api()['inputs'])+ x, y, w, h = box(beta)+ drag(held(alpha, 'Alpha task'), (x + w // 2, y + h // 2))+ wait(lambda: ids() == [beta, alpha], 'dropping on the middle of Beta swaps the two panes')+ assert value('#{pane_active}', alpha) == '1', 'the held pane keeps the focus after a swap'+ hn('select-pane', '-t', beta)+ x, y, w, h = box(beta)+ drag(held(alpha, 'Alpha task'), (x + w // 2, y + h - 2))+ wait(lambda: box(alpha)[0] == box(beta)[0] and box(alpha)[1] > box(beta)[1],+ "dropping on Beta's bottom quarter puts Alpha below it")+ assert value('#{pane_active}', alpha) == '1', 'the held pane is focused where it lands'+ print('PASS workspace: dropping a pane by its name swaps it or puts it beside another', flush=True)++ # A tab: Beta in a window of its own is dropped on this window's name in the status bar.+ hn('swap-pane', '-s', alpha, '-t', beta)+ hn('select-layout', original)+ number = value('#{window_index}', alpha)+ hn('break-pane', '-d', '-n', 'Dragged', '-s', beta)+ hn('select-window', '-t', 'Dragged')++ def tab():+ # The status bar's " N:name" cell of this window (the clock's "10:17" is not one).+ lines = screen().splitlines()+ for row in range(len(lines) - 1, len(lines) - 3, -1):+ if (index := lines[row].find(f' {number}:')) >= 0:+ return width(lines[row][:index]) + 3, row+ return None+ wait(lambda: value('#{window_name}') == 'Dragged' and tab(), f'the status bar shows tab {number}')+ drag(held(beta, 'Beta task'), tab())+ wait(lambda: beta in ids('-t', f':{number}'), f'dropping on the tab moves Beta into window {number}')+ wait(lambda: 'Dragged' not in hn('list-windows', '-F', '#{window_name}').splitlines(),+ 'the window Beta left, with no pane, closes')+ assert value('#{window_index}') == number and value('#{pane_active}', beta) == '1', \+ 'the view follows the held pane into its window, focused there'+ assert ids('-t', f':{number}') == [alpha, beta], ids('-t', f':{number}')+ assert len(api()['inputs']) == before, ('a pane drag must not reach the terminal program', api()['inputs'][before:])+ hn('select-layout', original)+ if border:+ hn('set', '-g', '@hn-border', border)+ else:+ hn('set', '-gu', '@hn-border')+ hn('select-pane', '-t', alpha)+ wait(lambda: value('#{window_layout}') == original, 'restore layout after pane drags')+ wait(lambda: painted_workspace(alpha, beta), 'restored layout paints both pane titles')+ print('PASS workspace: dropping a pane on a tab moves it into that window', flush=True)+++def side_bar_machines_journey():+ # In the side bar each machine lists its harnesses no window here shows: a click opens one in+ # a window, a right press on the machine offers what can be done on it, and a harness that+ # stops leaves the list.+ bar = hn('show', '-gv', '@hn-status-bar', ok=False)+ hn('set', '-g', '@hn-status-bar', 'left')+ width = 26+ windows = lambda: len(hn('list-windows', '-F', '#{window_id}').splitlines())+ shown('✓ Remote')+ api({'action': 'remote-agent', 'agent': 'delta', 'name': 'Delta remote task'})+ shown('Delta remote task')+ snapshot('side-bar-machines')+ before = windows()+ click_text('Delta remote task', before=width)+ wait(lambda: windows() == before + 1, 'a click opens the harness in a window')+ shown('Delta remote task terminal')+ # (The second: the first is the bar's top line, the machine this window is on.)+ click_text('✓ Remote', occurrence=1, button=2, before=width)+ shown('New Harness on Remote…')+ shown('Open its harnesses')+ snapshot('side-bar-machine-menu')+ keys('Escape')+ wait(lambda: 'New Harness on Remote…' not in screen(), 'Esc closes the machine menu')+ # Its window closed, the harness is a row under its machine again; stopped, it goes.+ hn('kill-window')+ wait(lambda: windows() == before, 'its window closes')+ shown('Delta remote task')+ api({'action': 'remote-agent', 'agent': 'delta', 'stop': True})+ wait(lambda: 'Delta remote task' not in screen(), 'a stopped harness leaves the side bar')+ if bar:+ hn('set', '-g', '@hn-status-bar', bar)+ else:+ hn('set', '-gu', '@hn-status-bar')+ print('PASS workspace: the side bar lists each machine\'s harnesses, opens one with a click, and offers its menu', flush=True)mock = None@@ -460,9 +604,18 @@ try:if '--title-drag' in sys.argv:api({'action': 'terminal-mouse'})title_drag_journey(alpha, beta)+ title_drag_journey(alpha, beta, 'box')+ sys.exit(0)+ if '--pane-drag' in sys.argv:+ api({'action': 'terminal-mouse'})+ pane_drag_journey(alpha, beta)+ sys.exit(0)+ if '--side-bar' in sys.argv:+ side_bar_machines_journey()sys.exit(0)machine_prompt_journey()+ side_bar_machines_journey()# Local use is complete before any sign-in. The tiny footer entry explains the benefit,# then lets the user return without starting an authentication request.@@ -559,6 +712,10 @@ try:shown('Arrange panes')click_text('Rename')shown('Tab name')+ # hn's own rename is a dialog with an input box, not tmux's status-line prompt.+ shown('┌─Rename Tab ·')+ shown('[ Cancel ] [ Rename ]')+ snapshot('rename-tab-dialog')hn('select-window', '-t', 'Remote')keys('C-u')tmux('send-keys', '-l', '-t', 'test', 'Renamed workspace')@@ -595,16 +752,16 @@ try:hn('select-pane', '-t', beta)api({'action': 'config', 'patch': {'closeFailure': 'SAVE_FAILED'}})x, y, w = map(int, value('#{pane_left} #{pane_top} #{pane_width}', beta).split())- click_text('×', occurrence=1, row=y - 1)+ close_from_menu(occurrence=1, row=y - 1)shown('Cancel')assert not [r for r in requests('agent_close') if r['payload'].get('mode') != 'inspect']snapshot('confirm-stop')keys('Enter')wait(lambda: 'Cancel' not in screen(), 'Cancel is the default stop action')assert len(hn('list-panes', '-F', '#{pane_id}').splitlines()) == 2- click_text('×', occurrence=1, row=y - 1)+ close_from_menu(occurrence=1, row=y - 1)shown('Stop? Saved history will remain.')- click_text('(s)')+ click_text('[ Stop ]')shown('could not save')assert len(hn('list-panes', '-F', '#{pane_id}').splitlines()) == 2snapshot('stop-save-failed')@@ -617,6 +774,8 @@ try:api({'action': 'terminal-mouse'})overlay_dismiss_journey(alpha)title_drag_journey(alpha, beta)+ title_drag_journey(alpha, beta, 'box')+ pane_drag_journey(alpha, beta)x, y = map(int, value('#{pane_left} #{pane_top}', alpha).split())before = len(api()['inputs'])click(x + 4, y + 4)@@ -697,7 +856,7 @@ try:hn('select-window', '-t', 'Remote')shown('Gamma remote task terminal')_, remote_y = map(int, value('#{pane_left} #{pane_top}').split())- click_text('×', row=remote_y - 1)+ close_from_menu(row=remote_y - 1)wait(lambda: not any(t['id'] == 'remote' for t in api()['desk']['tabs']), 'idle remote session is stopped and removed')remote_close = [r['payload']['mode'] for r in requests('agent_close') if r['payload']['agentId'] == 'gamma']assert remote_close == ['inspect', 'idle'], remote_closediff --git a/tui/tests/workspace-mock.mjs b/tui/tests/workspace-mock.mjsindex 182d123b1..6d4dd3a11 100644--- a/tui/tests/workspace-mock.mjs+++ b/tui/tests/workspace-mock.mjs@@ -81,6 +81,12 @@ const server = http.createServer(async (req, res) => {state.visibleMachines = update.remote ? [state.currentLocal, REMOTE] : [state.currentLocal]state.machinesStale = update.stale === truebroadcast(state.currentLocal, 'machines_changed', {})+ } else if (update.action === 'remote-agent') {+ // A harness on the remote computer that no tab shows (the side bar lists it), or it stopped.+ let target = agents[REMOTE].find(a => a.id === update.agent)+ if (!target) { target = makeAgent(update.agent, update.name, 'codex', '/work/remote'); agents[REMOTE].push(target); state.activities[update.agent] = 'idle' }+ if (update.stop) { target.status = 'stopped'; target.terminal.available = false }+ broadcast(REMOTE, 'agent_synced', { agent: target })} else if (update.action === 'desk-refresh') deskChanged()else if (update.action === 'disconnect') { for (const peer of peers) if (peer.machine === update.machine) peer.ws.terminate() }else if (update.action === 'activity') state.activities[update.agent] = update.activity