The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
hn: Keybinds is its own panel — the prefix stays, a command's key after it changes
Timc1e126cf85f9
diff --git a/tui/src/config.rs b/tui/src/config.rsindex c199bbe6a..9e40c0be5 100644--- a/tui/src/config.rs+++ b/tui/src/config.rs@@ -228,14 +228,18 @@ pub fn path() -> PathBuf {/// Read the file and fold its switches into the environment (the environment wins).pub fn load() -> Config {+ let Ok(text) = std::fs::read_to_string(path()) else { return Config::default() };+ // SAFETY: called from `main` before the async runtime (or any other thread) exists.+ read(&text, |name, value| { if std::env::var(name).is_err() { unsafe { std::env::set_var(name, value) } } })+}++/// The file's [text] as [load] reads it, its switches handed to [setenv].+fn read(text: &str, setenv: impl Fn(&str, &str)) -> Config {let mut config = Config::default();- let Ok(text) = std::fs::read_to_string(path()) else { return config };let value: toml::Value = match text.parse() {Ok(v) => v,Err(error) => { config.problems.push(format!("tui.toml: {}", error.to_string().lines().next().unwrap_or(""))); return config }};- // SAFETY: called from `main` before the async runtime (or any other thread) exists.- let setenv = |name: &str, value: &str| { if std::env::var(name).is_err() { unsafe { std::env::set_var(name, value) } } };if let Some(p) = value.get("prefix").and_then(|v| v.as_str()) {match crate::keys::parse(p) { Ok(c) => { config.prefix = c; config.prefix_set = true } Err(e) => config.problems.push(format!("tui.toml prefix: {e}")) }}@@ -281,24 +285,12 @@ fn sets(line: &str, key: &str) -> bool {rest.is_some_and(|r| r.trim_start().starts_with('='))}-/// [text] with the top-level `key = "value"` set ([value] None: taken out), the rest as written.-fn with_top(text: &str, key: &str, value: Option<&str>) -> String {- let mut lines: Vec<String> = text.lines().map(str::to_string).collect();- let end = lines.iter().position(|l| is_section_header(l.trim())).unwrap_or(lines.len());- let line = value.map(|v| format!("{key} = {}", toml_str(v)));- match (lines[..end].iter().position(|l| sets(l, key)), line) {- (Some(i), Some(l)) => lines[i] = l,- (Some(i), None) => { lines.remove(i); }- (None, Some(l)) => {- // After the top's last setting (before the blank line that ends it).- let at = lines[..end].iter().rposition(|l| !l.trim().is_empty()).map(|i| i + 1).unwrap_or(0);- lines.insert(at, l);- }- (None, None) => {}- }- let mut out = lines.join("\n");- out.push('\n');- out+/// The table [line] opens (`[ prefix_keys ] # mine` opens `prefix_keys`), if it is a header.+fn table_of(line: &str) -> Option<&str> {+ let rest = line.trim_start().strip_prefix('[')?;+ let (name, after) = rest.split_once(']')?;+ let after = after.trim_start();+ (after.is_empty() || after.starts_with('#')).then(|| name.trim())}/// [text] with `"entry" = "value"` in [table] (made when there is none), the rest as written.@@ -306,9 +298,9 @@ fn with_entry(text: &str, table: &str, entry: &str, value: &str) -> String {let mut lines: Vec<String> = text.lines().map(str::to_string).collect();let line = format!("{} = {}", toml_str(entry), toml_str(value));let header = format!("[{table}]");- match lines.iter().position(|l| l.trim() == header) {+ match lines.iter().position(|l| table_of(l) == Some(table)) {Some(h) => {- let end = lines[h + 1..].iter().position(|l| is_section_header(l.trim())).map(|i| h + 1 + i).unwrap_or(lines.len());+ let end = lines[h + 1..].iter().position(|l| table_of(l).is_some() || is_section_header(l.trim())).map(|i| h + 1 + i).unwrap_or(lines.len());match lines[h + 1..end].iter().position(|l| sets(l, entry)) {Some(i) => lines[h + 1 + i] = line,None => { let at = lines[h + 1..end].iter().rposition(|l| !l.trim().is_empty()).map(|i| h + 2 + i).unwrap_or(h + 1); lines.insert(at, line) }@@ -332,9 +324,6 @@ fn rewrite(change: impl FnOnce(&str) -> String) -> std::io::Result<()> {std::fs::write(p, change(&existing))}-/// `prefix` / `prefix2` in tui.toml ([value] None: taken out).-pub fn write_top(key: &str, value: Option<&str>) -> std::io::Result<()> { rewrite(|t| with_top(t, key, value)) }-/// One key after the prefix in tui.toml's `[prefix_keys]`: its command, or "none".pub fn write_prefix_key(key: &str, command: &str) -> std::io::Result<()> { rewrite(|t| with_entry(t, "prefix_keys", key, command)) }@@ -550,27 +539,45 @@ mod tests {// ── keys ──- /// The prefix and a command's key go into tui.toml as the panel sets them: the top's- /// `prefix` replaced (or added, before the first table), `[prefix_keys]` made or added to,- /// every other line as it was.+ /// A command's key goes into tui.toml as the panel sets it: `[prefix_keys]` made or added+ /// to, every other line as it was — and read back at start as written.#[test]fn keys_chosen_in_the_panel_are_written_into_tui_toml() {- let text = "# mine\nprefix = \"D-b\"\n\n[look]\nfocus = \"line\"\n";- let t = with_top(text, "prefix", Some("C-a"));- assert_eq!(t, "# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n");- let t = with_top(&t, "prefix2", Some("C-b"));- assert_eq!(t, "# mine\nprefix = \"C-a\"\nprefix2 = \"C-b\"\n\n[look]\nfocus = \"line\"\n");- assert_eq!(with_top(&t, "prefix2", None), "# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n");- let t = with_entry(&t, "prefix_keys", "h", "new-harness");+ let text = "# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n";+ let t = with_entry(text, "prefix_keys", "h", "new-harness");assert!(t.ends_with("focus = \"line\"\n\n[prefix_keys]\n\"h\" = \"new-harness\"\n"), "{t}");let t = with_entry(&t, "prefix_keys", "N", "none");let t = with_entry(&t, "prefix_keys", "h", "kill-pane");+ assert!(t.starts_with("# mine\nprefix = \"C-a\"\n\n[look]\nfocus = \"line\"\n"), "{t}");assert!(t.ends_with("[prefix_keys]\n\"h\" = \"kill-pane\"\n\"N\" = \"none\"\n"), "{t}");// A key that is a quote itself.assert!(with_entry("", "prefix_keys", "\"", "split-window").contains("\"\\\"\" = \"split-window\""));- // And read back as written.- let v: toml::Value = t.parse().unwrap();- assert_eq!(v["prefix"].as_str(), Some("C-a"));- assert_eq!(v["prefix_keys"]["h"].as_str(), Some("kill-pane"));+ // And read back as the start reads it: the prefix, and each key with its command (none: unbound).+ let c = read(&t, |_, _| {});+ assert!(c.problems.is_empty(), "{:?}", c.problems);+ assert_eq!(crate::keys::name(&c.prefix), "C-a");+ let mut keys: Vec<(String, Option<String>)> = c.prefix_keys.iter().map(|(k, v)| (crate::keys::name(k), v.clone())).collect();+ keys.sort();+ assert_eq!(keys, [("N".to_string(), None), ("h".to_string(), Some("kill-pane".to_string()))]);+ }++ /// `[prefix_keys]` is found however its header is written — spaced, or with a comment after+ /// it — so a second table (which TOML refuses) is never added.+ #[test]+ fn the_prefix_keys_header_is_found_spaced_or_commented() {+ for header in ["[ prefix_keys ]", "[prefix_keys] # mine", " [ prefix_keys ] # mine"] {+ let text = format!("{header}\n\"h\" = \"new-harness\"\n\n[look] # the look\nfocus = \"line\"\n");+ let t = with_entry(&text, "prefix_keys", "n", "none");+ assert_eq!(t.matches("prefix_keys").count(), 1, "{t}");+ assert_eq!(t, format!("{header}\n\"h\" = \"new-harness\"\n\"n\" = \"none\"\n\n[look] # the look\nfocus = \"line\"\n"));+ let c = read(&t, |_, _| {});+ assert!(c.problems.is_empty(), "{:?}", c.problems);+ assert_eq!(c.prefix_keys.len(), 2);+ let t = with_entry(&t, "prefix_keys", "h", "kill-pane");+ assert!(t.contains("\"h\" = \"kill-pane\"\n\"n\" = \"none\"\n\n[look]"), "{t}");+ }+ // (Another table whose name only starts the same is not it.)+ let t = with_entry("[prefix_keys_old]\n\"h\" = \"x\"\n", "prefix_keys", "n", "none");+ assert!(t.ends_with("\n[prefix_keys]\n\"n\" = \"none\"\n"), "{t}");}}diff --git a/tui/src/input.rs b/tui/src/input.rsindex d69f9a25e..6851912bb 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -684,6 +684,8 @@ 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")] }+ // ── 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")] }PickerKind::Store => {let catalog = app.dsh.get(&app.fleet.local_id).cloned().unwrap_or_default();@@ -842,15 +844,8 @@ pub fn run(app: &mut App, command: &str) {"help" => launch(app, "?", Filter::All),"layout" => picker(app, PickerKind::Layout, "layout", ""),"theme" | "appearance" => picker(app, PickerKind::Theme, "Appearance", "Search appearance"),- // ── keys ── Keybinds: Appearance, opened at its keys (Esc: the other settings).- "keybinds" => {- picker(app, PickerKind::Theme, "Appearance", "Search appearance");- if let Some(Modal::Picker { kind, mut picker }) = app.modal.take() {- crate::settings::open_section(app, &mut picker, "keys");- picker.vset(0, 1);- app.modal = Some(Modal::Picker { kind, picker });- }- }+ // ── keys ── Keybinds: a panel of its own (from the command list it opens in place).+ "keybinds" => picker(app, PickerKind::Keybinds, "Keybinds", "Search keybinds"),"commands" => picker(app, PickerKind::Commands, "Commands", "Type a command — appearance, new, layout, models…"),"store" => launch(app, "*", Filter::All),"new" => crate::new_harness::open(app, None, None),@@ -1069,7 +1064,7 @@ pub fn refill(app: &mut App) {if let Some(Modal::Picker { kind, mut picker }) = app.modal.take() {let was = picker.current_id();// (The settings panel changes only by your keys: a refresh would step out of its section.)- if !matches!(kind, PickerKind::Route { .. } | PickerKind::Palette | PickerKind::Help | PickerKind::Layout | PickerKind::Theme | PickerKind::Commands) { fill(app, &kind, &mut picker) }+ if !matches!(kind, PickerKind::Route { .. } | PickerKind::Palette | PickerKind::Help | PickerKind::Layout | PickerKind::Theme | PickerKind::Commands | PickerKind::Keybinds) { fill(app, &kind, &mut picker) }// (The cursor put on another row by the list, not by a key: a moment before it answers.)if was.is_some() && picker.current_id() != was { picker.landed = Some(Instant::now()) }app.modal = Some(Modal::Picker { kind, picker });@@ -2065,6 +2060,12 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: 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");+ app.modal = Some(Modal::Picker { kind: PickerKind::Commands, picker });+ return;+ }match key.code {KeyCode::Esc => { SPLIT.with(|s| s.set(None)); return }KeyCode::Char('c' | 'g' | 'q') if ctrl => { SPLIT.with(|s| s.set(None)); return }@@ -2579,8 +2580,14 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {let keep = |app: &mut App, kind: PickerKind, picker: Picker| app.modal = Some(Modal::Picker { kind, picker });// A list of keys, buffers, commands or text: only Enter picks — the harness lists' keys (C-v// beside, C-x below, M-p pause …) do nothing here, as keys fzf has no action for.- if choice != Choice::Enter && matches!(kind, PickerKind::Keys | PickerKind::Buffers | PickerKind::Palette | PickerKind::Commands | PickerKind::Help | PickerKind::Messages | PickerKind::Output { .. }) { return keep(app, kind, picker) }+ if choice != Choice::Enter && matches!(kind, PickerKind::Keys | PickerKind::Buffers | PickerKind::Palette | PickerKind::Commands | PickerKind::Keybinds | PickerKind::Help | PickerKind::Messages | PickerKind::Output { .. }) { return keep(app, kind, picker) }match kind.clone() {+ // ── keys ── Enter on a command: the next key pressed is its key; on the prefix, where it is set.+ PickerKind::Keybinds => {+ let (knob, value) = id.as_deref().map(|id| id.split_once(':').unwrap_or((id, ""))).unwrap_or_default();+ if let Some(msg) = crate::settings::set_key(app, knob, value) { picker.say(msg) }+ return keep(app, kind, picker);+ }PickerKind::Open { .. } if id.as_deref().map(|i| i.starts_with("session:")).unwrap_or(false) => {let sid = id.as_deref().and_then(|i| i.strip_prefix("session:")).and_then(|n| n.parse().ok()).unwrap_or(app.session_id);SPLIT.with(|s| s.set(None));@@ -2722,8 +2729,7 @@ fn choose(app: &mut App, kind: PickerKind, mut picker: Picker, choice: Choice) {if let Some(section) = under {// Inside a section: Enter sets that option (and the ● moves to it).if let Some((knob, value)) = id.split_once(':') {- // (The prefix is a key, not a look: tui.toml's top, not its [look].)- let msg = crate::settings::set_key(app, knob, value).unwrap_or_else(|| app.set_look(knob, value));+ let msg = app.set_look(knob, value);picker.say(msg);picker.set_rows(modal::theme_options(app, §ion));// (A switch — Dim other panes — is the same row turned over.)@@ -2748,6 +2754,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:keybinds" {+ // ── keys ── (in this same panel too; Esc comes back here)+ crate::settings::into_keybinds(app, &mut picker);+ return keep(app, PickerKind::Keybinds, picker);} else if let Some(view) = id.strip_prefix("cmd:").and_then(crate::devices::View::of) {// ── machines & devices ── (in this same panel too; Esc comes back here)return crate::devices::from_commands(app, picker, view);diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex 3721f5c52..f1d3e31d4 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -49,6 +49,8 @@ pub enum PickerKind {Theme,/// C-b Enter: every command by name, in the settings panel — type a few letters, Enter runs it.Commands,+ /// Keybinds: the prefix (fixed) and each command's key after it — Enter on one changes it.+ Keybinds,/// A task routed to a harness; [voice]: the dial's spoken task it answers.Route { text: String, voice: Option<String> },/// `show-messages`, `list-keys`, `choose-buffer`.@@ -199,7 +201,8 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("equalize", "Equalize Panes", "⌥=", "", "Panes"),("pane-tab", "Move Pane to New Swarm", "", "", "Panes"),("find", "Find in Pane…", "⌥⇧F", "search this pane's history", "Panes"),- ("copy-mode", "Copy Mode", "⌥V", "select and copy with the keyboard", "Panes"),+ // (Not "keyboard": `keyb` is Keybinds.)+ ("copy-mode", "Copy Mode", "⌥V", "move over the pane's text, select and copy", "Panes"),("machines", "Machines", "⌥M", "", "Machines"),("store", "Harness Store", "⌥S", "", "Machines"),// ── machines & devices ──@@ -208,7 +211,7 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("devices", "Machines & devices…", "", "this computer's password, your machines, links, add a machine", "Machines"),// (hn itself: how it looks, its keys, and closing it.)("theme", "Appearance…", "", "theme, status bar, borders, focus, layout — settings", "Settings & help"),- ("keybinds", "Keybinds…", "", "the prefix and every command's key, grouped — Enter changes one", "Settings & help"),+ ("keybinds", "Keybinds…", "", "every command's key after the prefix — Enter changes one", "Settings & help"),("help", "Quick help", "⌥/", "what the search box can do: > @ # : * ?", "Settings & help"),("quit", "Close hn", "⌥Q", "your harnesses keep running", "Settings & help"),];@@ -558,22 +561,15 @@ pub const KEYBINDS: &[(&str, &str, &str)] = &[("Detach", "detach-client", "General"),];-/// The Keybinds page: the prefix and the second one, then each command with its key now (or —).-/// Enter on one: the next key you press is it.+/// The Keybinds panel: the prefix (fixed here: tui.toml's), then each command with its key now+/// (or —). Enter on one: the next key you press is it.pub fn keybind_rows(app: &App) -> Vec<Row> {let prefix = crate::keys::name(&app.keymap.prefix);- let key_row = |id: String, title: &str, key: String, hint: &str, group: &str| Row::new(id, title)- .detail(vec![span(hint, fg(theme::MUTED))]).right(key).group(group);- let mut rows = vec![- key_row("prefix:press".into(), "Prefix", prefix.clone(), "the key before every command", "Prefix"),- key_row("prefix2:press".into(), "Second prefix", app.keymap.prefix2.map(|c| crate::keys::name(&c)).unwrap_or_else(|| "none".into()),- "one more — for a terminal that keeps ⌘ keys (⌫ while choosing: none)", "Prefix"),- ];- rows.extend(KEYBINDS.iter().enumerate().map(|(i, (title, runs, group))| {+ let fixed = Row::new("prefix", "Prefix").detail(vec![span("the key before every command — set in tui.toml", fg(theme::MUTED))]).right(format!("{prefix} (fixed)"));+ std::iter::once(fixed).chain(KEYBINDS.iter().enumerate().map(|(i, (title, runs, group))| {let key = key_running(app, runs).map(|c| format!("{prefix} {}", crate::keys::name(&c))).unwrap_or_else(|| "—".into());- key_row(format!("key:{i}"), title, key, "", group)- }));- rows+ Row::new(format!("key:{i}"), *title).right(key).group(*group)+ })).collect()}/// The tmux command one of hn's own commands is on a key as.@@ -654,8 +650,7 @@ pub fn theme_sections(app: &App) -> Vec<Row> {// ── status bar ──sec("section:bar", "Status bar", "status_bar", status_bar_of(app)),sec("section:boxes", "Borders", "every pane its own box", if border_style_of(app) == "box" { "on" } else { "off" }),- // ── keys ──- sec("section:keys", "Keybinds", "the prefix, and every command's key", &crate::keys::name(&app.keymap.prefix)),+ // (Keys are Keybinds', a panel of their own in Commands.)]}@@ -692,8 +687,6 @@ pub fn theme_options(app: &App, section: &str) -> Vec<Row> {let dim = Row::new(if on { "dim:off" } else { "dim:on" }, "Dim other panes").lead(lead(on)).detail(vec![span(if on { "on" } else { "the panes you are not in, a little quieter" }, fg(theme::MUTED))]);styles.chain(std::iter::once(dim)).collect() }- // ── keys ──- "keys" => keybind_rows(app),"theme" => {let cur = o.get("@hn-theme", "", None).unwrap_or_default();// First, no theme: the terminal's own colours.@@ -799,9 +792,7 @@ mod theme_row_tests {let ids: Vec<&str> = rows.iter().map(|r| r.id.as_str()).collect();assert_eq!(ids, vec!["section:status", "section:focus", "section:theme",// ── status bar ──- "section:bar", "section:boxes",- // ── keys ──- "section:keys"]);+ "section:bar", "section:boxes"]);// Each section shows its current value and opens onto a non-empty option list.assert!(rows.iter().all(|r| !r.right.is_empty()), "each section shows a value");for r in &rows {@@ -848,49 +839,119 @@ mod theme_row_tests {// ── keys ──- /// Keybinds: the prefixes first, then the commands grouped with their keys now. A key chosen- /// there is the command's (its old key given up, the command in full kept); Esc changes- /// nothing; the prefix is the key pressed; ⌫ leaves no second prefix.+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};++ /// A key pressed while a command's key is being chosen; what was said (no panel open: the+ /// client's message).+ fn press(app: &mut App, code: KeyCode, mods: KeyModifiers) -> String {+ crate::settings::captured(app, KeyEvent::new(code, mods));+ app.toast.as_ref().map(|t| t.0.clone()).unwrap_or_default()+ }++ /// What the key after the prefix runs now.+ fn runs(app: &App, code: KeyCode, mods: KeyModifiers) -> Option<String> { app.keymap.prefix_command(&crate::keys::of(&KeyEvent::new(code, mods))).map(|b| b.command.clone()) }++ /// Enter on [title]'s Keybinds row: its key is the next one pressed.+ fn change(app: &mut App, title: &str) -> Option<String> {+ let i = KEYBINDS.iter().position(|k| k.0 == title).unwrap().to_string();+ crate::settings::set_key(app, "key", &i)+ }++ fn right(app: &App, title: &str) -> String { keybind_rows(app).into_iter().find(|r| r.label == title).map(|r| r.right).unwrap() }++ /// Keybinds: the prefix first — fixed, information only — then the commands grouped with+ /// their keys now. Appearance has no keys section.#[test]- fn keybinds_show_every_key_grouped_and_change_one() {- use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+ fn keybinds_are_the_fixed_prefix_then_every_command_grouped() {let mut app = app();let rows = keybind_rows(&app);- assert_eq!((rows[0].id.as_str(), rows[1].id.as_str()), ("prefix:press", "prefix2:press"));+ assert_eq!((rows[0].id.as_str(), rows[0].label.as_str(), rows[0].right.as_str()), ("prefix", "Prefix", "C-b (fixed)"));+ assert!(rows.iter().all(|r| !r.id.starts_with("prefix2")), "no second prefix row");let mut groups: Vec<String> = Vec::new();for g in rows.iter().filter_map(|r| r.group.clone()) { if groups.last() != Some(&g) { groups.push(g) } }- assert_eq!(groups, ["Prefix", "Navigation", "Panes", "Swarms (windows)", "Harnesses", "General"]);- let right = |app: &App, title: &str| keybind_rows(app).into_iter().find(|r| r.label == title).map(|r| r.right).unwrap();+ assert_eq!(groups, ["Navigation", "Panes", "Swarms (windows)", "Harnesses", "General"]);assert_eq!(right(&app, "Split right"), "C-b %");- let press = |app: &mut App, code: KeyCode, mods: KeyModifiers| crate::settings::captured(app, KeyEvent::new(code, mods));- let chord = |code: KeyCode| crate::keys::of(&KeyEvent::new(code, KeyModifiers::NONE));- // Split right onto h: % is free again.- let i = KEYBINDS.iter().position(|k| k.0 == "Split right").unwrap().to_string();- assert!(crate::settings::set_key(&mut app, "key", &i).is_some_and(|s| s.contains("Press")));- press(&mut app, KeyCode::Char('h'), KeyModifiers::NONE);- assert_eq!(app.keymap.prefix_command(&chord(KeyCode::Char('h'))).map(|b| b.command.as_str()), Some("split-window -h"));- assert!(app.keymap.prefix_command(&chord(KeyCode::Char('%'))).is_none());+ // Enter on the prefix: said where it is set, nothing waits for a key.+ assert!(crate::settings::set_key(&mut app, "prefix", "").is_some_and(|s| s.contains("tui.toml")));+ assert!(app.capturing.is_none());+ assert!(theme_sections(&app).iter().all(|r| r.id != "section:keys") && theme_options(&app, "keys").is_empty());+ }++ /// A key chosen is the command's: its old key given up, the command in full kept (Rename+ /// swarm still asks for the name).+ #[test]+ fn a_key_chosen_frees_the_old_one_and_keeps_the_full_command() {+ let mut app = app();+ assert!(change(&mut app, "Split right").is_some_and(|s| s == "Split right: press a key · Esc cancels"));+ assert!(press(&mut app, KeyCode::Char('h'), KeyModifiers::NONE).starts_with("Split right: C-b h"));+ assert_eq!(runs(&app, KeyCode::Char('h'), KeyModifiers::NONE).as_deref(), Some("split-window -h"));+ assert_eq!(runs(&app, KeyCode::Char('%'), KeyModifiers::NONE), None);assert_eq!(right(&app, "Split right"), "C-b h");- // Rename swarm keeps its prompt on its new key.- let i = KEYBINDS.iter().position(|k| k.0 == "Rename swarm…").unwrap().to_string();- let _ = crate::settings::set_key(&mut app, "key", &i);- press(&mut app, KeyCode::Char('R'), KeyModifiers::SHIFT);- assert!(app.keymap.prefix_command(&crate::keys::of(&KeyEvent::new(KeyCode::Char('R'), KeyModifiers::SHIFT))).is_some_and(|b| b.command.contains("command-prompt")));- // Esc: nothing changes.- let _ = crate::settings::set_key(&mut app, "key", &i);- press(&mut app, KeyCode::Esc, KeyModifiers::NONE);assert!(app.capturing.is_none());- assert_eq!(app.keymap.prefix_command(&chord(KeyCode::Char('h'))).map(|b| b.command.as_str()), Some("split-window -h"));- // The prefix, then no second prefix.- let _ = crate::settings::set_key(&mut app, "prefix", "press");- press(&mut app, KeyCode::Char('a'), KeyModifiers::CONTROL);- assert_eq!(crate::keys::name(&app.keymap.prefix), "C-a");- let _ = crate::settings::set_key(&mut app, "prefix2", "press");- press(&mut app, KeyCode::Char('b'), KeyModifiers::CONTROL);- assert_eq!(app.keymap.prefix2.map(|c| crate::keys::name(&c)).as_deref(), Some("C-b"));- let _ = crate::settings::set_key(&mut app, "prefix2", "press");- press(&mut app, KeyCode::Backspace, KeyModifiers::NONE);- assert_eq!(app.keymap.prefix2, None);+ let _ = change(&mut app, "Rename swarm…");+ press(&mut app, KeyCode::F(5), KeyModifiers::NONE);+ assert!(runs(&app, KeyCode::F(5), KeyModifiers::NONE).is_some_and(|c| c.contains("command-prompt") && c.contains("rename-window")));+ assert_eq!(runs(&app, KeyCode::Char(','), KeyModifiers::NONE), None);+ }++ /// A key that runs another command is replaced only on its second press: the first says+ /// what it runs.+ #[test]+ fn a_key_in_use_needs_a_second_press() {+ let mut app = app();+ let _ = change(&mut app, "Split right");+ assert_eq!(press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE), "C-b n is Next swarm — n again to replace · Esc to keep");+ assert!(app.capturing.is_some(), "still waiting");+ assert_eq!(runs(&app, KeyCode::Char('n'), KeyModifiers::NONE).as_deref(), Some("next-window"));+ assert_eq!(runs(&app, KeyCode::Char('%'), KeyModifiers::NONE).as_deref(), Some("split-window -h"));+ assert!(press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE).starts_with("Split right: C-b n"));+ assert!(app.capturing.is_none());+ assert_eq!(runs(&app, KeyCode::Char('n'), KeyModifiers::NONE).as_deref(), Some("split-window -h"));+ assert_ne!(right(&app, "Next swarm"), "C-b n");+ // A command with no title of its own is named by its command.+ let _ = change(&mut app, "Split down");+ assert!(press(&mut app, KeyCode::Char('t'), KeyModifiers::NONE).starts_with("C-b t is clock-mode — t again"));+ }++ /// Esc — or any other key, once a key in use is named — keeps every key as it was.+ #[test]+ fn esc_or_another_key_keeps_every_key() {+ let mut app = app();+ let _ = change(&mut app, "Split right");+ assert_eq!(press(&mut app, KeyCode::Esc, KeyModifiers::NONE), "Unchanged");+ assert!(app.capturing.is_none());+ for other in [KeyCode::Esc, KeyCode::Char('y')] {+ let _ = change(&mut app, "Split right");+ press(&mut app, KeyCode::Char('n'), KeyModifiers::NONE);+ assert_eq!(press(&mut app, other, KeyModifiers::NONE), "Unchanged");+ assert!(app.capturing.is_none());+ assert_eq!(runs(&app, KeyCode::Char('n'), KeyModifiers::NONE).as_deref(), Some("next-window"));+ assert_eq!(runs(&app, KeyCode::Char('%'), KeyModifiers::NONE).as_deref(), Some("split-window -h"));+ assert_eq!(runs(&app, KeyCode::Char('y'), KeyModifiers::NONE), None);+ }+ }++ /// The prefix (and the second one), Enter, and Esc with a modifier are refused, each with+ /// why; the panel keeps waiting for a key.+ #[test]+ fn the_prefix_enter_and_a_modified_esc_are_refused() {+ let mut app = app();+ app.keymap.prefix2 = Some(crate::keys::parse("C-a").unwrap());+ let _ = change(&mut app, "Split right");+ let before = app.keymap.prefix_table.clone();+ for (code, mods, why) in [+ (KeyCode::Char('b'), KeyModifiers::CONTROL, "C-b is the prefix — press another key · Esc cancels"),+ (KeyCode::Char('a'), KeyModifiers::CONTROL, "C-a is the second prefix — press another key · Esc cancels"),+ (KeyCode::Enter, KeyModifiers::NONE, "Enter can not be a key here (C-b Enter is Commands) — press another key · Esc cancels"),+ (KeyCode::Esc, KeyModifiers::ALT, "Esc can not be a key here (it cancels) — press another key · Esc cancels"),+ (KeyCode::Esc, KeyModifiers::CONTROL, "Esc can not be a key here (it cancels) — press another key · Esc cancels"),+ ] {+ assert_eq!(press(&mut app, code, mods), why);+ assert!(app.capturing.is_some(), "still waiting after {why}");+ }+ assert_eq!(app.keymap.prefix_table.len(), before.len());+ assert!(app.keymap.prefix_table.iter().zip(&before).all(|(a, b)| a.chord == b.chord && a.command == b.command), "nothing rebound");+ assert_eq!(press(&mut app, KeyCode::Esc, KeyModifiers::NONE), "Unchanged");}// ── status bar ──diff --git a/tui/src/settings.rs b/tui/src/settings.rsindex 0e31073bd..0f513c41b 100644--- a/tui/src/settings.rs+++ b/tui/src/settings.rs@@ -22,7 +22,7 @@ pub fn set_fzf_lists(on: bool) { FZF_LISTS.store(on, std::sync::atomic::Ordering/// The lists drawn as this panel rather than as fzf's full-screen list: every one, unless/// `@hn-lists fzf` asks for fzf's.pub fn is_panel(kind: &PickerKind) -> bool {- matches!(kind, PickerKind::Theme | PickerKind::Commands | PickerKind::Devices(_) | PickerKind::Models) || !FZF_LISTS.load(std::sync::atomic::Ordering::Relaxed)+ matches!(kind, PickerKind::Theme | PickerKind::Commands | PickerKind::Keybinds | PickerKind::Devices(_) | PickerKind::Models) || !FZF_LISTS.load(std::sync::atomic::Ordering::Relaxed)}/// Whether [kind]'s list reads top-down (↑ toward its first row): fzf's under --layout=reverse,@@ -67,8 +67,26 @@ pub fn into_settings(app: &App, picker: &mut Picker) {picker.vset(0, 1);}+// ── keys ──+/// Keybinds chosen in the command list: the same panel lists the keys, and Esc comes back.+pub fn into_keybinds(app: &App, picker: &mut Picker) {+ picker.from_commands = true;+ picker.placeholder = "Search keybinds".into();+ picker.keep_order = true;+ picker.live = false;+ picker.theme_in = None;+ picker.clear_query();+ picker.rows.clear();+ picker.set_rows(crate::modal::keybind_rows(app));+ picker.scroll = 0;+ picker.vset(0, 1);+}+/// Back from the settings to the command list, the cursor on Settings.-pub fn back_to_commands(app: &App, picker: &mut Picker) {+pub fn back_to_commands(app: &App, picker: &mut Picker) { back_to_commands_at(app, picker, "cmd:theme") }++/// Back to the command list, the cursor on [at] (the command that opened the panel).+pub fn back_to_commands_at(app: &App, picker: &mut Picker, at: &str) {picker.from_commands = false;picker.theme_in = None;picker.placeholder = "Type a command — appearance, new, layout, models…".into();@@ -78,45 +96,34 @@ pub fn back_to_commands(app: &App, picker: &mut Picker) {picker.rows.clear();picker.set_rows(crate::modal::command_rows_for(app, false));picker.scroll = 0;- cursor_to(picker, "cmd:theme");+ cursor_to(picker, at);}/// Put the cursor on the row [id] (where the filter shows it).pub fn cursor_to(picker: &mut Picker, id: &str) { picker.select(id) }-// ── keys: the prefix and a command's key, chosen in the panel ────────────────────+// ── keys: a command's key, chosen in the panel ───────────────────────────────────-/// What the next key becomes: the prefix, the second prefix, or [command]'s key after the prefix.+/// What the next key becomes: [command]'s key after the prefix. [pending]: a key that runs+/// another command, pressed once — the same key again replaces it.#[derive(Clone, Debug)]-pub enum Capture { Prefix, Prefix2, Command { command: String, title: String, own: bool } }+pub enum Capture { Command { command: String, title: String, own: bool, pending: Option<crate::keys::Chord> } }-const PRESS: &str = "Press the key you want · Esc cancels";+const PRESS: &str = "press a key · Esc cancels";+const AGAIN: &str = "press another key · Esc cancels";-/// Appearance's Prefix and Second prefix: a key chosen (`C-b`, `none`), or `press` — the next-/// key you press. None: not one of these knobs.+/// A Keybinds row chosen: a command's (`key`, its index) waits for the next key pressed; the+/// prefix's says where it is set. None: not a Keybinds row.pub fn set_key(app: &mut App, knob: &str, value: &str) -> Option<String> {- // A Keybinds row: its command's key is the next key pressed.- if knob == "key" {- let (title, runs, _) = value.parse::<usize>().ok().and_then(|i| crate::modal::KEYBINDS.get(i))?;- app.capturing = Some(Capture::Command { command: runs.to_string(), title: title.to_string(), own: true });- return Some(format!("{}: {PRESS}", title.trim_end_matches('…')));- }- let second = match knob { "prefix" => false, "prefix2" => true, _ => return None };- if value == "press" { app.capturing = Some(if second { Capture::Prefix2 } else { Capture::Prefix }); return Some(PRESS.into()) }- let chord = if value == "none" { None } else { match crate::keys::parse(value) { Ok(c) => Some(c), Err(e) => return Some(e) } };- Some(apply_prefix(app, second, chord))-}--/// The prefix (or the second one, [chord] None: none) set as `set -g prefix` sets it — every-/// hn window takes it — and written to tui.toml.-fn apply_prefix(app: &mut App, second: bool, chord: Option<crate::keys::Chord>) -> String {- let (option, name) = (if second { "prefix2" } else { "prefix" }, chord.map(|c| crate::keys::name(&c)));- let Some(name) = name.or_else(|| second.then(|| "None".to_string())) else { return String::new() };- crate::commands::execute(app, &format!("set -g {option} {}", crate::tmuxconf::quote_word(&name)));- app.server_dirty = true;- let saved = crate::config::write_top(option, (name != "None").then_some(name.as_str()));- let what = if second { "Second prefix" } else { "Prefix" };- match saved { Ok(()) => format!("{what}: {name} — saved to tui.toml"), Err(e) => format!("{what}: {name} — could not write tui.toml: {e}") }+ match knob {+ "key" => {+ let (title, runs, _) = value.parse::<usize>().ok().and_then(|i| crate::modal::KEYBINDS.get(i))?;+ app.capturing = Some(Capture::Command { command: runs.to_string(), title: title.to_string(), own: true, pending: None });+ Some(format!("{}: {PRESS}", title.trim_end_matches('…')))+ }+ "prefix" => Some(format!("The prefix is {} — set `prefix` in tui.toml to change it", crate::keys::name(&app.keymap.prefix))),+ _ => None,+ }}/// Alt-k on a command in the command panel: its key is the next key you press. A command with@@ -128,39 +135,64 @@ pub fn capture_for_row(app: &mut App, picker: &mut Picker) {else { id.strip_prefix("cmd:").and_then(crate::modal::runs_of).map(str::to_string) };let Some(command) = command else { picker.say(format!("{title} can not have a key here: it asks for words")); return };picker.say(format!("{}: {PRESS}", title.trim_end_matches('…')));- app.capturing = Some(Capture::Command { command, title, own: id.starts_with("cmd:") });+ app.capturing = Some(Capture::Command { command, title, own: id.starts_with("cmd:"), pending: None });}-/// The key pressed while waiting ([Capture]): Esc cancels; else it becomes what was asked. What-/// changed is said in the panel, whose rows show it.+/// The key pressed while waiting ([Capture]): Esc cancels; a key that can not be one is refused,+/// and one that runs another command is named first — the same key again replaces it, any other+/// keeps it; else it becomes the command's. What happened is said in the panel, whose rows show it.pub fn captured(app: &mut App, key: crossterm::event::KeyEvent) {- let Some(what) = app.capturing.take() else { return };+ use crossterm::event::KeyCode;+ let Some(Capture::Command { command, title, own, pending }) = app.capturing.take() else { return };let chord = crate::keys::of(&key);- let plain = |code: crossterm::event::KeyCode| key.code == code && key.modifiers.is_empty();- let said = if plain(crossterm::event::KeyCode::Esc) { "Unchanged".to_string() } else {- match what {- Capture::Prefix => apply_prefix(app, false, Some(chord)),- // (⌫: no second prefix.)- Capture::Prefix2 if plain(crossterm::event::KeyCode::Backspace) => apply_prefix(app, true, None),- Capture::Prefix2 => apply_prefix(app, true, Some(chord)),- Capture::Command { command, title, own } => rebind(app, &command, &title, own, chord),+ let name = crate::keys::name(&chord);+ let prefix = crate::keys::name(&app.keymap.prefix);+ let wait = |pending| Some(Capture::Command { command: command.clone(), title: title.clone(), own, pending });+ let (said, next) = if key.code == KeyCode::Esc && key.modifiers.is_empty() { ("Unchanged".to_string(), None) }+ else if let Some(p) = pending { if p == chord { (rebind(app, &command, &title, own, chord), None) } else { ("Unchanged".to_string(), None) } }+ else if chord == app.keymap.prefix { (format!("{name} is the prefix — {AGAIN}"), wait(None)) }+ else if Some(chord) == app.keymap.prefix2 { (format!("{name} is the second prefix — {AGAIN}"), wait(None)) }+ else if key.code == KeyCode::Enter { (format!("Enter can not be a key here ({prefix} Enter is Commands) — {AGAIN}"), wait(None)) }+ else if key.code == KeyCode::Esc { (format!("Esc can not be a key here (it cancels) — {AGAIN}"), wait(None)) }+ else if let Some(other) = app.keymap.prefix_command(&chord).map(|b| b.command.clone()).filter(|c| *c != full_command(app, &command, own)) {+ (format!("{prefix} {name} is {} — {name} again to replace · Esc to keep", running(app, &chord, &other)), wait(Some(chord)))}- };+ else { (rebind(app, &command, &title, own, chord), None) };+ app.capturing = next;// The panel's rows again, with the key as it is now.if let Some(crate::modal::Modal::Picker { kind, picker }) = app.modal.take() {let mut picker = picker;+ let at = picker.current_id();match &kind {- PickerKind::Theme => if let Some(section) = picker.theme_in.clone() { let at = picker.current_id(); picker.set_rows(crate::modal::theme_options(app, §ion)); if let Some(at) = at { cursor_to(&mut picker, &at) } }- else { picker.set_rows(crate::modal::theme_sections(app)) },- PickerKind::Commands => { let at = picker.current_id(); picker.set_rows(crate::modal::command_rows_for(app, !picker.query.is_empty())); if let Some(at) = at { cursor_to(&mut picker, &at) } }+ 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())),_ => {}}+ if let Some(at) = at { cursor_to(&mut picker, &at) }picker.say(said);app.modal = Some(crate::modal::Modal::Picker { kind, picker });} else { app.say(said, theme::MUTED) }app.redraw_all = true;}+/// What [chord] (running [command]) is called: its Keybinds title, else the command itself.+fn running(app: &App, chord: &crate::keys::Chord, command: &str) -> String {+ crate::modal::KEYBINDS.iter().find(|(_, runs, _)| crate::modal::key_running(app, runs).as_ref() == Some(chord))+ .map(|(title, _, _)| title.trim_end_matches('…').to_string()).unwrap_or_else(|| command.to_string())+}++/// [command]'s key now: the one running exactly it — or, for one of hn's own commands, the key+/// the panel shows for it (its command with words after it).+fn current_key(app: &App, command: &str, own: bool) -> Option<crate::keys::Chord> {+ if own { crate::modal::key_running(app, command) } else { app.keymap.prefix_table.iter().find(|b| b.command == command).map(|b| b.chord) }+}++/// What [command]'s key runs in full (a rename still asks for the name) — [command] itself where+/// it has no key.+fn full_command(app: &App, command: &str, own: bool) -> String {+ current_key(app, command, own).and_then(|o| app.keymap.prefix_command(&o)).map(|b| b.command.clone()).unwrap_or_else(|| command.to_string())+}+/// [command] on [chord] after the prefix, and on no other key (a command with two keys, `%` and/// `|`, has the one chosen); whatever the new key ran replaced — all written to tui.toml's/// `[prefix_keys]`.@@ -170,11 +202,8 @@ fn rebind(app: &mut App, command: &str, title: &str, own: bool, chord: crate::kelet key = crate::keys::name(&chord);let was = app.keymap.prefix_command(&chord).map(|b| b.command.clone()).filter(|c| c != command && !c.contains(command));let mut saved = Ok(());- // Its key now: the one running exactly it — or, for one of hn's own commands, the key the- // panel shows for it (its command with words after it).- let old = if own { crate::modal::key_running(app, command) } else { app.keymap.prefix_table.iter().find(|b| b.command == command).map(|b| b.chord) };- // The new key runs what the old one did, in full (a rename still asks for the name).- let full = old.and_then(|o| app.keymap.prefix_command(&o)).map(|b| b.command.clone()).unwrap_or_else(|| command.to_string());+ // The new key runs what the old one did, in full.+ let full = full_command(app, command, own);let olds: Vec<crate::keys::Chord> = app.keymap.prefix_table.iter().filter(|b| b.command == full && b.chord != chord).map(|b| b.chord).collect();for old in olds {app.keymap.unbind(Table::Prefix, &old);@@ -360,8 +389,8 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:// (Commands need no preview: the list takes the width, a row's hint beside its name. A list// that is the whole answer — output, messages, keys — has none either.)// (Keybinds are keys, not a look: no preview; the list takes the width, a key beside each.)- let settings = matches!(kind, PickerKind::Theme) && picker.theme_in.as_deref() != Some("keys");- let side = inner_w >= 64 && (settings || (picker.preview && !matches!(kind, PickerKind::Commands | PickerKind::Theme)));+ let settings = matches!(kind, PickerKind::Theme);+ let side = inner_w >= 64 && (settings || (picker.preview && !matches!(kind, PickerKind::Commands | PickerKind::Theme | PickerKind::Keybinds)));// (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) };@@ -396,6 +425,9 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:PickerKind::Theme if picker.theme_in.is_some() => Some("↑↓ move enter apply ← back esc back"),PickerKind::Theme if picker.from_commands => Some("↑↓ move → open type to search esc back"),PickerKind::Theme => Some("↑↓ move → open type to search esc close"),+ // ── keys ──+ PickerKind::Keybinds if picker.from_commands => Some("↑↓ move enter change type to search esc back"),+ PickerKind::Keybinds => Some("↑↓ move enter change type to search esc close"),_ => None,};match (flash, keys) {@@ -407,13 +439,14 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:}/// The menus, whose footer says their keys (the other lists give that row to their rows).-fn keyed(kind: &PickerKind) -> bool { matches!(kind, PickerKind::Theme | PickerKind::Commands) }+fn keyed(kind: &PickerKind) -> bool { matches!(kind, PickerKind::Theme | PickerKind::Commands | PickerKind::Keybinds) }/// The panel's title: the list's own name (the launcher's for its lists, else what opened it).fn title(app: &App, kind: &PickerKind, picker: &Picker) -> String {match kind {PickerKind::Theme => "Appearance".into(),PickerKind::Commands => "Commands".into(),+ PickerKind::Keybinds => "Keybinds".into(),PickerKind::Devices(view) => view.title().into(),k if crate::modal::is_launcher(k) => capital(&crate::modal::launcher_title(app, k).0),_ => capital(&picker.heading.clone().unwrap_or_else(|| picker.title.clone())),@@ -428,8 +461,6 @@ pub fn section_title(section: &str) -> &'static str {"theme" => "Theme",// ── status bar ──"bar" => "Status bar", "boxes" => "Borders",- // ── keys ──- "keys" => "Keybinds",_ => "",}}diff --git a/tui/src/ui.rs b/tui/src/ui.rsindex 2bac423e5..0b6fa1102 100644--- a/tui/src/ui.rs+++ b/tui/src/ui.rs@@ -3081,6 +3081,70 @@ mod theme_render_tests {assert!(matches!(kind, PickerKind::Commands));assert_eq!(picker.current_id().as_deref(), Some("cmd:theme"));}++ // ── keys ──++ /// Keybinds from the command list: its own panel in the same place — no preview, the+ /// prefix first and fixed — where Enter on a command waits for its key, a key in use is+ /// replaced on its second press, and Esc steps back to the commands.+ #[test]+ fn keybinds_open_from_commands_change_a_key_and_esc_goes_back() {+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+ let mut app = app();+ // (As the client takes a key: a key being waited for goes there first.)+ let key = |app: &mut App, code: KeyCode| {+ let k = KeyEvent::new(code, KeyModifiers::NONE);+ if app.capturing.is_some() { crate::settings::captured(app, k) } else { crate::input::modal_key(app, k) }+ };+ let said = |app: &App| match &app.modal { Some(Modal::Picker { picker, .. }) => picker.flash.as_ref().map(|f| f.0.clone()).unwrap_or_default(), _ => panic!("closed") };+ crate::commands::execute_bound(&mut app, "choose-command");+ screen(&mut app);+ let at = match &app.modal { Some(Modal::Picker { picker, .. }) => picker.screen_area.get(), _ => panic!("no panel") };+ for c in "keyb".chars() { key(&mut app, KeyCode::Char(c)) }+ let Some(Modal::Picker { picker, .. }) = &app.modal else { panic!("closed") };+ assert_eq!(picker.current_id().as_deref(), Some("cmd:keybinds"));+ key(&mut app, KeyCode::Enter);+ let s = screen(&mut app);+ let Some(Modal::Picker { kind, picker }) = &app.modal else { panic!("closed") };+ assert!(matches!(kind, PickerKind::Keybinds) && picker.from_commands);+ assert_eq!(picker.screen_area.get(), at, "the panel stayed where it was");+ assert!(s.contains("Keybinds") && s.contains("Prefix") && s.contains("C-b (fixed)") && s.contains("Split right") && s.contains("Navigation"), "{s}");+ assert!(!s.contains("Preview") && !s.contains("Appearance") && !s.contains("Second prefix"), "{s}");+ // The prefix: information only.+ assert_eq!(picker.current_id().as_deref(), Some("prefix"));+ key(&mut app, KeyCode::Enter);+ assert!(app.capturing.is_none() && said(&app).contains("tui.toml"), "{}", said(&app));+ // Split right onto n (Next swarm's): named first, replaced on the second press.+ if let Some(Modal::Picker { picker, .. }) = &mut app.modal { let i = crate::modal::KEYBINDS.iter().position(|k| k.0 == "Split right").unwrap(); picker.select(&format!("key:{i}")) }+ key(&mut app, KeyCode::Enter);+ assert_eq!(said(&app), "Split right: press a key · Esc cancels");+ key(&mut app, KeyCode::Char('n'));+ assert_eq!(said(&app), "C-b n is Next swarm — n again to replace · Esc to keep");+ key(&mut app, KeyCode::Char('n'));+ assert!(said(&app).starts_with("Split right: C-b n"), "{}", said(&app));+ let s = screen(&mut app);+ assert!(s.lines().any(|l| l.contains("Split right") && l.contains("C-b n")), "the row shows its key now:\n{s}");+ // Esc: back to the commands, the cursor on Keybinds.+ key(&mut app, KeyCode::Esc);+ let Some(Modal::Picker { kind, picker }) = &app.modal else { panic!("Esc closed it") };+ assert!(matches!(kind, PickerKind::Commands));+ assert_eq!(picker.current_id().as_deref(), Some("cmd:keybinds"));+ // Alt-k on a command in the list: the same — a key in use is named first.+ if let Some(Modal::Picker { picker, .. }) = &mut app.modal { picker.select("cmd:split-down") }+ crate::input::modal_key(&mut app, KeyEvent::new(KeyCode::Char('k'), KeyModifiers::ALT));+ assert!(app.capturing.is_some());+ key(&mut app, KeyCode::Char('n'));+ assert!(said(&app).starts_with("C-b n is Split right — n again"), "{}", said(&app));+ key(&mut app, KeyCode::Esc);+ assert_eq!(said(&app), "Unchanged");+ assert_eq!(app.keymap.prefix_command(&crate::keys::parse("n").unwrap()).map(|b| b.command.as_str()), Some("split-window -h"));+ // Opened by name (not from the list), Esc closes it.+ app.modal = None;+ crate::input::run(&mut app, "keybinds");+ assert!(matches!(&app.modal, Some(Modal::Picker { kind: PickerKind::Keybinds, picker }) if !picker.from_commands));+ key(&mut app, KeyCode::Esc);+ assert!(app.modal.is_none());+ }}#[cfg(test)]diff --git a/tui/tests/keybinds.py b/tui/tests/keybinds.pynew file mode 100644index 000000000..74f786485--- /dev/null+++ b/tui/tests/keybinds.py@@ -0,0 +1,134 @@+#!/usr/bin/env python3+"""Keybinds with real hn keys: open it from Commands, put Split right on h, C-b h splits.++Only a private fixture backend, temporary HOME (its own tui.toml) and explicitly named hn/tmux+sockets.+"""+import os+from pathlib import Path+import shlex+import shutil+import socket+import subprocess+import tempfile+import time+import urllib.request++ROOT = Path(__file__).resolve().parents[1]+PORT = int(os.environ.get('HN_KEYBINDS_PORT', '19787'))+assert 19783 <= PORT <= 19789, 'refusing non-test keybinds port'+PREFIX = f'hn-keybinds-{os.getpid()}'+BASE = Path(tempfile.mkdtemp(prefix='hnkb-', dir='/tmp')).resolve()+HN = BASE / 'hn'+shutil.copy2(os.environ.get('HN_KEYBINDS_BINARY', ROOT / 'target/release/harness-tui'), HN)+TMUX = shutil.which('tmux')+assert TMUX+ENV = {k: os.environ[k] for k in ('PATH', 'LANG', 'LC_ALL', 'TZ') if k in os.environ}+ENV.update(HOME=str(BASE), HN_TMPDIR=str(BASE), HN_SOCKET_NAME=PREFIX, PORT=str(PORT),+ TERM='xterm-256color', COLORTERM='truecolor', SHELL='/bin/sh', HARNESS_TUI_DESK='sync',+ HARNESS_TUI_NOTIFY='off', HN_DESKTOP='off', MOCK_DEMO='1', MOCK_RECONNECT='1')+TOML = BASE / '.config' / 'harness' / 'tui.toml'++def hn(*args, ok=True):+ assert PREFIX.startswith('hn-keybinds-')+ p = subprocess.run([str(HN), '-L', PREFIX, '--port', str(PORT), '-f', '/dev/null', *args],+ env=ENV, cwd=BASE, text=True, capture_output=True, timeout=12)+ if ok: assert p.returncode == 0, (args, p.stdout, p.stderr)+ return p.stdout.strip()++def tmux(*args, ok=True):+ p = subprocess.run([TMUX, '-L', PREFIX + '-outer', *args], env=ENV, cwd=BASE,+ text=True, capture_output=True, timeout=10)+ if ok: assert p.returncode == 0, (args, p.stderr)+ return p.stdout++def state():+ with urllib.request.urlopen(f'http://127.0.0.1:{PORT}/test/dial', timeout=2) as r: return r.read()++def screen(): return tmux('capture-pane', '-p', '-t', 'test')+def wait(fn, label, seconds=8):+ end = time.monotonic() + seconds+ while time.monotonic() < end:+ if fn(): return+ time.sleep(.05)+ raise AssertionError(label + '\n' + screen())+def shows(text): wait(lambda: text in screen(), text)+def gone(text): wait(lambda: text not in screen(), 'still shows ' + text)+def keys(*args): tmux('send-keys', '-t', 'test', *args); time.sleep(.15)+def type_text(text): tmux('send-keys', '-l', '-t', 'test', text); time.sleep(.15)+def panes(): return int(hn('display-message', '-p', '#{window_panes}'))++def start():+ command = shlex.join(['env', '-u', 'TMUX', '-u', 'TMUX_PANE', '-u', 'HN_SOCKET',+ *[f'{k}={v}' for k, v in ENV.items()], str(HN), '-L', PREFIX,+ '--port', str(PORT), '-f', '/dev/null'])+ tmux('-f', '/dev/null', 'new-session', '-d', '-s', 'test', '-x', '150', '-y', '42', command)+ tmux('set-window-option', '-t', 'test', 'remain-on-exit', 'on')+ shows('Fix flaky login test')++mock = None+started = False+try:+ with socket.socket() as probe: probe.bind(('127.0.0.1', PORT))+ mock = subprocess.Popen(['node', str(ROOT / 'tests/mock-daemon.mjs'), str(PORT)], env=ENV,+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)+ for _ in range(100):+ assert mock.poll() is None+ try: state(); break+ except OSError: time.sleep(.05)+ else: raise AssertionError('mock startup timeout')+ start()+ started = True++ # C-b Enter → keyb → Enter: Keybinds, its own panel, the prefix first and fixed.+ keys('C-b', 'Enter'); shows('Commands')+ type_text('keyb'); keys('Enter'); shows('(fixed)')+ s = screen()+ assert 'Keybinds' in s and 'Split right' in s and 'Preview' not in s and 'Appearance' not in s, s+ # Split right → Enter → h.+ type_text('split right'); wait(lambda: '› Split right' in screen(), 'cursor on Split right')+ keys('Enter'); shows('press a key')+ keys('h'); shows('saved to tui.toml')+ assert any('Split right' in l and 'C-b h' in l for l in screen().splitlines()), screen()+ # Esc back to Commands, Esc closes.+ keys('Escape'); shows('Commands'); gone('(fixed)')+ keys('Escape'); gone('Commands')+ toml = TOML.read_text()+ assert '[prefix_keys]' in toml and '"h" = "split-window -h"' in toml and '"%" = "none"' in toml, toml+ # C-b h splits; C-b % does nothing now.+ before = panes()+ keys('C-b', 'h'); wait(lambda: panes() == before + 1, 'C-b h splits')+ keys('C-b', '%'); time.sleep(.5)+ assert panes() == before + 1, 'C-b % no longer splits'+ print('PASS Keybinds: opened from Commands, Split right on h, C-b h splits and C-b % does not', flush=True)++ # A restart reads tui.toml: still h.+ hn('kill-server', ok=False); tmux('kill-server', ok=False); started = False+ time.sleep(.3)+ start(); started = True+ before = panes()+ keys('C-b', 'h'); wait(lambda: panes() == before + 1, 'C-b h splits after a restart')+ keys('C-b', '%'); time.sleep(.5)+ assert panes() == before + 1, 'C-b % still free after a restart'+ print('PASS Keybinds: after a restart C-b h still splits', flush=True)++finally:+ try:+ if started:+ hn('kill-server', ok=False); tmux('kill-server', ok=False)+ def clients():+ rows = subprocess.check_output(['ps', '-ax', '-o', 'pid=,command='], text=True).splitlines()+ return [int(parts[0]) for row in rows if len(parts := row.strip().split(None, 1)) == 2+ and parts[1].startswith(str(HN) + ' ') and f'-L {PREFIX} ' in parts[1]]+ for pid in clients():+ try: os.kill(pid, 15)+ except ProcessLookupError: pass+ deadline = time.monotonic() + 5+ while clients() and time.monotonic() < deadline: time.sleep(.05)+ assert not clients(), 'Keybinds test client did not exit'+ finally:+ if mock:+ mock.terminate()+ try: mock.wait(timeout=5)+ except subprocess.TimeoutExpired: mock.kill(); mock.wait()+ shutil.rmtree(BASE, ignore_errors=True)