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 — change the prefix and any command's key in the panel
Tim440c8e2890c9
diff --git a/tui/src/app.rs b/tui/src/app.rsindex fd1775e24..9f5a51828 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -778,6 +778,8 @@ pub struct App {pub mouse_changed: bool,/// Whether the terminal window has focus (focus reporting) — notifications go out when it does not.pub terminal_focused: bool,+ /// Waiting for a key to become the prefix, or a command's key (settings.rs): the next key.+ pub capturing: Option<crate::settings::Capture>,/// The Harness device on this desk, and hn's half of talking to it (dial.rs).pub dial: crate::dial::Dial,/// A key table of your own the next key is looked up in (`switch-client -T`).@@ -994,6 +996,7 @@ impl App {desk_stale: false,lastw: Vec::new(),terminal_focused: true,+ capturing: None,dial: Default::default(),options: Default::default(),jobs: Default::default(),diff --git a/tui/src/config.rs b/tui/src/config.rsindex 57aaa1f22..01c9617ef 100644--- a/tui/src/config.rs+++ b/tui/src/config.rs@@ -3,6 +3,10 @@//! ```toml//! prefix = "ctrl+a" # instead of ctrl+space//! prefix2 = "C-b" # a second one (⌘ keys reach only some terminals)+//!+//! [prefix_keys] # after the prefix (Alt-k in the command panel writes these)+//! "h" = "new-harness"+//! "N" = "none"//! desk = "read" # sync | read | off (as HARNESS_TUI_DESK)//! predict = "off" # auto | always | off (as HARNESS_TUI_PREDICT)//! notify = false # OS notifications through the terminal@@ -144,6 +148,8 @@ pub struct Config {/// A second prefix (tmux's prefix2), where the file names one: `prefix = "D-b"` (⌘B, which/// only some terminals pass on) with `prefix2 = "C-b"` works in every terminal.pub prefix2: Option<Chord>,+ /// `[prefix_keys]`: keys after the prefix, each with its command (None: unbound).+ pub prefix_keys: Vec<(Chord, Option<String>)>,pub keys: Vec<(Chord, Option<String>)>,/// The `[look]` table, if any.pub look: Option<Look>,@@ -204,7 +210,7 @@ impl Look {impl Default for Config {fn default() -> Self {- Config { prefix: Chord::normal(KeyCode::Char('b'), KeyModifiers::CONTROL), prefix_set: false, prefix2: None, keys: Vec::new(), look: None, problems: Vec::new() }+ Config { prefix: Chord::normal(KeyCode::Char('b'), KeyModifiers::CONTROL), prefix_set: false, prefix2: None, prefix_keys: Vec::new(), keys: Vec::new(), look: None, problems: Vec::new() }}}@@ -246,10 +252,90 @@ pub fn load() -> Config {}}}+ // [prefix_keys]: after the prefix, a key and the command it runs ("none": nothing) — what+ // Alt-k in the command panel writes.+ if let Some(keys) = value.get("prefix_keys").and_then(|v| v.as_table()) {+ for (chord, command) in keys {+ let Some(command) = command.as_str() else { config.problems.push(format!("tui.toml prefix_keys.{chord}: expected a command")); continue };+ match crate::keys::parse(chord) {+ Ok(c) => config.prefix_keys.push((c, if command == "none" { None } else { Some(command.to_string()) })),+ Err(e) => config.problems.push(format!("tui.toml prefix_keys: {e}")),+ }+ }+ }if let Some(look) = value.get("look").and_then(|v| v.as_table()) { config.look = Some(look_of(look, &mut config.problems)) }config}+// ── keys ──++/// A TOML string: [s] quoted.+fn toml_str(s: &str) -> String { format!("\"{}\"", s.replace('\\', "\\\\").replace('"', "\\\"")) }++/// Whether [line] sets [key] (bare or quoted).+fn sets(line: &str, key: &str) -> bool {+ let t = line.trim_start();+ let rest = t.strip_prefix(&toml_str(key)).or_else(|| t.strip_prefix(key).filter(|_| key.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')));+ 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+}++/// [text] with `"entry" = "value"` in [table] (made when there is none), the rest as written.+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) {+ Some(h) => {+ let end = lines[h + 1..].iter().position(|l| 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) }+ }+ }+ None => {+ if lines.last().is_some_and(|l| !l.trim().is_empty()) { lines.push(String::new()) }+ lines.push(header);+ lines.push(line);+ }+ }+ let mut out = lines.join("\n");+ out.push('\n');+ out+}++fn rewrite(change: impl FnOnce(&str) -> String) -> std::io::Result<()> {+ let p = path();+ let existing = std::fs::read_to_string(&p).unwrap_or_default();+ if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)? }+ 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)) }+/// The `[look]` table as read, a knob that is not a string said in [problems].fn look_of(look: &toml::Table, problems: &mut Vec<String>) -> Look {let mut l = Look::default();@@ -459,4 +545,30 @@ mod tests {let top = Look { status_bar: Some("top".into()), ..Default::default() }.assignments();assert_eq!(get(&top, "status-position").as_deref(), Some("top"));}++ // ── 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.+ #[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");+ 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.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"));+ }}diff --git a/tui/src/input.rs b/tui/src/input.rsindex 323bf2534..0e25672d3 100644--- a/tui/src/input.rs+++ b/tui/src/input.rs@@ -52,6 +52,9 @@ fn on_key(app: &mut App, key: KeyEvent) {app.key_name = Some(keys::name(&chord));// A message goes on the next key, as tmux's does.app.toast = None;+ // ── keys ── Waiting for a key (a prefix, or a command's key, chosen in the panel): this is it,+ // whatever it is — the prefix too.+ if app.capturing.is_some() { crate::settings::captured(app, key); return }// display-panes (cmd_display_panes_key), before any table: a number, or a letter for 10 on,// runs its template for that pane (select-pane) and closes it — as does one no pane has;// any other key (every key with -N) closes it and goes on as it would have.@@ -680,7 +683,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")] }+ 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::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();@@ -839,6 +842,15 @@ 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 });+ }+ }"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),@@ -1963,6 +1975,12 @@ fn picker_key(app: &mut App, key: KeyEvent, kind: PickerKind, picker: Picker) {let _ = was;let ctrl = key.modifiers.contains(KeyModifiers::CONTROL);let alt = key.modifiers.contains(KeyModifiers::ALT);+ // ── keys ── Alt-k on a command: the next key you press is its key (Ctrl-k moves, as in fzf).+ if matches!(kind, PickerKind::Commands) && alt && !ctrl && key.code == KeyCode::Char('k') {+ crate::settings::capture_for_row(app, &mut picker);+ app.modal = Some(Modal::Picker { kind, picker });+ return;+ }// Jump mode consumes one key, then fires jump or jump-cancel as fzf does.if let Some(accept) = picker.jumping.take() {let mut event = "jump-cancel";@@ -2702,7 +2720,8 @@ 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(':') {- let msg = app.set_look(knob, value);+ // (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));picker.say(msg);picker.set_rows(modal::theme_options(app, §ion));// (A switch — Dim other panes — is the same row turned over.)@@ -2897,7 +2916,7 @@ pub fn is_command(id: &str) -> bool {| "broadcast" | "clone" | "restart" | "pause" | "take" | "rename" | "tab" | "rename-tab" | "close-tab" | "next-tab" | "prev-tab"| "split-right" | "split-down" | "close-pane" | "zoom" | "equalize" | "pane-tab" | "copy-mode" | "find" | "tab-left" | "tab-right"| "last-tab" | "next-waiting" | "prev-waiting" | "resume-focused" | "last-harness" | "tree" | "info" | "messages" | "keys"- | "theme" | "appearance" | "commands" | "choose-buffer" | "quit"+ | "theme" | "appearance" | "commands" | "choose-buffer" | "quit" | "keybinds"// ── machines & devices ──| "connect-machine" | "add-phone" | "devices")}diff --git a/tui/src/main.rs b/tui/src/main.rsindex e495e77b6..64a5ca854 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -432,6 +432,9 @@ async fn run(config: config::Config) -> io::Result<()> {for (chord, command) in &config.keys {match command { Some(c) => app.keymap.bind(keys::Table::Root, *chord, c.clone(), false), None => app.keymap.unbind(keys::Table::Root, chord) }}+ for (chord, command) in &config.prefix_keys {+ match command { Some(c) => app.keymap.bind(keys::Table::Prefix, *chord, c.clone(), false), None => app.keymap.unbind(keys::Table::Prefix, chord) }+ }// The server's options, keys, buffers and environment: this client's if it is the first// (tmux reads its configuration once, when its server starts).server::join(&mut app);diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex daaa51d2e..6c7c2ff37 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -183,7 +183,7 @@ pub const COMMANDS: &[(&str, &str, &str, &str, &str)] = &[("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", "App"),+ ("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"),@@ -208,7 +208,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"),- ("keys", "Keyboard shortcuts…", "", "every key and what it does, searched as you type", "Settings & help"),+ ("keybinds", "Keybinds…", "", "the prefix and every command's key, grouped — 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"),];@@ -503,7 +503,82 @@ pub fn command_rows_for(app: &App, searching: bool) -> Vec<Row> {/// The key (prefix, then the key) that runs one of hn's own commands, as the prefix table has it/// now — so a rebinding shows. The command each menu entry is on a key as.fn own_key(app: &App, id: &str) -> Option<String> {- let runs = match id {+ let runs = runs_of(id)?;+ let hit = key_running(app, runs)?;+ Some(format!("{} {}", crate::keys::name(&app.keymap.prefix), crate::keys::name(&hit)))+}++/// The key after the prefix that runs [runs] now, where one does.+pub fn key_running(app: &App, runs: &str) -> Option<crate::keys::Chord> {+ let table = &app.keymap.prefix_table;+ let hit = table.iter().find(|b| b.command == runs)+ .or_else(|| table.iter().find(|b| b.command.split(|c: char| c.is_whitespace() || c == '{' || c == '"').any(|w| w == runs)))+ .or_else(|| table.iter().find(|b| b.command.contains(runs)))?;+ Some(hit.chord)+}++// ── keys ──++/// Keybinds: (title, the command its key runs, group) — the keys a person reaches for, grouped+/// as they think of them. Every other key is `C-b ?` (list-keys), as in tmux.+pub const KEYBINDS: &[(&str, &str, &str)] = &[+ ("Harnesses…", "choose-tree -Zs", "Navigation"),+ ("Harnesses needing input", "choose-tree -a", "Navigation"),+ ("Next harness waiting on you", "next-harness", "Navigation"),+ ("Machines…", "choose-tree -m", "Navigation"),+ ("Pane left", "select-pane -L", "Navigation"),+ ("Pane right", "select-pane -R", "Navigation"),+ ("Pane up", "select-pane -U", "Navigation"),+ ("Pane down", "select-pane -D", "Navigation"),+ ("Next swarm", "next-window", "Navigation"),+ ("Previous swarm", "previous-window", "Navigation"),+ ("Last swarm", "last-window", "Navigation"),+ ("Split right", "split-window -h", "Panes"),+ ("Split down", "split-window", "Panes"),+ ("Close pane", "kill-pane", "Panes"),+ ("Zoom pane", "resize-pane -Z", "Panes"),+ ("Equalize panes", "select-layout -E", "Panes"),+ ("Next layout", "next-layout", "Panes"),+ ("Copy mode", "copy-mode", "Panes"),+ ("Find in pane…", "find-window", "Panes"),+ ("New swarm", "new-window", "Swarms (windows)"),+ ("Rename swarm…", "rename-window", "Swarms (windows)"),+ ("Close swarm", "kill-window", "Swarms (windows)"),+ ("Move pane to a new swarm", "break-pane", "Swarms (windows)"),+ ("New harness…", "new-harness", "Harnesses"),+ ("New terminal", "new-terminal", "Harnesses"),+ ("Models…", "choose-tree -i", "Harnesses"),+ ("Send to harness…", "send-task", "Harnesses"),+ ("Clone harness", "clone-harness", "Harnesses"),+ ("Restart harness", "restart-harness", "Harnesses"),+ ("Pause harness", "pause-harness", "Harnesses"),+ ("Commands", "choose-command", "General"),+ ("Every key (tmux's list)", "list-keys -N", "General"),+ ("Command prompt", "command-prompt", "General"),+ ("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.+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 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+}++/// The tmux command one of hn's own commands is on a key as.+pub fn runs_of(id: &str) -> Option<&'static str> {+ Some(match id {"open" => "choose-tree -Zs", "models" => "choose-tree -i", "new" => "new-harness", "terminal" => "new-terminal","inbox" => "choose-tree -a", "next-waiting" => "next-harness", "send" => "send-task", "broadcast" => "broadcast","clone" => "clone-harness", "restart" => "restart-harness", "pause" => "pause-harness", "tab" => "new-window",@@ -512,12 +587,7 @@ fn own_key(app: &App, id: &str) -> Option<String> {"equalize" => "select-layout -E", "find" => "find-window", "copy-mode" => "copy-mode", "machines" => "choose-tree -m","store" => "choose-tree -S", "help" => "list-keys -N", "theme" | "commands" => "choose-command",_ => return None,- };- let table = &app.keymap.prefix_table;- let hit = table.iter().find(|b| b.command == runs)- .or_else(|| table.iter().find(|b| b.command.split(|c: char| c.is_whitespace() || c == '{' || c == '"').any(|w| w == runs)))- .or_else(|| table.iter().find(|b| b.command.contains(runs)))?;- Some(format!("{} {}", crate::keys::name(&app.keymap.prefix), crate::keys::name(&hit.chord)))+ })}/// Commands that mean nothing without words after them.@@ -585,6 +655,8 @@ 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)),]}@@ -621,6 +693,8 @@ 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),"split" => { let cur = o.look_orientation().to_string();["auto", "vertical", "horizontal"].iter().map(|v| opt(format!("layout_orientation:{v}"), *v, cur == *v, "layout_orientation")).collect() }"layout" => { let cur = current("@hn-layout-preset", "auto");@@ -730,7 +804,9 @@ 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:split", "section:layout", "section:theme",// ── status bar ──- "section:bar", "section:boxes"]);+ "section:bar", "section:boxes",+ // ── keys ──+ "section:keys"]);// 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 {@@ -776,6 +852,53 @@ mod theme_row_tests {assert_eq!(split_ids, vec!["layout_orientation:auto", "layout_orientation:vertical", "layout_orientation:horizontal"]);}+ // ── 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.+ #[test]+ fn keybinds_show_every_key_grouped_and_change_one() {+ use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};+ 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"));+ 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!(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());+ 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);+ }+// ── status bar ──#[test]diff --git a/tui/src/settings.rs b/tui/src/settings.rsindex 67182102c..a8dc37d31 100644--- a/tui/src/settings.rs+++ b/tui/src/settings.rs@@ -84,6 +84,110 @@ pub fn back_to_commands(app: &App, picker: &mut Picker) {/// 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 ────────────────────++/// What the next key becomes: the prefix, the second prefix, or [command]'s key after the prefix.+#[derive(Clone, Debug)]+pub enum Capture { Prefix, Prefix2, Command { command: String, title: String, own: bool } }++const PRESS: &str = "Press the key you want · 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.+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}") }+}++/// Alt-k on a command in the command panel: its key is the next key you press. A command with+/// no key of its own to run (one that needs words) says so.+pub fn capture_for_row(app: &mut App, picker: &mut Picker) {+ let Some(id) = picker.current_id() else { return };+ let title = picker.rows.iter().find(|r| r.id == id).map(|r| r.label.clone()).unwrap_or_default();+ let command = if let Some(name) = id.strip_prefix("tmux:") { (!crate::modal::NEEDS_ARGS.contains(&name)).then(|| name.to_string()) }+ 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:") });+}++/// 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.+pub fn captured(app: &mut App, key: crossterm::event::KeyEvent) {+ let Some(what) = 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),+ }+ };+ // 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;+ 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) } }+ _ => {}+ }+ picker.say(said);+ app.modal = Some(crate::modal::Modal::Picker { kind, picker });+ } else { app.say(said, theme::MUTED) }+ app.redraw_all = true;+}++/// [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]`.+fn rebind(app: &mut App, command: &str, title: &str, own: bool, chord: crate::keys::Chord) -> String {+ use crate::keys::Table;+ let title = title.trim_end_matches('…');+ let 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());+ 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);+ saved = saved.and(crate::config::write_prefix_key(&crate::keys::name(&old), "none"));+ }+ app.keymap.bind(Table::Prefix, chord, full.clone(), false);+ app.server_dirty = true;+ saved = saved.and(crate::config::write_prefix_key(&key, &full));+ let prefix = crate::keys::name(&app.keymap.prefix);+ let replaced = was.map(|c| format!(" (it ran {c})")).unwrap_or_default();+ match saved { Ok(()) => format!("{title}: {prefix} {key}{replaced} — saved to tui.toml"), Err(e) => format!("{title}: {prefix} {key}{replaced} — could not write tui.toml: {e}") }+}+/// The panel's colours, shared with the New Harness form so the two read as one component:/// its surface, muted and accent text, and the backdrop laid over the panes behind it.pub struct Chrome { pub base: Style, pub muted: Style, pub accent: Style, pub backdrop: Style, pub selected: Style }@@ -252,8 +356,9 @@ pub fn draw(buf: &mut Buffer, app: &App, body: Rect, kind: &PickerKind, picker:let rows = bottom.saturating_sub(top) as usize;// (Commands need no preview: the list takes the width, a row's hint beside its name. A list// that is the whole answer — output, messages, keys — has none either.)- let settings = matches!(kind, PickerKind::Theme);- let side = inner_w >= 64 && (settings || (picker.preview && !matches!(kind, PickerKind::Commands)));+ // (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)));// (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) };@@ -320,6 +425,8 @@ pub fn section_title(section: &str) -> &'static str {"split" => "Split direction", "layout" => "Layout", "theme" => "Theme",// ── status bar ──"bar" => "Status bar", "boxes" => "Borders",+ // ── keys ──+ "keys" => "Keybinds",_ => "",}}