From 2f1ce2c072eee9947480d7f757f36840443094ca Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 11:43:51 +0000 Subject: [PATCH 1/5] Remember last chosen provider/model in HX_HOME/last.json --- crates/hx-cli/src/main.rs | 23 ++++++++++++++---- crates/hx-core/src/switch.rs | 46 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 4 deletions(-) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index f5d76c2..2c96c8e 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -99,6 +99,8 @@ struct Config { explore_model: Option, /// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift). mouse: Option, + /// Reuse the last model chosen with /model or /provider (default true). + remember_model: Option, /// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI. permissions: Option, /// Replaces the built-in system prompt (AGENTS.md etc. are still appended). @@ -146,6 +148,7 @@ impl Config { max_tokens: o.max_tokens.or(c.max_tokens), explore_model: o.explore_model.or(c.explore_model), mouse: o.mouse.or(c.mouse), + remember_model: o.remember_model.or(c.remember_model), permissions: o.permissions.or(c.permissions), system_prompt: o.system_prompt.or(c.system_prompt), lsp: o.lsp.or(c.lsp), @@ -478,10 +481,18 @@ async fn main() -> Result<()> { let cwd = std::env::current_dir()?; let cfg = Config::load(&cwd)?; let kinds = logged_in(); - // default provider: configured, else the first one logged in + let last_path = context::hx_home().join("last.json"); + let remember = cfg.remember_model != Some(false); + // last /model choice, only while its provider is still logged in + let last = remember + .then(|| hx_core::switch::Last::load(&last_path)) + .flatten() + .filter(|l| kinds.contains(&l.provider)); + // default provider: flag, config, last choice, else the first one logged in let kind = cli .provider .or(cfg.provider) + .or(last.as_ref().map(|l| l.provider)) .or(kinds.first().copied()) .unwrap_or(Kind::Claude); let models = catalog(&kinds).await; @@ -490,7 +501,9 @@ async fn main() -> Result<()> { (None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind), _ => kind, }; - let model = cli.model.or(cfg.model).unwrap_or_else(|| { + // the remembered model applies only to the provider it was chosen on + let last_model = last.filter(|l| l.provider == kind).map(|l| l.model); + let model = cli.model.or(cfg.model).or(last_model).unwrap_or_else(|| { match kind { Kind::Claude => cfg.claude_model.clone(), Kind::Codex => cfg.codex_model.clone(), @@ -667,7 +680,8 @@ async fn main() -> Result<()> { models.clone(), Box::new(provider), cfg.compact_at.is_none(), - ), + ) + .remember_in(last_path.clone()), }, ) .await; @@ -685,7 +699,8 @@ async fn main() -> Result<()> { models.clone(), Box::new(provider), cfg.compact_at.is_none(), - ), + ) + .remember_in(last_path), pricing, specs, open_sessions, diff --git a/crates/hx-core/src/switch.rs b/crates/hx-core/src/switch.rs index 0734a92..6e2c0f4 100644 --- a/crates/hx-core/src/switch.rs +++ b/crates/hx-core/src/switch.rs @@ -23,7 +23,22 @@ pub struct Switched { pub window: u64, } +/// Last chosen provider + model, kept in `$HX_HOME/last.json` so the next start reuses it. +#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)] +pub struct Last { + pub provider: Kind, + pub model: String, +} + +impl Last { + /// `None` when the file is missing or unreadable. + pub fn load(path: &std::path::Path) -> Option { + serde_json::from_slice(&std::fs::read(path).ok()?).ok() + } +} + pub struct Switcher { + remember: Option, kind: Kind, models: Vec, make_provider: MakeProvider, @@ -40,6 +55,7 @@ impl Switcher { auto_compact: bool, ) -> Self { Self { + remember: None, kind, models, make_provider, @@ -47,6 +63,12 @@ impl Switcher { } } + /// Write every successful switch to `path` (best effort). + pub fn remember_in(mut self, path: std::path::PathBuf) -> Self { + self.remember = Some(path); + self + } + /// The provider the agent currently uses. pub fn kind(&self) -> Kind { self.kind @@ -81,6 +103,14 @@ impl Switcher { } else { agent.set_model(model.as_str()); } + if let Some(p) = &self.remember { + let last = Last { + provider: kind, + model: model.clone(), + }; + // ponytail: failing to save must not fail the switch + let _ = serde_json::to_vec(&last).map(|b| std::fs::write(p, b)); + } let window = models::window(&self.models, &model); if self.auto_compact { agent.fit_window(window); @@ -219,6 +249,22 @@ mod tests { ); } + #[test] + fn switches_are_remembered() { + let (sw, mut a, _m, d) = setup(true, false); + let f = d.path().join("last.json"); + assert_eq!(Last::load(&f), None); + let mut sw = sw.remember_in(f.clone()); + sw.set_model(&mut a, "gpt-x").unwrap(); + let want = Last { + provider: Kind::Codex, + model: "gpt-x".into(), + }; + assert_eq!(Last::load(&f), Some(want)); + std::fs::write(&f, "junk").unwrap(); + assert_eq!(Last::load(&f), None); + } + #[test] fn configured_threshold_is_left_alone() { let (mut sw, mut a, _m, _d) = setup(false, false); From 2c1d2a6c85d62e2d9524f8659870cbe109600701 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 12:02:51 +0000 Subject: [PATCH 2/5] tui: drag-select text in chat, copy via OSC 52 (+ /copy) --- Cargo.lock | 1 + crates/hx-core/src/command.rs | 3 +- crates/hx-tui/Cargo.toml | 1 + crates/hx-tui/src/lib.rs | 191 ++++++++++++++++++++++++++++--- crates/hx-tui/src/scroll.rs | 4 + crates/hx-tui/src/select.rs | 204 ++++++++++++++++++++++++++++++++++ 6 files changed, 390 insertions(+), 14 deletions(-) create mode 100644 crates/hx-tui/src/select.rs diff --git a/Cargo.lock b/Cargo.lock index 7013cc9..a2177c1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1057,6 +1057,7 @@ name = "hx-tui" version = "0.1.0" dependencies = [ "async-trait", + "base64 0.23.1", "crossterm", "futures", "hx-ai", diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index bdff3f9..571fba1 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -61,6 +61,7 @@ pub fn builtins(models: &[&str]) -> Vec { b("clear", "alias of /new", None), b("sessions", "browse, resume, delete sessions", None), b("lsp", "language server status", None), + b("copy", "copy the last answer to the clipboard", None), b("usage", "subscription limits, resets, credits", None), b( "keys", @@ -307,7 +308,7 @@ mod tests { assert_eq!(c("/").items.len(), MAX_ITEMS); assert_eq!(labels(&c("/mo")), ["/model"]); - assert_eq!(labels(&c("/co")), ["/compact"]); + assert_eq!(labels(&c("/co")), ["/copy", "/compact"]); let r = c("/rev"); assert_eq!(labels(&r), ["/review"]); assert_eq!(r.items[0].detail, "skill · code review"); diff --git a/crates/hx-tui/Cargo.toml b/crates/hx-tui/Cargo.toml index 3f84606..9a3fffb 100644 --- a/crates/hx-tui/Cargo.toml +++ b/crates/hx-tui/Cargo.toml @@ -6,6 +6,7 @@ license.workspace = true [dependencies] async-trait = "0.1.92" +base64 = "0.23.1" crossterm = { version = "0.29.0", features = ["event-stream"] } futures = "0.3.34" hx-ai = { version = "0.1.0", path = "../hx-ai" } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index a2abbe3..803f7f4 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -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, /// 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, + 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, @@ -292,6 +299,9 @@ 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(), @@ -440,6 +450,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 +716,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 +885,8 @@ 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(); + app.sel = None; + app.drag = false; if app.probe { if k.code == KeyCode::Esc { app.probe = false; @@ -1018,6 +1139,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); @@ -1243,6 +1374,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); @@ -1734,6 +1868,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}; @@ -1793,6 +1955,9 @@ 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(), @@ -1872,7 +2037,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(); @@ -1881,10 +2046,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 @@ -1922,7 +2087,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, diff --git a/crates/hx-tui/src/scroll.rs b/crates/hx-tui/src/scroll.rs index a1ef465..4e219bc 100644 --- a/crates/hx-tui/src/scroll.rs +++ b/crates/hx-tui/src/scroll.rs @@ -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) } diff --git a/crates/hx-tui/src/select.rs b/crates/hx-tui/src/select.rs new file mode 100644 index 0000000..440beb2 --- /dev/null +++ b/crates/hx-tui/src/select.rs @@ -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))); + } +} From ab2af421a4674cafb26c01ac5fea814583da40a5 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 12:05:29 +0000 Subject: [PATCH 3/5] Thinking levels: Tab cycles off/low/medium/high, /effort --- crates/hx-ai/src/anthropic.rs | 23 +++++++++ crates/hx-ai/src/codex.rs | 19 +++---- crates/hx-ai/src/lib.rs | 94 +++++++++++++++++++++++++++++++++++ crates/hx-cli/src/main.rs | 1 + crates/hx-core/src/agent.rs | 12 +++++ crates/hx-core/src/command.rs | 5 ++ crates/hx-core/src/compact.rs | 1 + crates/hx-tui/src/lib.rs | 36 +++++++++++--- crates/hx-tui/src/status.rs | 5 ++ 9 files changed, 180 insertions(+), 16 deletions(-) diff --git a/crates/hx-ai/src/anthropic.rs b/crates/hx-ai/src/anthropic.rs index c61b7fb..678b8b8 100644 --- a/crates/hx-ai/src/anthropic.rs +++ b/crates/hx-ai/src/anthropic.rs @@ -120,6 +120,18 @@ pub fn body(req: &Request) -> Value { if !tools.is_empty() { b["tools"] = tools.into(); } + // ponytail: fixed token budgets; newer models may prefer adaptive thinking, add when needed + let budget = match req.effort { + crate::Effort::Off => 0, + crate::Effort::Low => 4_000, + crate::Effort::Medium => 10_000, + crate::Effort::High => 24_000, + }; + if budget > 0 { + b["thinking"] = json!({"type": "enabled", "budget_tokens": budget}); + // the budget counts against max_tokens, which must leave room for the reply + b["max_tokens"] = req.max_tokens.max(budget + 4_096).into(); + } b } @@ -377,6 +389,16 @@ mod tests { use super::*; use crate::ToolSpec; + #[test] + fn effort_sets_thinking_budget() { + let mut r = req(); + assert!(body(&r).get("thinking").is_none()); + r.effort = crate::Effort::High; + let b = body(&r); + assert_eq!(b["thinking"]["budget_tokens"], 24_000); + assert!(b["max_tokens"].as_u64().unwrap() > 24_000); + } + #[test] fn quota_and_models() { let mut h = reqwest::header::HeaderMap::new(); @@ -427,6 +449,7 @@ mod tests { input_schema: json!({"type": "object"}), }], max_tokens: 1024, + effort: crate::Effort::Off, } } diff --git a/crates/hx-ai/src/codex.rs b/crates/hx-ai/src/codex.rs index bbbda8f..31ea913 100644 --- a/crates/hx-ai/src/codex.rs +++ b/crates/hx-ai/src/codex.rs @@ -12,8 +12,6 @@ pub struct Codex { auth: Auth, base_url: String, http: reqwest::Client, - /// "none" | "minimal" | "low" | "medium" | "high" - pub reasoning_effort: Option, } impl Codex { @@ -22,7 +20,6 @@ impl Codex { auth, base_url: "https://chatgpt.com/backend-api/codex".into(), http: reqwest::Client::new(), - reasoning_effort: Some("medium".into()), } } pub fn login_default() -> Result { @@ -42,7 +39,7 @@ fn split_id(id: &str) -> (&str, Option<&str>) { } } -pub fn body(req: &Request, effort: Option<&str>) -> Value { +pub fn body(req: &Request) -> Value { let mut input = vec![]; for m in &req.messages { for b in &m.content { @@ -109,9 +106,12 @@ pub fn body(req: &Request, effort: Option<&str>) -> Value { "text": {"verbosity": "low"}, "include": ["reasoning.encrypted_content"], }); - if let Some(e) = effort { - b["reasoning"] = json!({"effort": e, "summary": "auto"}); - } + // Off has no Codex equivalent (see Effort::levels); send the lowest level instead + let e = match req.effort { + crate::Effort::Off | crate::Effort::Low => "low", + e => e.name(), + }; + b["reasoning"] = json!({"effort": e, "summary": "auto"}); b } @@ -368,7 +368,7 @@ impl Provider for Codex { .header("OpenAI-Beta", "responses=experimental") .header("accept", "text/event-stream") .header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION"))) - .json(&body(&req, self.reasoning_effort.as_deref())) + .json(&body(&req)) .send() .await .map_err(|e| Error::Http(e.to_string()))?; @@ -528,8 +528,9 @@ mod tests { input_schema: json!({"type":"object"}), }], max_tokens: 100, + effort: crate::Effort::Low, }; - let b = body(&req, Some("low")); + let b = body(&req); let inp = b["input"].as_array().unwrap(); assert_eq!(inp[0]["content"][0]["type"], "input_text"); assert_eq!(inp[1]["type"], "reasoning"); diff --git a/crates/hx-ai/src/lib.rs b/crates/hx-ai/src/lib.rs index 07c0421..ae10dd7 100644 --- a/crates/hx-ai/src/lib.rs +++ b/crates/hx-ai/src/lib.rs @@ -138,6 +138,99 @@ pub enum StopReason { Other, } +/// How hard the model thinks before answering. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Effort { + Off, + Low, + #[default] + Medium, + High, +} + +impl Effort { + pub const ALL: [Effort; 4] = [Effort::Off, Effort::Low, Effort::Medium, Effort::High]; + + /// Start level per provider: Claude thinks only when asked (token cost), Codex always reasons. + pub fn default_for(k: auth::Kind) -> Self { + match k { + auth::Kind::Claude => Effort::Off, + auth::Kind::Codex => Effort::Medium, + } + } + + /// Levels the provider supports (Codex models can't switch reasoning off). + pub fn levels(k: auth::Kind) -> &'static [Effort] { + match k { + auth::Kind::Claude => &Self::ALL, + auth::Kind::Codex => &Self::ALL[1..], + } + } + + /// Next level in `levels(k)`, wrapping; a level the provider lacks maps to its first. + pub fn next(self, k: auth::Kind) -> Self { + let l = Self::levels(k); + l.iter() + .position(|&e| e == self) + .map_or(l[0], |i| l[(i + 1) % l.len()]) + } + + pub fn name(self) -> &'static str { + match self { + Effort::Off => "off", + Effort::Low => "low", + Effort::Medium => "medium", + Effort::High => "high", + } + } +} + +#[cfg(test)] +mod effort_tests { + use super::*; + use auth::Kind; + + #[test] + fn cycle_wraps_and_codex_skips_off() { + let mut e = Effort::Off; + let seen: Vec<_> = (0..5) + .map(|_| { + e = e.next(Kind::Claude); + e + }) + .collect(); + assert_eq!( + seen, + [ + Effort::Low, + Effort::Medium, + Effort::High, + Effort::Off, + Effort::Low + ] + ); + assert_eq!(Effort::High.next(Kind::Codex), Effort::Low); + assert_eq!( + Effort::Off.next(Kind::Codex), + Effort::Low, + "unsupported level" + ); + assert_eq!("high".parse::(), Ok(Effort::High)); + assert!("max".parse::().is_err()); + } +} + +impl std::str::FromStr for Effort { + type Err = String; + fn from_str(s: &str) -> std::result::Result { + Self::ALL + .into_iter() + .find(|e| e.name() == s) + .ok_or_else(|| format!("unknown level {s:?} (off, low, medium, high)")) + } +} + #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct Request { pub model: String, @@ -145,6 +238,7 @@ pub struct Request { pub messages: Vec, pub tools: Vec, pub max_tokens: u32, + pub effort: Effort, } /// Incremental stream events. Providers must emit `Done` last with the full assembled message. diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 2c96c8e..3ac7731 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -544,6 +544,7 @@ async fn main() -> Result<()> { cx, ); agent.set_model(model); + agent.set_effort(hx_ai::Effort::default_for(kind)); agent.set_system(context::system_prompt( cfg.system_prompt.as_deref(), &context::hx_home(), diff --git a/crates/hx-core/src/agent.rs b/crates/hx-core/src/agent.rs index 20ff894..22b6b70 100644 --- a/crates/hx-core/src/agent.rs +++ b/crates/hx-core/src/agent.rs @@ -32,6 +32,7 @@ pub struct Agent { model: String, system: String, max_tokens: u32, + effort: hx_ai::Effort, max_turns: u32, usage: Usage, session: Session, @@ -71,6 +72,7 @@ impl Agent { model: String::new(), system: String::new(), max_tokens: 16_384, + effort: hx_ai::Effort::Off, max_turns: 200, usage: Usage::default(), session, @@ -107,6 +109,15 @@ impl Agent { self.model = model.into(); } + pub fn effort(&self) -> hx_ai::Effort { + self.effort + } + + /// Thinking level for the following requests. + pub fn set_effort(&mut self, e: hx_ai::Effort) { + self.effort = e; + } + pub fn set_system(&mut self, system: impl Into) { self.system = system.into(); } @@ -239,6 +250,7 @@ impl Agent { messages: view.messages, tools: self.tools.specs(), max_tokens: self.max_tokens, + effort: self.effort, }; let mut s = self.provider.stream(req).await?; let mut done = None; diff --git a/crates/hx-core/src/command.rs b/crates/hx-core/src/command.rs index bdff3f9..b8b1d68 100644 --- a/crates/hx-core/src/command.rs +++ b/crates/hx-core/src/command.rs @@ -56,6 +56,11 @@ pub fn builtins(models: &[&str]) -> Vec { "switch provider", Enum(vec!["claude".into(), "codex".into()]), ), + b( + "effort", + "thinking level (tab on an empty line cycles)", + Enum(["off", "low", "medium", "high"].map(String::from).into()), + ), b("compact", "summarize old context", None), b("new", "start a new session (old one stays resumable)", None), b("clear", "alias of /new", None), diff --git a/crates/hx-core/src/compact.rs b/crates/hx-core/src/compact.rs index 2231623..7fcbcd6 100644 --- a/crates/hx-core/src/compact.rs +++ b/crates/hx-core/src/compact.rs @@ -43,6 +43,7 @@ impl Plan { messages: vec![Message::user(self.transcript.clone())], tools: vec![], max_tokens: 4096, + effort: hx_ai::Effort::Off, } } diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index a2abbe3..681b1c3 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -183,6 +183,10 @@ 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]; + } if sw.provider_changed { self.st.quota = None; } @@ -298,6 +302,7 @@ pub async fn run(setup: Setup) -> std::io::Result<()> { 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(), @@ -906,6 +911,10 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { 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.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(); @@ -1054,6 +1063,21 @@ 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::() { + Ok(e) if hx_ai::Effort::levels(app.st.kind).contains(&e) => { + app.st.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; @@ -1147,14 +1171,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)); }); } @@ -1799,6 +1820,7 @@ mod tests { st: status::Status { kind: Kind::Claude, model: "m1".into(), + effort: hx_ai::Effort::Off, usage: Usage::default(), ctx_tokens: 0, ctx_max: 150_000, diff --git a/crates/hx-tui/src/status.rs b/crates/hx-tui/src/status.rs index 6bd960c..1453cab 100644 --- a/crates/hx-tui/src/status.rs +++ b/crates/hx-tui/src/status.rs @@ -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 { 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, From 49be5673bdc386dfb7a7dfa47b1eb7f5e931edd2 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 12:08:27 +0000 Subject: [PATCH 4/5] Ask parallel permission prompts one by one; add allow-all-edits option --- crates/hx-core/src/lib.rs | 2 ++ crates/hx-core/src/permit.rs | 16 ++++++++++++++++ crates/hx-core/src/tool.rs | 25 +++++++++++++++++-------- crates/hx-tui/src/permit_view.rs | 7 +++++++ 4 files changed, 42 insertions(+), 8 deletions(-) diff --git a/crates/hx-core/src/lib.rs b/crates/hx-core/src/lib.rs index 8bf0f51..af3bfb8 100644 --- a/crates/hx-core/src/lib.rs +++ b/crates/hx-core/src/lib.rs @@ -59,6 +59,8 @@ pub struct State { pub permit: std::sync::OnceLock, /// Rules the user allowed for good. pub allow: Mutex, + /// Serializes permission prompts: parallel tool calls are asked one by one. + pub asking: tokio::sync::Mutex<()>, /// Every write/edit this session, for `/review`. pub edits: Mutex>, /// Same for multiple-choice questions. diff --git a/crates/hx-core/src/permit.rs b/crates/hx-core/src/permit.rs index 93bc467..fcc3315 100644 --- a/crates/hx-core/src/permit.rs +++ b/crates/hx-core/src/permit.rs @@ -77,6 +77,8 @@ pub struct Request { pub enum Decision { Once, Always, + /// All write/edit calls for the rest of this session (not persisted). + Edits, Deny, } @@ -161,6 +163,7 @@ fn glob(pat: &str, s: &str) -> bool { #[derive(Default)] pub struct Allow { rules: HashSet, + all_edits: bool, file: Option, } @@ -173,12 +176,16 @@ impl Allow { .unwrap_or_default(); Self { rules, + all_edits: false, file: Some(file), } } /// Is this request covered by a stored rule? `bash:cargo test *` also covers a bare `cargo test`. pub fn allows(&self, r: &Request) -> bool { + if self.all_edits && matches!(r.tool.as_str(), "write" | "edit") { + return true; + } if r.tool != "bash" { return self.rules.contains(&r.rule); } @@ -191,6 +198,11 @@ impl Allow { .any(|p| glob(p, &r.detail) || p.strip_suffix(" *").is_some_and(|b| b == r.detail)) } + /// Allow every write/edit until the session ends. + pub fn allow_edits(&mut self) { + self.all_edits = true; + } + /// Remember a rule; the file is best effort (the rule holds for this session either way). pub fn add(&mut self, rule: &str) { if rule.is_empty() { @@ -265,5 +277,9 @@ mod tests { assert!(Allow::load(d.path()).allows(&bash("cargo test -q"))); a.add(""); assert!(!a.allows(&bash(""))); + let e = request("edit", &json!({"path": "a.rs"})); + assert!(!a.allows(&e)); + a.allow_edits(); + assert!(a.allows(&e) && !a.allows(&bash("make"))); } } diff --git a/crates/hx-core/src/tool.rs b/crates/hx-core/src/tool.rs index fdb690c..0157472 100644 --- a/crates/hx-core/src/tool.rs +++ b/crates/hx-core/src/tool.rs @@ -109,15 +109,18 @@ impl Registry { && let Some(ask) = cx.state.permit.get() { let req = crate::permit::request(name, &args); - let known = cx - .state - .allow - .lock() - .unwrap_or_else(|e| e.into_inner()) - .allows(&req); - if !known { + let allowed = || { + cx.state + .allow + .lock() + .unwrap_or_else(|e| e.into_inner()) + .allows(&req) + }; + // One prompt at a time; re-check after waiting, an earlier answer may cover this call. + let _turn = cx.state.asking.lock().await; + if !allowed() { let rule = req.rule.clone(); - match ask(req).await { + match ask(req.clone()).await { crate::permit::Decision::Once => {} crate::permit::Decision::Always => cx .state @@ -125,6 +128,12 @@ impl Registry { .lock() .unwrap_or_else(|e| e.into_inner()) .add(&rule), + crate::permit::Decision::Edits => cx + .state + .allow + .lock() + .unwrap_or_else(|e| e.into_inner()) + .allow_edits(), crate::permit::Decision::Deny => { return ToolResult::err( "denied by the user; do not retry, ask what to do instead", diff --git a/crates/hx-tui/src/permit_view.rs b/crates/hx-tui/src/permit_view.rs index d1714e0..81c30e4 100644 --- a/crates/hx-tui/src/permit_view.rs +++ b/crates/hx-tui/src/permit_view.rs @@ -33,6 +33,9 @@ impl Prompt { .unwrap_or(&self.req.rule); v.push((Decision::Always, format!("[a] allow always: {r}"))); } + if matches!(self.req.tool.as_str(), "write" | "edit") { + v.push((Decision::Edits, "[e] allow all edits this session".into())); + } v.push((Decision::Deny, "[n] deny".into())); v } @@ -41,6 +44,9 @@ impl Prompt { match k.code { KeyCode::Char('y' | 'Y') => Some(Decision::Once), KeyCode::Char('a' | 'A') if self.can_always() => Some(Decision::Always), + KeyCode::Char('e' | 'E') if matches!(self.req.tool.as_str(), "write" | "edit") => { + Some(Decision::Edits) + } KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(Decision::Deny), KeyCode::Up | KeyCode::Left => { let n = self.opts().len(); @@ -60,6 +66,7 @@ impl Prompt { match d { Decision::Once => "allowed", Decision::Always => "allowed always", + Decision::Edits => "allowed all edits this session:", Decision::Deny => "denied", } } From e1143f0b8b573c571e5a564421ed1acbca019492 Mon Sep 17 00:00:00 2001 From: hermes Date: Tue, 6 Oct 2026 12:15:17 +0000 Subject: [PATCH 5/5] Remember thinking level in last.json too --- crates/hx-cli/src/main.rs | 18 +++++++++++++---- crates/hx-core/src/switch.rs | 39 ++++++++++++++++++++++++++---------- crates/hx-tui/src/lib.rs | 3 +++ 3 files changed, 45 insertions(+), 15 deletions(-) diff --git a/crates/hx-cli/src/main.rs b/crates/hx-cli/src/main.rs index 3ac7731..865b9c2 100644 --- a/crates/hx-cli/src/main.rs +++ b/crates/hx-cli/src/main.rs @@ -502,7 +502,9 @@ async fn main() -> Result<()> { _ => kind, }; // the remembered model applies only to the provider it was chosen on - let last_model = last.filter(|l| l.provider == kind).map(|l| l.model); + let last = last.filter(|l| l.provider == kind); + let last_effort = last.as_ref().and_then(|l| l.effort); + let last_model = last.map(|l| l.model); let model = cli.model.or(cfg.model).or(last_model).unwrap_or_else(|| { match kind { Kind::Claude => cfg.claude_model.clone(), @@ -543,8 +545,16 @@ async fn main() -> Result<()> { Session::open(&path)?, cx, ); + let effort = last_effort + .filter(|e| hx_ai::Effort::levels(kind).contains(e)) + .unwrap_or(hx_ai::Effort::default_for(kind)); + let start = hx_core::switch::Last { + provider: kind, + model: model.clone(), + effort: Some(effort), + }; agent.set_model(model); - agent.set_effort(hx_ai::Effort::default_for(kind)); + agent.set_effort(effort); agent.set_system(context::system_prompt( cfg.system_prompt.as_deref(), &context::hx_home(), @@ -682,7 +692,7 @@ async fn main() -> Result<()> { Box::new(provider), cfg.compact_at.is_none(), ) - .remember_in(last_path.clone()), + .remember_in(last_path.clone(), start.clone()), }, ) .await; @@ -701,7 +711,7 @@ async fn main() -> Result<()> { Box::new(provider), cfg.compact_at.is_none(), ) - .remember_in(last_path), + .remember_in(last_path, start), pricing, specs, open_sessions, diff --git a/crates/hx-core/src/switch.rs b/crates/hx-core/src/switch.rs index 6e2c0f4..c33b645 100644 --- a/crates/hx-core/src/switch.rs +++ b/crates/hx-core/src/switch.rs @@ -24,10 +24,13 @@ pub struct Switched { } /// Last chosen provider + model, kept in `$HX_HOME/last.json` so the next start reuses it. -#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq)] +#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Clone)] pub struct Last { pub provider: Kind, pub model: String, + /// Thinking level; absent in files written before it was saved. + #[serde(default)] + pub effort: Option, } impl Last { @@ -38,7 +41,7 @@ impl Last { } pub struct Switcher { - remember: Option, + remember: Option<(std::path::PathBuf, Last)>, kind: Kind, models: Vec, make_provider: MakeProvider, @@ -64,11 +67,20 @@ impl Switcher { } /// Write every successful switch to `path` (best effort). - pub fn remember_in(mut self, path: std::path::PathBuf) -> Self { - self.remember = Some(path); + /// `start` is what the agent starts with. + pub fn remember_in(mut self, path: std::path::PathBuf, start: Last) -> Self { + self.remember = Some((path, start)); self } + /// Save a new thinking level next to the model (best effort). + pub fn remember_effort(&mut self, e: hx_ai::Effort) { + if let Some((p, l)) = &mut self.remember { + l.effort = Some(e); + let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b)); + } + } + /// The provider the agent currently uses. pub fn kind(&self) -> Kind { self.kind @@ -103,13 +115,11 @@ impl Switcher { } else { agent.set_model(model.as_str()); } - if let Some(p) = &self.remember { - let last = Last { - provider: kind, - model: model.clone(), - }; + if let Some((p, l)) = &mut self.remember { + l.provider = kind; + l.model = model.clone(); // ponytail: failing to save must not fail the switch - let _ = serde_json::to_vec(&last).map(|b| std::fs::write(p, b)); + let _ = serde_json::to_vec(&*l).map(|b| std::fs::write(&*p, b)); } let window = models::window(&self.models, &model); if self.auto_compact { @@ -254,11 +264,18 @@ mod tests { let (sw, mut a, _m, d) = setup(true, false); let f = d.path().join("last.json"); assert_eq!(Last::load(&f), None); - let mut sw = sw.remember_in(f.clone()); + let start = Last { + provider: Kind::Claude, + model: "m".into(), + effort: None, + }; + let mut sw = sw.remember_in(f.clone(), start); sw.set_model(&mut a, "gpt-x").unwrap(); + sw.remember_effort(hx_ai::Effort::High); let want = Last { provider: Kind::Codex, model: "gpt-x".into(), + effort: Some(hx_ai::Effort::High), }; assert_eq!(Last::load(&f), Some(want)); std::fs::write(&f, "junk").unwrap(); diff --git a/crates/hx-tui/src/lib.rs b/crates/hx-tui/src/lib.rs index 681b1c3..a50d60a 100644 --- a/crates/hx-tui/src/lib.rs +++ b/crates/hx-tui/src/lib.rs @@ -186,6 +186,7 @@ impl App { // 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; @@ -913,6 +914,7 @@ fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option { 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 => { @@ -1070,6 +1072,7 @@ async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) { "effort" => match arg.parse::() { 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!(