From cafdaaae5d8c94c9c3346a7d13ad3425d39332cf Mon Sep 17 00:00:00 2001 From: hermes Date: Fri, 2 Oct 2026 23:04:14 +0000 Subject: [PATCH] input: shift-enter newline via keyboard protocol, tmux modifyOtherKeys, backslash-enter, wrapping, /keys --- README.md | 4 +- crates/hx-core/src/command.rs | 5 ++ crates/hx-tui/src/editor.rs | 57 +++++++++++++++ crates/hx-tui/src/lib.rs | 132 ++++++++++++++++++++++++++++++++-- tests/tui_smoke.py | 4 ++ 5 files changed, 195 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index ba55946..ca4de93 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,9 @@ hx -r # pick a session to resume hx -r parser # resume the session whose title best matches "parser" ``` -TUI: `enter` send, `alt-enter`/`ctrl-j` newline, `esc` abort, `ctrl-o` expand tool output. +TUI: `enter` send, `shift-enter`/`alt-enter`/`ctrl-j` newline (or end a line with `\` and press enter), `esc` abort, `ctrl-o` expand tool output. + +Shift-enter needs a terminal that reports it; hx turns on the kitty keyboard protocol when the terminal answers the probe. Works in ghostty, kitty, WezTerm (`enable_kitty_keyboard = true`), iTerm2, foot, Alacritty 0.13+, Windows Terminal (map shift-enter to `\u001b[13;2u`) and zellij 0.41+. tmux 3.2+ needs `set -g extended-keys on` and `set -g extended-keys-format csi-u`. Elsewhere use `alt-enter`, `ctrl-j` or a trailing `\`. `/keys` prints every key as hx receives it, to see what a terminal or multiplexer (e.g. herdr) passes through. Long input lines wrap; the box grows up to 10 rows. Scrolling (chat, side panel, agent view): mouse wheel (3 lines, targets the region under the pointer), `pgup`/`pgdn` half a page, `alt-pgup`/`alt-pgdn` a full page, `alt-↑`/`alt-↓` 3 lines, `ctrl-home`/`ctrl-end` top / back to the live bottom. A scrolled-up view stays put while new text streams in (footer shows `↑N` lines below); reaching the bottom or sending a prompt follows again. The wheel needs mouse capture, which disables plain terminal text selection (use shift-drag): turn it off with `mouse = false` in config or `HX_MOUSE=0`. `/help` lists commands: builtins (`/model`, `/provider`, `/compact`, `/clear`, `/lsp`, `/mcp`, `/skills`, `/new`, `/sessions`, `/resume`, `/usage`, `/quit`), MCP diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index c1744f6..67171c3 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -62,6 +62,11 @@ pub fn builtins(models: &[&str]) -> Vec { b("sessions", "browse, resume, delete sessions", None), b("lsp", "language server status", None), b("usage", "subscription limits, resets, credits", None), + b( + "keys", + "show keys as hx receives them (debug shift-enter)", + None, + ), b( "stats", "token dashboard: cache hit, per-request usage", diff --git a/crates/hx-tui/src/editor.rs b/crates/hx-tui/src/editor.rs index 3616beb..4fcfd40 100644 --- a/crates/hx-tui/src/editor.rs +++ b/crates/hx-tui/src/editor.rs @@ -150,6 +150,37 @@ impl Editor { self.cur = start + text.len(); } + /// Buffer as screen rows hard-wrapped at `w` chars, plus the cursor's (row, col). + /// The cursor at the end of a full row sits on a fresh row below it. + // ponytail: counts chars, not cell width; CJK/emoji can overflow a row by a cell. Use unicode-width if it matters. + pub fn wrapped(&self, w: usize) -> (Vec, (usize, usize)) { + let w = w.max(1); + let (cur_line, cur_col) = self.cursor_rc(); + let mut rows = vec![]; + let mut cur = (0, 0); + for (i, line) in self.buf.split('\n').enumerate() { + let chars: Vec = line.chars().collect(); + let mut n = chars.len().div_ceil(w).max(1); + if i == cur_line { + cur = (rows.len() + cur_col / w, cur_col % w); + n = n.max(cur_col / w + 1); + } + rows.extend((0..n).map(|k| chars.iter().skip(k * w).take(w).collect::())); + } + (rows, cur) + } + + /// Enter after a typed `\`: the backslash becomes a newline (for terminals that cannot + /// tell shift-enter from enter). True when it did. + pub fn continue_line(&mut self) -> bool { + if self.buf[..self.cur].ends_with('\\') { + self.backspace(); + self.insert("\n"); + return true; + } + false + } + /// (row, col) of the cursor in chars. pub fn cursor_rc(&self) -> (usize, usize) { let before = &self.buf[..self.cur]; @@ -172,6 +203,32 @@ fn advance(buf: &str, from: usize, to: usize, col: usize) -> usize { mod tests { use super::*; + #[test] + fn wraps_and_places_cursor() { + let mut e = Editor::default(); + e.insert("abcdef\nxy"); + let (rows, cur) = e.wrapped(4); + assert_eq!(rows, ["abcd", "ef", "xy"]); + assert_eq!(cur, (2, 2)); + // cursor right after a full row goes to the next row + let mut e = Editor::default(); + e.insert("abcd"); + let (rows, cur) = e.wrapped(4); + assert_eq!((rows.len(), cur), (2, (1, 0))); + // trailing newline is an empty row + e.insert("\n"); + assert_eq!(e.wrapped(4).0, ["abcd", ""]); + } + + #[test] + fn backslash_enter_continues() { + let mut e = Editor::default(); + e.insert("a\\"); + assert!(e.continue_line()); + assert_eq!(e.buf, "a\n"); + assert!(!e.continue_line()); + } + #[test] fn edit_and_multiline_nav() { let mut e = Editor::default(); diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index b9b1d33..d1ef361 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -157,6 +157,10 @@ struct App { tokio::sync::oneshot::Sender, )>, review: Option, + /// `/keys`: show every key as hx receives it until esc + probe: bool, + /// keyboard protocol was switched on (shift-enter is distinguishable) + kbd: bool, stats: Option<(hx_core::stats::Summary, String)>, /// lens/context/MCP side panel (ctrl-l), wide terminals only side: bool, @@ -190,7 +194,7 @@ impl App { } } -const KEYS: &str = "ctrl-g agents · enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \ +const KEYS: &str = "ctrl-g agents · enter send · shift-enter/alt-enter/ctrl-j/\\ newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \ tab complete @file / command"; const PLACEHOLDER: &str = "/ commands · @ files · ctrl-p picker · /help keys"; /// Columns from which listings go to a side panel. @@ -239,6 +243,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { yolo, mcp, } = setup; + // asked before the alternate screen; terminals that do not answer return false + let kbd = crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false); let (tx, mut rx) = mpsc::unbounded_channel(); agent.bus.add(Forward(tx.clone())); { @@ -315,6 +321,8 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { choose: None, perm: None, review: None, + probe: false, + kbd, stats: None, side: true, lens_lines: vec![], @@ -341,6 +349,30 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { commands: &commands, }; let mut term = ratatui::init(); + // Kitty keyboard protocol (pushed on the alternate screen): shift-enter arrives as Enter+SHIFT (ghostty, kitty, wezterm, iTerm2, + // foot, alacritty, zellij). Not pushed when the terminal does not answer the query. + // tmux does not speak the kitty protocol; it forwards shift-enter only after the app asks + // xterm-style (modifyOtherKeys), and as `ESC[13;2u` only with `extended-keys-format csi-u`. + let tmux = !kbd && std::env::var_os("TMUX").is_some(); + if tmux { + print!("\x1b[>4;2m"); + } + if kbd { + use crossterm::event::{KeyboardEnhancementFlags as F, PushKeyboardEnhancementFlags}; + let _ = crossterm::execute!( + std::io::stdout(), + PushKeyboardEnhancementFlags(F::DISAMBIGUATE_ESCAPE_CODES) + ); + // a crash must not leave the shell in this mode + let prev = std::panic::take_hook(); + std::panic::set_hook(Box::new(move |i| { + let _ = crossterm::execute!( + std::io::stdout(), + crossterm::event::PopKeyboardEnhancementFlags + ); + prev(i) + })); + } if mouse { let _ = crossterm::execute!(std::io::stdout(), crossterm::event::EnableMouseCapture); } @@ -478,6 +510,15 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { if mouse { let _ = crossterm::execute!(std::io::stdout(), crossterm::event::DisableMouseCapture); } + if tmux { + print!("\x1b[>4;0m"); + } + if kbd { + let _ = crossterm::execute!( + std::io::stdout(), + crossterm::event::PopKeyboardEnhancementFlags + ); + } ratatui::restore(); let a = agent.lock().await; let cost = pricing(a.model()) @@ -725,6 +766,22 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { let alt = k.modifiers.contains(KeyModifiers::ALT); let shift = k.modifiers.contains(KeyModifiers::SHIFT); app.hint.clear(); + if app.probe { + if k.code == KeyCode::Esc { + app.probe = false; + } + app.t.push(Item::Info(format!( + "key: {:?} {:?}{}", + k.code, + k.modifiers, + if k.code == KeyCode::Esc { + " (probe off)" + } else { + "" + } + ))); + return None; + } if app.sessions.is_some() { return sessions_key(app, k); } @@ -817,6 +874,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { KeyCode::Esc if app.panel.is_some() => app.panel = None, KeyCode::Char('j') if ctrl => app.ed.insert("\n"), KeyCode::Enter if alt || shift => app.ed.insert("\n"), + KeyCode::Enter if app.ed.continue_line() => {} KeyCode::Enter => { if let Action::Submit(s) = app.ed.submit() { return Some(s); @@ -936,6 +994,13 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs)); show(app, "help", h); } + "keys" => { + app.probe = true; + app.t.push(Item::Info(format!( + "keyboard protocol: {}. Press keys (try shift-enter); esc ends. `enter` shows as {{Enter, NONE}} when the terminal or multiplexer cannot tell shift-enter apart.", + if app.kbd { "on" } else { "off (use alt-enter, ctrl-j or a trailing \\)" } + ))); + } "stats" => { let sess = agent.lock().await; let sum = hx_core::stats::summary(sess.session()); @@ -1096,9 +1161,9 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { fn draw(f: &mut ratatui::Frame, app: &mut App) { let th = theme::t(); - let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n'))) - .min(10) as u16 - + 2; + let text_w = f.area().width.saturating_sub(2) as usize; + let (rows, (cur_r, cur_c)) = app.ed.wrapped(text_w); + let input_h = rows.len().min(10) as u16 + 2; let act_h = u16::from(app.busy); app.wide = f.area().width >= WIDE; if let Some(agents::View::Detail { id, ed, scroll }) = &mut app.agents { @@ -1213,12 +1278,13 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) { ), gut, ); - let (r, c) = app.ed.cursor_rc(); + let (r, c) = (cur_r, cur_c); let skip = (r as u16).saturating_sub(text.height.saturating_sub(1)); if app.ed.buf.is_empty() { f.render_widget(Span::styled(PLACEHOLDER, th.dim()), text); } else { - f.render_widget(Paragraph::new(app.ed.buf.as_str()).scroll((skip, 0)), text); + let lines: Vec = rows.into_iter().map(Line::raw).collect(); + f.render_widget(Paragraph::new(lines).scroll((skip, 0)), text); } let chrome = status::Chrome { ask: app.ask.as_ref().map(|(q, _)| q.as_str()), @@ -1427,6 +1493,58 @@ mod tests { .join("\n") } + #[test] + fn shift_enter_newline_enter_submits_backslash_continues() { + let mut app = test_app(); + let ab = AbortHandle::detached(); + let press = |app: &mut App, c, m| on_key(app, KeyEvent::new(c, m), &ab); + app.ed.insert("a"); + assert!(press(&mut app, KeyCode::Enter, KeyModifiers::SHIFT).is_none()); + app.ed.insert("b\\"); + assert!(press(&mut app, KeyCode::Enter, KeyModifiers::NONE).is_none()); + app.ed.insert("c"); + assert_eq!(app.ed.buf, "a\nb\nc"); + assert_eq!( + press(&mut app, KeyCode::Enter, KeyModifiers::NONE).as_deref(), + Some("a\nb\nc") + ); + } + + #[test] + fn input_wraps_and_grows() { + let mut app = test_app(); + app.ed.insert(&"x".repeat(45)); + app.ed.insert("\nend"); + let s = screen(&mut app, 20, 12); + // 45 chars at width 18 = 3 rows, plus "end" = 4 rows; cursor on the last + let rows: Vec<&str> = s.lines().collect(); + assert!(rows.iter().any(|r| r.contains("end")), "{s}"); + assert_eq!( + rows.iter().filter(|r| r.contains("xxxxxx")).count(), + 3, + "{s}" + ); + } + + #[test] + fn keys_probe_reports_and_ends_on_esc() { + let mut app = test_app(); + let ab = AbortHandle::detached(); + app.probe = true; + on_key( + &mut app, + KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT), + &ab, + ); + assert!(app.probe && app.ed.buf.is_empty()); + on_key( + &mut app, + KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), + &ab, + ); + assert!(!app.probe); + } + #[test] fn side_panel_only_on_wide_terminals() { let mut app = test_app(); @@ -1702,6 +1820,8 @@ mod tests { choose: None, perm: None, review: None, + probe: false, + kbd: false, stats: None, side: true, lens_lines: vec![], diff --git a/tests/tui_smoke.py b/tests/tui_smoke.py index 78579a8..0c84d4d 100644 --- a/tests/tui_smoke.py +++ b/tests/tui_smoke.py @@ -26,6 +26,7 @@ if pid == 0: import fcntl, termios, struct fcntl.ioctl(fd, termios.TIOCSWINSZ, struct.pack("HHHH", 30, 100, 0, 0)) +os.write(fd, b"\x1b[?62;c") # answer hx's keyboard-protocol probe like a terminal without kitty support buf = b"" def pump(t): global buf @@ -55,6 +56,9 @@ pump(1.5) check("startup footer", "Claude") check("latest default model", "claude-sonnet-5-5") check("1M window", "/900k") +send(b"l1"); send(b"\x1b[13;2u"); send(b"l2") # shift-enter as CSI-u (kitty protocol) +check("shift-enter is a newline, not a submit", "l1") +send(b"\x15\x7f\x15") # kill line 2, join, kill line 1 send(b"/skills\r") check("skills from ~/.agents", "/deploy — ship it") check("project .agents skills", "/lint — project lint")