merge main

This commit is contained in:
hermes committed 2026-10-06 12:53:24 +00:00
commit 9cb95ac5b6
14 files changed
+665 -34

No files matched your search

+210 -20
View File
@@ -8,6 +8,7 @@ pub mod picker;
pub mod popup;
pub mod review;
pub mod scroll;
pub mod select;
pub mod sessions;
pub mod stats_view;
pub mod status;
@@ -15,7 +16,7 @@ pub mod theme;
pub mod transcript;
use crossterm::event::{
Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers, MouseButton,
};
use editor::{Action, Editor};
use futures::StreamExt;
@@ -25,11 +26,12 @@ use hx_core::agent::{AbortHandle, Agent};
use hx_core::command::{self as cmd, CmdSpec, Completion, Source};
use hx_core::hook::{Event, Hook, HookAction};
use hx_core::switch::Switcher;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Modifier;
use ratatui::text::Line;
use ratatui::text::Span;
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Wrap};
use ratatui::widgets::{Block, Borders, Clear, Paragraph, Widget, Wrap};
use std::collections::VecDeque;
use std::sync::Arc;
use std::time::Instant;
@@ -51,7 +53,7 @@ pub struct Setup {
pub specs: Vec<CmdSpec>,
/// Open the session picker at startup (`hx -r`).
pub open_sessions: bool,
/// Capture the mouse (wheel scrolling); terminal text selection then needs shift-drag.
/// Capture the mouse (wheel scrolling, drag-select + copy in the chat via OSC 52).
pub mouse: bool,
/// No permission prompts (`--yolo`).
pub yolo: bool,
@@ -123,6 +125,11 @@ struct App {
panel_scroll: scroll::Scroll,
/// where the chat / side panel / agent detail were last drawn (mouse wheel targets)
areas: Areas,
/// chat text selection (content coordinates) and whether the button is still down
sel: Option<select::Sel>,
drag: bool,
/// last left press for double/triple click: (when, content pos, count)
click: Option<(Instant, (u16, u16), u8)>,
expanded: bool,
busy: bool,
queue: VecDeque<String>,
@@ -183,6 +190,11 @@ impl App {
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
self.st.kind = sw.kind;
self.st.model = sw.model.clone();
// keep the level when the new provider has it, else its first (Codex has no "off")
if !hx_ai::Effort::levels(sw.kind).contains(&self.st.effort) {
self.st.effort = hx_ai::Effort::levels(sw.kind)[0];
self.sw.remember_effort(self.st.effort);
}
if sw.provider_changed {
self.st.quota = None;
}
@@ -292,12 +304,16 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
scroll: Default::default(),
panel_scroll: Default::default(),
areas: Default::default(),
sel: None,
drag: false,
click: None,
expanded: false,
busy: false,
queue: VecDeque::new(),
st: status::Status {
kind: switcher.kind(),
model: agent.model().to_string(),
effort: agent.effort(),
usage: Usage::default(),
ctx_tokens: agent.context_tokens(),
ctx_max: agent.compact_at(),
@@ -440,6 +456,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
}
TEvent::Mouse(m) => on_mouse(&mut app, m),
TEvent::Paste(s) => app.ed.insert(&s),
TEvent::Resize(..) => app.sel = None,
_ => {}
}
}
@@ -705,12 +722,120 @@ fn inside(r: Rect, x: u16, y: u16) -> bool {
/// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat.
fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
use crossterm::event::MouseEventKind::{ScrollDown, ScrollUp};
let up = match m.kind {
ScrollUp => true,
ScrollDown => false,
_ => return,
};
use crossterm::event::MouseEventKind::{Down, Drag, ScrollDown, ScrollUp, Up};
match m.kind {
ScrollUp => wheel(app, m, true),
ScrollDown => wheel(app, m, false),
Down(MouseButton::Left) | Drag(MouseButton::Left) | Up(MouseButton::Left) => {
select_mouse(app, m)
}
_ => {}
}
}
/// The chat text as drawn, full height (for extracting a selection).
fn chat_buf(app: &App) -> Buffer {
let w = app.areas.chat.width;
let para = Paragraph::new(app.t.lines(app.expanded, w)).wrap(Wrap { trim: false });
let r = Rect::new(0, 0, w, para.line_count(w) as u16);
let mut b = Buffer::empty(r);
Widget::render(para, r, &mut b);
b
}
/// Put `t` on the clipboard (OSC 52) and say so in the footer.
fn copy(app: &mut App, t: &str) {
let t = select::clamp(t);
if t.is_empty() {
return;
}
if !cfg!(test) {
use std::io::Write;
let mut o = std::io::stdout();
let _ = o.write_all(select::osc52(t).as_bytes());
let _ = o.flush();
}
app.hint = format!("copied {} chars", t.chars().count());
}
/// Left button in the chat: drag selects, release copies; double click = word, triple = line.
fn select_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
use crossterm::event::MouseEventKind::{Down, Drag};
if app.agents.is_some()
|| app.picker.is_some()
|| app.sessions.is_some()
|| app.choose.is_some()
|| app.review.is_some()
|| app.perm.is_some()
{
return;
}
let c = app.areas.chat;
if c.width == 0 || c.height == 0 {
return;
}
if matches!(m.kind, Down(_)) {
app.sel = None;
app.drag = false;
if !inside(c, m.column, m.row) {
return;
}
} else if !app.drag {
return;
} else if matches!(m.kind, Drag(_)) {
// dragging past the top/bottom edge scrolls
if m.row <= c.y {
app.scroll.up(1);
} else if m.row + 1 >= c.y + c.height {
app.scroll.down(1);
}
}
let x = m.column.clamp(c.x, c.x + c.width - 1) - c.x;
let y = m.row.clamp(c.y, c.y + c.height - 1) - c.y;
let p = (app.scroll.top().saturating_add(y), x);
match m.kind {
Down(_) => {
let now = Instant::now();
let n = match app.click {
Some((t, q, n)) if q == p && now.duration_since(t).as_millis() < 400 => n % 3 + 1,
_ => 1,
};
app.click = Some((now, p, n));
if n == 1 {
app.sel = Some(select::Sel { anchor: p, head: p });
app.drag = true;
} else {
let b = chat_buf(app);
let s = if n == 2 {
select::word(&b, p.0, p.1)
} else {
select::line(&b, p.0)
};
let t = select::text(&b, &s);
app.sel = Some(s);
copy(app, &t);
}
}
Drag(_) => {
if let Some(s) = &mut app.sel {
s.head = p;
}
}
_ => {
app.drag = false;
match app.sel {
Some(s) if s.anchor != p => {
let t = select::text(&chat_buf(app), &s);
copy(app, &t);
}
_ => app.sel = None,
}
}
}
}
/// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat.
fn wheel(app: &mut App, m: crossterm::event::MouseEvent, up: bool) {
let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
scroll
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() {
@@ -766,6 +891,8 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
let alt = k.modifiers.contains(KeyModifiers::ALT);
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
app.hint.clear();
app.sel = None;
app.drag = false;
if app.probe {
if k.code == KeyCode::Esc {
app.probe = false;
@@ -906,6 +1033,11 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
KeyCode::End => app.ed.end(),
KeyCode::Up => app.ed.up(),
KeyCode::Down => app.ed.down(),
KeyCode::Tab if app.ed.buf.is_empty() => {
app.st.effort = app.st.effort.next(app.st.kind);
app.sw.remember_effort(app.st.effort);
app.hint = format!("thinking: {}", app.st.effort.name());
}
KeyCode::Tab => {
let c = completion(app);
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect();
@@ -1018,6 +1150,16 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
None => app.t.push(Item::Info("no edits to review".into())),
}
}
"copy" => {
let last = app.t.items.iter().rev().find_map(|i| match i {
Item::Assistant(t) => Some(t.clone()),
_ => None,
});
match last {
Some(t) => copy(app, &t),
None => app.hint = "nothing to copy".into(),
}
}
"usage" => {
let r = status::report(&app.st, status::now_secs());
show(app, "usage", r);
@@ -1068,6 +1210,22 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
}
}
"effort" if arg.is_empty() => app.t.push(Item::Info(format!(
"thinking: {} (off, low, medium, high)",
app.st.effort.name()
))),
"effort" => match arg.parse::<hx_ai::Effort>() {
Ok(e) if hx_ai::Effort::levels(app.st.kind).contains(&e) => {
app.st.effort = e;
app.sw.remember_effort(e);
app.t.push(Item::Info(format!("thinking → {}", e.name())));
}
Ok(_) => app.t.push(Item::Error(format!(
"{:?} cannot turn thinking off",
app.st.kind
))),
Err(e) => app.t.push(Item::Error(e)),
},
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
"model" => {
let mut a = agent.lock().await;
@@ -1161,14 +1319,11 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
app.since = Instant::now();
let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone());
let effort = app.st.effort;
tokio::spawn(async move {
let r = agent
.lock()
.await
.run(prompt)
.await
.map(|_| ())
.map_err(|e| e.to_string());
let mut a = agent.lock().await;
a.set_effort(effort);
let r = a.run(prompt).await.map(|_| ()).map_err(|e| e.to_string());
let _ = tx.send(Ui::Done(r));
});
}
@@ -1257,6 +1412,9 @@ fn draw(f: &mut ratatui::Frame, app: &mut App) {
let total = para.line_count(main.width) as u16;
let top = app.scroll.resolve(total, main.height);
f.render_widget(para.scroll((top, 0)), main);
if let Some(s) = &app.sel {
select::paint(f.buffer_mut(), main, top, s);
}
if !sub_rows.is_empty() {
let w = subs_area.width.min(56);
@@ -1748,6 +1906,34 @@ mod tests {
assert_eq!((app.ed.cur, app.scroll.behind()), (0, 0));
}
#[test]
fn mouse_drag_selects_and_click_clears() {
use crossterm::event::{MouseEvent, MouseEventKind::*};
let ev = |kind, column, row| MouseEvent {
kind,
column,
row,
modifiers: KeyModifiers::NONE,
};
let mut app = test_app();
long_chat(&mut app, 30);
draw_at(&mut app, 80, 20);
let c = app.areas.chat;
let l = MouseButton::Left;
on_mouse(&mut app, ev(Down(l), c.x + 1, c.y));
on_mouse(&mut app, ev(Drag(l), c.x + 5, c.y + 2));
assert!(app.drag && app.sel.is_some());
on_mouse(&mut app, ev(Up(l), c.x + 5, c.y + 2));
assert!(!app.drag && app.sel.is_some() && app.hint.starts_with("copied"));
// a plain click (no drag) clears; a key press clears too
on_mouse(&mut app, ev(Down(l), c.x + 9, c.y + 4));
on_mouse(&mut app, ev(Up(l), c.x + 9, c.y + 4));
assert!(app.sel.is_none());
// presses outside the chat start nothing
on_mouse(&mut app, ev(Down(l), 5, 19));
assert!(!app.drag);
}
#[test]
fn mouse_wheel_goes_to_region_under_pointer() {
use crossterm::event::{MouseEvent, MouseEventKind};
@@ -1807,12 +1993,16 @@ mod tests {
scroll: Default::default(),
panel_scroll: Default::default(),
areas: Default::default(),
sel: None,
drag: false,
click: None,
expanded: false,
busy: false,
queue: VecDeque::new(),
st: status::Status {
kind: Kind::Claude,
model: "m1".into(),
effort: hx_ai::Effort::Off,
usage: Usage::default(),
ctx_tokens: 0,
ctx_max: 150_000,
@@ -1886,7 +2076,7 @@ mod tests {
};
assert_eq!(
labels(&app),
Some((vec!["/clear".into(), "/compact".into()], 0))
Some((vec!["/copy".into(), "/clear".into(), "/compact".into()], 0))
);
let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap();
term.draw(|f| draw(f, &mut app)).unwrap();
@@ -1895,10 +2085,10 @@ mod tests {
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect();
assert_eq!(
rows[3], " │ /clear alias of /new │ ",
rows[3], "│ /clear alias of /new │",
"{rows:#?}"
);
assert!(rows[4].starts_with(" │ /compact summarize"), "{rows:#?}");
assert!(rows[4].starts_with("│ /compact summarize"), "{rows:#?}");
assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}");
// footer at 100 cols, and a hint replacing only the right side
@@ -1936,7 +2126,7 @@ mod tests {
key(&mut app, KeyCode::Down);
key(&mut app, KeyCode::Up);
key(&mut app, KeyCode::Up);
assert_eq!(labels(&app).unwrap().1, 1, "wraps");
assert_eq!(labels(&app).unwrap().1, 2, "wraps");
assert_eq!(
key(&mut app, KeyCode::Enter),
None,
+4
View File
@@ -37,6 +37,10 @@ impl Scroll {
self.top = None;
}
}
/// First visible line as of the last draw.
pub fn top(&self) -> u16 {
self.cur()
}
pub fn half_page(&self) -> u16 {
(self.height / 2).max(1)
}
+204
View File
@@ -0,0 +1,204 @@
//! Mouse text selection in the chat view. Coordinates are `(row, col)` in the wrapped content
//! (not the screen), so scrolling doesn't move a selection. Text comes from an off-screen render.
use base64::Engine;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::Span;
/// OSC 52 payloads above this many bytes are cut (some terminals drop bigger ones).
pub const MAX_COPY: usize = 100_000;
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sel {
pub anchor: (u16, u16),
pub head: (u16, u16),
}
impl Sel {
fn span(&self) -> ((u16, u16), (u16, u16)) {
if self.anchor <= self.head {
(self.anchor, self.head)
} else {
(self.head, self.anchor)
}
}
/// Inclusive column range selected on `row`.
fn cols(&self, row: u16, width: u16) -> Option<(u16, u16)> {
let (a, b) = self.span();
if row < a.0 || row > b.0 {
return None;
}
let lo = if row == a.0 { a.1 } else { 0 };
let hi = if row == b.0 {
b.1
} else {
width.saturating_sub(1)
};
Some((lo, hi))
}
}
/// Reverse-video the selected cells of the visible rows (`top` = first content row shown).
pub fn paint(buf: &mut Buffer, area: Rect, top: u16, s: &Sel) {
for y in 0..area.height {
let Some((lo, hi)) = s.cols(top.saturating_add(y), area.width) else {
continue;
};
let hi = hi.min(area.width.saturating_sub(1));
if lo <= hi {
let r = Rect::new(area.x + lo, area.y + y, hi - lo + 1, 1);
buf.set_style(r, Style::new().add_modifier(Modifier::REVERSED));
}
}
}
/// Selected text from a buffer rendered at origin (0, 0); trailing blanks per row are dropped.
pub fn text(buf: &Buffer, s: &Sel) -> String {
let (w, h) = (buf.area.width, buf.area.height);
if w == 0 || h == 0 {
return String::new();
}
let (a, b) = s.span();
let mut rows = vec![];
for row in a.0..=b.0.min(h - 1) {
let Some((lo, hi)) = s.cols(row, w) else {
continue;
};
let (mut line, mut x) = (String::new(), lo);
while x <= hi.min(w - 1) {
let sym = buf[(x, row)].symbol();
line.push_str(sym);
x += Span::raw(sym).width().max(1) as u16; // skip the trailing cell of wide chars
}
rows.push(line.trim_end().to_string());
}
rows.join("\n")
}
fn is_word(sym: &str) -> bool {
sym.chars()
.any(|c| c.is_alphanumeric() || "_-./~".contains(c))
}
/// Double click: the word under `(row, col)`, or just that cell when it isn't on a word.
pub fn word(buf: &Buffer, row: u16, col: u16) -> Sel {
let one = Sel {
anchor: (row, col),
head: (row, col),
};
let w = buf.area.width;
if row >= buf.area.height || col >= w || !is_word(buf[(col, row)].symbol()) {
return one;
}
let ok = |x: u16| is_word(buf[(x, row)].symbol());
let (mut lo, mut hi) = (col, col);
while lo > 0 && ok(lo - 1) {
lo -= 1;
}
while hi + 1 < w && ok(hi + 1) {
hi += 1;
}
Sel {
anchor: (row, lo),
head: (row, hi),
}
}
/// Triple click: the whole row.
pub fn line(buf: &Buffer, row: u16) -> Sel {
let hi = buf.area.width.saturating_sub(1);
Sel {
anchor: (row, 0),
head: (row, hi),
}
}
/// Cut `t` to `MAX_COPY` bytes on a char boundary.
pub fn clamp(t: &str) -> &str {
let mut n = MAX_COPY.min(t.len());
while !t.is_char_boundary(n) {
n -= 1;
}
&t[..n]
}
/// The OSC 52 sequence that puts `t` on the system clipboard.
pub fn osc52(t: &str) -> String {
format!(
"\x1b]52;c;{}\x07",
base64::engine::general_purpose::STANDARD.encode(t)
)
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::widgets::{Paragraph, Widget};
fn buf(s: &str, w: u16) -> Buffer {
let r = Rect::new(0, 0, w, s.lines().count() as u16);
let mut b = Buffer::empty(r);
Paragraph::new(s).render(r, &mut b);
b
}
#[test]
fn text_spans_rows_either_direction_and_skips_wide_tails() {
let b = buf("hello world\nsecond 日本 x\nthird", 20);
let fwd = Sel {
anchor: (0, 6),
head: (1, 5),
};
assert_eq!(text(&b, &fwd), "world\nsecond");
let rev = Sel {
anchor: (1, 5),
head: (0, 6),
};
assert_eq!(text(&b, &rev), "world\nsecond");
let wide = Sel {
anchor: (1, 7),
head: (1, 10),
};
assert_eq!(text(&b, &wide), "日本");
let past = Sel {
anchor: (2, 0),
head: (9, 3),
};
assert_eq!(text(&b, &past), "third");
}
#[test]
fn word_and_line_pick() {
let b = buf("see src/main.rs now", 30);
assert_eq!(text(&b, &word(&b, 0, 6)), "src/main.rs");
assert_eq!(
word(&b, 0, 3),
Sel {
anchor: (0, 3),
head: (0, 3)
}
);
assert_eq!(text(&b, &line(&b, 0)), "see src/main.rs now");
}
#[test]
fn paint_reverses_only_selected_cells() {
let mut b = buf("abcdef\nghijkl", 10);
let s = Sel {
anchor: (0, 4),
head: (1, 1),
};
paint(&mut b, Rect::new(0, 0, 10, 2), 0, &s);
let rev = |x, y| b[(x, y)].modifier.contains(Modifier::REVERSED);
assert!(!rev(3, 0) && rev(4, 0) && rev(9, 0) && rev(0, 1) && rev(1, 1) && !rev(2, 1));
}
#[test]
fn osc52_and_clamp() {
assert_eq!(osc52("hi"), "\x1b]52;c;aGk=\x07");
let big = "é".repeat(MAX_COPY);
assert!(clamp(&big).len() <= MAX_COPY && big.starts_with(clamp(&big)));
}
}
+5
View File
@@ -13,6 +13,7 @@ use ratatui::text::{Line, Span};
pub struct Status {
pub kind: Kind,
pub model: String,
pub effort: hx_ai::Effort,
pub usage: Usage,
pub ctx_tokens: usize,
/// auto-compact threshold: the context bar's 100%
@@ -226,6 +227,9 @@ pub fn footer(st: &Status, c: &Chrome, width: u16, now: u64) -> Line<'static> {
fn tail(st: &Status, c: &Chrome) -> Vec<String> {
let mut t = vec![format!("{:?}", st.kind), st.model.clone()];
if st.effort != hx_ai::Effort::Off {
t.push(format!("think {}", st.effort.name()));
}
if c.queued > 0 {
t.push(format!("{} queued", c.queued));
}
@@ -322,6 +326,7 @@ mod tests {
Status {
kind: Kind::Claude,
model: "m1".into(),
effort: hx_ai::Effort::Off,
usage: Usage::default(),
ctx_tokens: 0,
ctx_max: 150_000,