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

Generated
+1
View File
@@ -1057,6 +1057,7 @@ name = "hx-tui"
version = "0.1.0" version = "0.1.0"
dependencies = [ dependencies = [
"async-trait", "async-trait",
"base64 0.23.1",
"crossterm", "crossterm",
"futures", "futures",
"hx-ai", "hx-ai",
+23
View File
@@ -120,6 +120,18 @@ pub fn body(req: &Request) -> Value {
if !tools.is_empty() { if !tools.is_empty() {
b["tools"] = tools.into(); 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 b
} }
@@ -377,6 +389,16 @@ mod tests {
use super::*; use super::*;
use crate::ToolSpec; 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] #[test]
fn quota_and_models() { fn quota_and_models() {
let mut h = reqwest::header::HeaderMap::new(); let mut h = reqwest::header::HeaderMap::new();
@@ -427,6 +449,7 @@ mod tests {
input_schema: json!({"type": "object"}), input_schema: json!({"type": "object"}),
}], }],
max_tokens: 1024, max_tokens: 1024,
effort: crate::Effort::Off,
} }
} }
+10 -9
View File
@@ -12,8 +12,6 @@ pub struct Codex {
auth: Auth, auth: Auth,
base_url: String, base_url: String,
http: reqwest::Client, http: reqwest::Client,
/// "none" | "minimal" | "low" | "medium" | "high"
pub reasoning_effort: Option<String>,
} }
impl Codex { impl Codex {
@@ -22,7 +20,6 @@ impl Codex {
auth, auth,
base_url: "https://chatgpt.com/backend-api/codex".into(), base_url: "https://chatgpt.com/backend-api/codex".into(),
http: reqwest::Client::new(), http: reqwest::Client::new(),
reasoning_effort: Some("medium".into()),
} }
} }
pub fn login_default() -> Result<Self> { pub fn login_default() -> Result<Self> {
@@ -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![]; let mut input = vec![];
for m in &req.messages { for m in &req.messages {
for b in &m.content { for b in &m.content {
@@ -109,9 +106,12 @@ pub fn body(req: &Request, effort: Option<&str>) -> Value {
"text": {"verbosity": "low"}, "text": {"verbosity": "low"},
"include": ["reasoning.encrypted_content"], "include": ["reasoning.encrypted_content"],
}); });
if let Some(e) = effort { // Off has no Codex equivalent (see Effort::levels); send the lowest level instead
b["reasoning"] = json!({"effort": e, "summary": "auto"}); let e = match req.effort {
} crate::Effort::Off | crate::Effort::Low => "low",
e => e.name(),
};
b["reasoning"] = json!({"effort": e, "summary": "auto"});
b b
} }
@@ -368,7 +368,7 @@ impl Provider for Codex {
.header("OpenAI-Beta", "responses=experimental") .header("OpenAI-Beta", "responses=experimental")
.header("accept", "text/event-stream") .header("accept", "text/event-stream")
.header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION"))) .header("user-agent", concat!("hx/", env!("CARGO_PKG_VERSION")))
.json(&body(&req, self.reasoning_effort.as_deref())) .json(&body(&req))
.send() .send()
.await .await
.map_err(|e| Error::Http(e.to_string()))?; .map_err(|e| Error::Http(e.to_string()))?;
@@ -528,8 +528,9 @@ mod tests {
input_schema: json!({"type":"object"}), input_schema: json!({"type":"object"}),
}], }],
max_tokens: 100, max_tokens: 100,
effort: crate::Effort::Low,
}; };
let b = body(&req, Some("low")); let b = body(&req);
let inp = b["input"].as_array().unwrap(); let inp = b["input"].as_array().unwrap();
assert_eq!(inp[0]["content"][0]["type"], "input_text"); assert_eq!(inp[0]["content"][0]["type"], "input_text");
assert_eq!(inp[1]["type"], "reasoning"); assert_eq!(inp[1]["type"], "reasoning");
+94
View File
@@ -138,6 +138,99 @@ pub enum StopReason {
Other, 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::<Effort>(), Ok(Effort::High));
assert!("max".parse::<Effort>().is_err());
}
}
impl std::str::FromStr for Effort {
type Err = String;
fn from_str(s: &str) -> std::result::Result<Self, String> {
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)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Request { pub struct Request {
pub model: String, pub model: String,
@@ -145,6 +238,7 @@ pub struct Request {
pub messages: Vec<Message>, pub messages: Vec<Message>,
pub tools: Vec<ToolSpec>, pub tools: Vec<ToolSpec>,
pub max_tokens: u32, pub max_tokens: u32,
pub effort: Effort,
} }
/// Incremental stream events. Providers must emit `Done` last with the full assembled message. /// Incremental stream events. Providers must emit `Done` last with the full assembled message.
+30 -4
View File
@@ -99,6 +99,8 @@ struct Config {
explore_model: Option<String>, explore_model: Option<String>,
/// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift). /// Capture the mouse for wheel scrolling (default true; false = terminal selection works without shift).
mouse: Option<bool>, mouse: Option<bool>,
/// Reuse the last model chosen with /model or /provider (default true).
remember_model: Option<bool>,
/// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI. /// "ask" (default) or "yolo": whether bash/write/edit prompt in the TUI.
permissions: Option<String>, permissions: Option<String>,
/// Replaces the built-in system prompt (AGENTS.md etc. are still appended). /// 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), max_tokens: o.max_tokens.or(c.max_tokens),
explore_model: o.explore_model.or(c.explore_model), explore_model: o.explore_model.or(c.explore_model),
mouse: o.mouse.or(c.mouse), mouse: o.mouse.or(c.mouse),
remember_model: o.remember_model.or(c.remember_model),
permissions: o.permissions.or(c.permissions), permissions: o.permissions.or(c.permissions),
system_prompt: o.system_prompt.or(c.system_prompt), system_prompt: o.system_prompt.or(c.system_prompt),
lsp: o.lsp.or(c.lsp), lsp: o.lsp.or(c.lsp),
@@ -478,10 +481,18 @@ async fn main() -> Result<()> {
let cwd = std::env::current_dir()?; let cwd = std::env::current_dir()?;
let cfg = Config::load(&cwd)?; let cfg = Config::load(&cwd)?;
let kinds = logged_in(); 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 let kind = cli
.provider .provider
.or(cfg.provider) .or(cfg.provider)
.or(last.as_ref().map(|l| l.provider))
.or(kinds.first().copied()) .or(kinds.first().copied())
.unwrap_or(Kind::Claude); .unwrap_or(Kind::Claude);
let models = catalog(&kinds).await; let models = catalog(&kinds).await;
@@ -490,7 +501,11 @@ async fn main() -> Result<()> {
(None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind), (None, Some(m)) => hx_ai::models::kind_of(&models, m).unwrap_or(kind),
_ => 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 = 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 { match kind {
Kind::Claude => cfg.claude_model.clone(), Kind::Claude => cfg.claude_model.clone(),
Kind::Codex => cfg.codex_model.clone(), Kind::Codex => cfg.codex_model.clone(),
@@ -530,7 +545,16 @@ async fn main() -> Result<()> {
Session::open(&path)?, Session::open(&path)?,
cx, 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_model(model);
agent.set_effort(effort);
agent.set_system(context::system_prompt( agent.set_system(context::system_prompt(
cfg.system_prompt.as_deref(), cfg.system_prompt.as_deref(),
&context::hx_home(), &context::hx_home(),
@@ -667,7 +691,8 @@ async fn main() -> Result<()> {
models.clone(), models.clone(),
Box::new(provider), Box::new(provider),
cfg.compact_at.is_none(), cfg.compact_at.is_none(),
), )
.remember_in(last_path.clone(), start.clone()),
}, },
) )
.await; .await;
@@ -685,7 +710,8 @@ async fn main() -> Result<()> {
models.clone(), models.clone(),
Box::new(provider), Box::new(provider),
cfg.compact_at.is_none(), cfg.compact_at.is_none(),
), )
.remember_in(last_path, start),
pricing, pricing,
specs, specs,
open_sessions, open_sessions,
+12
View File
@@ -32,6 +32,7 @@ pub struct Agent {
model: String, model: String,
system: String, system: String,
max_tokens: u32, max_tokens: u32,
effort: hx_ai::Effort,
max_turns: u32, max_turns: u32,
usage: Usage, usage: Usage,
session: Session, session: Session,
@@ -71,6 +72,7 @@ impl Agent {
model: String::new(), model: String::new(),
system: String::new(), system: String::new(),
max_tokens: 16_384, max_tokens: 16_384,
effort: hx_ai::Effort::Off,
max_turns: 200, max_turns: 200,
usage: Usage::default(), usage: Usage::default(),
session, session,
@@ -107,6 +109,15 @@ impl Agent {
self.model = model.into(); 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<String>) { pub fn set_system(&mut self, system: impl Into<String>) {
self.system = system.into(); self.system = system.into();
} }
@@ -239,6 +250,7 @@ impl Agent {
messages: view.messages, messages: view.messages,
tools: self.tools.specs(), tools: self.tools.specs(),
max_tokens: self.max_tokens, max_tokens: self.max_tokens,
effort: self.effort,
}; };
let mut s = self.provider.stream(req).await?; let mut s = self.provider.stream(req).await?;
let mut done = None; let mut done = None;
+7 -1
View File
@@ -56,12 +56,18 @@ pub fn builtins(models: &[&str]) -> Vec<CmdSpec> {
"switch provider", "switch provider",
Enum(vec!["claude".into(), "codex".into()]), 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("compact", "summarize old context", None),
b("new", "start a new session (old one stays resumable)", None), b("new", "start a new session (old one stays resumable)", None),
b("clear", "alias of /new", None), b("clear", "alias of /new", None),
b("sessions", "browse, resume, delete sessions", None), b("sessions", "browse, resume, delete sessions", None),
b("yolo", "toggle: run every tool without asking", None), b("yolo", "toggle: run every tool without asking", None),
b("lsp", "language server status", 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("usage", "subscription limits, resets, credits", None),
b( b(
"keys", "keys",
@@ -308,7 +314,7 @@ mod tests {
assert_eq!(c("/").items.len(), MAX_ITEMS); assert_eq!(c("/").items.len(), MAX_ITEMS);
assert_eq!(labels(&c("/mo")), ["/model"]); assert_eq!(labels(&c("/mo")), ["/model"]);
assert_eq!(labels(&c("/co")), ["/compact"]); assert_eq!(labels(&c("/co")), ["/copy", "/compact"]);
let r = c("/rev"); let r = c("/rev");
assert_eq!(labels(&r), ["/review"]); assert_eq!(labels(&r), ["/review"]);
assert_eq!(r.items[0].detail, "skill · code review"); assert_eq!(r.items[0].detail, "skill · code review");
+1
View File
@@ -43,6 +43,7 @@ impl Plan {
messages: vec![Message::user(self.transcript.clone())], messages: vec![Message::user(self.transcript.clone())],
tools: vec![], tools: vec![],
max_tokens: 4096, max_tokens: 4096,
effort: hx_ai::Effort::Off,
} }
} }
+63
View File
@@ -23,7 +23,25 @@ pub struct Switched {
pub window: u64, 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, 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<hx_ai::Effort>,
}
impl Last {
/// `None` when the file is missing or unreadable.
pub fn load(path: &std::path::Path) -> Option<Self> {
serde_json::from_slice(&std::fs::read(path).ok()?).ok()
}
}
pub struct Switcher { pub struct Switcher {
remember: Option<(std::path::PathBuf, Last)>,
kind: Kind, kind: Kind,
models: Vec<ModelInfo>, models: Vec<ModelInfo>,
make_provider: MakeProvider, make_provider: MakeProvider,
@@ -40,6 +58,7 @@ impl Switcher {
auto_compact: bool, auto_compact: bool,
) -> Self { ) -> Self {
Self { Self {
remember: None,
kind, kind,
models, models,
make_provider, make_provider,
@@ -47,6 +66,21 @@ impl Switcher {
} }
} }
/// Write every successful switch to `path` (best effort).
/// `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. /// The provider the agent currently uses.
pub fn kind(&self) -> Kind { pub fn kind(&self) -> Kind {
self.kind self.kind
@@ -81,6 +115,12 @@ impl Switcher {
} else { } else {
agent.set_model(model.as_str()); agent.set_model(model.as_str());
} }
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(&*l).map(|b| std::fs::write(&*p, b));
}
let window = models::window(&self.models, &model); let window = models::window(&self.models, &model);
if self.auto_compact { if self.auto_compact {
agent.fit_window(window); agent.fit_window(window);
@@ -219,6 +259,29 @@ 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 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();
assert_eq!(Last::load(&f), None);
}
#[test] #[test]
fn configured_threshold_is_left_alone() { fn configured_threshold_is_left_alone() {
let (mut sw, mut a, _m, _d) = setup(false, false); let (mut sw, mut a, _m, _d) = setup(false, false);
+1
View File
@@ -6,6 +6,7 @@ license.workspace = true
[dependencies] [dependencies]
async-trait = "0.1.92" async-trait = "0.1.92"
base64 = "0.23.1"
crossterm = { version = "0.29.0", features = ["event-stream"] } crossterm = { version = "0.29.0", features = ["event-stream"] }
futures = "0.3.34" futures = "0.3.34"
hx-ai = { version = "0.1.0", path = "../hx-ai" } hx-ai = { version = "0.1.0", path = "../hx-ai" }
+210 -20
View File
@@ -8,6 +8,7 @@ pub mod picker;
pub mod popup; pub mod popup;
pub mod review; pub mod review;
pub mod scroll; pub mod scroll;
pub mod select;
pub mod sessions; pub mod sessions;
pub mod stats_view; pub mod stats_view;
pub mod status; pub mod status;
@@ -15,7 +16,7 @@ pub mod theme;
pub mod transcript; pub mod transcript;
use crossterm::event::{ 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 editor::{Action, Editor};
use futures::StreamExt; 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::command::{self as cmd, CmdSpec, Completion, Source};
use hx_core::hook::{Event, Hook, HookAction}; use hx_core::hook::{Event, Hook, HookAction};
use hx_core::switch::Switcher; use hx_core::switch::Switcher;
use ratatui::buffer::Buffer;
use ratatui::layout::{Constraint, Layout, Rect}; use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::Modifier; use ratatui::style::Modifier;
use ratatui::text::Line; use ratatui::text::Line;
use ratatui::text::Span; 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::collections::VecDeque;
use std::sync::Arc; use std::sync::Arc;
use std::time::Instant; use std::time::Instant;
@@ -51,7 +53,7 @@ pub struct Setup {
pub specs: Vec<CmdSpec>, pub specs: Vec<CmdSpec>,
/// Open the session picker at startup (`hx -r`). /// Open the session picker at startup (`hx -r`).
pub open_sessions: bool, 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, pub mouse: bool,
/// No permission prompts (`--yolo`). /// No permission prompts (`--yolo`).
pub yolo: bool, pub yolo: bool,
@@ -123,6 +125,11 @@ struct App {
panel_scroll: scroll::Scroll, panel_scroll: scroll::Scroll,
/// where the chat / side panel / agent detail were last drawn (mouse wheel targets) /// where the chat / side panel / agent detail were last drawn (mouse wheel targets)
areas: Areas, 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, expanded: bool,
busy: bool, busy: bool,
queue: VecDeque<String>, queue: VecDeque<String>,
@@ -183,6 +190,11 @@ impl App {
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) { fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
self.st.kind = sw.kind; self.st.kind = sw.kind;
self.st.model = sw.model.clone(); 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 { if sw.provider_changed {
self.st.quota = None; self.st.quota = None;
} }
@@ -292,12 +304,16 @@ pub async fn run(setup: Setup) -> std::io::Result<()> {
scroll: Default::default(), scroll: Default::default(),
panel_scroll: Default::default(), panel_scroll: Default::default(),
areas: Default::default(), areas: Default::default(),
sel: None,
drag: false,
click: None,
expanded: false, expanded: false,
busy: false, busy: false,
queue: VecDeque::new(), queue: VecDeque::new(),
st: status::Status { st: status::Status {
kind: switcher.kind(), kind: switcher.kind(),
model: agent.model().to_string(), model: agent.model().to_string(),
effort: agent.effort(),
usage: Usage::default(), usage: Usage::default(),
ctx_tokens: agent.context_tokens(), ctx_tokens: agent.context_tokens(),
ctx_max: agent.compact_at(), 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::Mouse(m) => on_mouse(&mut app, m),
TEvent::Paste(s) => app.ed.insert(&s), 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. /// Mouse wheel scrolls the region under the pointer: agent detail, side panel, or chat.
fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) { fn on_mouse(app: &mut App, m: crossterm::event::MouseEvent) {
use crossterm::event::MouseEventKind::{ScrollDown, ScrollUp}; use crossterm::event::MouseEventKind::{Down, Drag, ScrollDown, ScrollUp, Up};
let up = match m.kind { match m.kind {
ScrollUp => true, ScrollUp => wheel(app, m, true),
ScrollDown => false, ScrollDown => wheel(app, m, false),
_ => return, 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 { let s = if let Some(agents::View::Detail { scroll, .. }) = &mut app.agents {
scroll scroll
} else if app.picker.is_some() || app.sessions.is_some() || app.choose.is_some() { } 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 alt = k.modifiers.contains(KeyModifiers::ALT);
let shift = k.modifiers.contains(KeyModifiers::SHIFT); let shift = k.modifiers.contains(KeyModifiers::SHIFT);
app.hint.clear(); app.hint.clear();
app.sel = None;
app.drag = false;
if app.probe { if app.probe {
if k.code == KeyCode::Esc { if k.code == KeyCode::Esc {
app.probe = false; 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::End => app.ed.end(),
KeyCode::Up => app.ed.up(), KeyCode::Up => app.ed.up(),
KeyCode::Down => app.ed.down(), 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 => { KeyCode::Tab => {
let c = completion(app); let c = completion(app);
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect(); 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())), 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" => { "usage" => {
let r = status::report(&app.st, status::now_secs()); let r = status::report(&app.st, status::now_secs());
show(app, "usage", r); 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}"))), 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" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
"model" => { "model" => {
let mut a = agent.lock().await; 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(); app.since = Instant::now();
let prompt = expand_mentions(&line, cwd); let prompt = expand_mentions(&line, cwd);
let (agent, tx) = (agent.clone(), tx.clone()); let (agent, tx) = (agent.clone(), tx.clone());
let effort = app.st.effort;
tokio::spawn(async move { tokio::spawn(async move {
let r = agent let mut a = agent.lock().await;
.lock() a.set_effort(effort);
.await let r = a.run(prompt).await.map(|_| ()).map_err(|e| e.to_string());
.run(prompt)
.await
.map(|_| ())
.map_err(|e| e.to_string());
let _ = tx.send(Ui::Done(r)); 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 total = para.line_count(main.width) as u16;
let top = app.scroll.resolve(total, main.height); let top = app.scroll.resolve(total, main.height);
f.render_widget(para.scroll((top, 0)), main); 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() { if !sub_rows.is_empty() {
let w = subs_area.width.min(56); let w = subs_area.width.min(56);
@@ -1748,6 +1906,34 @@ mod tests {
assert_eq!((app.ed.cur, app.scroll.behind()), (0, 0)); 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] #[test]
fn mouse_wheel_goes_to_region_under_pointer() { fn mouse_wheel_goes_to_region_under_pointer() {
use crossterm::event::{MouseEvent, MouseEventKind}; use crossterm::event::{MouseEvent, MouseEventKind};
@@ -1807,12 +1993,16 @@ mod tests {
scroll: Default::default(), scroll: Default::default(),
panel_scroll: Default::default(), panel_scroll: Default::default(),
areas: Default::default(), areas: Default::default(),
sel: None,
drag: false,
click: None,
expanded: false, expanded: false,
busy: false, busy: false,
queue: VecDeque::new(), queue: VecDeque::new(),
st: status::Status { st: status::Status {
kind: Kind::Claude, kind: Kind::Claude,
model: "m1".into(), model: "m1".into(),
effort: hx_ai::Effort::Off,
usage: Usage::default(), usage: Usage::default(),
ctx_tokens: 0, ctx_tokens: 0,
ctx_max: 150_000, ctx_max: 150_000,
@@ -1886,7 +2076,7 @@ mod tests {
}; };
assert_eq!( assert_eq!(
labels(&app), 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(); let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap();
term.draw(|f| draw(f, &mut app)).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()) .map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect(); .collect();
assert_eq!( assert_eq!(
rows[3], " │ /clear alias of /new │ ", rows[3], "│ /clear alias of /new │",
"{rows:#?}" "{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:#?}"); assert!(rows[9].ends_with("Claude · m1"), "{rows:#?}");
// footer at 100 cols, and a hint replacing only the right side // 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::Down);
key(&mut app, KeyCode::Up); key(&mut app, KeyCode::Up);
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!( assert_eq!(
key(&mut app, KeyCode::Enter), key(&mut app, KeyCode::Enter),
None, None,
+4
View File
@@ -37,6 +37,10 @@ impl Scroll {
self.top = None; self.top = None;
} }
} }
/// First visible line as of the last draw.
pub fn top(&self) -> u16 {
self.cur()
}
pub fn half_page(&self) -> u16 { pub fn half_page(&self) -> u16 {
(self.height / 2).max(1) (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 struct Status {
pub kind: Kind, pub kind: Kind,
pub model: String, pub model: String,
pub effort: hx_ai::Effort,
pub usage: Usage, pub usage: Usage,
pub ctx_tokens: usize, pub ctx_tokens: usize,
/// auto-compact threshold: the context bar's 100% /// 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> { fn tail(st: &Status, c: &Chrome) -> Vec<String> {
let mut t = vec![format!("{:?}", st.kind), st.model.clone()]; 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 { if c.queued > 0 {
t.push(format!("{} queued", c.queued)); t.push(format!("{} queued", c.queued));
} }
@@ -322,6 +326,7 @@ mod tests {
Status { Status {
kind: Kind::Claude, kind: Kind::Claude,
model: "m1".into(), model: "m1".into(),
effort: hx_ai::Effort::Off,
usage: Usage::default(), usage: Usage::default(),
ctx_tokens: 0, ctx_tokens: 0,
ctx_max: 150_000, ctx_max: 150_000,