Skip to content

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.

hn: panels sized by kind, a clearer command list, the mouse and the Models list

Tim8e12a3756db1
diff --git a/tui/src/app.rs b/tui/src/app.rs
index ac4af638e..32ed48bf1 100644
--- a/tui/src/app.rs
+++ b/tui/src/app.rs
@@ -3594,6 +3594,8 @@ impl App {
/// the mouse opened is up (tmux's MODE_MOUSE_ALL).
pub fn wants_motion(&self) -> bool {
matches!(&self.modal, Some(crate::modal::Modal::Menu(m)) if !m.no_mouse)
+ // (A panel's list: the row under the mouse is the one chosen.)
+ || matches!(&self.modal, Some(crate::modal::Modal::Picker { kind, .. }) if crate::settings::is_panel(kind) && !crate::theme::fzf_opts().no_mouse)
|| self.rects.iter().any(|(id, _)| self.panes.get(id).map(|p| p.mode().contains(alacritty_terminal::term::TermMode::MOUSE_MOTION)).unwrap_or(false))
}
diff --git a/tui/src/devices.rs b/tui/src/devices.rs
index 80128c59c..e969ad583 100644
--- a/tui/src/devices.rs
+++ b/tui/src/devices.rs
@@ -1351,7 +1351,7 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, view: View, picker: &mut Pi
settings::put(buf, body.x, body.y, body.width, &format!("{} · resize or Esc", view.title()), c.base);
return None;
}
- let r = settings::area(body);
+ let r = settings::area(body, PickerKind::Devices(view).size(), 0);
settings::fill(buf, r, c.base);
picker.screen_area.set(r);
picker.preview_area.set(None);
diff --git a/tui/src/format.rs b/tui/src/format.rs
index de7c818f1..14a2a9d6e 100644
--- a/tui/src/format.rs
+++ b/tui/src/format.rs
@@ -1391,6 +1391,8 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V
// The spinner's frame now, for a format of your own.
"spinner" => crate::theme::spinner(app.tick).to_string(),
"daemon_down" => app.daemon_down.then_some("1").unwrap_or("0").into(),
+ // A model being got for a harness, while it is: `↻ qwen3-coder 42%` (empty otherwise).
+ "model_progress" => crate::models::status_text(app).unwrap_or_default(),
// The pane is another window's to type in (this one watches), when it is the only one.
"pane_watching" => (pane.map(|p| matches!(p.phase, crate::pane::Phase::Watching(_))).unwrap_or(false) && tab.map(|t| t.panes().len() < 2).unwrap_or(false)).then_some("1").unwrap_or("0").into(),
// However many panes the window has: whether another window has the pane to type in, and who.
diff --git a/tui/src/input.rs b/tui/src/input.rs
index 6ed7c9432..d0e2843a5 100644
--- a/tui/src/input.rs
+++ b/tui/src/input.rs
@@ -288,6 +288,14 @@ fn modal_mouse(app: &mut App, mouse: MouseEvent) {
let up = matches!(mouse.kind, MouseEventKind::ScrollUp);
if let Some(Modal::Picker { picker, kind }) = &mut app.modal {
if in_preview { picker.preview_by(if up { -1 } else { 1 }) }
+ // A panel's list: the wheel scrolls it, three lines a notch, and chooses nothing —
+ // the mouse over a row does (Moved). (Up shows what is over the top: in a list read
+ // bottom-up, its later lines.)
+ else if inside(list) && crate::settings::is_panel(kind) && !(shift && multi) {
+ let later = if crate::settings::top_down(kind) { !up } else { up };
+ picker.scroll = if later { picker.scroll + 3 } else { picker.scroll.saturating_sub(3) };
+ picker.free_scroll = true;
+ }
else if inside(list) {
if shift && multi { picker.toggle_mark(); }
let r: i64 = if crate::settings::top_down(kind) { -1 } else { 1 };
@@ -314,6 +322,10 @@ fn modal_mouse(app: &mut App, mouse: MouseEvent) {
}
}
MouseEventKind::Up(_) => { if let Some(Modal::Picker { picker, .. }) = &mut app.modal { picker.bar_drag = false; picker.preview_drag = None; picker.border_drag = false; picker.preview_bar_drag = false } }
+ // A panel's list: the row under the mouse is the one chosen (the list does not move).
+ MouseEventKind::Moved if inside(list) => {
+ if let Some(Modal::Picker { picker, kind }) = &mut app.modal { if crate::settings::is_panel(kind) { picker.click(mouse.row); } }
+ }
// fzf's right click: the row under it, then toggle (a mark, in a list that takes marks).
MouseEventKind::Down(MouseButton::Right) if !inside(list) => {}
MouseEventKind::Down(MouseButton::Right) => {
@@ -341,6 +353,11 @@ fn modal_mouse(app: &mut App, mouse: MouseEvent) {
let hit = match &mut app.modal { Some(Modal::Picker { picker, .. }) if inside(list) => Some(picker.click(mouse.row)), Some(Modal::Picker { .. }) => Some(false), _ => None };
match hit {
Some(true) if shift => { if multi { if let Some(Modal::Picker { picker, .. }) = &mut app.modal { picker.toggle_mark(); } } }
+ // A panel's list: the mouse over a row has chosen it already, so one click runs it.
+ Some(true) if matches!(&app.modal, Some(Modal::Picker { kind, .. }) if crate::settings::is_panel(kind)) => {
+ app.last_click = None;
+ modal_key(app, KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE))
+ }
Some(true) => {
let double = matches!(app.last_click, Some((9, _, r, at, _)) if r == mouse.row && at.elapsed() < Duration::from_millis(400));
app.last_click = Some((9, mouse.column, mouse.row, std::time::Instant::now(), 1));
@@ -652,7 +669,7 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {
}
}
picker.hints = vec![("enter", "use · get"), ("C-s", "stop a local model")];
- picker.empty = if app.focused().is_none() { "Focus a harness to switch its model.".into() } else { "Loading its models…".into() };
+ picker.empty = if crate::models::target(app).is_none() { crate::models::no_target_why(app) } else { "Loading its models…".into() };
picker.status = app.focused().and_then(|f| app.panes.get(&f)).and_then(|p| app.fleet.agent(&p.machine_id, &p.agent_id)).map(|a| a.name.clone()).unwrap_or_default();
}
PickerKind::Inbox => {
@@ -685,7 +702,7 @@ fn fill_rows(app: &App, kind: &PickerKind, picker: &mut Picker) {
}
// (Typed into, it ranks by match, best first, as fzf does; empty, it keeps its groups. A
// query matches a command's name and keywords, not the description shown beside it.)
- PickerKind::Commands => { picker.live = true; picker.set_rows(modal::command_rows_for(app, !picker.query.is_empty())); picker.hints = vec![("enter", "run"), ("M-k", "change its key")] }
+ PickerKind::Commands => { picker.live = true; picker.set_rows(modal::command_rows_for(app, !picker.query.is_empty(), crate::settings::in_tmux(picker))); picker.hints = vec![("enter", "run"), ("M-k", "change its key")] }
// ── keys ──
PickerKind::Keybinds => { picker.keep_order = true; picker.set_rows(modal::keybind_rows(app)); picker.hints = vec![("enter", "change"), ("esc", "done")] }
PickerKind::Help => { picker.set_rows(modal::mode_rows(app)); picker.hints = vec![("enter", "go")] }
@@ -810,7 +827,8 @@ fn prepare(app: &mut App, kind: &PickerKind) {
fn load_models(app: &mut App) {
// ── models: this computer's models, the grids and the saved APIs (models.rs) ──
crate::models::open(app);
- let Some((machine, agent)) = focused_agent(app) else { return };
+ // (The harness a Use moves: the focused one, or the only one on screen.)
+ let Some(crate::models::Target { machine, agent, .. }) = crate::models::target(app) else { return };
let Some(link) = app.link(&machine) else { return };
let mark = loading(format!("models {machine} {agent}"), true);
let key = (machine, agent.clone());
@@ -1964,6 +1982,8 @@ fn schedule_said(app: &mut App, kind: &PickerKind, picker: &Picker) {
fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {
// ── machines & devices ── (a line typed or a y/n answered in the panel; Esc/← a level back)
let (kind, mut picker) = match crate::devices::key(app, kind, picker, key) { Ok(()) => return, Err(back) => back };
+ // A key: the list follows the cursor again (the wheel had left it where it put it).
+ picker.free_scroll = false;
// A row a key goes to is one you chose to look at (the list moving it there is not).
let was = picker.current_id();
let key_moves = matches!(key.code, KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown | KeyCode::Tab | KeyCode::BackTab)
@@ -2026,12 +2046,34 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {
// unbind / toggle-bind: that key does nothing in this list now.
if picker.unbound.contains(&fzf_key_name(&key)) { app.modal = Some(Modal::Picker { kind, picker }); return }
let up: i64 = if crate::settings::top_down(&kind) { -1 } else { 1 };
+ // ── tabs ── The launcher's tab row: ↓ past the list's last row goes onto it; there ←/→ open the
+ // next tab (as typing its character does), ↑ or Enter goes back to the list, and any other key
+ // does what it does in the list — a key typed searches the tab chosen, Esc closes.
+ let mut tabbed = false;
+ if modal::is_launcher(&kind) && !ctrl && !alt && !shift {
+ if picker.on_tabs {
+ match key.code {
+ KeyCode::Left | KeyCode::Right => {
+ picker.query = modal::next_tab(&picker.query, if key.code == KeyCode::Right { 1 } else { -1 });
+ picker.qcursor = picker.query.chars().count();
+ tabbed = true;
+ }
+ KeyCode::Up | KeyCode::Enter => { picker.on_tabs = false; app.modal = Some(Modal::Picker { kind, picker }); return }
+ KeyCode::Down => { app.modal = Some(Modal::Picker { kind, picker }); return }
+ _ => picker.on_tabs = false,
+ }
+ } else if key.code == KeyCode::Down && !(0..picker.visible.len() as i64).contains(&(picker.cursor as i64 - up)) {
+ picker.on_tabs = true;
+ app.modal = Some(Modal::Picker { kind, picker });
+ return;
+ }
+ }
// FZF_DEFAULT_OPTS --bind: your key:action pairs come first (the last bind for a key wins,
// as in fzf). A key bound only to what hn does not run (execute, become, reload …) keeps this
// list's own meaning of it; one with an action hn runs never falls back to it.
let name = fzf_key_name(&key);
let bound = theme::fzf_opts().binds.iter().rev().find(|(k, _)| *k == name).map(|(_, a)| a.clone()).filter(|a| !falls_back(&name, a));
- if let Some(actions) = bound {
+ if tabbed {} else if let Some(actions) = bound {
match bound_actions(&mut picker, &actions, up, multi) {
End::Accept => { choose(app, kind, picker, Choice::Enter); return }
End::Abort => { SPLIT.with(|s| s.set(None)); return }
@@ -2062,6 +2104,14 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {
return;
}
}
+ // A model's question (Enter · Esc): Esc takes it back, and the view stays.
+ if matches!(kind, PickerKind::Models) && key.code == KeyCode::Esc && crate::models::cancel(app, &mut picker) { app.modal = Some(Modal::Picker { kind, picker }); return }
+ // tmux's commands, opened from their row: Esc is a step back to hn's.
+ if matches!(kind, PickerKind::Commands) && key.code == KeyCode::Esc && crate::settings::in_tmux(&picker) {
+ crate::settings::back_to_commands_at(app, &mut picker, "cmd:tmux-commands");
+ app.modal = Some(Modal::Picker { kind, picker });
+ return;
+ }
// ── keys ── Keybinds opened from the command list: Esc is a step back to it.
if matches!(kind, PickerKind::Keybinds) && key.code == KeyCode::Esc && picker.from_commands {
crate::settings::back_to_commands_at(app, &mut picker, "cmd:keybinds");
@@ -2197,7 +2247,7 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {
// The command list: tmux's commands join it once you search, and leave when you stop.
if matches!(kind, PickerKind::Commands) && before.is_empty() != picker.query.is_empty() {
picker.rows.clear();
- picker.set_rows(modal::command_rows_for(app, !picker.query.is_empty()));
+ picker.set_rows(modal::command_rows_for(app, !picker.query.is_empty(), crate::settings::in_tmux(&picker)));
}
// The panel's lists: what you type puts the cursor on the best match.
if crate::settings::is_panel(&kind) { picker.to_top() }
@@ -2709,14 +2759,15 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {
// (The engine's own models: only Enter switches.)
if choice != Choice::Enter { return keep(app, kind, picker) }
let Some(model) = id else { return keep(app, kind, picker) };
- let Some((machine, agent)) = focused_agent(app) else { return };
+ let Some(crate::models::Target { machine, agent, .. }) = crate::models::target(app) else { return };
let Some(link) = app.link(&machine) else { return };
let label = picker.current().map(|r| r.label.clone()).unwrap_or_default();
app.say(format!("Switching to {label}…"), theme::SOFT);
app.spawn(async move { link.rpc("agent_update", json!({ "agentId": agent, "selectedModel": model }), Duration::from_secs(60)).await }, move |app, reply| match reply {
Ok(reply) => {
if let Some(row) = reply.get("agent") { let key = (machine.clone(), row.get("id").and_then(|v| v.as_str()).unwrap_or("").to_string()); let a = crate::fleet::agent_from(&machine, row, app.fleet.agents.get(&key)); app.fleet.agents.insert(key, a); }
- app.say(format!("Now on {label}"), theme::ONLINE);
+ crate::models::close(app);
+ app.say(format!("✓ Now on {label}"), theme::ONLINE);
}
Err(e) => app.say(format!("Could not switch: {e}"), theme::DANGER),
});
@@ -2756,6 +2807,10 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {
// Settings open in this same panel, where the command list was.
crate::settings::into_settings(app, &mut picker);
return keep(app, PickerKind::Theme, picker);
+ } else if id == "cmd:tmux-commands" {
+ // tmux's commands, grouped, in this same panel (Esc comes back here).
+ crate::settings::into_tmux(app, &mut picker);
+ return keep(app, kind, picker);
} else if id == "cmd:keybinds" {
// ── keys ── (in this same panel too; Esc comes back here)
crate::settings::into_keybinds(app, &mut picker);
diff --git a/tui/src/modal.rs b/tui/src/modal.rs
index e077bd9bd..f3b6625f4 100644
--- a/tui/src/modal.rs
+++ b/tui/src/modal.rs
@@ -175,36 +175,36 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[
("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"),
- ("new", "New Harness…", "⌥N", "", "Harness"),
- ("terminal", "New Terminal", "⌥⇧T", "a shell on this pane's machine", "Harness"),
+ ("new", "New harness…", "⌥N", "", "Harness"),
+ ("terminal", "New terminal", "⌥⇧T", "a shell on this pane's machine", "Harness"),
("inbox", "Harnesses needing input", "⌥⇧I", "", "Harness"),
("next-waiting", "Next harness waiting on you", "⌥A", "oldest question first", "Harness"),
("send", "Send to harness…", "⌥B", "type a task — Harness picks who", "Harness"),
("broadcast", "Broadcast to this swarm…", "", "one message to every harness in the swarm", "Harness"),
- ("clone", "Clone Harness", "⌥⇧N", "a second one with this one's history", "Harness"),
- ("restart", "Restart Harness", "⌥⇧E", "", "Harness"),
- ("pause", "Pause Harness", "", "stop the engine, keep the conversation", "Harness"),
- ("rename", "Rename Harness…", "", "", "Harness"),
- ("take", "Take Control", "", "reclaim all panes across every tab", "General"),
- ("tab", "New Swarm", "⌥T", "", "Swarms"),
- ("rename-tab", "Rename Swarm…", "⌥⇧R", "", "Swarms"),
- ("close-tab", "Close Swarm", "⌥⇧W", "harnesses keep running", "Swarms"),
- ("next-tab", "Next Swarm", "⌥}", "", "Swarms"),
- ("prev-tab", "Previous Swarm", "⌥{", "", "Swarms"),
- ("tab-left", "Move Swarm Left", "⌥<", "", "Swarms"),
- ("tab-right", "Move Swarm Right", "⌥>", "", "Swarms"),
- ("split-right", "Split Right", "⌥\\", "", "Panes"),
- ("split-down", "Split Down", "⌥-", "", "Panes"),
- ("close-pane", "Close Pane", "⌥W", "the harness keeps running", "Panes"),
- ("zoom", "Zoom Pane", "⌥Z", "", "Panes"),
+ ("clone", "Clone harness", "⌥⇧N", "a second one with this one's history", "Harness"),
+ ("restart", "Restart harness", "⌥⇧E", "", "Harness"),
+ ("pause", "Pause harness", "", "stop the engine, keep the conversation", "Harness"),
+ ("rename", "Rename harness…", "", "", "Harness"),
+ ("take", "Take control", "", "reclaim all panes across every tab", "General"),
+ ("tab", "New swarm", "⌥T", "", "Swarms"),
+ ("rename-tab", "Rename swarm…", "⌥⇧R", "", "Swarms"),
+ ("close-tab", "Close swarm", "⌥⇧W", "harnesses keep running", "Swarms"),
+ ("next-tab", "Next swarm", "⌥}", "", "Swarms"),
+ ("prev-tab", "Previous swarm", "⌥{", "", "Swarms"),
+ ("tab-left", "Move swarm left", "⌥<", "", "Swarms"),
+ ("tab-right", "Move swarm right", "⌥>", "", "Swarms"),
+ ("split-right", "Split right", "⌥\\", "", "Panes"),
+ ("split-down", "Split down", "⌥-", "", "Panes"),
+ ("close-pane", "Close pane", "⌥W", "the harness keeps running", "Panes"),
+ ("zoom", "Zoom pane", "⌥Z", "", "Panes"),
("layout", "Layout…", "⌥L", "grid, columns, main + stack…", "Panes"),
- ("equalize", "Equalize Panes", "⌥=", "", "Panes"),
- ("pane-tab", "Move Pane to New Swarm", "", "", "Panes"),
- ("find", "Find in Pane…", "⌥⇧F", "search this pane's history", "Panes"),
+ ("equalize", "Equalize panes", "⌥=", "", "Panes"),
+ ("pane-tab", "Move pane to a new swarm", "", "", "Panes"),
+ ("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"),
+ ("copy-mode", "Copy mode", "⌥V", "move over the pane's text, select and copy", "Panes"),
("machines", "Machines", "⌥M", "", "Machines"),
- ("store", "Harness Store", "⌥S", "", "Machines"),
+ ("store", "Harness store", "⌥S", "", "Machines"),
// ── machines & devices ──
("connect-machine", "Connect a machine…", "", "a machine not linked yet, with its remote password", "Machines"),
("add-phone", "Add phone…", "", "a QR code your phone scans to sign in and pair", "Machines"),
@@ -360,6 +360,19 @@ pub fn launcher_kind(query: &str, current: &PickerKind) -> PickerKind {
}
}
+// ── tabs ──
+
+/// The launcher's tabs, in order: the query's first character that opens each (none: harnesses).
+pub const LAUNCHER_TABS: &[(Option<char>, &str)] = &[(None, "harnesses"), (Some('>'), "commands"), (Some('@'), "machines"),
+ (Some('#'), "projects"), (Some(':'), "models"), (Some('*'), "store"), (Some('?'), "help")];
+
+/// The query that opens the tab [step] along from [query]'s — round from the last to the first.
+pub fn next_tab(query: &str, step: i64) -> String {
+ let here = crate::picker::scope_of(query);
+ let at = LAUNCHER_TABS.iter().position(|(c, _)| *c == here).unwrap_or(0) as i64;
+ LAUNCHER_TABS[(at + step).rem_euclid(LAUNCHER_TABS.len() as i64) as usize].0.map(String::from).unwrap_or_default()
+}
+
pub fn is_launcher(kind: &PickerKind) -> bool {
matches!(kind, PickerKind::Open { .. } | PickerKind::Palette | PickerKind::Machines | PickerKind::Projects | PickerKind::Models | PickerKind::Store | PickerKind::Help)
}
@@ -373,7 +386,9 @@ pub fn launcher_title(app: &App, kind: &PickerKind) -> (String, String) {
PickerKind::Palette => ("commands".into(), "Run anything by name".into()),
PickerKind::Machines => ("machines".into(), "Choose a machine, then one of its harnesses".into()),
PickerKind::Projects => ("projects".into(), "Choose a project, then one of its harnesses".into()),
- PickerKind::Models => ("models".into(), "Search models — Enter uses one on the focused harness".into()),
+ // (Which harness Enter moves, in the title: the focused one, or the only one on screen.)
+ PickerKind::Models => (crate::models::target(app).and_then(|t| app.fleet.agent(&t.machine, &t.agent)).map(|a| format!("models · for {}", a.name)).unwrap_or_else(|| "models".into()),
+ "Search models — Enter uses one on the focused harness".into()),
PickerKind::Store => ("store".into(), "Find a harness in the Store".into()),
PickerKind::Help => ("quick access".into(), "What this box can do".into()),
_ => (String::new(), String::new()),
@@ -484,23 +499,57 @@ pub fn palette_rows(app: &App) -> Vec<Row> {
pub fn command_rows(app: &App) -> Vec<Row> {
let own = COMMANDS.iter().map(|(id, title, _, hint, group)| {
let key = own_key(app, id).unwrap_or_default();
- // (Ranked above a tmux command that matches as well: `appe` is Appearance, not a word in
- // set-buffer's description.)
- Row::new(format!("cmd:{id}"), *title).extra(format!("{id} {hint} {group}")).detail(vec![span(*hint, fg(theme::MUTED))]).right(key).group(*group).boost(40)
+ // (Tier 0: searched, listed above every tmux command that matches — `appe` is Appearance,
+ // not a word in set-buffer's description.)
+ Row::new(format!("cmd:{id}"), *title).extra(format!("{id} {hint} {group}")).detail(vec![span(*hint, fg(theme::MUTED))]).right(key).group(*group)
});
- let tmux = crate::commands::COMMANDS.iter().map(|(name, alias, about)| {
+ // tmux's after them, grouped (Windows, Panes…), and none one of hn's runs already (Copy mode is
+ // copy-mode): each group's rows together, in TMUX_GROUPS' order.
+ let ours: Vec<&str> = COMMANDS.iter().filter_map(|(id, ..)| runs_of(id)).collect();
+ let mut tmux: Vec<(usize, Row)> = crate::commands::COMMANDS.iter().filter(|(name, ..)| !ours.contains(name)).map(|(name, alias, about)| {
let key = app.keymap.key_for_name(name).unwrap_or_default();
+ let group = tmux_group(name);
// (Found by its name and alias: its description is shown, not searched — a word in it
// would outrank what you meant, `appe` → set-buffer's "appends".)
- Row::new(format!("tmux:{name}"), *name).extra(alias.to_string()).detail(vec![span(*about, fg(theme::MUTED))]).right(key).group("tmux commands")
- });
- own.chain(tmux).collect()
+ let row = Row::new(format!("tmux:{name}"), *name).extra(alias.to_string()).detail(vec![span(*about, fg(theme::MUTED))]).right(key).group(format!("tmux · {group}")).tier(1);
+ (TMUX_GROUPS.iter().position(|g| *g == group).unwrap_or(TMUX_GROUPS.len()), row)
+ }).collect();
+ tmux.sort_by_key(|(g, _)| *g);
+ own.chain(tmux.into_iter().map(|(_, r)| r)).collect()
+}
+
+/// tmux's commands' groups, in the order the list shows them.
+const TMUX_GROUPS: &[&str] = &["Windows", "Panes", "Layouts", "Copy & buffers", "Harnesses", "Sessions & clients", "Keys", "Options & config", "Messages & prompts"];
+
+/// The group a tmux command is listed under, by what it acts on.
+fn tmux_group(name: &str) -> &'static str {
+ let has = |w: &str| name.contains(w);
+ if has("harness") || has("task") || has("broadcast") || matches!(name, "send-message" | "take-control" | "open-viewer" | "new-terminal") { "Harnesses" }
+ else if has("layout") { "Layouts" }
+ else if has("buffer") || name == "copy-mode" { "Copy & buffers" }
+ else if has("window-option") || has("option") || has("environment") || matches!(name, "source-file" | "customize-mode") { "Options & config" }
+ else if has("pane") || matches!(name, "split-window" | "clear-history") { "Panes" }
+ else if has("window") { "Windows" }
+ else if has("session") || has("client") || matches!(name, "kill-server" | "choose-tree") { "Sessions & clients" }
+ else if has("key") { "Keys" }
+ else { "Messages & prompts" }
}
-/// The command list as it shows: hn's own commands when it opens, tmux's too once you search —
-/// they are many, and there for the one you type.
-pub fn command_rows_for(app: &App, searching: bool) -> Vec<Row> {
- command_rows(app).into_iter().filter(|r| searching || !r.id.starts_with("tmux:")).collect()
+/// The command list as it shows: hn's own commands and one row for tmux's — searched, tmux's too,
+/// after hn's (their tier); [in_tmux] (Enter on that row): tmux's alone, grouped.
+pub fn command_rows_for(app: &App, searching: bool, in_tmux: bool) -> Vec<Row> {
+ let all = command_rows(app);
+ if in_tmux { return all.into_iter().filter(|r| r.id.starts_with("tmux:")).collect() }
+ let n = crate::commands::COMMANDS.len();
+ let more = Row::new("cmd:tmux-commands", "tmux commands…").extra("tmux every command")
+ .detail(vec![span(format!("every tmux command, grouped — {n} of them"), fg(theme::MUTED))]).group("Settings & help");
+ let (own, tmux): (Vec<Row>, Vec<Row>) = all.into_iter().partition(|r| r.id.starts_with("cmd:"));
+ // (The row for tmux's after hn's own settings, before Close hn.)
+ let at = own.iter().position(|r| r.id == "cmd:quit").unwrap_or(own.len());
+ let mut rows = own;
+ rows.insert(at, more);
+ if searching { rows.extend(tmux) }
+ rows
}
/// The key (prefix, then the key) that runs one of hn's own commands, as the prefix table has it
@@ -863,6 +912,42 @@ mod theme_row_tests {
fn right(app: &App, title: &str) -> String { keybind_rows(app).into_iter().find(|r| r.label == title).map(|r| r.right).unwrap() }
+ // ── commands ──
+
+ /// The command list: hn's own commands, each named in sentence case, and one row for tmux's —
+ /// Enter on it lists them, grouped (Windows, Panes…), none that one of hn's runs already. A
+ /// search finds both, hn's first.
+ #[test]
+ fn commands_are_hns_then_tmuxs_grouped_and_never_twice() {
+ let app = app();
+ let rows = command_rows_for(&app, false, false);
+ let own: Vec<&Row> = rows.iter().filter(|r| r.id.starts_with("cmd:")).collect();
+ assert!(rows.iter().all(|r| r.id.starts_with("cmd:")), "tmux's are behind their one row");
+ assert!(own.iter().any(|r| r.id == "cmd:tmux-commands"));
+ let inside = command_rows_for(&app, false, true);
+ assert!(inside.iter().all(|r| r.id.starts_with("tmux:")), "inside: tmux's only");
+ let tmux: Vec<&Row> = inside.iter().collect();
+ // Sentence case: no word after the first starts with a capital (but hn and names).
+ for r in &own {
+ let caps: Vec<&str> = r.label.split_whitespace().skip(1).filter(|w| w.starts_with(|c: char| c.is_uppercase())).collect();
+ assert!(caps.is_empty(), "{:?} {caps:?}", r.label);
+ }
+ // Grouped: each group's rows together, every group named for tmux.
+ let mut groups: Vec<String> = Vec::new();
+ for g in tmux.iter().filter_map(|r| r.group.clone()) { if groups.last() != Some(&g) { assert!(!groups.contains(&g), "{g} split"); groups.push(g) } }
+ assert!(groups.len() > 3 && groups.iter().all(|g| g.starts_with("tmux · ")), "{groups:?}");
+ // Never twice: copy-mode, new-window, clone-harness are hn's own already.
+ for name in ["copy-mode", "new-window", "clone-harness", "kill-pane"] { assert!(!tmux.iter().any(|r| r.label == name), "{name} twice") }
+ assert!(tmux.iter().any(|r| r.label == "select-layout"));
+ // Searched: hn's matches before tmux's, whatever they score.
+ let mut p = crate::picker::Picker::new("Commands", "");
+ p.set_rows(command_rows_for(&app, true, false));
+ p.set_query("lay");
+ let shown: Vec<&str> = p.visible.iter().map(|(i, _)| p.rows[*i].id.as_str()).collect();
+ let first_tmux = shown.iter().position(|id| id.starts_with("tmux:")).unwrap();
+ assert!(shown[..first_tmux].contains(&"cmd:layout") && shown[first_tmux..].iter().all(|id| id.starts_with("tmux:")), "{shown:?}");
+ }
+
/// Keybinds: the prefix and the second one first, then the commands grouped with their keys
/// now. Appearance has no keys section.
#[test]
diff --git a/tui/src/models.rs b/tui/src/models.rs
index 3d746df49..2a77ff504 100644
--- a/tui/src/models.rs
+++ b/tui/src/models.rs
@@ -270,6 +270,39 @@ pub struct Switch { pub machine: String, pub agent: String, pub to: String, pub
const SWITCH_FOR: Duration = Duration::from_secs(60);
+/// A Use over: its row, its model's name, the step it reached, and why it failed (None: ready);
+/// [seen]: the cursor has been on its row since (leaving the row then ends it).
+#[derive(Clone, Debug)]
+pub struct Ended { pub row: String, pub name: String, pub step: Step, pub failed: Option<String>, pub seen: bool }
+
+/// A Use's steps, as its preview lists them.
+pub const STEPS: [&str; 4] = ["Download", "Start", "Serve", "Switch harness"];
+
+/// A step's mark: done ✓, under way ↻ (its progress, when the daemon sends one), failed ✗, or
+/// still to come.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub enum Mark { Done, Now(Option<f64>), Failed, Later }
+
+/// The marks of a Use at [step], [op] the operation on its model; [ended]: Some(true) ready,
+/// Some(false) failed at [step], None under way.
+pub fn checklist(step: Step, op: Option<&Operation>, ended: Option<bool>) -> [Mark; 4] {
+ let at = match step { Step::Get => 0, Step::Start => 1, Step::Serve => 2, Step::Switch => 3 };
+ std::array::from_fn(|i| match (i.cmp(&at), ended) {
+ (_, Some(true)) | (std::cmp::Ordering::Less, _) => Mark::Done,
+ (std::cmp::Ordering::Equal, Some(false)) => Mark::Failed,
+ (std::cmp::Ordering::Equal, None) => Mark::Now(progress(step, op)),
+ _ => Mark::Later,
+ })
+}
+
+/// How far the operation under [step] is, while it runs and the daemon says (a download's or a
+/// start's; serving and switching have none).
+fn progress(step: Step, op: Option<&Operation>) -> Option<f64> {
+ op.filter(|o| matches!(step, Step::Get | Step::Start) && o.active()).and_then(|o| o.progress)
+}
+
+fn percent(p: f64) -> u32 { (p * 100.0).floor() as u32 }
+
/// The model the focused harness is being moved to, while it is.
fn switching_for<'a>(app: &'a App, t: Option<&Target>) -> Option<&'a str> {
let (t, s) = (t?, app.models_view.switching.as_ref()?);
@@ -308,6 +341,12 @@ pub struct Models {
pub switching: Option<Switch>,
/// Why the last Use of a row failed (row id, words): its preview says so.
pub use_error: Option<(String, String)>,
+ /// The first Enter's question on a row (row id, words), in its preview until Enter, Esc or the
+ /// cursor leaves the row.
+ pub confirm: Option<(String, String)>,
+ /// How the last Use ended: its preview's checklist and ✓ / ✗ stay until the cursor leaves its
+ /// row or another action starts.
+ pub ended: Option<Ended>,
/// Sections a wake was sent for and not yet answered; the re-reads that follow one.
pub asking: HashSet<String>,
pub follow_until: Option<Instant>,
@@ -351,10 +390,29 @@ fn due(last: Option<&Instant>, every: Duration, now: Instant) -> bool { last.is_
pub struct Target { pub machine: String, pub agent: String, pub engine: String, pub grid_model: String, pub base_url: String }
pub fn target(app: &App) -> Option<Target> {
- let (machine, agent) = crate::input::focused_agent(app)?;
- let a = app.fleet.agent(&machine, &agent)?;
- if a.engine == "terminal" { return None }
- Some(Target { engine: a.engine.clone(), grid_model: a.grid_model.clone(), base_url: a.grid_base_url.clone(), machine, agent })
+ let of = |machine: String, agent: String| -> Option<Target> {
+ let a = app.fleet.agent(&machine, &agent)?;
+ (a.engine != "terminal").then(|| Target { engine: a.engine.clone(), grid_model: a.grid_model.clone(), base_url: a.grid_base_url.clone(), machine, agent })
+ };
+ if let Some(t) = crate::input::focused_agent(app).and_then(|(m, a)| of(m, a)) { return Some(t) }
+ // No pane focused at all: the harness on screen, when it is the only one. (A pane that is
+ // focused — a shell, a terminal — is the one meant: never another harness in its place.)
+ if app.focused().is_some() { return None }
+ let mut shown = app.rects.iter().filter_map(|(id, _)| app.panes.get(id)).filter_map(|p| of(p.machine_id.clone(), p.agent_id.clone()));
+ let only = shown.next()?;
+ shown.next().is_none().then_some(only)
+}
+
+/// Why there is no harness to move: what the focused pane is, said so a person can act on it.
+pub fn no_target_why(app: &App) -> String {
+ let Some(focus) = app.focused() else { return "No pane is focused — click a harness's pane, then open Models".into() };
+ let Some(p) = app.panes.get(&focus) else { return "The focused pane is not a harness's".into() };
+ if p.agent_id.is_empty() { return "The focused pane is a shell, not a harness — start one with New harness".into() }
+ match app.fleet.agent(&p.machine_id, &p.agent_id) {
+ None => format!("This pane's harness ({}) is not in the list yet — try again in a moment", p.agent_id.chars().take(8).collect::<String>()),
+ Some(a) if a.engine == "terminal" => "The focused pane is a terminal — its model can not be switched; a harness's can".into(),
+ Some(_) => NO_HARNESS.into(),
+ }
}
/// Whether [engine] can be pointed at a model here: the daemon's picture says it may.
@@ -586,22 +644,29 @@ pub fn rows(app: &App, query: &str) -> Vec<Row> {
None => out.push(note("local", if !up(app, &machine) { "Connect this computer to see its models." } else { v.local_error.get(&machine).map(String::as_str).unwrap_or("Finding models that fit…") }, &head)),
Some(s) => {
if let Some(n) = &s.notice { out.push(note("notice", n, &head)) }
- let rank = |m: &LocalModel| if v.op_for(&machine, m).is_some_and(Operation::active) || v.pending.as_ref().is_some_and(|p| p.1 == m.id) { 0 } else if m.running() { 1 } else if m.downloaded() { 2 } else { 3 };
- let mut mine: Vec<(u8, usize, &LocalModel)> = s.models.iter().enumerate().map(|(i, m)| (rank(m), i, m)).filter(|(r, _, _)| *r < 3).collect();
- mine.sort_by_key(|(r, i, _)| (*r, *i));
+ // What can be used now first: one being got or started, one running here, one the own
+ // grid serves from another machine; then one downloaded and stopped; a grid's offline
+ // one last. (In the daemon's order within each.)
+ let rank = |m: &LocalModel| if v.op_for(&machine, m).is_some_and(Operation::active) || v.pending.as_ref().is_some_and(|p| p.1 == m.id) { 0 } else if m.running() { 1 } else if m.downloaded() { 3 } else { 5 };
+ let mut mine: Vec<(u8, usize, Row)> = s.models.iter().enumerate().map(|(i, m)| (rank(m), i, m)).filter(|(r, _, _)| *r < 5).map(|(r, i, m)| (r, i, local_row(app, m, t, &head))).collect();
let theirs = v.grids.get(&machine).is_some_and(|g| g.sections.iter().any(|s| s.own && !s.models.is_empty()));
+ if let Some(g) = v.grids.get(&machine) {
+ // (This computer's running ones are listed by their local names.)
+ let here: Vec<&LocalModel> = s.models.iter().filter(|m| m.running()).collect();
+ let served = g.sections.iter().filter(|s| s.own).flat_map(|s| s.models.iter().map(move |x| (s, x)))
+ .filter(|(_, x)| !here.iter().any(|m| x.id.eq_ignore_ascii_case(&m.id) || x.id.eq_ignore_ascii_case(&m.name)));
+ mine.extend(served.enumerate().map(|(i, (s, x))| (if x.offline.is_some() { 4 } else { 2 }, i, grid_row(app, s, x, t, &head))));
+ }
+ mine.sort_by_key(|(r, i, _)| (*r, *i));
if mine.is_empty() && !theirs && !searching { out.push(note("none", "No models here yet — get one below", &head)) }
- out.extend(mine.into_iter().map(|(_, _, m)| local_row(app, m, t, &head)));
+ out.extend(mine.into_iter().map(|(_, _, r)| r));
}
}
if let Some(g) = v.grids.get(&machine) {
- // (This computer's own are above, by their local names.)
- let here: Vec<&LocalModel> = snap.map(|s| s.models.iter().filter(|m| m.running()).collect()).unwrap_or_default();
- for s in g.sections.iter().filter(|s| s.own) {
- for x in s.models.iter().filter(|x| !here.iter().any(|m| x.id.eq_ignore_ascii_case(&m.id) || x.id.eq_ignore_ascii_case(&m.name))) {
- out.push(grid_row(app, s, x, t, &head));
- }
+ // (Without this computer's list yet, the own grid's models as they come.)
+ if snap.is_none() {
+ for s in g.sections.iter().filter(|s| s.own) { for x in &s.models { out.push(grid_row(app, s, x, t, &head)) } }
}
for s in g.sections.iter().filter(|s| !s.own) {
let words = section_words(s, v.asking.contains(&s.name));
@@ -777,10 +842,10 @@ pub fn plan_enter(app: &App, id: &str) -> Plan {
if !f.get { return say(if !m.can_start { "This model does not fit here now." } else { "It cannot be got now. Try again in a moment." }) }
let supports = v.local.get(&app.fleet.local_id).is_some_and(|s| s.supports_download);
let go = if f.get_use { Plan::Use { model: m.id.clone(), download: true } } else { Plan::Act { model: m.id.clone(), action: if supports { "download" } else { "start" } } };
- // A download is gigabytes: the first Enter says what the second will do.
+ // A download is gigabytes: the first Enter asks, in the preview, what the second will do.
let size = m.size.map(gb).map(|s| format!(" ({s})")).unwrap_or_default();
- let then = if f.get_use { " — then it starts and this harness moves onto it" } else { "" };
- Plan::Arm(format!("Enter again to get {}{size}{then}", m.name), Box::new(go))
+ let then = if f.get_use { ", start it, move this harness onto it" } else { "" };
+ Plan::Arm(format!("Get {}{size}{then}? Enter · Esc", m.name), Box::new(go))
}
/// What ^S does on row [id]: stop a local model (asked first).
@@ -800,12 +865,19 @@ pub fn choose(app: &mut App, picker: &mut Picker, id: &str, stop: bool) {
}
fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {
- if !matches!(plan, Plan::Arm(..)) { picker.armed = None }
+ if !matches!(plan, Plan::Arm(..)) { picker.armed = None; app.models_view.confirm = None }
+ // (Anything but words starts another action: the last Use's end leaves its preview.)
+ if !matches!(plan, Plan::Nothing | Plan::Say(_)) { app.models_view.ended = None }
match plan {
Plan::Nothing => {}
+ // (No harness: why, from what the focused pane is.)
+ Plan::Say(s) if s == NO_HARNESS => picker.say(no_target_why(app)),
Plan::Say(s) => picker.say(s),
Plan::Arm(words, then) => {
+ app.models_view.confirm = None;
if picker.armed.as_deref() == Some(key) { picker.armed = None; run(app, picker, *then, key) }
+ // Enter on a local model asks in its preview, where it stays until answered.
+ else if let Some(row) = key.strip_suffix("\u{1f}enter").filter(|id| id.starts_with("mv:local:")) { picker.armed = Some(key.to_string()); app.models_view.confirm = Some((row.to_string(), words)) }
else { picker.armed = Some(key.to_string()); picker.say(words) }
}
Plan::Retarget { machine, payload, name } => {
@@ -813,7 +885,8 @@ fn run(app: &mut App, picker: &mut Picker, plan: Plan, key: &str) {
picker.say(format!("Switching {who} to {name}…"));
retarget(app, &machine, payload, &name, false);
}
- Plan::Use { model, download } => { start_use(app, &model, download); if let Some(u) = app.models_view.using.clone() { picker.say(using_label(app, &u)) } }
+ // (Its steps are the preview's checklist.)
+ Plan::Use { model, download } => start_use(app, &model, download),
Plan::Act { model, action } => { picker.say(format!("{}…", pending_word(action))); act(app, &model, action) }
Plan::Wake(name) => { wake(app, &name); picker.say(STARTING_UP_WAIT) }
Plan::More => app.models_view.more = !app.models_view.more,
@@ -837,6 +910,42 @@ pub fn using_label(app: &App, u: &Use) -> String {
}
}
+/// Esc on the view: a first Enter's question taken back (true), the view left open.
+pub fn cancel(app: &mut App, picker: &mut Picker) -> bool {
+ let asked = app.models_view.confirm.take().is_some();
+ if asked { picker.armed = None }
+ asked
+}
+
+/// The status bar's word on a Use while it runs (`#{model_progress}`): `↻ qwen3-coder 42%`, or
+/// the step under way where the daemon sends no progress.
+/// What the model list is waiting on now, for its title (beside a spinner): a Use's step, else a
+/// harness being moved. None: nothing.
+pub fn working(app: &App) -> Option<String> {
+ if let Some(s) = status_text(app) { return Some(s.trim_start_matches("↻ ").to_string()) }
+ app.models_view.switching.as_ref().map(|s| format!("switching to {}", s.name))
+}
+
+pub fn status_text(app: &App) -> Option<String> {
+ let u = app.models_view.using.as_ref()?;
+ let op = local_model(app, &u.model).and_then(|m| app.models_view.op_for(&app.fleet.local_id, &m).cloned());
+ let doing = match u.step { Step::Get => "downloading", Step::Start => "starting", Step::Serve => "waiting to serve", Step::Switch => "switching" };
+ Some(match progress(u.step, op.as_ref()) { Some(p) => format!("↻ {} {}%", u.name, percent(p)), None => format!("↻ {} {doing}", u.name) })
+}
+
+/// The cursor's row in the open view: a question, or a Use's end, is its row's until the cursor
+/// leaves it (or the view closes).
+fn follow(app: &mut App) {
+ let here = match &app.modal { Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker }) => picker.current_id(), _ => None };
+ let v = &mut app.models_view;
+ if v.confirm.as_ref().is_some_and(|(row, _)| here.as_ref() != Some(row)) {
+ v.confirm = None;
+ if let Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker }) = app.modal.as_mut() { picker.armed = None }
+ }
+ let v = &mut app.models_view;
+ if let Some(e) = v.ended.as_mut() { if here.as_ref() == Some(&e.row) { e.seen = true } else if e.seen { v.ended = None } }
+}
+
// ── talking to the daemon ────────────────────────────────────────────────────────
/// One request of the view's to [machine]'s daemon, its reply applied on the loop. False when the
@@ -1001,8 +1110,7 @@ fn retarget(app: &mut App, machine: &str, payload: Value, name: &str, job: bool)
app.models_view.switching = Some(Switch { machine: machine.to_string(), agent, to, name: name.to_string(), since: Instant::now() });
if !rpc(app, machine, "agent_retarget", payload, Duration::from_secs(60), move |app, r| on_retarget(app, &n, job, r)) {
app.models_view.switching = None;
- app.say("That machine is not connected", theme::WARN);
- if job { app.models_view.using = None }
+ if job { fail(app, "That machine is not connected") } else { app.say("That machine is not connected", theme::WARN) }
}
}
@@ -1021,19 +1129,29 @@ fn retarget_error(e: &RpcError) -> String {
/// The daemon moved the harness (its pane restarts on the model — "Switching…" stays until its
/// frame says so), or said why not.
pub fn on_retarget(app: &mut App, name: &str, job: bool, reply: Result<Value, RpcError>) {
- if job { app.models_view.using = None }
+ let used = if job { app.models_view.using.take() } else { None };
let who = app.models_view.switching.as_ref().and_then(|s| app.fleet.agent(&s.machine, &s.agent)).map(|a| a.name.clone()).unwrap_or_else(|| "the harness".into());
+ // (A Use's last step: its end, and the one toast that says it.)
+ let end = |app: &mut App, failed: Option<String>| if let Some(u) = &used { app.models_view.ended = Some(Ended { row: format!("mv:local:{}", u.model), name: u.name.clone(), step: Step::Switch, failed, seen: false }) };
match reply {
- Ok(_) => app.say(format!("Switching {who} to {name}…"), theme::ONLINE),
+ // Moved: the list has done its job — it closes, and the status line says so.
+ Ok(_) if used.is_some() => { end(app, None); close(app); app.say(format!("✓ {name} is ready · {who} is on it"), theme::ONLINE) }
+ Ok(_) => { close(app); app.say(format!("✓ Switching {who} to {name}…"), theme::ONLINE) }
Err(e) => {
- let w = format!("Could not switch {who} to {name}: {}", retarget_error(&e));
+ let why = retarget_error(&e);
+ let w = format!("Could not switch {who} to {name}: {why}");
if let Some(s) = app.models_view.switching.take() { app.models_view.use_error = Some((format!("mv:switch:{}", s.to), w.clone())) }
- app.say(w, theme::DANGER);
+ if used.is_some() { end(app, Some(format!("Could not switch {who}: {why}"))); app.say(format!("✗ {w}"), theme::DANGER) } else { app.say(w, theme::DANGER) }
}
}
crate::input::refill(app);
}
+/// The model list, if it is what is open: closed (a harness moved onto a model — its job done).
+pub fn close(app: &mut App) {
+ if matches!(app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, .. })) { app.modal = None }
+}
+
// ── Use, step by step ────────────────────────────────────────────────────────────
/// What a Use does next, from what the daemon last said.
@@ -1073,13 +1191,17 @@ fn start_use(app: &mut App, model: &str, download: bool) {
let Some(m) = local_model(app, model) else { return };
let supports = app.models_view.local.get(&app.fleet.local_id).is_some_and(|s| s.supports_download);
app.models_view.using = Some(Use { model: m.id.clone(), name: m.name.clone(), machine: t.machine, agent: t.agent, step: if download { Step::Get } else { Step::Start }, since: Instant::now() });
+ app.models_view.ended = None;
act(app, &m.id, if download && supports { "download" } else { "start" });
}
+/// The Use stops at its step: its row's preview says why (✗) and how to try again, and one toast.
fn fail(app: &mut App, why: &str) {
let Some(job) = app.models_view.using.take() else { return };
- app.models_view.use_error = Some((format!("mv:local:{}", job.model), why.to_string()));
- app.say(format!("{}: {why}", job.name), theme::WARN);
+ let row = format!("mv:local:{}", job.model);
+ app.models_view.use_error = Some((row.clone(), why.to_string()));
+ app.models_view.ended = Some(Ended { row, name: job.name.clone(), step: job.step, failed: Some(why.to_string()), seen: false });
+ app.say(format!("✗ {}: {why}", job.name), theme::DANGER);
}
/// Take the Use on as far as what the daemon has said allows.
@@ -1122,6 +1244,7 @@ pub fn loading(app: &App) -> bool { !app.models_view.reading.is_empty() || !app.
/// [grids_every] says, and take a Use on (its deadlines).
pub fn tick(app: &mut App) {
let open = matches!(&app.modal, Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, .. }));
+ follow(app);
app.models_view.starts.retain(|_, at| at.elapsed() < START_CAP);
if app.models_view.switching.as_ref().is_some_and(|s| switched(app, s)) { app.models_view.switching = None }
let machine = app.fleet.local_id.clone();
@@ -1182,6 +1305,42 @@ fn bold(t: impl Into<String>) -> Line<'static> { Line::from(span(t, Style::defau
fn warn(t: impl Into<String>) -> Line<'static> { Line::from(span(t, fg(theme::WARN))) }
fn dim(t: impl Into<String>) -> Line<'static> { Line::from(span(t, Style::default().add_modifier(Modifier::DIM))) }
+/// A local row's first-Enter question, or its Use's checklist — Download · Start · Serve · Switch
+/// harness — and how it ended: what its preview says under its status.
+fn use_lines(app: &App, m: &LocalModel, id: &str) -> Vec<Line<'static>> {
+ let v = &app.models_view;
+ if let Some((_, words)) = v.confirm.as_ref().filter(|(row, _)| row == id) { return vec![Line::raw(""), Line::from(span(words.clone(), theme::bold(theme::accent())))] }
+ let ended = v.ended.as_ref().filter(|e| e.row == id);
+ let (step, op, since) = match (v.using.as_ref().filter(|u| u.model == m.id), ended) {
+ (Some(u), _) => (u.step, v.op_for(&app.fleet.local_id, m).cloned(), Some(u.since)),
+ (None, Some(e)) => (e.step, None, None),
+ _ => return vec![],
+ };
+ let ended = ended.filter(|_| since.is_none());
+ let mut out = vec![Line::raw("")];
+ for (name, mark) in STEPS.iter().zip(checklist(step, op.as_ref(), ended.map(|e| e.failed.is_none()))) {
+ out.push(match mark {
+ Mark::Done => Line::from(span(format!("✓ {name}"), fg(theme::ONLINE))),
+ Mark::Now(Some(p)) => Line::from(span(format!("↻ {name} {} {}%", bar(p), percent(p)), fg(theme::accent()))),
+ Mark::Now(None) => Line::from(span(format!("↻ {name} · {}", elapsed(since.map(|s| s.elapsed().as_secs()).unwrap_or(0))), fg(theme::accent()))),
+ Mark::Failed => Line::from(span(format!("✗ {name}"), fg(theme::DANGER))),
+ Mark::Later => dim(format!(" {name}")),
+ });
+ }
+ match ended.map(|e| (e.failed.as_ref(), &e.name)) {
+ Some((None, name)) => { out.push(Line::raw("")); out.push(Line::from(span(format!("✓ Ready · this harness is on {name}"), theme::bold(theme::ONLINE)))) }
+ Some((Some(why), _)) => { out.push(Line::raw("")); out.push(Line::from(span(format!("✗ Failed · {why}"), fg(theme::DANGER)))); out.push(Line::from(span("Enter tries again.", fg(theme::accent())))) }
+ None => {}
+ }
+ out
+}
+
+/// [p] of a bar 16 cells wide.
+fn bar(p: f64) -> String { let n = ((p * 16.0).round() as usize).min(16); format!("{}{}", "█".repeat(n), "░".repeat(16 - n)) }
+
+/// A step's time so far: `12s`, `3m 05s`.
+fn elapsed(secs: u64) -> String { if secs < 60 { format!("{secs}s") } else { format!("{}m {:02}s", secs / 60, secs % 60) } }
+
/// The preview of row [id]: what decides between models, and what Enter does.
pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {
let t = target(app);
@@ -1200,7 +1359,9 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {
else if m.running() { "Running".into() } else if m.downloaded() { "Downloaded".into() } else { "Not downloaded".into() };
let status = if f.switching { format!("{SWITCHING} this harness is moving onto it") } else if f.in_use { format!("{status} · this harness is on it") } else { status };
let mut out = vec![bold(m.name.clone()), Line::raw(status)];
- out.extend(failed);
+ // (A Use's end says why it failed itself.)
+ if !v.ended.as_ref().is_some_and(|e| e.row == id) { out.extend(failed) }
+ out.extend(use_lines(app, &m, id));
out.push(Line::raw(""));
let here = this_computer();
if let Some(size) = m.size {
@@ -1253,7 +1414,7 @@ pub fn preview(app: &App, id: &str) -> Vec<Line<'static>> {
out.push(Line::raw(""));
out.push(kv("Machine", node.to_string()));
out.push(kv("Source", if own { "On your machines".to_string() } else { format!("Shared · {grid}") }));
- let said = match plan_enter(app, id) { Plan::Retarget { .. } => "Enter moves this harness onto it.".to_string(), Plan::Arm(..) => "Enter twice moves this harness onto it anyway.".into(), Plan::Say(w) => w, _ => String::new() };
+ let said = match plan_enter(app, id) { Plan::Retarget { .. } => "Enter moves this harness onto it.".to_string(), Plan::Arm(..) => "Enter twice moves this harness onto it anyway.".into(), Plan::Say(w) if w == NO_HARNESS => no_target_why(app), Plan::Say(w) => w, _ => String::new() };
if !said.is_empty() { out.push(Line::raw("")); out.push(Line::from(span(said, fg(theme::accent())))) }
return out;
}
@@ -1347,6 +1508,42 @@ mod tests {
app.fleet.agents.insert(key, a);
}
+ /// On your machines: what can be used now first — a model running here, then one the own grid
+ /// serves from another machine — then one downloaded and stopped; a grid's offline one last.
+ #[test]
+ fn models_ready_now_come_before_ones_not_running() {
+ let mut app = app();
+ on_local(&mut app, "local", Ok(local_reply(qwen("running", Value::Null), false)));
+ let mut g = grids_reply(&["box-model"]);
+ g["grids"][0]["models"].as_array_mut().unwrap().push(json!({ "id": "away-model", "node": "lap", "unavailable": { "reason": "offline", "machine": "lap" } }));
+ on_grids(&mut app, "local", Ok(g));
+ let mine: Vec<String> = super::rows(&app, "").into_iter().filter(|r| r.group.as_deref().is_some_and(|g| g.starts_with("On your machines")) && is_row(&r.id)).map(|r| r.id).collect();
+ assert_eq!(mine, vec!["mv:local:qwen-35b".to_string(), "mv:grid:own-grid\tstudio\tbox-model".into(), "mv:local:gemma-12b".into(), "mv:grid:own-grid\tlap\taway-model".into()]);
+ }
+
+ /// Which harness Enter moves: the focused pane's. A focused terminal is the one meant — never
+ /// the harness beside it — and the panel says why there is none; with nothing focused, the one
+ /// harness on screen.
+ #[test]
+ fn the_focused_pane_is_the_harness_meant_and_why_none_is_said() {
+ let mut app = app();
+ assert_eq!(target(&app).map(|t| t.agent).as_deref(), Some("a1"));
+ let key = ("local".to_string(), "t1".to_string());
+ let a = crate::fleet::agent_from("local", &json!({ "id": "t1", "name": "shell", "engine": "terminal" }), None);
+ app.fleet.agents.insert(key, a);
+ app.panes.insert(2, crate::pane::Pane::new(2, "local", "t1", 75, 40));
+ app.rects = vec![(1, ratatui::layout::Rect::new(0, 0, 75, 40)), (2, ratatui::layout::Rect::new(75, 0, 75, 40))];
+ app.tabs[0].focus = Some(2);
+ assert!(target(&app).is_none(), "not the claude harness beside it");
+ assert!(no_target_why(&app).contains("terminal"), "{}", no_target_why(&app));
+ app.tabs[0].focus = None;
+ assert_eq!(target(&app).map(|t| t.agent).as_deref(), Some("a1"), "nothing focused: the one harness on screen");
+ assert!(no_target_why(&app).contains("No pane is focused"));
+ app.panes.insert(3, crate::pane::Pane::new(3, "local", "zz9abc", 75, 40));
+ app.tabs[0].focus = Some(3);
+ assert!(no_target_why(&app).contains("zz9abc"), "{}", no_target_why(&app));
+ }
+
fn model(id: &str, state: &str, gib: f64) -> Value {
json!({ "id": id, "name": id, "state": state, "sizeBytes": gib * GIB, "canStart": state != "running", "canStop": state == "running", "estTokS": 40 })
}
@@ -1407,26 +1604,36 @@ mod tests {
assert_eq!(in_use_row(&rows).as_deref(), Some("mv:sub:claude\t7f0c"));
assert!(row(&rows, "mv:local:qwen-35b").right.ends_with("Get"));
- // Get: the first Enter only says what the second will do.
+ // Get: the first Enter only asks, in the preview, what the second will do.
let mut picker = Picker::new("models", "");
+ let qwen_preview = |app: &App| text(&preview(app, "mv:local:qwen-35b"));
choose(&mut app, &mut picker, "mv:local:qwen-35b", false);
assert!(app.models_view.sent.is_empty(), "nothing downloads on the first Enter");
- assert!(flash(&picker).starts_with("Enter again to get Qwen3.6-35B-A3B (20 GB) — then it starts"), "{}", flash(&picker));
+ assert!(flash(&picker).is_empty(), "no fading flash: {}", flash(&picker));
+ assert!(qwen_preview(&app).contains("Get Qwen3.6-35B-A3B (20 GB), start it, move this harness onto it? Enter · Esc"), "{}", qwen_preview(&app));
choose(&mut app, &mut picker, "mv:local:qwen-35b", false);
assert_eq!(last_sent(&app), ("local".into(), "grid_fleet_model_download".into(), json!({ "modelId": "qwen-35b" })));
assert_eq!(app.models_view.using.as_ref().map(|u| u.step), Some(Step::Get));
+ assert!(!qwen_preview(&app).contains("Enter · Esc"), "{}", qwen_preview(&app));
- // The daemon takes it; its progress is the row's word.
+ // The daemon takes it; its progress is the row's word, the checklist's bar and the status bar's.
on_act(&mut app, "local", Ok(json!({ "operation": op("download", "downloading", "running", Some(0.1)) })));
assert_eq!(last_sent(&app).1, "grid_fleet_models_list");
on_local(&mut app, "local", Ok(local_reply(qwen("available", op("download", "downloading", "running", Some(0.42))), true)));
assert!(row(&rows_of(&app), "mv:local:qwen-35b").right.ends_with("Downloading 42%"));
assert_eq!(app.models_view.using.as_ref().map(|u| u.step), Some(Step::Get), "a download has no deadline");
+ let p = qwen_preview(&app);
+ assert!(p.contains("↻ Download") && p.contains("█") && p.contains("42%") && p.contains("\n Start\n Serve\n Switch harness"), "{p}");
+ assert_eq!(status_text(&app).as_deref(), Some("↻ Qwen3.6-35B-A3B 42%"));
+ assert_eq!(crate::format::expand(&app, "#{?model_progress,#{model_progress},none}", app.active, app.focused(), false), "↻ Qwen3.6-35B-A3B 42%");
// Downloaded: it is started.
on_local(&mut app, "local", Ok(local_reply(qwen("downloaded", op("download", "downloading", "done", None)), false)));
assert_eq!(last_sent(&app), ("local".into(), "grid_fleet_model_start".into(), json!({ "modelId": "qwen-35b" })));
assert_eq!(app.models_view.using.as_ref().map(|u| u.step), Some(Step::Start));
+ let p = qwen_preview(&app);
+ assert!(p.contains("✓ Download") && p.contains("↻ Start · 0s") && !p.contains("█"), "{p}");
+ assert_eq!(status_text(&app).as_deref(), Some("↻ Qwen3.6-35B-A3B starting"));
on_act(&mut app, "local", Ok(json!({ "operation": op("start", "starting", "running", None) })));
on_local(&mut app, "local", Ok(local_reply(qwen("downloaded", op("start", "starting", "running", None)), true)));
assert_eq!(app.models_view.using.as_ref().map(|u| u.step), Some(Step::Start), "still starting");
@@ -1444,7 +1651,10 @@ mod tests {
assert_eq!(pane_note(&app, "local", "a1").as_deref(), Some("Switching to Qwen3.6-35B-A3B…"));
on_retarget(&mut app, "Qwen3.6-35B-A3B", true, Ok(json!({ "retargeted": true })));
assert!(app.models_view.using.is_none());
- assert!(toast(&app).contains("Switching fix-login to Qwen3.6-35B-A3B"), "{}", toast(&app));
+ assert_eq!(toast(&app), "✓ Qwen3.6-35B-A3B is ready · fix-login is on it");
+ let p = qwen_preview(&app);
+ assert!(p.contains("✓ Switch harness") && p.contains("✓ Ready · this harness is on Qwen3.6-35B-A3B"), "{p}");
+ assert!(status_text(&app).is_none(), "nothing runs");
frame(&mut app, json!({ "model": "qwen-35b", "state": "awake" }));
let rows = rows_of(&app);
assert!(row(&rows, "mv:local:qwen-35b").right.ends_with("✓ In use"));
@@ -1490,8 +1700,8 @@ mod tests {
assert_eq!(last_sent(&app), ("local".into(), "grid_fleet_model_start".into(), json!({ "modelId": "gemma-12b" })));
on_act(&mut app, "local", Err(RpcError::new("Stop a running model to make room, then try again.", "")));
assert!(app.models_view.using.is_none());
- assert_eq!(toast(&app), "gemma-12b: Stop a running model to make room, then try again.");
- assert!(text(&preview(&app, "mv:local:gemma-12b")).contains("Stop a running model to make room"));
+ assert_eq!(toast(&app), "✗ gemma-12b: Stop a running model to make room, then try again.");
+ assert!(text(&preview(&app, "mv:local:gemma-12b")).contains("✗ Failed · Stop a running model to make room"));
// A download the daemon reports failed.
let job = Use { model: "qwen-35b".into(), name: "Qwen".into(), machine: "local".into(), agent: "a1".into(), step: Step::Get, since: Instant::now() };
@@ -1508,6 +1718,61 @@ mod tests {
assert_eq!(next(&serving, Some(&snap), None, false, Some(&parse_grids(&grids_reply(&["QWEN-35B"]))), Instant::now()), Next::Retarget { grid: "own-grid".into(), model: "QWEN-35B".into() });
}
+ /// A Use's four steps, from where it is and the operation on its model: done, the one under
+ /// way (with its progress only while the daemon sends one), failed, or still to come.
+ #[test]
+ fn the_steps_follow_the_use_and_its_operation() {
+ use Mark::*;
+ let o = |action: &str, stage: &str, phase: &str, p: Option<f64>| Operation::parse(&op(action, stage, phase, p));
+ assert_eq!(checklist(Step::Get, o("download", "downloading", "running", Some(0.42)).as_ref(), None), [Now(Some(0.42)), Later, Later, Later]);
+ assert_eq!(checklist(Step::Get, None, None), [Now(None), Later, Later, Later]);
+ assert_eq!(checklist(Step::Get, o("download", "downloading", "done", Some(1.0)).as_ref(), None), [Now(None), Later, Later, Later], "a finished operation is no bar");
+ assert_eq!(checklist(Step::Start, o("start", "starting", "running", None).as_ref(), None), [Done, Now(None), Later, Later]);
+ assert_eq!(checklist(Step::Serve, None, None), [Done, Done, Now(None), Later]);
+ assert_eq!(checklist(Step::Switch, None, None), [Done, Done, Done, Now(None)]);
+ assert_eq!(checklist(Step::Switch, None, Some(true)), [Done, Done, Done, Done]);
+ assert_eq!(checklist(Step::Start, o("start", "starting", "failed", None).as_ref(), Some(false)), [Done, Failed, Later, Later]);
+ assert_eq!(checklist(Step::Get, None, Some(false)), [Failed, Later, Later, Later]);
+ }
+
+ /// How a Use ended stays in its row's preview — past the 3 s a flash lasts — until the cursor
+ /// leaves the row; Esc takes back a confirm without closing the view.
+ #[test]
+ fn the_end_state_stays_until_the_cursor_leaves_the_row() {
+ let mut app = loaded();
+ let mut picker = Picker::new("models", "");
+ picker.set_rows(rows(&app, ""));
+ choose(&mut app, &mut picker, "mv:local:gemma-12b", false);
+ on_act(&mut app, "local", Err(RpcError::new("Stop a running model to make room, then try again.", "")));
+ picker.select("mv:local:gemma-12b");
+ picker.flash = Some(("old".into(), Instant::now() - Duration::from_secs(10)));
+ app.modal = Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker });
+ let gemma = |app: &App| text(&preview(app, "mv:local:gemma-12b"));
+ for _ in 0..3 { tick(&mut app) }
+ assert!(gemma(&app).contains("✗ Failed · Stop a running model") && gemma(&app).contains("Enter tries again."), "{}", gemma(&app));
+ let Some(crate::modal::Modal::Picker { picker, .. }) = app.modal.as_mut() else { panic!() };
+ picker.select("mv:local:qwen-35b");
+ tick(&mut app);
+ assert!(!gemma(&app).contains("✗ Failed"), "{}", gemma(&app));
+
+ // A confirm: Esc takes it back, and the next Enter asks again.
+ let Some(crate::modal::Modal::Picker { mut picker, .. }) = app.modal.take() else { panic!() };
+ choose(&mut app, &mut picker, "mv:local:qwen-35b", false);
+ assert!(text(&preview(&app, "mv:local:qwen-35b")).contains("? Enter · Esc"));
+ assert!(cancel(&mut app, &mut picker));
+ assert!(!text(&preview(&app, "mv:local:qwen-35b")).contains("? Enter · Esc"));
+ assert!(!cancel(&mut app, &mut picker), "nothing left to take back: Esc closes");
+ choose(&mut app, &mut picker, "mv:local:qwen-35b", false);
+ assert!(app.models_view.sent.iter().all(|s| s.1 != "grid_fleet_model_download"), "asked again, not started");
+ // Moving off the row takes the confirm back too.
+ picker.select("mv:local:gemma-12b");
+ app.modal = Some(crate::modal::Modal::Picker { kind: crate::modal::PickerKind::Models, picker });
+ tick(&mut app);
+ assert!(!text(&preview(&app, "mv:local:qwen-35b")).contains("? Enter · Esc"));
+ let Some(crate::modal::Modal::Picker { picker, .. }) = &app.modal else { panic!() };
+ assert!(picker.armed.is_none());
+ }
+
/// One local model runs at a time: with another running, Use says to stop it first, and Get
/// only downloads. While an operation runs, nothing else starts.
#[test]
diff --git a/tui/src/new_harness.rs b/tui/src/new_harness.rs
index b53a2dd58..ef3123ec2 100644
--- a/tui/src/new_harness.rs
+++ b/tui/src/new_harness.rs
@@ -1719,8 +1719,8 @@ mod tests {
assert_eq!(hit.intersection(area), *hit);
}
if form.area.width > 0 {
- // The menus' panel: one size and place whatever is open.
- assert_eq!(form.area, crate::settings::area(area));
+ // The form's panel: its own height, one size and place whatever is open.
+ assert_eq!(form.area, crate::settings::area(area, crate::settings::PanelSize::Form, view::HEIGHT));
let left = form.area.x - area.x;
let right = area.right() - form.area.right();
assert!(left.abs_diff(right) <= 1, "not centered in {area:?}");
diff --git a/tui/src/new_harness/view.rs b/tui/src/new_harness/view.rs
index 3354bfcb5..a0b86be94 100644
--- a/tui/src/new_harness/view.rs
+++ b/tui/src/new_harness/view.rs
@@ -46,6 +46,13 @@ fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Style) {
buf.set_stringn(x, y, out, width as usize, style);
}
+/// The most fields the form shows (Agent, Project, Options, Model, Approvals, Profile, Branch,
+/// Worktree, Create).
+const MOST_FIELDS: u16 = 9;
+/// The form's height: its most fields, two rows apart, two rows over them — the same collapsed or
+/// expanded, so it does not move.
+pub(super) const HEIGHT: u16 = 2 + MOST_FIELDS * 2;
+
/// The form's surface, as the settings panel draws its own: filled, no border.
fn panel(buf: &mut Buffer, r: Rect, base: Style) { crate::settings::fill(buf, r, base) }
@@ -67,11 +74,11 @@ pub fn draw(buf: &mut Buffer, body: Rect, form: &mut Form) -> Option<Position> {
// The settings panel's colours, and its quiet backdrop over the working panes.
let crate::settings::Chrome { base, muted, accent, backdrop, .. } = crate::settings::chrome();
crate::settings::backdrop(buf, body, backdrop);
- // The form is the menus' panel: centred, the one size whatever is open — and a chooser (an
- // agent, a machine, a folder…) opens in its place, as a section of Appearance does, so
- // nothing moves.
+ // The form is a Form panel: centred, as tall as its fields, the one size whatever is open —
+ // and a chooser (an agent, a machine, a folder…) opens in its place, as a section of
+ // Appearance does, so nothing moves.
let side = false;
- let r = crate::settings::area(body);
+ let r = crate::settings::area(body, crate::settings::PanelSize::Form, HEIGHT);
let (x, y, form_w, form_h) = (r.x, r.y, r.width, r.height);
let (child_w, child_h) = (form_w, form_h);
let fields = form.fields();
diff --git a/tui/src/options/mod.rs b/tui/src/options/mod.rs
index e8d4122bb..0de30d410 100644
--- a/tui/src/options/mod.rs
+++ b/tui/src/options/mod.rs
@@ -100,12 +100,12 @@ pub fn defaults() -> &'static BTreeMap<String, String> {
// has it] when another window has the pane to type in, and its project and branch
// where there is room. Git context stays here; the status bar keeps the location cue.
m.insert("pane-border-format".into(), " #{pane_heading}#{?pane_where,#[align=right] #[dim]#{pane_where} #[nodim],}".into());
- // Window navigation on the left; connection, quota, fleet, machine and clock on the
- // right. The quoted name is this computer's name in Harness, independent of focus.
+ // Window navigation on the left; connection, a model being got, quota, fleet, machine and
+ // clock on the right. The quoted name is this computer's name in Harness, independent of focus.
// One cell at each outer edge aligns status text with the pane surfaces.
// Two spaces separate the window list from the information on the right.
m.insert("status-left".into(), " #{?client_prefix,#[bold]›#[nobold] ,}".into());
- m.insert("status-right".into(), " #{?daemon_down,#[bold]daemon down#[nobold] ,}#{?usage_remaining,#{usage_remaining_mark} ,}#{?fleet,#{s/ / /:fleet} ,}#{?pane_watching,[watching] ,}\"#{=/21/…:local_machine}\" %H:%M ".into());
+ m.insert("status-right".into(), " #{?daemon_down,#[bold]daemon down#[nobold] ,}#{?model_progress,#{model_progress} ,}#{?usage_remaining,#{usage_remaining_mark} ,}#{?fleet,#{s/ / /:fleet} ,}#{?pane_watching,[watching] ,}\"#{=/21/…:local_machine}\" %H:%M ".into());
// Each window's most urgent harness at a glance (the symbol its pane titles show) and its
// name in a few whole words (#{window_short_name}): a harness is named for its task.
// Keep tmux's familiar current/previous markers beside the name, then any other
diff --git a/tui/src/picker.rs b/tui/src/picker.rs
index e82d20498..e1282c6db 100644
--- a/tui/src/picker.rs
+++ b/tui/src/picker.rs
@@ -35,6 +35,9 @@ pub struct Row {
pub right_narrow: Option<String>,
/// Its line comes before its right column wherever both don't fit (a question, a failure).
pub line_first: bool,
+ /// A search lists a lower tier's matches first, however well a higher one's match (the command
+ /// list: hn's own, then tmux's).
+ pub tier: u8,
}
/// A list narrower than this shows a row's narrow right column.
@@ -55,8 +58,9 @@ impl Row {
impl Row {
pub fn new(id: impl Into<String>, label: impl Into<String>) -> Row {
- Row { id: id.into(), label: label.into(), extra: String::new(), group: None, lead: vec![], detail: vec![], right: String::new(), disabled: false, boost: 0, volatile_detail: false, volatile_right: 0, label_dim: 0, right_narrow: None, line_first: false }
+ Row { id: id.into(), label: label.into(), extra: String::new(), group: None, lead: vec![], detail: vec![], right: String::new(), disabled: false, boost: 0, volatile_detail: false, volatile_right: 0, label_dim: 0, right_narrow: None, line_first: false, tier: 0 }
}
+ pub fn tier(mut self, tier: u8) -> Row { self.tier = tier; self }
pub fn extra(mut self, text: impl Into<String>) -> Row { self.extra = text.into(); self }
pub fn group(mut self, text: impl Into<String>) -> Row { self.group = Some(text.into()); self }
pub fn lead(mut self, spans: Vec<Span<'static>>) -> Row { self.lead = spans; self }
@@ -217,6 +221,11 @@ pub struct Picker {
pub theme_in: Option<String>,
/// Opened from the command list (C-b Space): Esc goes back to it rather than closing.
pub from_commands: bool,
+ /// The launcher's tab row has the keys (↓ past the list's last row): ←/→ open the next tab.
+ pub on_tabs: bool,
+ /// The wheel scrolled the panel's list: it stays where it was put, wherever the cursor is,
+ /// until a key moves it.
+ pub free_scroll: bool,
}
impl Picker {
@@ -296,6 +305,8 @@ impl Picker {
search: None,
theme_in: None,
from_commands: false,
+ on_tabs: false,
+ free_scroll: false,
preview_of: None,
preview_fresh: std::cell::Cell::new(true),
preview_reposition: Default::default(),
@@ -380,6 +391,7 @@ impl Picker {
// A live list's rows are its order (by urgency), as fzf's are over lines
// drawn to one width: length decides nothing between them.
let mut rank = crate::fzf::rank(&hit, &chars, if self.live { &live_tiebreak } else { &o.tiebreak });
+ rank.insert(0, row.tier as i64);
// --tac: the input read bottom-up, ties too.
rank.push(if o.tac { -(index as i64) } else { index as i64 });
scored.push((rank, index, hit.positions.iter().map(|p| *p as u32).collect()));
diff --git a/tui/src/settings.rs b/tui/src/settings.rs
index 97924792a..1326430dc 100644
--- a/tui/src/settings.rs
+++ b/tui/src/settings.rs
@@ -94,11 +94,27 @@ pub fn back_to_commands_at(app: &App, picker: &mut Picker, at: &str) {
picker.live = true;
picker.clear_query();
picker.rows.clear();
- picker.set_rows(crate::modal::command_rows_for(app, false));
+ picker.set_rows(crate::modal::command_rows_for(app, false, false));
picker.scroll = 0;
cursor_to(picker, at);
}
+// ── tmux's commands: one row in the command list, Enter lists them here ──
+
+/// The command list is showing tmux's commands (Enter on their row; Esc comes back).
+pub fn in_tmux(picker: &Picker) -> bool { picker.theme_in.as_deref() == Some("tmux") }
+
+/// Enter on "tmux commands…": tmux's commands, grouped, in this same panel.
+pub fn into_tmux(app: &App, picker: &mut Picker) {
+ picker.theme_in = Some("tmux".into());
+ picker.placeholder = "Search tmux commands".into();
+ picker.clear_query();
+ picker.rows.clear();
+ picker.set_rows(crate::modal::command_rows_for(app, false, true));
+ picker.scroll = 0;
+ picker.vset(0, 1);
+}
+
/// Put the cursor on the row [id] (where the filter shows it).
pub fn cursor_to(picker: &mut Picker, id: &str) { picker.select(id) }
@@ -207,7 +223,7 @@ fn show_captured(app: &mut App, said: String) {
let at = picker.current_id();
match &kind {
PickerKind::Keybinds => picker.set_rows(crate::modal::keybind_rows(app)),
- PickerKind::Commands => picker.set_rows(crate::modal::command_rows_for(app, !picker.query.is_empty())),
+ PickerKind::Commands => picker.set_rows(crate::modal::command_rows_for(app, !picker.query.is_empty(), in_tmux(&picker))),
_ => {}
}
if let Some(at) = at { cursor_to(&mut picker, &at) }
@@ -345,13 +361,54 @@ pub fn put(buf: &mut Buffer, x: u16, y: u16, width: u16, text: &str, style: Styl
used as u16
}
-/// Where the panel goes in [body]: centred, and the same size whatever the list holds.
-pub fn area(body: Rect) -> Rect {
- // (Room for a preview that can be read: nine tenths of the window each way, and at least 4
- // columns and 2 rows of it around the panel.)
- let w = (body.width * 9 / 10).min(body.width.saturating_sub(4));
- let h = (body.height * 9 / 10).min(body.height.saturating_sub(2));
- Rect::new(body.x + (body.width - w) / 2, body.y + (body.height - h) / 2, w, h)
+// ── sizes ──
+
+/// A panel's size: Large for a list with a preview, Palette for a short menu near the top, Form
+/// for a form, as tall as its fields.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum PanelSize { Large, Palette, Form }
+
+/// Of the window, in tenths: the most a panel takes each way (a palette's height, its own).
+const SHARE: u16 = 9;
+const PALETTE_SHARE_H: u16 = 7;
+/// Large: as wide as this at most, however wide the window.
+const LARGE_MAX_W: u16 = 160;
+/// (Room for a command's name, its hint and its key apart.)
+const PALETTE_W: u16 = 96;
+const FORM_W: u16 = 80;
+/// A palette's top: this part of the way down the window (in its upper third).
+const PALETTE_TOP: u16 = 6;
+/// A palette's rows around its list: the title, the query, the gaps and the footer.
+const PALETTE_CHROME: u16 = 8;
+/// Around any panel, at least 4 columns and 2 rows of the window.
+const MARGIN_W: u16 = 4;
+const MARGIN_H: u16 = 2;
+
+impl PickerKind {
+ /// Each list's size, in one place: a new kind does not compile until it has one.
+ pub fn size(&self) -> PanelSize {
+ match self {
+ // (Every launcher tab is the same size — Help too — so ←/→ on the tab row never moves it.)
+ PickerKind::Open { .. } | PickerKind::Palette | PickerKind::Projects | PickerKind::Models | PickerKind::Inbox | PickerKind::Machines | PickerKind::Store | PickerKind::Help | PickerKind::Theme
+ | PickerKind::Route { .. } | PickerKind::Messages | PickerKind::Keys | PickerKind::Buffers | PickerKind::Output { .. } | PickerKind::Devices(_) => PanelSize::Large,
+ PickerKind::Commands | PickerKind::Keybinds | PickerKind::Layout => PanelSize::Palette,
+ }
+ }
+}
+
+/// Where a panel of [size] goes in [body]; [content]: the rows it needs (a palette's list rows, a
+/// form's height) — a large panel's size is the window's.
+pub fn area(body: Rect, size: PanelSize, content: u16) -> Rect {
+ let most_w = (body.width * SHARE / 10).min(body.width.saturating_sub(MARGIN_W));
+ let most_h = (body.height * SHARE / 10).min(body.height.saturating_sub(MARGIN_H));
+ let (w, h) = match size {
+ PanelSize::Large => (most_w.min(LARGE_MAX_W), most_h),
+ PanelSize::Palette => (most_w.min(PALETTE_W), content.saturating_add(PALETTE_CHROME).min(body.height * PALETTE_SHARE_H / 10).min(most_h)),
+ PanelSize::Form => (most_w.min(FORM_W), content.min(most_h)),
+ };
+ let x = body.x + (body.width - w) / 2;
+ let y = if size == PanelSize::Palette { body.y + (body.height - h).min(body.height / PALETTE_TOP) } else { body.y + (body.height - h) / 2 };
+ Rect::new(x, y, w, h)
}
/// Draw the panel for [picker] over [body]; returns where the terminal cursor goes (the query),
@@ -367,7 +424,10 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
put(buf, body.x, body.y, body.width, &format!("{} · resize or Esc", title(app, kind, picker)), c.base);
return (None, None);
}
- let r = area(body);
+ // (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));
@@ -379,8 +439,10 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
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.
- let status = picker.busy.clone().unwrap_or_else(|| picker.status.clone());
+ // 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);
@@ -398,24 +460,31 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
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);
+ // (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 lists it switches between, the one you are in marked.
+ // 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 [(Some('>'), "commands"), (Some('@'), "machines"), (Some('#'), "projects"), (Some(':'), "models"), (Some('*'), "store"), (Some('?'), "help")] {
- let text = format!("{} {name}", ch.unwrap_or(' '));
+ 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 on = here == ch;
- sx += put(buf, sx, qy, right.saturating_sub(sx), &text, if on { c.base.add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { c.muted }) + 3;
+ 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.
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)); }
- // Over that: this list's keys, `key what` · `key what`, the keys bold.
+ // 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;
- for (i, (k, what)) in picker.hints.iter().enumerate() {
+ 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);
@@ -432,7 +501,8 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
// 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);
- let side = inner_w >= 64 && (settings || (picker.preview && !matches!(kind, PickerKind::Commands | PickerKind::Theme | PickerKind::Keybinds)));
+ // (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.)
let list_w = if !side { inner_w } else if settings { (inner_w * 2 / 5).clamp(28, 40) } else { (inner_w / 2).clamp(30, 56) };
@@ -463,6 +533,7 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
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"),
@@ -477,7 +548,7 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:
(None, Some(keys)) => { put(buf, x, fy, inner_w, keys, c.muted); }
(None, None) => {}
}
- (Some(cursor), shown)
+ (cursor, shown)
}
/// The menus, whose footer says their keys (the other lists give that row to their rows).
@@ -503,6 +574,8 @@ pub fn section_title(section: &str) -> &'static str {
"theme" => "Theme",
// ── status bar ──
"bar" => "Status bar", "boxes" => "Borders",
+ // (The command list's tmux commands.)
+ "tmux" => "tmux commands",
_ => "",
}
}
@@ -560,8 +633,11 @@ pub fn list_from(buf: &mut Buffer, picker: &mut Picker, r: Rect, c: &Chrome, det
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 };
- if top < picker.scroll { picker.scroll = top }
- if at_line >= picker.scroll + n { picker.scroll = at_line + 1 - n }
+ // (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 };
@@ -1023,6 +1099,62 @@ mod tests {
assert_ne!(a.base.bg, a.selected.bg, "the cursor's row stands out");
}
+ // ── sizes ──
+
+ /// Each size's numbers on a small, a medium and a very wide body.
+ #[test]
+ fn each_size_has_its_numbers_on_small_medium_and_very_wide_bodies() {
+ let small = Rect::new(0, 0, 40, 12);
+ assert_eq!(area(small, PanelSize::Large, 0), Rect::new(2, 1, 36, 10));
+ assert_eq!(area(small, PanelSize::Palette, 5), Rect::new(2, 2, 36, 8));
+ assert_eq!(area(small, PanelSize::Form, 20), Rect::new(2, 1, 36, 10));
+ let medium = Rect::new(0, 0, 120, 40);
+ assert_eq!(area(medium, PanelSize::Large, 0), Rect::new(6, 2, 108, 36));
+ // (Rows and chrome; at most seven tenths of the height; in the upper third.)
+ assert_eq!(area(medium, PanelSize::Palette, 5), Rect::new(12, 6, 96, 13));
+ assert_eq!(area(medium, PanelSize::Palette, 100), Rect::new(12, 6, 96, 28));
+ assert_eq!(area(medium, PanelSize::Form, 20), Rect::new(20, 10, 80, 20));
+ let wide = Rect::new(0, 0, 400, 60);
+ assert_eq!(area(wide, PanelSize::Large, 0), Rect::new(120, 3, 160, 54));
+ assert_eq!(area(wide, PanelSize::Palette, 5), Rect::new(152, 10, 96, 13));
+ assert_eq!(area(wide, PanelSize::Form, 20), Rect::new(160, 20, 80, 20));
+ }
+
+ /// Each list says its size: the launcher's lists, Models, Machines, Store, Appearance and the
+ /// devices are large; Commands and Help a palette.
+ #[test]
+ fn each_kind_has_its_size() {
+ let open = PickerKind::Open { filter: modal::Filter::All, machine: None, project: None };
+ for k in [open, PickerKind::Models, PickerKind::Machines, PickerKind::Store, PickerKind::Help, PickerKind::Theme, PickerKind::Devices(crate::devices::View::Machines)] { assert_eq!(k.size(), PanelSize::Large, "{k:?}") }
+ for k in [PickerKind::Commands, PickerKind::Keybinds] { assert_eq!(k.size(), PanelSize::Palette, "{k:?}") }
+ }
+
+ /// Commands is a palette near the top, narrower than the harnesses' panel; its height does not
+ /// change as a search narrows it.
+ #[test]
+ fn commands_is_a_palette_narrower_than_harnesses() {
+ let app = app((200, 51));
+ let body = Rect::new(0, 0, 200, 50);
+ let mut c = Picker::new("Commands", "Type a command");
+ c.set_rows(modal::command_rows_for(&app, false, false));
+ draw(&mut Buffer::empty(body), &app, body, &PickerKind::Commands, &mut c);
+ let mut h = Picker::new("harnesses", "");
+ draw(&mut Buffer::empty(body), &app, body, &PickerKind::Open { filter: modal::Filter::All, machine: None, project: None }, &mut h);
+ let (cr, hr) = (c.screen_area.get(), h.screen_area.get());
+ assert!(cr.width < hr.width, "{cr:?} {hr:?}");
+ assert!(cr.y < body.height / 3, "{cr:?}");
+ c.set_query("lay");
+ draw(&mut Buffer::empty(body), &app, body, &PickerKind::Commands, &mut c);
+ assert_eq!(c.screen_area.get(), cr);
+ let mut help = Picker::new("help", "");
+ help.set_rows(modal::mode_rows(&app));
+ draw(&mut Buffer::empty(body), &app, body, &PickerKind::Help, &mut help);
+ let before = help.screen_area.get();
+ help.set_query("zzz");
+ draw(&mut Buffer::empty(body), &app, body, &PickerKind::Help, &mut help);
+ assert_eq!(help.screen_area.get(), before, "the palette does not jump as you type");
+ }
+
#[test]
fn every_layout_tiles_the_screen_without_overlap() {
let r = Rect::new(0, 0, 50, 16);
diff --git a/tui/src/ui.rs b/tui/src/ui.rs
index dbcfb7b92..438dbce1f 100644
--- a/tui/src/ui.rs
+++ b/tui/src/ui.rs
@@ -3064,7 +3064,7 @@ mod theme_render_tests {
assert_eq!(bound(KeyCode::Char(' ')).as_deref(), Some("next-layout"));
crate::commands::execute_bound(&mut app, "choose-command");
let s = screen(&mut app);
- assert!(s.contains("Commands") && s.contains("New Harness"), "{s}");
+ assert!(s.contains("Commands") && s.contains("New harness"), "{s}");
let at = match &app.modal { Some(Modal::Picker { picker, .. }) => picker.screen_area.get(), _ => panic!("no panel") };
// (A few letters are enough: the best match comes first.)
for c in "appe".chars() { crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)) }
@@ -3075,11 +3075,126 @@ mod theme_render_tests {
assert!(s.contains("Pane titles") && s.contains("Preview"), "{s}");
let Some(Modal::Picker { kind, picker }) = &app.modal else { panic!("closed") };
assert!(matches!(kind, PickerKind::Theme) && picker.from_commands);
- assert_eq!(picker.screen_area.get(), at, "the panel stayed where it was");
+ // (The commands a palette; Appearance, with its preview, the large panel around it.)
+ let large = picker.screen_area.get();
+ assert!(large.width > at.width && large.contains(at.as_position()), "{at:?} in {large:?}");
crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ let s = screen(&mut app);
let Some(Modal::Picker { kind, picker }) = &app.modal else { panic!("Esc closed it") };
- assert!(matches!(kind, PickerKind::Commands));
+ assert!(matches!(kind, PickerKind::Commands), "{s}");
assert_eq!(picker.current_id().as_deref(), Some("cmd:theme"));
+ assert_eq!(picker.screen_area.get(), at, "back in the palette's place");
+ }
+
+ // ── tabs ──
+
+ /// The launcher's tab row: ↓ past the list's last row goes onto it; there ←/→ open the next
+ /// tab (round from the last to the first), ↑ goes back to the list, and a key typed searches
+ /// the tab chosen. The panel keeps its size from tab to tab.
+ #[test]
+ fn down_past_the_list_goes_onto_the_tabs_and_arrows_switch_them() {
+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
+ // (A tab opened fetches what it lists, as it does when typed.)
+ let rt = tokio::runtime::Runtime::new().unwrap();
+ let _in = rt.enter();
+ let mut app = app();
+ let key = |app: &mut App, code: KeyCode| crate::input::modal_key(app, KeyEvent::new(code, KeyModifiers::NONE));
+ let now =|app: &App| match &app.modal { Some(Modal::Picker { kind, picker }) => (kind.clone(), picker.on_tabs, picker.query.clone()), _ => panic!("closed") };
+ crate::input::run(&mut app, "open");
+ screen(&mut app);
+ let (rows, at) = match &app.modal { Some(Modal::Picker { picker, .. }) => (picker.visible.len(), picker.screen_area.get()), _ => panic!("no panel") };
+ // (As many ↓ as rows and one more: past the last row, onto the tabs; another stays there.)
+ for _ in 0..=rows + 1 { key(&mut app, KeyCode::Down) }
+ assert!(now(&app).1, "on the tabs");
+ let s = screen(&mut app);
+ assert!(s.contains("← → switch") && s.contains("harnesses"), "{s}");
+ key(&mut app, KeyCode::Right);
+ let (kind, tabs, query) = now(&app);
+ assert!(matches!(kind, PickerKind::Palette) && tabs && query == ">", "{kind:?} {query}");
+ key(&mut app, KeyCode::Right); key(&mut app, KeyCode::Right);
+ assert!(matches!(now(&app).0, PickerKind::Projects));
+ for _ in 0..3 { key(&mut app, KeyCode::Left) }
+ assert!(matches!(now(&app).0, PickerKind::Open { .. }) && now(&app).2.is_empty());
+ key(&mut app, KeyCode::Left);
+ assert!(matches!(now(&app).0, PickerKind::Help), "round to the last tab");
+ screen(&mut app);
+ assert_eq!(match &app.modal { Some(Modal::Picker { picker, .. }) => picker.screen_area.get(), _ => panic!() }, at, "the same size on every tab");
+ key(&mut app, KeyCode::Right);
+ key(&mut app, KeyCode::Up);
+ assert!(!now(&app).1, "↑ back to the list");
+ // Typed on the tabs: a search in the tab chosen.
+ for _ in 0..=rows + 1 { key(&mut app, KeyCode::Down) }
+ for _ in 0..3 { key(&mut app, KeyCode::Right) }
+ key(&mut app, KeyCode::Char('w'));
+ let (kind, tabs, query) = now(&app);
+ assert!(matches!(kind, PickerKind::Projects) && !tabs && query == "#w", "{kind:?} {query}");
+ }
+
+ // ── mouse ──
+
+ /// The mouse over a panel's list: the wheel scrolls the list and the chosen row stays chosen;
+ /// the row under the mouse is the one chosen; a key brings the list back to it.
+ #[test]
+ fn the_wheel_scrolls_a_panel_and_the_mouse_over_a_row_chooses_it() {
+ use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseEvent, MouseEventKind};
+ let mut app = app();
+ crate::commands::execute_bound(&mut app, "choose-command");
+ screen(&mut app);
+ let state = |app: &App| match &app.modal { Some(Modal::Picker { picker, .. }) => (picker.cursor, picker.scroll, picker.list_area.get(), picker.row_at.clone()), _ => panic!("closed") };
+ let (cursor, scroll, list, _) = state(&app);
+ let mouse = |app: &mut App, kind: MouseEventKind, row: u16| crate::input::handle(app, Event::Mouse(MouseEvent { kind, column: list.x + 4, row, modifiers: KeyModifiers::NONE }));
+ assert!(app.wants_motion(), "a panel asks for the mouse's moves");
+ for _ in 0..3 { mouse(&mut app, MouseEventKind::ScrollDown, list.y + 2) }
+ screen(&mut app);
+ let (now, scrolled, _, rows) = state(&app);
+ assert_eq!(now, cursor, "the wheel does not choose");
+ assert!(scrolled > scroll, "the list scrolled: {scroll} → {scrolled}");
+ // Over a row: that row is chosen, and the list stays where the wheel left it.
+ let (y, vi) = rows[3];
+ mouse(&mut app, MouseEventKind::Moved, y);
+ screen(&mut app);
+ let (now, still, _, _) = state(&app);
+ assert_eq!((now, still), (vi, scrolled), "the row under the mouse, the list where it was");
+ // A key: the list follows the cursor again.
+ for _ in 0..40 { crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)) }
+ screen(&mut app);
+ assert_eq!(state(&app).1, 0, "back at the top with the cursor");
+ }
+
+ /// One click on a panel's row runs it (the mouse over it chose it already): "tmux commands…"
+ /// opens tmux's, grouped, in the same panel; Esc comes back to hn's, on that row.
+ #[test]
+ fn one_click_runs_a_row_and_tmux_commands_open_behind_their_row() {
+ use crossterm::event::{Event, KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind};
+ let mut app = app();
+ crate::commands::execute_bound(&mut app, "choose-command");
+ screen(&mut app);
+ let picker = |app: &App| match &app.modal { Some(Modal::Picker { kind, picker }) => (kind.clone(), picker.theme_in.clone(), picker.current_id(), picker.row_at.clone(), picker.list_area.get()), _ => panic!("closed") };
+ // To the row, by keys (it may be below the fold), then one click on it.
+ for c in "tmux".chars() { crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Char(c), KeyModifiers::NONE)) }
+ screen(&mut app);
+ let (_, _, at, rows, list) = picker(&app);
+ assert_eq!(at.as_deref(), Some("cmd:tmux-commands"), "the row first for `tmux`");
+ let y = rows.iter().find(|(_, vi)| match &app.modal { Some(Modal::Picker { picker, .. }) => picker.rows[picker.visible[*vi].0].id == "cmd:tmux-commands", _ => false }).unwrap().0;
+ crate::input::handle(&mut app, Event::Mouse(MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: list.x + 4, row: y, modifiers: KeyModifiers::NONE }));
+ let s = screen(&mut app);
+ let (kind, inside, _, _, _) = picker(&app);
+ assert!(matches!(kind, PickerKind::Commands) && inside.as_deref() == Some("tmux"), "one click opened it");
+ assert!(s.contains("tmux commands") && s.contains("tmux · Windows") && !s.contains("New harness"), "{s}");
+ crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
+ let (kind, inside, at, _, _) = picker(&app);
+ assert!(matches!(kind, PickerKind::Commands) && inside.is_none() && at.as_deref() == Some("cmd:tmux-commands"), "Esc back to hn's, on its row");
+ }
+
+ /// A harness moved onto a model: the model list closes, the status line says it.
+ #[test]
+ fn a_model_switched_closes_the_model_list() {
+ let mut app = app();
+ crate::input::run(&mut app, "models");
+ assert!(matches!(app.modal, Some(Modal::Picker { kind: PickerKind::Models, .. })));
+ crate::models::on_retarget(&mut app, "qwen3-coder", false, Ok(serde_json::json!({})));
+ assert!(app.modal.is_none(), "closed");
+ assert!(app.toast.as_ref().is_some_and(|t| format!("{t:?}").contains("qwen3-coder")), "{:?}", app.toast);
}
// ── keys ──