1282 lines
45 KiB
Rust
1282 lines
45 KiB
Rust
//! Interactive terminal UI.
|
||
|
||
pub mod editor;
|
||
pub mod picker;
|
||
pub mod popup;
|
||
pub mod sessions;
|
||
pub mod status;
|
||
pub mod theme;
|
||
pub mod transcript;
|
||
|
||
use crossterm::event::{
|
||
Event as TEvent, EventStream, KeyCode, KeyEvent, KeyEventKind, KeyModifiers,
|
||
};
|
||
use editor::{Action, Editor};
|
||
use futures::StreamExt;
|
||
use hx_ai::Usage;
|
||
use hx_ai::auth::Kind;
|
||
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::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 std::collections::VecDeque;
|
||
use std::sync::Arc;
|
||
use std::time::Instant;
|
||
use tokio::sync::{Mutex, mpsc};
|
||
use transcript::{Item, Transcript};
|
||
|
||
pub struct Setup {
|
||
pub agent: Agent,
|
||
/// Switches model and provider; also knows the current provider and the model catalog.
|
||
pub switcher: Switcher,
|
||
/// Pricing lookup for the footer; None = unknown.
|
||
pub pricing: fn(&str) -> Option<hx_ai::Pricing>,
|
||
/// `/lsp` status lines.
|
||
pub lsp_status: LspStatus,
|
||
/// Extra slash commands (MCP prompts, `/mcp`): `(name, arg)` -> None = not mine,
|
||
/// Some(Ok(Send(text))) = send as a user prompt, Some(Ok(Show(text))) = show, Some(Err) = error.
|
||
pub commands: Commands,
|
||
/// Everything completable/listed by `/help`: builtins, skills, MCP prompts, extensions.
|
||
pub specs: Vec<CmdSpec>,
|
||
/// Open the session picker at startup (`hx -r`).
|
||
pub open_sessions: bool,
|
||
}
|
||
|
||
pub enum CmdOut {
|
||
Send(String),
|
||
Show(String),
|
||
}
|
||
|
||
pub type Commands = Box<
|
||
dyn Fn(
|
||
&str,
|
||
&str,
|
||
) -> Option<
|
||
std::pin::Pin<Box<dyn std::future::Future<Output = Result<CmdOut, String>> + Send>>,
|
||
> + Send
|
||
+ Sync,
|
||
>;
|
||
|
||
pub type LspStatus = Box<
|
||
dyn Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Vec<String>> + Send>> + Send,
|
||
>;
|
||
|
||
enum Ui {
|
||
Ev(Event),
|
||
Ask(String, tokio::sync::oneshot::Sender<bool>),
|
||
Done(Result<(), String>),
|
||
Compacted(Result<bool, String>),
|
||
}
|
||
|
||
/// Forwards agent events to the UI loop.
|
||
struct Forward(mpsc::UnboundedSender<Ui>);
|
||
#[async_trait::async_trait]
|
||
impl Hook for Forward {
|
||
async fn on(&self, ev: &Event) -> HookAction {
|
||
let _ = self.0.send(Ui::Ev(ev.clone()));
|
||
HookAction::Continue
|
||
}
|
||
}
|
||
|
||
struct App {
|
||
t: Transcript,
|
||
ed: Editor,
|
||
files: Vec<String>,
|
||
/// lines scrolled up from the bottom
|
||
scroll: u16,
|
||
expanded: bool,
|
||
busy: bool,
|
||
queue: VecDeque<String>,
|
||
/// numbers the footer and `/usage` show
|
||
st: status::Status,
|
||
/// model/provider switching (`/model`, `/provider`)
|
||
sw: Switcher,
|
||
/// when the current run started (activity line)
|
||
since: Instant,
|
||
quit: bool,
|
||
hint: String,
|
||
specs: Vec<CmdSpec>,
|
||
/// open completion popup and selected row
|
||
popup: Option<popup::Popup>,
|
||
picker: Option<picker::Picker>,
|
||
sessions: Option<sessions::Sessions>,
|
||
/// session title for footer / terminal title; None until the first prompt
|
||
title: Option<String>,
|
||
/// right-hand panel on wide terminals: (title, text) of the last listing / expanded output
|
||
panel: Option<(String, String)>,
|
||
session_path: std::path::PathBuf,
|
||
/// terminal at least WIDE columns (set on draw)
|
||
wide: bool,
|
||
/// pending yes/no question from a tool
|
||
ask: Option<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||
/// condensed lens state for the footer, refreshed by a timer
|
||
lens: (String, bool),
|
||
}
|
||
|
||
impl App {
|
||
/// Mirror a model/provider switch into what the footer shows.
|
||
fn apply_switch(&mut self, sw: &hx_core::switch::Switched) {
|
||
self.st.kind = sw.kind;
|
||
self.st.model = sw.model.clone();
|
||
if sw.provider_changed {
|
||
self.st.quota = None;
|
||
}
|
||
}
|
||
|
||
/// The context bar's 100% is the agent's compaction threshold.
|
||
fn ctx_max_from(&mut self, a: &Agent) {
|
||
self.st.ctx_max = a.compact_at();
|
||
}
|
||
}
|
||
|
||
const KEYS: &str = "enter send · alt-enter/ctrl-j newline · esc/ctrl-c abort · ctrl-o expand · pgup/pgdn scroll · \
|
||
tab complete @file / command";
|
||
const PLACEHOLDER: &str = "/ commands · @ files · ctrl-p picker · /help keys";
|
||
/// Columns from which listings go to a side panel.
|
||
const WIDE: u16 = 140;
|
||
|
||
pub fn project_files(root: &std::path::Path) -> Vec<String> {
|
||
ignore::WalkBuilder::new(root)
|
||
.hidden(true)
|
||
.build()
|
||
.flatten()
|
||
.filter(|e| e.file_type().is_some_and(|t| t.is_file()))
|
||
.filter_map(|e| {
|
||
e.path()
|
||
.strip_prefix(root)
|
||
.ok()
|
||
.map(|p| p.to_string_lossy().into_owned())
|
||
})
|
||
.take(20_000)
|
||
.collect()
|
||
}
|
||
|
||
/// Expand `@path` mentions of existing files into attached contents.
|
||
fn expand_mentions(s: &str, root: &std::path::Path) -> String {
|
||
let mut att = String::new();
|
||
for w in s.split_whitespace().filter_map(|w| w.strip_prefix('@')) {
|
||
let p = root.join(w);
|
||
if let Ok(c) = std::fs::read_to_string(&p)
|
||
&& c.len() < 200_000
|
||
{
|
||
att.push_str(&format!("\n\n<file path=\"{w}\">\n{c}\n</file>"));
|
||
}
|
||
}
|
||
format!("{s}{att}")
|
||
}
|
||
|
||
pub async fn run(setup: Setup) -> std::io::Result<()> {
|
||
let Setup {
|
||
mut agent,
|
||
switcher,
|
||
pricing,
|
||
lsp_status,
|
||
commands,
|
||
specs,
|
||
open_sessions,
|
||
} = setup;
|
||
let (tx, mut rx) = mpsc::unbounded_channel();
|
||
agent.bus.add(Forward(tx.clone()));
|
||
{
|
||
let tx = tx.clone();
|
||
let _ = agent
|
||
.cx
|
||
.state
|
||
.ask
|
||
.set(std::sync::Arc::new(move |q: String| {
|
||
let (otx, orx) = tokio::sync::oneshot::channel();
|
||
let _ = tx.send(Ui::Ask(q, otx));
|
||
Box::pin(async move { orx.await.unwrap_or(false) })
|
||
}));
|
||
}
|
||
let abort: AbortHandle = agent.abort_handle();
|
||
let cwd = agent.cx.cwd.clone();
|
||
let mut app = App {
|
||
t: Transcript::default(),
|
||
ed: Editor::default(),
|
||
files: project_files(&cwd),
|
||
scroll: 0,
|
||
expanded: false,
|
||
busy: false,
|
||
queue: VecDeque::new(),
|
||
st: status::Status {
|
||
kind: switcher.kind(),
|
||
model: agent.model().to_string(),
|
||
usage: Usage::default(),
|
||
ctx_tokens: hx_core::compact::estimate_tokens(&agent.session().messages()),
|
||
ctx_max: agent.compact_at(),
|
||
quota: None,
|
||
pricing,
|
||
},
|
||
sw: switcher,
|
||
since: Instant::now(),
|
||
quit: false,
|
||
hint: String::new(),
|
||
specs,
|
||
popup: None,
|
||
picker: None,
|
||
sessions: None,
|
||
title: hx_core::session::title(&agent.session().messages()),
|
||
panel: None,
|
||
session_path: agent.session().path().to_path_buf(),
|
||
wide: false,
|
||
ask: None,
|
||
lens: (String::new(), false),
|
||
};
|
||
sessions::history(&mut app.t, &agent.session().messages());
|
||
if open_sessions {
|
||
open_sessions_picker(&mut app);
|
||
}
|
||
app.t.push(Item::Info(format!(
|
||
"hx · {:?} · {}",
|
||
app.st.kind, app.st.model
|
||
)));
|
||
let agent = Arc::new(Mutex::new(agent));
|
||
|
||
let ctx = Ctx {
|
||
agent: &agent,
|
||
tx: &tx,
|
||
cwd: &cwd,
|
||
lsp_status: &lsp_status,
|
||
commands: &commands,
|
||
};
|
||
let mut term = ratatui::init();
|
||
let mut keys = EventStream::new();
|
||
let mut tick = tokio::time::interval(std::time::Duration::from_millis(50));
|
||
let mut lens_tick = tokio::time::interval(std::time::Duration::from_secs(2));
|
||
let mut dirty = true;
|
||
let mut last_title = String::new();
|
||
while !app.quit {
|
||
if std::mem::take(&mut dirty) {
|
||
let t = format!("hx · {}", app.title.as_deref().unwrap_or("new session"));
|
||
if t != last_title {
|
||
// OSC 2: terminal window title
|
||
use std::io::Write;
|
||
let _ = write!(std::io::stdout(), "\x1b]2;{t}\x07");
|
||
last_title = t;
|
||
}
|
||
term.draw(|f| draw(f, &mut app))?;
|
||
}
|
||
tokio::select! {
|
||
k = keys.next() => {
|
||
let Some(Ok(ev)) = k else { break };
|
||
dirty = true;
|
||
match ev {
|
||
TEvent::Key(k) if k.kind != KeyEventKind::Release && app.ask.is_some() => {
|
||
let yes = match k.code {
|
||
KeyCode::Char('y' | 'Y') => Some(true),
|
||
KeyCode::Char('n' | 'N') | KeyCode::Esc => Some(false),
|
||
_ => None,
|
||
};
|
||
if let Some(yes) = yes
|
||
&& let Some((q, reply)) = app.ask.take()
|
||
{
|
||
app.t.push(Item::Info(format!("{q} {}", if yes { "yes" } else { "no" })));
|
||
let _ = reply.send(yes);
|
||
}
|
||
}
|
||
TEvent::Key(k) if k.kind != KeyEventKind::Release => {
|
||
if let Some(line) = on_key(&mut app, k, &abort) {
|
||
submit(&mut app, line, &ctx).await;
|
||
}
|
||
}
|
||
TEvent::Paste(s) => app.ed.insert(&s),
|
||
_ => {}
|
||
}
|
||
}
|
||
Some(u) = rx.recv() => {
|
||
dirty = true;
|
||
match u {
|
||
Ui::Ask(q, reply) => app.ask = Some((q, reply)),
|
||
Ui::Ev(e) => {
|
||
if let Event::Stream(hx_ai::StreamEvent::Quota(q)) = &e {
|
||
app.st.quota = Some(q.clone());
|
||
}
|
||
if let Event::Stream(hx_ai::StreamEvent::Done { usage, .. }) = &e {
|
||
app.st.usage.add(usage);
|
||
app.st.ctx_tokens = (usage.input_tokens + usage.cache_read_tokens + usage.cache_write_tokens + usage.output_tokens) as usize;
|
||
}
|
||
app.t.apply(&e);
|
||
}
|
||
Ui::Done(r) => {
|
||
app.busy = false;
|
||
match r {
|
||
Err(e) if e == "aborted" => app.t.push(Item::Info("aborted".into())),
|
||
Err(e) => app.t.push(Item::Error(e)),
|
||
Ok(()) => {}
|
||
}
|
||
if let Some(next) = app.queue.pop_front() {
|
||
submit(&mut app, next, &ctx).await;
|
||
}
|
||
}
|
||
Ui::Compacted(r) => {
|
||
app.busy = false;
|
||
app.t.push(match r {
|
||
Ok(true) => Item::Info("context compacted".into()),
|
||
Ok(false) => Item::Info("nothing to compact".into()),
|
||
Err(e) => Item::Error(e),
|
||
});
|
||
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&agent.lock().await.session().messages());
|
||
}
|
||
}
|
||
}
|
||
_ = tick.tick(), if app.busy => dirty = true,
|
||
_ = lens_tick.tick() => {
|
||
// short timeout: the manager lock can be held while a server starts
|
||
let to = std::time::Duration::from_millis(200);
|
||
if let Ok(v) = tokio::time::timeout(to, lsp_status()).await {
|
||
let s = status::lens_summary(&v);
|
||
dirty |= s != app.lens;
|
||
app.lens = s;
|
||
}
|
||
}
|
||
}
|
||
}
|
||
ratatui::restore();
|
||
let a = agent.lock().await;
|
||
let cost = pricing(a.model())
|
||
.map(|p| format!(" ${:.4}", app.st.usage.cost(&p)))
|
||
.unwrap_or_default();
|
||
eprintln!(
|
||
"[{} in / {} out tokens{cost}; session {}]",
|
||
app.st.usage.input_tokens + app.st.usage.cache_read_tokens,
|
||
app.st.usage.output_tokens,
|
||
a.session().path().display()
|
||
);
|
||
Ok(())
|
||
}
|
||
|
||
/// Sessions live next to the current one.
|
||
fn sessions_dir(app: &App) -> &std::path::Path {
|
||
app.session_path
|
||
.parent()
|
||
.unwrap_or(std::path::Path::new("."))
|
||
}
|
||
|
||
fn open_sessions_picker(app: &mut App) {
|
||
let dir = sessions_dir(app).to_path_buf();
|
||
let root = dir.parent().unwrap_or(&dir).to_path_buf();
|
||
app.picker = None;
|
||
app.popup = None;
|
||
app.sessions = Some(sessions::Sessions::new(&dir, &root, &app.session_path));
|
||
}
|
||
|
||
/// Session picker keys. Returns `/resume <path>` to submit on enter.
|
||
fn sessions_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||
match app.sessions.as_mut()?.key(k) {
|
||
sessions::Act::None => None,
|
||
sessions::Act::Close => {
|
||
app.sessions = None;
|
||
None
|
||
}
|
||
sessions::Act::Resume(p) => {
|
||
app.sessions = None;
|
||
(p != app.session_path).then(|| format!("/resume {}", p.display()))
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Replace the agent's session (resume or new) and rebuild the transcript.
|
||
fn switch_session(app: &mut App, a: &mut Agent, sess: hx_core::session::Session) {
|
||
app.t = Transcript::default();
|
||
let msgs = sess.messages();
|
||
sessions::history(&mut app.t, &msgs);
|
||
app.st.ctx_tokens = hx_core::compact::estimate_tokens(&msgs);
|
||
app.title = hx_core::session::title(&msgs);
|
||
app.session_path = sess.path().to_path_buf();
|
||
a.replace_session(sess);
|
||
}
|
||
|
||
/// Picker keys. Returns a line to submit when an entry runs.
|
||
fn picker_key(app: &mut App, k: KeyEvent) -> Option<String> {
|
||
match app.picker.as_mut()?.key(k) {
|
||
picker::Act::None => None,
|
||
picker::Act::Close => {
|
||
app.picker = None;
|
||
None
|
||
}
|
||
picker::Act::Run(l) => {
|
||
app.picker = None;
|
||
Some(l)
|
||
}
|
||
picker::Act::Insert(l) => {
|
||
app.picker = None;
|
||
app.ed.buf = l;
|
||
app.ed.cur = app.ed.buf.len();
|
||
live_popup(app);
|
||
None
|
||
}
|
||
}
|
||
}
|
||
|
||
/// Show a listing: right panel on wide terminals, transcript otherwise.
|
||
fn show(app: &mut App, title: &str, text: String) {
|
||
if app.wide {
|
||
app.panel = Some((title.into(), text));
|
||
} else {
|
||
app.t.push(Item::Info(text));
|
||
}
|
||
}
|
||
|
||
/// Returns a line to submit, if any.
|
||
fn on_key(app: &mut App, k: KeyEvent, abort: &AbortHandle) -> Option<String> {
|
||
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
|
||
let alt = k.modifiers.contains(KeyModifiers::ALT);
|
||
let shift = k.modifiers.contains(KeyModifiers::SHIFT);
|
||
app.hint.clear();
|
||
if app.sessions.is_some() {
|
||
return sessions_key(app, k);
|
||
}
|
||
if app.picker.is_some() {
|
||
return picker_key(app, k);
|
||
}
|
||
if ctrl && k.code == KeyCode::Char('p') {
|
||
app.popup = None;
|
||
app.picker = Some(picker::Picker::new(
|
||
&app.specs,
|
||
sessions_dir(app),
|
||
&app.session_path,
|
||
));
|
||
return None;
|
||
}
|
||
if let Some(p) = &mut app.popup {
|
||
match p.key(k, &app.ed.buf, app.ed.cur) {
|
||
popup::Act::Consumed => return None,
|
||
popup::Act::Close => {
|
||
app.popup = None;
|
||
return None;
|
||
}
|
||
popup::Act::Accept => {
|
||
accept(app);
|
||
return None;
|
||
}
|
||
popup::Act::Pass => app.popup = None,
|
||
}
|
||
}
|
||
match k.code {
|
||
KeyCode::Char('c') if ctrl => {
|
||
if app.busy {
|
||
app.queue.clear();
|
||
abort.abort();
|
||
} else if app.ed.buf.is_empty() {
|
||
app.quit = true;
|
||
} else {
|
||
app.ed = std::mem::take(&mut app.ed);
|
||
app.ed.buf.clear();
|
||
app.ed.cur = 0;
|
||
}
|
||
}
|
||
KeyCode::Char('d') if ctrl && app.ed.buf.is_empty() && !app.busy => app.quit = true,
|
||
KeyCode::Esc if app.busy => {
|
||
app.queue.clear();
|
||
abort.abort();
|
||
}
|
||
KeyCode::Char('o') if ctrl => app.expanded = !app.expanded,
|
||
KeyCode::Esc if app.panel.is_some() => app.panel = None,
|
||
KeyCode::Char('j') if ctrl => app.ed.insert("\n"),
|
||
KeyCode::Enter if alt || shift => app.ed.insert("\n"),
|
||
KeyCode::Enter => {
|
||
if let Action::Submit(s) = app.ed.submit() {
|
||
return Some(s);
|
||
}
|
||
}
|
||
KeyCode::Char('u') if ctrl => app.ed.kill_line(),
|
||
KeyCode::Char('w') if ctrl => app.ed.kill_word(),
|
||
KeyCode::Char('a') if ctrl => app.ed.home(),
|
||
KeyCode::Char('e') if ctrl => app.ed.end(),
|
||
KeyCode::Char(c) if !ctrl => {
|
||
app.ed.insert(c.encode_utf8(&mut [0; 4]));
|
||
live_popup(app);
|
||
}
|
||
KeyCode::Backspace => {
|
||
app.ed.backspace();
|
||
live_popup(app);
|
||
}
|
||
KeyCode::Delete => app.ed.delete(),
|
||
KeyCode::Left => app.ed.left(),
|
||
KeyCode::Right => app.ed.right(),
|
||
KeyCode::Home => app.ed.home(),
|
||
KeyCode::End => app.ed.end(),
|
||
KeyCode::Up => app.ed.up(),
|
||
KeyCode::Down => app.ed.down(),
|
||
KeyCode::PageUp => app.scroll = app.scroll.saturating_add(10),
|
||
KeyCode::PageDown => app.scroll = app.scroll.saturating_sub(10),
|
||
KeyCode::Tab => {
|
||
let c = completion(app);
|
||
let labels: Vec<&str> = c.items.iter().map(|i| i.label.as_str()).collect();
|
||
match labels.len() {
|
||
0 => app.hint = "no match".into(),
|
||
1 => {
|
||
let l = format!("{} ", labels[0]);
|
||
app.ed.replace(c.start, &l);
|
||
}
|
||
_ => {
|
||
let pre = cmd::common_prefix(&labels);
|
||
if pre.len() > app.ed.cur - c.start {
|
||
app.ed.replace(c.start, &pre);
|
||
}
|
||
app.popup = popup::Popup::new(completion(app));
|
||
}
|
||
}
|
||
}
|
||
_ => {}
|
||
}
|
||
None
|
||
}
|
||
|
||
fn completion(app: &App) -> Completion {
|
||
cmd::complete(&app.ed.buf, app.ed.cur, &app.specs, &app.files)
|
||
}
|
||
|
||
/// Commands and their arguments complete as you type; `@file` waits for Tab (the file list is big).
|
||
fn live_popup(app: &mut App) {
|
||
app.popup = None;
|
||
if !app.ed.buf.starts_with('/') || app.ed.buf.contains('\n') {
|
||
return;
|
||
}
|
||
let c = completion(app);
|
||
if !app.ed.buf[c.start..app.ed.cur].starts_with('@') {
|
||
app.popup = popup::Popup::new(c);
|
||
}
|
||
}
|
||
|
||
fn accept(app: &mut App) {
|
||
if let Some(p) = app.popup.take() {
|
||
app.ed
|
||
.replace(p.comp.start, &format!("{} ", p.selected_label()));
|
||
live_popup(app);
|
||
}
|
||
}
|
||
|
||
/// Everything `submit` needs besides the app state.
|
||
struct Ctx<'a> {
|
||
agent: &'a Arc<Mutex<Agent>>,
|
||
tx: &'a mpsc::UnboundedSender<Ui>,
|
||
cwd: &'a std::path::Path,
|
||
lsp_status: &'a LspStatus,
|
||
commands: &'a Commands,
|
||
}
|
||
|
||
async fn submit(app: &mut App, mut line: String, c: &Ctx<'_>) {
|
||
let Ctx {
|
||
agent,
|
||
tx,
|
||
cwd,
|
||
lsp_status,
|
||
commands,
|
||
} = *c;
|
||
app.scroll = 0;
|
||
let shown = line.clone();
|
||
if let Some(cmd) = line.clone().strip_prefix('/') {
|
||
let (c, arg) = cmd
|
||
.split_once(' ')
|
||
.map_or((cmd, ""), |(a, b)| (a, b.trim()));
|
||
if app.busy && c != "quit" {
|
||
app.t.push(Item::Error("busy; esc to abort first".into()));
|
||
return;
|
||
}
|
||
match c {
|
||
"quit" | "exit" => app.quit = true,
|
||
"help" => {
|
||
let h = format!("{}\n\nkeys: {KEYS} · ctrl-p picker", cmd::help(&app.specs));
|
||
show(app, "help", h);
|
||
}
|
||
"usage" => {
|
||
let r = status::report(&app.st, status::now_secs());
|
||
show(app, "usage", r);
|
||
}
|
||
"skills" => {
|
||
let dirs = hx_core::context::skill_dirs(&hx_core::context::hx_home(), cwd);
|
||
let l = skills_list(&app.specs, &dirs);
|
||
show(app, "skills", l);
|
||
}
|
||
"lsp" => {
|
||
let st = lsp_status().await;
|
||
let l = if st.is_empty() {
|
||
"lsp: no servers started".into()
|
||
} else {
|
||
format!("lsp:\n{}", st.join("\n"))
|
||
};
|
||
show(app, "lsp", l);
|
||
}
|
||
"resume" if !arg.is_empty() => match hx_core::session::Session::open(arg) {
|
||
Ok(sess) => {
|
||
switch_session(app, &mut *agent.lock().await, sess);
|
||
app.t.push(Item::Info(format!("resumed {arg}")));
|
||
}
|
||
Err(e) => app.t.push(Item::Error(format!("/resume: {e}"))),
|
||
},
|
||
"sessions" | "resume" => open_sessions_picker(app),
|
||
"new" | "clear" => {
|
||
let p = hx_core::session::new_path(sessions_dir(app));
|
||
match hx_core::session::Session::open(&p) {
|
||
Ok(sess) => {
|
||
switch_session(app, &mut *agent.lock().await, sess);
|
||
app.t.push(Item::Info("new session".into()));
|
||
}
|
||
Err(e) => app.t.push(Item::Error(format!("/new: {e}"))),
|
||
}
|
||
}
|
||
"model" if arg.is_empty() => app.t.push(Item::Info(format!("model: {}", app.st.model))),
|
||
"model" => {
|
||
let mut a = agent.lock().await;
|
||
match app.sw.set_model(&mut a, arg) {
|
||
Ok(sw) => {
|
||
app.apply_switch(&sw);
|
||
app.ctx_max_from(&a);
|
||
app.t.push(Item::Info(format!(
|
||
"model → {} ({:?}) · context {}k",
|
||
sw.model,
|
||
sw.kind,
|
||
sw.window / 1000
|
||
)));
|
||
}
|
||
Err(e) => app.t.push(Item::Error(format!("/model {arg}: {e}"))),
|
||
}
|
||
}
|
||
"provider" => match arg.parse::<Kind>().map_err(|e| e.to_string()) {
|
||
Ok(k) => {
|
||
let mut a = agent.lock().await;
|
||
match app.sw.set_provider(&mut a, k) {
|
||
Ok(sw) => {
|
||
app.apply_switch(&sw);
|
||
app.ctx_max_from(&a);
|
||
app.t.push(Item::Info(format!(
|
||
"provider → {:?} ({})",
|
||
sw.kind, sw.model
|
||
)));
|
||
}
|
||
Err(e) => app.t.push(Item::Error(e)),
|
||
}
|
||
}
|
||
Err(e) => app.t.push(Item::Error(e)),
|
||
},
|
||
"compact" => {
|
||
app.busy = true;
|
||
app.since = Instant::now();
|
||
app.t.push(Item::Info("compacting…".into()));
|
||
let (agent, tx) = (agent.clone(), tx.clone());
|
||
tokio::spawn(async move {
|
||
let r = agent
|
||
.lock()
|
||
.await
|
||
.compact(4)
|
||
.await
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(Ui::Compacted(r));
|
||
});
|
||
}
|
||
_ if let Some(Source::Skill(p)) =
|
||
app.specs.iter().find(|s| s.name == c).map(|s| &s.source) =>
|
||
{
|
||
match cmd::skill_prompt(c, p, arg) {
|
||
Ok(t) => line = t,
|
||
Err(e) => app.t.push(Item::Error(format!("/{c}: {e}"))),
|
||
}
|
||
}
|
||
_ => match commands(c, arg) {
|
||
None => app
|
||
.t
|
||
.push(Item::Error(format!("unknown command /{c}; /help"))),
|
||
Some(f) => match f.await {
|
||
Ok(CmdOut::Show(t)) => show(app, c, t),
|
||
Ok(CmdOut::Send(t)) => line = t,
|
||
Err(e) => app.t.push(Item::Error(e)),
|
||
},
|
||
},
|
||
}
|
||
if line.starts_with('/') {
|
||
return;
|
||
}
|
||
}
|
||
if app.busy {
|
||
app.t.push(Item::Info(format!(
|
||
"queued: {}",
|
||
line.lines().next().unwrap_or_default()
|
||
)));
|
||
app.queue.push_back(line);
|
||
return;
|
||
}
|
||
// a command that expanded into a prompt shows as typed
|
||
if app.title.is_none() {
|
||
app.title = hx_core::session::title(&[hx_ai::Message::user(shown.clone())]);
|
||
}
|
||
app.t.push(Item::User(if shown.starts_with('/') {
|
||
shown
|
||
} else {
|
||
line.clone()
|
||
}));
|
||
app.busy = true;
|
||
app.since = Instant::now();
|
||
let prompt = expand_mentions(&line, cwd);
|
||
let (agent, tx) = (agent.clone(), tx.clone());
|
||
tokio::spawn(async move {
|
||
let r = agent
|
||
.lock()
|
||
.await
|
||
.run(prompt)
|
||
.await
|
||
.map(|_| ())
|
||
.map_err(|e| e.to_string());
|
||
let _ = tx.send(Ui::Done(r));
|
||
});
|
||
}
|
||
|
||
fn draw(f: &mut ratatui::Frame, app: &mut App) {
|
||
let th = theme::t();
|
||
let input_h = (app.ed.buf.lines().count().max(1) + usize::from(app.ed.buf.ends_with('\n')))
|
||
.min(10) as u16
|
||
+ 2;
|
||
let act_h = u16::from(app.busy);
|
||
app.wide = f.area().width >= WIDE;
|
||
let foot_h = status::rows_for(f.area().width, app.ask.is_some());
|
||
let [main, act, input, status_row] = Layout::vertical([
|
||
Constraint::Min(3),
|
||
Constraint::Length(act_h),
|
||
Constraint::Length(input_h),
|
||
Constraint::Length(foot_h),
|
||
])
|
||
.areas(f.area());
|
||
|
||
let main = match &app.panel {
|
||
Some((title, text)) if app.wide => {
|
||
let [m, side] =
|
||
Layout::horizontal([Constraint::Min(60), Constraint::Percentage(40)]).areas(main);
|
||
f.render_widget(
|
||
Paragraph::new(text.as_str())
|
||
.wrap(Wrap { trim: false })
|
||
.block(
|
||
Block::new()
|
||
.borders(Borders::LEFT)
|
||
.border_style(th.dim())
|
||
.title(Span::styled(format!(" {title} · esc "), th.dim())),
|
||
),
|
||
side,
|
||
);
|
||
m
|
||
}
|
||
_ => main,
|
||
};
|
||
let para = Paragraph::new(app.t.lines(app.expanded, main.width)).wrap(Wrap { trim: false });
|
||
let total = para.line_count(main.width) as u16;
|
||
let max_up = total.saturating_sub(main.height);
|
||
app.scroll = app.scroll.min(max_up);
|
||
f.render_widget(para.scroll((max_up - app.scroll, 0)), main);
|
||
|
||
if app.busy {
|
||
let (what, t0) = app.t.running().unwrap_or(("thinking…".into(), app.since));
|
||
let frame = (app.since.elapsed().as_millis() / 80) as usize;
|
||
f.render_widget(transcript::activity_line(&what, t0.elapsed(), frame), act);
|
||
}
|
||
|
||
let block = Block::default()
|
||
.borders(Borders::TOP | Borders::BOTTOM)
|
||
.border_style(th.dim());
|
||
let inner = block.inner(input);
|
||
f.render_widget(block, input);
|
||
let [gut, text] = Layout::horizontal([Constraint::Length(2), Constraint::Min(1)]).areas(inner);
|
||
f.render_widget(
|
||
Span::styled(
|
||
format!("{} ", th.sym.user),
|
||
th.accent().add_modifier(Modifier::BOLD),
|
||
),
|
||
gut,
|
||
);
|
||
let (r, c) = app.ed.cursor_rc();
|
||
let skip = (r as u16).saturating_sub(text.height.saturating_sub(1));
|
||
if app.ed.buf.is_empty() {
|
||
f.render_widget(Span::styled(PLACEHOLDER, th.dim()), text);
|
||
} else {
|
||
f.render_widget(Paragraph::new(app.ed.buf.as_str()).scroll((skip, 0)), text);
|
||
}
|
||
let chrome = status::Chrome {
|
||
ask: app.ask.as_ref().map(|(q, _)| q.as_str()),
|
||
hint: &app.hint,
|
||
queued: app.queue.len(),
|
||
scroll: app.scroll,
|
||
title: app.title.as_deref(),
|
||
lens: &app.lens.0,
|
||
lens_warn: app.lens.1,
|
||
};
|
||
f.render_widget(
|
||
Paragraph::new(status::rows(
|
||
&app.st,
|
||
&chrome,
|
||
status_row.width,
|
||
status::now_secs(),
|
||
)),
|
||
status_row,
|
||
);
|
||
if let Some(popup::Popup { comp, sel }) = &app.popup {
|
||
let col = Span::raw(
|
||
&app.ed.buf[app.ed.buf[..comp.start].rfind('\n').map_or(0, |i| i + 1)..comp.start],
|
||
)
|
||
.width() as u16;
|
||
draw_popup(f, comp, *sel, text.x + col, input.y);
|
||
}
|
||
f.set_cursor_position((text.x + c as u16, text.y + r as u16 - skip));
|
||
if let Some(p) = &app.picker {
|
||
p.draw(f);
|
||
}
|
||
if let Some(s) = &mut app.sessions {
|
||
s.draw(f);
|
||
}
|
||
}
|
||
|
||
/// `/skills`: each skill with its file, then the searched dirs (so a missing skill is easy to debug).
|
||
fn skills_list(specs: &[CmdSpec], dirs: &[std::path::PathBuf]) -> String {
|
||
let sk: Vec<String> = specs
|
||
.iter()
|
||
.filter_map(|s| match &s.source {
|
||
Source::Skill(p) => Some(format!("/{} — {}\n {}", s.name, s.summary, p.display())),
|
||
_ => None,
|
||
})
|
||
.collect();
|
||
let dirs: Vec<String> = dirs
|
||
.iter()
|
||
.map(|d| {
|
||
format!(
|
||
" {}{}",
|
||
d.display(),
|
||
if d.is_dir() { "" } else { " (missing)" }
|
||
)
|
||
})
|
||
.collect();
|
||
format!(
|
||
"skills ({}):\n{}\nsearched (later wins):\n{}",
|
||
sk.len(),
|
||
sk.join("\n"),
|
||
dirs.join("\n")
|
||
)
|
||
}
|
||
|
||
/// Bordered candidate list ending just above row `bottom`, starting at column `x` (the token).
|
||
fn draw_popup(f: &mut ratatui::Frame, c: &Completion, sel: usize, x: u16, bottom: u16) {
|
||
let th = theme::t();
|
||
let lw = c
|
||
.items
|
||
.iter()
|
||
.map(|i| i.label.chars().count())
|
||
.max()
|
||
.unwrap_or(0);
|
||
let lines: Vec<Line> = c
|
||
.items
|
||
.iter()
|
||
.enumerate()
|
||
.map(|(n, i)| {
|
||
let base = if n == sel { th.sel() } else { th.plain() };
|
||
Line::from(vec![
|
||
Span::styled(format!(" {:<lw$} ", i.label), base),
|
||
Span::styled(
|
||
format!("{} ", i.detail),
|
||
if n == sel { base } else { th.dim() },
|
||
),
|
||
])
|
||
})
|
||
.collect();
|
||
let area = f.area();
|
||
let w = (lines.iter().map(Line::width).max().unwrap_or(0) as u16 + 2).min(area.width);
|
||
let h = (lines.len() as u16 + 2).min(bottom);
|
||
let x = x.saturating_sub(1).min(area.width - w);
|
||
let r = Rect::new(x, bottom - h, w, h);
|
||
f.render_widget(Clear, r);
|
||
f.render_widget(
|
||
Paragraph::new(lines).block(Block::bordered().border_style(th.dim())),
|
||
r,
|
||
);
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use hx_ai::Provider;
|
||
use hx_core::switch::MakeProvider;
|
||
use ratatui::backend::TestBackend;
|
||
|
||
#[test]
|
||
fn mentions() {
|
||
let d = std::env::temp_dir().join(format!("hx-tui-{}", std::process::id()));
|
||
std::fs::create_dir_all(&d).unwrap();
|
||
std::fs::write(d.join("a.txt"), "AAA").unwrap();
|
||
let s = expand_mentions("see @a.txt and @nope", &d);
|
||
assert!(s.starts_with("see @a.txt and @nope") && s.contains("<file path=\"a.txt\">\nAAA"));
|
||
assert!(!s.contains("nope\">"));
|
||
}
|
||
|
||
#[test]
|
||
fn draw_snapshot() {
|
||
let mut app = test_app();
|
||
app.files = vec![];
|
||
app.specs = vec![];
|
||
app.st.ctx_tokens = 12_000;
|
||
app.t.push(Item::User("hello".into()));
|
||
app.t.push(Item::Assistant("hi **there**".into()));
|
||
app.ed.insert("typing");
|
||
let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap();
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
let rows: Vec<String> = (0..10)
|
||
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||
.collect();
|
||
let all = rows.join("\n");
|
||
assert!(all.contains("❯ hello"), "{all}");
|
||
assert!(all.contains("◆ hi there"), "{all}");
|
||
assert!(rows[7].starts_with("❯ typing"), "{all}");
|
||
assert!(rows[9].starts_with("ctx ▰▱▱▱▱▱▱▱▱▱ 12k/150k "), "{all}");
|
||
assert!(rows[9].ends_with("Claude · m1"), "{all}");
|
||
}
|
||
|
||
fn key(app: &mut App, code: KeyCode) -> Option<String> {
|
||
on_key(
|
||
app,
|
||
KeyEvent::new(code, KeyModifiers::NONE),
|
||
&AbortHandle::detached(),
|
||
)
|
||
}
|
||
|
||
fn test_app() -> App {
|
||
App {
|
||
t: Transcript::default(),
|
||
ed: Editor::default(),
|
||
files: vec!["src/main.rs".into(), "src/lib.rs".into()],
|
||
scroll: 0,
|
||
expanded: false,
|
||
busy: false,
|
||
queue: VecDeque::new(),
|
||
st: status::Status {
|
||
kind: Kind::Claude,
|
||
model: "m1".into(),
|
||
usage: Usage::default(),
|
||
ctx_tokens: 0,
|
||
ctx_max: 150_000,
|
||
quota: None,
|
||
pricing: |_| None,
|
||
},
|
||
since: Instant::now(),
|
||
quit: false,
|
||
hint: String::new(),
|
||
sw: Switcher::new(
|
||
Kind::Claude,
|
||
vec![],
|
||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
||
true,
|
||
),
|
||
specs: cmd::builtins(&["sonnet", "opus"]),
|
||
popup: None,
|
||
picker: None,
|
||
sessions: None,
|
||
title: None,
|
||
panel: None,
|
||
session_path: "/nonexistent/s.jsonl".into(),
|
||
wide: false,
|
||
ask: None,
|
||
lens: (String::new(), false),
|
||
}
|
||
}
|
||
|
||
#[test]
|
||
fn skills_listing() {
|
||
let mut specs = cmd::builtins(&[]);
|
||
specs.push(CmdSpec::new(
|
||
"rev",
|
||
"review code",
|
||
Source::Skill("/s/rev/SKILL.md".into()),
|
||
cmd::ArgKind::Free,
|
||
));
|
||
let s = skills_list(&specs, &["/nonexistent-hx".into()]);
|
||
assert!(
|
||
s.starts_with("skills (1):\n/rev — review code\n /s/rev/SKILL.md"),
|
||
"{s}"
|
||
);
|
||
assert!(s.ends_with("/nonexistent-hx (missing)"), "{s}");
|
||
}
|
||
|
||
#[test]
|
||
fn popup_keys_and_render() {
|
||
let mut app = test_app();
|
||
for c in "/c".chars() {
|
||
key(&mut app, KeyCode::Char(c));
|
||
}
|
||
let labels = |a: &App| {
|
||
a.popup.as_ref().map(|popup::Popup { comp: c, sel: s }| {
|
||
(
|
||
c.items.iter().map(|i| i.label.clone()).collect::<Vec<_>>(),
|
||
*s,
|
||
)
|
||
})
|
||
};
|
||
assert_eq!(
|
||
labels(&app),
|
||
Some((vec!["/clear".into(), "/compact".into()], 0))
|
||
);
|
||
let mut term = ratatui::Terminal::new(TestBackend::new(40, 10)).unwrap();
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
let rows: Vec<String> = (0..10)
|
||
.map(|y| (0..40).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||
.collect();
|
||
assert_eq!(
|
||
rows[3], " │ /clear alias of /new │ ",
|
||
"{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
|
||
app.hint = "no match".into();
|
||
let mut term = ratatui::Terminal::new(TestBackend::new(100, 10)).unwrap();
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
let row = |y| -> String { (0..100).map(|x| buf[(x, y)].symbol().to_string()).collect() };
|
||
let (last, lens) = (row(8), row(9));
|
||
assert!(
|
||
last.starts_with("ctx ▱▱▱▱▱▱▱▱▱▱ 0k/150k · 0↑ 0↓") && last.ends_with("no match"),
|
||
"{last}"
|
||
);
|
||
assert!(
|
||
lens.starts_with("lens: starting") && lens.ends_with("Claude · m1"),
|
||
"{lens}"
|
||
);
|
||
app.hint.clear();
|
||
let mut foot = |app: &mut App| {
|
||
term.draw(|f| draw(f, app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
(0..100)
|
||
.map(|x| buf[(x, 9)].symbol().to_string())
|
||
.collect::<String>()
|
||
};
|
||
assert!(foot(&mut app).ends_with("new session · Claude · m1"));
|
||
app.title = Some("fix the flaky rust-analyzer test".into());
|
||
let last = foot(&mut app);
|
||
assert!(
|
||
last.starts_with("lens: ")
|
||
&& last.ends_with("fix the flaky rust-analyzer test · Claude · m1"),
|
||
"{last}"
|
||
);
|
||
app.title = None;
|
||
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!(
|
||
key(&mut app, KeyCode::Enter),
|
||
None,
|
||
"enter accepts partial token"
|
||
);
|
||
assert_eq!(app.ed.buf, "/compact ");
|
||
assert!(app.popup.is_none(), "no args for /compact");
|
||
assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/compact "));
|
||
|
||
// args complete live; empty arg + enter submits (shows current model)
|
||
for c in "/model ".chars() {
|
||
key(&mut app, KeyCode::Char(c));
|
||
}
|
||
assert_eq!(labels(&app).unwrap().0, ["opus", "sonnet"]);
|
||
assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/model "));
|
||
|
||
// @file waits for tab; esc closes; up with popup closed browses history
|
||
for c in "x @src".chars() {
|
||
key(&mut app, KeyCode::Char(c));
|
||
}
|
||
assert!(app.popup.is_none());
|
||
key(&mut app, KeyCode::Tab);
|
||
assert_eq!(app.ed.buf, "x @src/", "common prefix filled");
|
||
assert_eq!(labels(&app).unwrap().0.len(), 2);
|
||
key(&mut app, KeyCode::Esc);
|
||
assert!(app.popup.is_none());
|
||
key(&mut app, KeyCode::Char('m'));
|
||
key(&mut app, KeyCode::Tab);
|
||
assert_eq!(app.ed.buf, "x @src/main.rs ");
|
||
key(&mut app, KeyCode::Up);
|
||
assert_eq!(app.ed.buf, "/model ");
|
||
}
|
||
|
||
#[test]
|
||
fn picker_and_wide_panel() {
|
||
let mut app = test_app();
|
||
app.specs.push(CmdSpec::new(
|
||
"lsp",
|
||
"status",
|
||
Source::Builtin,
|
||
cmd::ArgKind::None,
|
||
));
|
||
on_key(
|
||
&mut app,
|
||
KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL),
|
||
&AbortHandle::detached(),
|
||
);
|
||
assert!(app.picker.is_some());
|
||
for c in "compa".chars() {
|
||
assert_eq!(
|
||
key(&mut app, KeyCode::Char(c)),
|
||
None,
|
||
"typing goes to the picker"
|
||
);
|
||
}
|
||
assert!(app.ed.buf.is_empty());
|
||
let mut term = ratatui::Terminal::new(TestBackend::new(60, 12)).unwrap();
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
let rows: Vec<String> = (0..12)
|
||
.map(|y| (0..60).map(|x| buf[(x, y)].symbol().to_string()).collect())
|
||
.collect();
|
||
assert!(rows[2].contains("❯ compa"), "{rows:#?}");
|
||
assert!(
|
||
rows[4].contains("/compact summarize old context"),
|
||
"{rows:#?}"
|
||
);
|
||
assert_eq!(key(&mut app, KeyCode::Enter).as_deref(), Some("/compact"));
|
||
assert!(app.picker.is_none());
|
||
on_key(
|
||
&mut app,
|
||
KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL),
|
||
&AbortHandle::detached(),
|
||
);
|
||
key(&mut app, KeyCode::Esc);
|
||
assert!(app.picker.is_none());
|
||
|
||
// wide: listings go to the side panel, esc closes it
|
||
let mut term = ratatui::Terminal::new(TestBackend::new(160, 12)).unwrap();
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
assert!(app.wide);
|
||
show(&mut app, "skills", "skills (0):".into());
|
||
assert!(app.t.items.is_empty());
|
||
term.draw(|f| draw(f, &mut app)).unwrap();
|
||
let buf = term.backend().buffer().clone();
|
||
let row0: String = (0..160).map(|x| buf[(x, 0)].symbol().to_string()).collect();
|
||
assert!(row0.contains("│ skills · esc"), "{row0}");
|
||
let row1: String = (0..160).map(|x| buf[(x, 1)].symbol().to_string()).collect();
|
||
assert!(row1.contains("│skills (0):"), "{row1}");
|
||
key(&mut app, KeyCode::Esc);
|
||
assert!(app.panel.is_none());
|
||
app.wide = false;
|
||
show(&mut app, "skills", "x".into());
|
||
assert_eq!(app.t.items, [Item::Info("x".into())]);
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn new_session_keeps_old_file() {
|
||
let t = tempfile::tempdir().unwrap();
|
||
let old = t.path().join("1.jsonl");
|
||
let mut s = hx_core::session::Session::open(&old).unwrap();
|
||
s.append(hx_ai::Message::user("first")).unwrap();
|
||
let before = std::fs::read_to_string(&old).unwrap();
|
||
let (agent, _) = Agent::new(
|
||
Arc::new(NoProvider),
|
||
Default::default(),
|
||
hx_core::session::Session::open(&old).unwrap(),
|
||
hx_core::tool::ToolCtx {
|
||
cwd: t.path().into(),
|
||
state: Default::default(),
|
||
},
|
||
);
|
||
let agent = Arc::new(Mutex::new(agent));
|
||
let (tx, _rx) = mpsc::unbounded_channel();
|
||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||
let cmds: Commands = Box::new(|_, _| None);
|
||
let ctx = Ctx {
|
||
agent: &agent,
|
||
tx: &tx,
|
||
cwd: t.path(),
|
||
lsp_status: &ls,
|
||
commands: &cmds,
|
||
};
|
||
let mut app = test_app();
|
||
app.session_path = old.clone();
|
||
app.title = Some("first".into());
|
||
submit(&mut app, "/clear".into(), &ctx).await;
|
||
let new = agent.lock().await.session().path().to_path_buf();
|
||
assert_ne!(new, old);
|
||
assert_eq!((new.parent(), app.title.as_deref()), (old.parent(), None));
|
||
assert_eq!(
|
||
std::fs::read_to_string(&old).unwrap(),
|
||
before,
|
||
"old file untouched"
|
||
);
|
||
// a second handle on the same file: the agent's session is read-only from outside
|
||
hx_core::session::Session::open(&new)
|
||
.unwrap()
|
||
.append(hx_ai::Message::user("second"))
|
||
.unwrap();
|
||
let l = hx_core::session::list(t.path());
|
||
assert_eq!(l.len(), 2);
|
||
assert_eq!(l[0].path, new, "newest first, so `hx -c` picks it");
|
||
submit(&mut app, format!("/resume {}", old.display()), &ctx).await;
|
||
assert_eq!(agent.lock().await.session().path(), old);
|
||
assert_eq!(app.title.as_deref(), Some("first"));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn model_switch_shows_in_footer_state() {
|
||
let t = tempfile::tempdir().unwrap();
|
||
let (agent, _) = Agent::new(
|
||
Arc::new(NoProvider),
|
||
Default::default(),
|
||
hx_core::session::Session::open(t.path().join("s.jsonl")).unwrap(),
|
||
hx_core::tool::ToolCtx {
|
||
cwd: t.path().into(),
|
||
state: Default::default(),
|
||
},
|
||
);
|
||
let agent = Arc::new(Mutex::new(agent));
|
||
let (tx, _rx) = mpsc::unbounded_channel();
|
||
let mut models = hx_ai::models::fallback(Kind::Claude);
|
||
models.extend(hx_ai::models::fallback(Kind::Codex));
|
||
let ls: LspStatus = Box::new(|| Box::pin(async { vec![] }));
|
||
let cmds: Commands = Box::new(|_, _| None);
|
||
let ctx = Ctx {
|
||
agent: &agent,
|
||
tx: &tx,
|
||
cwd: t.path(),
|
||
lsp_status: &ls,
|
||
commands: &cmds,
|
||
};
|
||
let mut app = test_app();
|
||
let fail: MakeProvider =
|
||
Box::new(|_| Err(hx_ai::Error::Http("not logged in to Codex".into())));
|
||
app.sw = Switcher::new(Kind::Claude, models.clone(), fail, true);
|
||
|
||
// codex not logged in: error shown, footer state unchanged
|
||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
||
assert_eq!((app.st.kind, app.st.model.as_str()), (Kind::Claude, "m1"));
|
||
assert!(matches!(app.t.items.last(), Some(Item::Error(e)) if e.contains("not logged in")));
|
||
|
||
app.sw = Switcher::new(
|
||
Kind::Claude,
|
||
models,
|
||
Box::new(|_| Ok(Arc::new(NoProvider))),
|
||
true,
|
||
);
|
||
app.st.quota = Some(Default::default());
|
||
submit(&mut app, "/model gpt-5.6-terra".into(), &ctx).await;
|
||
assert_eq!(
|
||
(app.st.kind, app.st.model.as_str()),
|
||
(Kind::Codex, "gpt-5.6-terra")
|
||
);
|
||
assert!(app.st.quota.is_none(), "quota belongs to the old provider");
|
||
assert_eq!(agent.lock().await.model(), "gpt-5.6-terra");
|
||
assert_eq!(app.st.ctx_max, agent.lock().await.compact_at());
|
||
// same provider: quota survives
|
||
app.st.quota = Some(Default::default());
|
||
submit(&mut app, "/model gpt-5.6-luna".into(), &ctx).await;
|
||
assert!(app.st.quota.is_some());
|
||
}
|
||
|
||
struct NoProvider;
|
||
#[async_trait::async_trait]
|
||
impl Provider for NoProvider {
|
||
async fn stream(
|
||
&self,
|
||
_: hx_ai::Request,
|
||
) -> hx_ai::Result<futures::stream::BoxStream<'static, hx_ai::Result<hx_ai::StreamEvent>>>
|
||
{
|
||
unimplemented!()
|
||
}
|
||
}
|
||
}
|