You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by wy...@apache.org on 2026/09/24 10:32:37 UTC
(maka) branch feat/runtime-host-rust updated: feat(tui): model chooser as a sheet with a thinking-level chooser
This is an automated email from the ASF dual-hosted git repository.
M4n5ter pushed a commit to branch feat/runtime-host-rust
in repository https://gitbox.apache.org/repos/asf/maka.git
The following commit(s) were added to refs/heads/feat/runtime-host-rust by this push:
new baf61dca9c feat(tui): model chooser as a sheet with a thinking-level chooser
baf61dca9c is described below
commit baf61dca9c8941277f80844d55aa60300f72e438
Author: M4n5ter <m4...@gmail.com>
AuthorDate: Thu Sep 24 18:32:27 2026 +0800
feat(tui): model chooser as a sheet with a thinking-level chooser
- Choosing a session or default model is a sheet: a scrollable list of
two-line rows (name; connection and model id) chosen by arrow or
click and applied with Enter, a "no default" first row for the
default model, nothing chosen on open, paging and retry at the bottom
left, and focus moving into the list when rows arrive.
- The thinking level is a kernel chooser of the default and the levels
the chosen model supports, replacing the hand-drawn stepper; the
command now sets a level instead of cycling, and only a level the
current model supports is accepted.
- In a list whose selection follows focus, an arrow at the edge now
chooses the focused row when it is not the choice yet, such as after
a refresh removed the previous one.
- The hand-drawn view, focus order and hover state are gone.
Generated-by: Claude Code
---
crates/cli/tests/integration/tui/models.rs | 22 +-
crates/tui/src/pages/manage.rs | 23 +-
crates/tui/src/pages/manage/models.rs | 433 +++++++----------------
crates/tui/src/pages/manage/models/catalog.rs | 16 +-
crates/tui/src/pages/manage/models/view.rs | 485 +++++++++++---------------
crates/tui/src/pages/manage/view.rs | 5 +-
crates/tui/src/ui/surface.rs | 9 +-
7 files changed, 378 insertions(+), 615 deletions(-)
diff --git a/crates/cli/tests/integration/tui/models.rs b/crates/cli/tests/integration/tui/models.rs
index 2246426c83..c1979169bc 100644
--- a/crates/cli/tests/integration/tui/models.rs
+++ b/crates/cli/tests/integration/tui/models.rs
@@ -146,10 +146,10 @@ fn model_choice_preserves_session_draft_and_default_and_uses_selected_context_wi
tui.wait_for("Alternate model");
tui.click_text("Alternate model");
tui.wait_for("› Alternate model");
- tui.click_text("Thinking level");
- tui.wait_for("‹ Low ›");
- tui.send(b"\x1b[C"); // Right cycles only the focused thinking control.
- tui.wait_for("‹ High ›");
+ tui.click_text("Thinking level"); // A chooser of the levels this model supports.
+ tui.wait_for("○ High");
+ tui.click_text("○ High");
+ tui.wait_for("High ▾");
tui.click_last_text("Use model");
tui.wait_until(|s| !s.contains("Cancel") && s.contains("switch-keeps-draft"));
runtime.block_on(async {
@@ -181,9 +181,11 @@ fn model_choice_preserves_session_draft_and_default_and_uses_selected_context_wi
tui.click_last_text("fixture-model");
tui.wait_for("Alternate model");
tui.click_text("Alternate model");
- tui.wait_for("‹ High ›");
+ tui.wait_for("High ▾");
tui.click_text("Thinking level");
- tui.wait_for("‹ Default ›");
+ tui.wait_for("○ Default");
+ tui.click_text("○ Default");
+ tui.wait_for("Default ▾");
tui.click_last_text("Use model");
tui.wait_until(|s| !s.contains("Cancel") && !s.contains("fixture-model · High"));
runtime.block_on(async {
@@ -200,11 +202,11 @@ fn model_choice_preserves_session_draft_and_default_and_uses_selected_context_wi
tui.click_last_text("fixture-model");
tui.wait_for("Alternate model");
tui.click_text("Alternate model");
- tui.wait_for("‹ Default ›");
+ tui.wait_for("Default ▾");
tui.click_text("Thinking level");
- tui.wait_for("‹ Low ›");
- tui.send(b"\x1b[C");
- tui.wait_for("‹ High ›");
+ tui.wait_for("○ High");
+ tui.click_text("○ High");
+ tui.wait_for("High ▾");
tui.click_last_text("Use model");
tui.wait_until(|s| !s.contains("Cancel") && s.contains("fixture-model · High"));
tui.click_text("switch-keeps-draft");
diff --git a/crates/tui/src/pages/manage.rs b/crates/tui/src/pages/manage.rs
index 2a7a3bef6d..feee67c07f 100644
--- a/crates/tui/src/pages/manage.rs
+++ b/crates/tui/src/pages/manage.rs
@@ -265,12 +265,11 @@ pub struct Dialog {
}
impl Dialog {
- /// Presented as a kernel sheet. OAuth, models, enabled models,
- /// locations and the directory browser still draw their own sub-view.
+ /// Presented as a kernel sheet. OAuth, enabled models, locations and
+ /// the directory browser still draw their own sub-view.
pub(crate) fn in_sheet(&self) -> bool {
self.kind != Kind::Oauth
&& self.enabled_models.is_none()
- && self.models.is_none()
&& self.locations.is_none()
&& self.browser.is_none()
}
@@ -1263,14 +1262,6 @@ impl App {
{
return self.enabled_models_input(event);
}
- if self
- .management
- .dialog
- .as_ref()
- .is_some_and(|d| d.models.is_some())
- {
- return self.models_input(event);
- }
if self
.management
.dialog
@@ -1303,7 +1294,14 @@ impl App {
&& key.kind != KeyEventKind::Release
&& let Some(command) = self.management.dialog.as_ref().and_then(|dialog| {
let chooser = dialog.chooser.is_some();
+ let models = dialog.models.is_some();
match key.code {
+ KeyCode::F(5) if models => Some(Command::Models(models::Command::Refresh)),
+ KeyCode::PageUp if models => Some(Command::Models(models::Command::Previous)),
+ KeyCode::PageDown if models => Some(Command::Models(models::Command::Next)),
+ KeyCode::Enter if models && key.modifiers.contains(KeyModifiers::CONTROL) => {
+ Some(Command::Save)
+ }
KeyCode::F(5) if dialog.credentials.is_some() => Some(Command::CredentialRetry),
KeyCode::F(5) if dialog.removal.is_some() => Some(Command::RemovalQuery),
KeyCode::F(5) if chooser => {
@@ -1406,9 +1404,6 @@ impl Management {
if let Some(locations) = &mut dialog.locations {
locations.invalidate_geometry();
}
- if let Some(models) = &mut dialog.models {
- models.invalidate_geometry();
- }
if let Some(models) = &mut dialog.enabled_models {
models.invalidate_geometry();
}
diff --git a/crates/tui/src/pages/manage/models.rs b/crates/tui/src/pages/manage/models.rs
index f3c437acae..18c8961e46 100644
--- a/crates/tui/src/pages/manage/models.rs
+++ b/crates/tui/src/pages/manage/models.rs
@@ -21,11 +21,10 @@ mod catalog;
mod view;
use super::{Command as Manage, Target};
use crate::app::{Action, App};
-use crossterm::event::{Event, KeyCode, KeyEventKind, KeyModifiers, MouseButton, MouseEventKind};
use maka_protocol::configuration::ConnectionCatalogQueryInput;
use maka_protocol::session::ThinkingLevel;
use serde_json::Value;
-pub(super) use view::draw;
+pub(super) use view::sheet;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Choice {
@@ -40,7 +39,8 @@ pub enum Command {
Refresh,
Previous,
Next,
- Thinking(bool),
+ /// None follows the model's own default.
+ Thinking(Option<ThinkingLevel>),
}
impl Command {
pub fn label(&self) -> &'static str {
@@ -63,8 +63,6 @@ pub struct Request {
pub(super) struct Models {
generation: u64,
pub catalog: catalog::Catalog,
- focus: usize,
- hovered: Option<Manage>,
pub for_default: bool,
pub clear_default: bool,
pub thinking: Option<ThinkingLevel>,
@@ -76,8 +74,6 @@ impl Models {
Self {
generation,
catalog,
- focus: 0,
- hovered: None,
for_default,
clear_default: false,
thinking: None,
@@ -104,27 +100,6 @@ impl Models {
.is_some_and(|row| row.thinking_levels.contains(level))
})
}
- fn cycle_thinking(&mut self, forward: bool) {
- let Some(row) = self.selection().filter(|_| self.has_thinking()) else {
- return;
- };
- let current = self
- .thinking_level()
- .and_then(|level| row.thinking_levels.iter().position(|v| *v == level))
- .map_or(0, |i| i + 1);
- let count = row.thinking_levels.len() + 1;
- let next = (current + if forward { 1 } else { count - 1 }) % count;
- self.thinking = next.checked_sub(1).map(|i| row.thinking_levels[i]);
- }
- fn tab(&mut self, forward: bool) {
- // Stable control identities: removing thinking must never turn Cancel into Save.
- let order: Vec<_> = [0, 1, 2, 3, 6, 4, 5]
- .into_iter()
- .filter(|id| *id != 6 || self.has_thinking())
- .collect();
- let index = order.iter().position(|id| *id == self.focus).unwrap_or(0);
- self.focus = order[(index + if forward { 1 } else { order.len() - 1 }) % order.len()];
- }
fn refresh(&mut self) {
if self.for_default {
self.clear_default = false;
@@ -132,27 +107,6 @@ impl Models {
}
self.catalog.refresh();
}
- fn move_selection(&mut self, down: bool) {
- if self.for_default
- && !down
- && self
- .catalog
- .rows
- .first()
- .is_some_and(|row| Some(&row.choice) == self.catalog.selected.as_ref())
- {
- self.clear_default = true;
- self.catalog.selected = None;
- } else if self.for_default && self.clear_default && !down {
- // The no-default choice is the first row.
- } else {
- self.clear_default = false;
- self.catalog.move_selection(down);
- }
- }
- pub fn invalidate_geometry(&mut self) {
- self.hovered = None;
- }
}
impl App {
@@ -205,7 +159,14 @@ impl App {
Command::Refresh => !models.catalog.loading,
Command::Previous => models.catalog.can_previous(),
Command::Next => models.catalog.can_next(),
- Command::Thinking(_) => models.has_thinking(),
+ Command::Thinking(level) => {
+ models.has_thinking()
+ && level.is_none_or(|level| {
+ models
+ .selection()
+ .is_some_and(|row| row.thinking_levels.contains(&level))
+ })
+ }
}
}
pub(super) fn models_action(&mut self, command: Command) -> Option<Action> {
@@ -215,24 +176,17 @@ impl App {
Command::Select(choice) => {
models.clear_default = false;
models.catalog.selected = Some(choice);
- models.focus = 0;
}
Command::ClearDefault => {
models.clear_default = true;
models.catalog.selected = None;
- models.focus = 0;
}
Command::Refresh => models.refresh(),
Command::Previous => models.catalog.change_page(false),
Command::Next => models.catalog.change_page(true),
- Command::Thinking(forward) => {
- models.cycle_thinking(forward);
- models.focus = 6;
- }
+ Command::Thinking(level) => models.thinking = level,
}
- models.hovered = None;
dialog.error = None;
- self.hits.clear();
None
}
pub fn models_request(&mut self) -> Option<Request> {
@@ -285,114 +239,6 @@ impl App {
models.catalog.selected = None;
}
models.catalog.complete(result);
- if models.focus == 6 && !models.has_thinking() {
- models.focus = 0;
- }
- }
- pub(super) fn models_input(&mut self, event: Event) -> (bool, Option<Action>) {
- let dialog = self.management.dialog.as_mut().expect("models dialog");
- let models = dialog.models.as_mut().expect("models chooser");
- let movable = !dialog.blocked && self.management.pending.is_none();
- if matches!(&event,Event::Key(k) if k.kind!=KeyEventKind::Release) {
- models.hovered = None;
- }
- let command = match event {
- Event::Key(key) if key.kind != KeyEventKind::Release => match key.code {
- KeyCode::Esc => Some(Manage::Close),
- KeyCode::Char('q') if key.modifiers.contains(KeyModifiers::CONTROL) => {
- return (true, Some(Action::Quit));
- }
- _ if !dialog.visible => None,
- KeyCode::Tab => {
- models.tab(true);
- return (true, None);
- }
- KeyCode::BackTab => {
- models.tab(false);
- return (true, None);
- }
- KeyCode::Left | KeyCode::Right | KeyCode::Up | KeyCode::Down
- if movable && models.focus == 6 && models.has_thinking() =>
- {
- Some(Manage::Models(Command::Thinking(matches!(
- key.code,
- KeyCode::Right | KeyCode::Down
- ))))
- }
- KeyCode::Up | KeyCode::Down if movable => {
- models.move_selection(key.code == KeyCode::Down);
- models.focus = 0;
- dialog.error = None;
- return (true, None);
- }
- KeyCode::Home | KeyCode::End if movable => {
- models.clear_default = models.for_default
- && (key.code == KeyCode::Home || models.catalog.rows.is_empty());
- models.catalog.selected = if models.clear_default {
- None
- } else if key.code == KeyCode::Home {
- models.catalog.rows.first()
- } else {
- models.catalog.rows.last()
- }
- .map(|r| r.choice.clone());
- models.focus = 0;
- dialog.error = None;
- return (true, None);
- }
- KeyCode::F(5) => Some(Manage::Models(Command::Refresh)),
- KeyCode::PageUp => Some(Manage::Models(Command::Previous)),
- KeyCode::PageDown => Some(Manage::Models(Command::Next)),
- KeyCode::Enter if key.modifiers.contains(KeyModifiers::CONTROL) => {
- Some(Manage::Save)
- }
- KeyCode::Enter => Some(focused(models)),
- _ => None,
- },
- Event::Mouse(mouse) if dialog.visible => {
- let hit = self
- .hits
- .iter()
- .rev()
- .find(|h| h.area.contains((mouse.column, mouse.row).into()))
- .and_then(|h| match &h.action {
- Action::Manage(c) => Some(c.clone()),
- _ => None,
- });
- match mouse.kind {
- MouseEventKind::Down(MouseButton::Left) => hit,
- MouseEventKind::Moved => {
- let changed = models.hovered != hit;
- models.hovered = hit;
- return (changed, None);
- }
- MouseEventKind::ScrollDown | MouseEventKind::ScrollUp
- if movable && matches!(hit, Some(Manage::Models(Command::Select(_)))) =>
- {
- models.move_selection(mouse.kind == MouseEventKind::ScrollDown);
- models.focus = 0;
- dialog.error = None;
- return (true, None);
- }
- _ => None,
- }
- }
- _ => None,
- };
- (
- command.is_some(),
- command.and_then(|c| self.apply(Action::Manage(c))),
- )
- }
-}
-fn focused(models: &Models) -> Manage {
- match models.focus {
- 1 => Manage::Models(Command::Refresh),
- 2 => Manage::Models(Command::Previous),
- 3 => Manage::Models(Command::Next),
- 4 => Manage::Close,
- 6 if models.has_thinking() => Manage::Models(Command::Thinking(true)),
- _ => Manage::Save,
}
}
@@ -417,6 +263,7 @@ mod tests {
i18n::{I18n, Locale, LocalePreference},
pages::manage::{Entity, Kind},
};
+ use crossterm::event::{Event, KeyCode, KeyModifiers, MouseButton, MouseEventKind};
use ratatui::{Terminal, backend::TestBackend};
use serde_json::json;
@@ -427,6 +274,77 @@ mod tests {
{"kind":"catalog_entry","connectionIndex":0,"entry":{"id":model,"canUseAsChatDefault":true}}
]})
}
+ /// Cells of each screen row; a wide glyph covers its neighbour.
+ fn lines(terminal: &Terminal<TestBackend>) -> Vec<String> {
+ let buffer = terminal.backend().buffer();
+ (0..buffer.area.height)
+ .map(|y| {
+ let (mut line, mut x) = (String::new(), 0);
+ while x < buffer.area.width {
+ let symbol = buffer[(x, y)].symbol();
+ line.push_str(symbol);
+ x += (unicode_width::UnicodeWidthStr::width(symbol) as u16).max(1);
+ }
+ line
+ })
+ .collect()
+ }
+ /// The first place `text` is drawn.
+ fn locate(terminal: &Terminal<TestBackend>, text: &str) -> (u16, u16) {
+ lines(terminal)
+ .iter()
+ .enumerate()
+ .find_map(|(y, line)| {
+ line.find(text).map(|byte| {
+ (
+ unicode_width::UnicodeWidthStr::width(&line[..byte]) as u16,
+ y as u16,
+ )
+ })
+ })
+ .unwrap_or_else(|| panic!("{text:?} is not on screen"))
+ }
+ /// A list row whose text inside the sheet is exactly `name`.
+ fn row(terminal: &Terminal<TestBackend>, name: &str) -> (u16, u16) {
+ lines(terminal)
+ .iter()
+ .enumerate()
+ .find_map(|(y, line)| {
+ let inside = line.split('│').nth(1)?;
+ (inside.trim() == name).then(|| {
+ let byte = line.find(name).unwrap();
+ (
+ unicode_width::UnicodeWidthStr::width(&line[..byte]) as u16,
+ y as u16,
+ )
+ })
+ })
+ .unwrap_or_else(|| panic!("no row {name:?}"))
+ }
+ fn click(app: &mut App, (x, y): (u16, u16)) {
+ app.input(Event::Mouse(crossterm::event::MouseEvent {
+ kind: MouseEventKind::Down(MouseButton::Left),
+ column: x,
+ row: y,
+ modifiers: KeyModifiers::NONE,
+ }));
+ }
+ fn key(app: &mut App, code: KeyCode) {
+ app.input(Event::Key(crossterm::event::KeyEvent::new(
+ code,
+ KeyModifiers::NONE,
+ )));
+ }
+ fn level(app: &App) -> Option<ThinkingLevel> {
+ app.management
+ .dialog
+ .as_ref()
+ .unwrap()
+ .models
+ .as_ref()
+ .unwrap()
+ .thinking_level()
+ }
#[test]
fn thinking_uses_current_catalog_levels_and_rechecks_before_submission() {
for locale in Locale::ALL {
@@ -467,95 +385,36 @@ mod tests {
let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
app.apply(Action::Manage(Manage::Models(Command::Select(choice))));
- for (width, height) in [(42, 17), (80, 24), (120, 40)] {
+ let label = app.i18n.text("session-thinking");
+ let high = app.i18n.text("thinking-high");
+ for (width, height) in [(48, 22), (80, 24), (120, 40)] {
let mut terminal = Terminal::new(TestBackend::new(width, height)).unwrap();
terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
- let hit = app
- .hits
- .iter()
- .find(|h| h.action == Action::Manage(Manage::Models(Command::Thinking(true))))
- .unwrap()
- .area;
- assert!(app.modal_area.unwrap().contains((hit.x, hit.y).into()));
- assert!(!app.hits.iter().any(|h| matches!(
- &h.action,
- Action::Manage(Manage::Models(Command::Select(_)))
- ) && h.area.intersects(hit)));
- app.input(Event::Mouse(crossterm::event::MouseEvent {
- kind: MouseEventKind::Down(MouseButton::Left),
- column: hit.x,
- row: hit.y,
- modifiers: KeyModifiers::NONE,
- }));
- assert_eq!(
- app.management
- .dialog
- .as_ref()
- .unwrap()
- .models
- .as_ref()
- .unwrap()
- .thinking_level(),
- Some(ThinkingLevel::High)
- );
+ // The level is a chooser of what this model supports.
+ click(&mut app, locate(&terminal, &label));
terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
- let previous = app
- .hits
- .iter()
- .find(|h| h.action == Action::Manage(Manage::Models(Command::Thinking(false))))
- .unwrap()
- .area;
- app.input(Event::Mouse(crossterm::event::MouseEvent {
- kind: MouseEventKind::Down(MouseButton::Left),
- column: previous.x + 1,
- row: previous.y,
- modifiers: KeyModifiers::NONE,
- }));
- assert_eq!(
- app.management
- .dialog
- .as_ref()
- .unwrap()
- .models
- .as_ref()
- .unwrap()
- .thinking_level(),
- Some(ThinkingLevel::Low)
- );
- app.input(Event::Key(crossterm::event::KeyEvent::new(
- KeyCode::Left,
- KeyModifiers::NONE,
- )));
- assert_eq!(
- app.management
- .dialog
- .as_ref()
- .unwrap()
- .models
- .as_ref()
- .unwrap()
- .thinking_level(),
- None
- );
- app.input(Event::Key(crossterm::event::KeyEvent::new(
- KeyCode::Right,
- KeyModifiers::NONE,
- )));
- assert_eq!(
- app.management
- .dialog
- .as_ref()
- .unwrap()
- .models
- .as_ref()
- .unwrap()
- .thinking_level(),
- Some(ThinkingLevel::Low)
- );
+ click(&mut app, locate(&terminal, &high));
+ assert_eq!(level(&app), Some(ThinkingLevel::High));
+ terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ // The keyboard opens it on the current level and moves from there.
+ key(&mut app, KeyCode::Enter);
+ key(&mut app, KeyCode::Up);
+ key(&mut app, KeyCode::Enter);
+ assert_eq!(level(&app), Some(ThinkingLevel::Low));
+ terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ key(&mut app, KeyCode::Enter);
+ key(&mut app, KeyCode::Up);
+ key(&mut app, KeyCode::Enter);
+ assert_eq!(level(&app), None, "the model's own default");
+ terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ key(&mut app, KeyCode::Enter);
+ key(&mut app, KeyCode::Down);
+ key(&mut app, KeyCode::Enter);
+ assert_eq!(level(&app), Some(ThinkingLevel::Low));
}
- // A catalog update withdraws the old controls and must not submit an obsolete level.
+ // A catalog update withdraws the old levels and must not submit an obsolete one.
app.models_catalog_changed();
- assert!(!app.models_enabled(&Command::Thinking(true)));
+ assert!(!app.models_enabled(&Command::Thinking(Some(ThinkingLevel::Low))));
assert!(!app.management_enabled(&Manage::Save));
data["items"][2]["entry"]["thinkingLevels"] = json!(["high"]);
let request = app.models_request().unwrap();
@@ -570,23 +429,14 @@ mod tests {
.unwrap();
assert_eq!(models.thinking, Some(ThinkingLevel::Low));
assert_eq!(models.thinking_level(), None);
- let models = app
- .management
- .dialog
- .as_mut()
- .unwrap()
- .models
- .as_mut()
- .unwrap();
- models.focus = 4;
- assert_eq!(focused(models), Manage::Close);
- models.catalog.rows[0].thinking_levels.clear();
- assert!(!models.has_thinking());
- assert_eq!(focused(models), Manage::Close);
- models.tab(true);
- assert_eq!(focused(models), Manage::Save);
let mut terminal = Terminal::new(TestBackend::new(80, 24)).unwrap();
terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ assert!(
+ lines(&terminal)
+ .iter()
+ .any(|line| line.contains(&app.i18n.text("thinking-default"))),
+ "an unsupported level shows the model's default, not the stale choice"
+ );
let ticket = app.management_request().unwrap();
assert_eq!(ticket.thinking_level, None);
assert_eq!(ticket.model.unwrap().model, "model");
@@ -596,7 +446,7 @@ mod tests {
let mut data = page("model");
data["items"][2]["entry"]["thinkingLevels"] = json!(["high"]);
defaults.catalog.complete(Ok(data));
- defaults.catalog.move_selection(true);
+ defaults.catalog.selected = defaults.catalog.rows.first().map(|row| row.choice.clone());
defaults.thinking = Some(ThinkingLevel::High);
assert!(!defaults.has_thinking());
assert_eq!(defaults.thinking_level(), None);
@@ -637,10 +487,8 @@ mod tests {
!app.management_enabled(&Manage::Save),
"configuration notification withdraws clear intent"
);
- app.input(Event::Key(crossterm::event::KeyEvent::new(
- KeyCode::Down,
- KeyModifiers::NONE,
- )));
+ terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ key(&mut app, KeyCode::Down);
assert!(app.management_enabled(&Manage::Save));
app.models_catalog_changed();
let request = app.models_request().unwrap();
@@ -650,18 +498,8 @@ mod tests {
"same model identity cannot silently retain old default intent"
);
terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
- let hit = app
- .hits
- .iter()
- .find(|h| h.action == Action::Manage(Manage::Models(Command::ClearDefault)))
- .unwrap()
- .area;
- app.input(Event::Mouse(crossterm::event::MouseEvent {
- kind: MouseEventKind::Down(MouseButton::Left),
- column: hit.x,
- row: hit.y,
- modifiers: KeyModifiers::NONE,
- }));
+ let none = app.i18n.text("default-model-none");
+ click(&mut app, locate(&terminal, &none));
let ticket = app.management_request().unwrap();
assert!(ticket.target.is_default_model());
assert_eq!(ticket.catalog_revision, Some(7));
@@ -726,18 +564,19 @@ mod tests {
slug: "fixture".into(),
model: "model".into(),
};
- let hit = app
- .hits
- .iter()
- .find(|h| h.action == Action::Manage(Manage::Models(Command::Select(choice.clone()))))
- .unwrap()
- .area;
- app.input(Event::Mouse(crossterm::event::MouseEvent {
- kind: MouseEventKind::Down(MouseButton::Left),
- column: hit.x,
- row: hit.y,
- modifiers: KeyModifiers::NONE,
- }));
+ click(&mut app, row(&terminal, "model"));
+ assert_eq!(
+ app.management
+ .dialog
+ .as_ref()
+ .unwrap()
+ .models
+ .as_ref()
+ .unwrap()
+ .catalog
+ .selected,
+ Some(choice)
+ );
assert!(!app.management_enabled(&Manage::Save));
app.models_completed(request, Ok(page("model")));
assert!(
@@ -760,10 +599,8 @@ mod tests {
!app.management_enabled(&Manage::Save),
"removed choice cannot silently select its neighbour"
);
- app.input(Event::Key(crossterm::event::KeyEvent::new(
- KeyCode::Down,
- KeyModifiers::NONE,
- )));
+ terminal.draw(|f| crate::view::draw(f, &mut app)).unwrap();
+ key(&mut app, KeyCode::Down);
let ticket = app.management_request().unwrap();
assert_eq!(ticket.target, target);
assert_eq!(ticket.model.as_ref().unwrap().model, "replacement");
diff --git a/crates/tui/src/pages/manage/models/catalog.rs b/crates/tui/src/pages/manage/models/catalog.rs
index 8c4f6611a4..852fe0e6bd 100644
--- a/crates/tui/src/pages/manage/models/catalog.rs
+++ b/crates/tui/src/pages/manage/models/catalog.rs
@@ -221,20 +221,6 @@ impl Catalog {
.iter()
.find(|row| Some(&row.choice) == self.selected.as_ref())
}
- pub fn move_selection(&mut self, down: bool) {
- let index = self
- .rows
- .iter()
- .position(|r| Some(&r.choice) == self.selected.as_ref())
- .map_or(0, |index| {
- if down {
- (index + 1).min(self.rows.len().saturating_sub(1))
- } else {
- index.saturating_sub(1)
- }
- });
- self.selected = self.rows.get(index).map(|r| r.choice.clone());
- }
}
#[cfg(test)]
@@ -308,7 +294,7 @@ mod tests {
"both enabled model IDs and chat capability are required"
);
assert!(catalog.selection().is_none());
- catalog.move_selection(true);
+ catalog.selected = catalog.rows.first().map(|row| row.choice.clone());
let selected = catalog.selection().unwrap().choice.clone();
assert_eq!(selected.connection_id, "id-0");
catalog.change_page(true);
diff --git a/crates/tui/src/pages/manage/models/view.rs b/crates/tui/src/pages/manage/models/view.rs
index fbabe08909..31faada026 100644
--- a/crates/tui/src/pages/manage/models/view.rs
+++ b/crates/tui/src/pages/manage/models/view.rs
@@ -17,303 +17,238 @@
* under the License.
*/
-use super::{Command, Manage, focused};
+use super::{Command, Manage, thinking_key};
use crate::{
- app::{Action, App, Hit},
- view::{button, safe, tone},
+ app::{Action, App},
+ pages::manage::Dialog,
+ ui::{Choice, Node, On, Role, Sheet, Size, Tone},
+ view::safe,
};
-use ratatui::{
- Frame,
- layout::{Margin, Rect},
- style::Style,
- widgets::{Block, Paragraph, Wrap},
-};
-use unicode_width::UnicodeWidthStr;
+use std::iter;
-pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect, base: Style) {
+/// Choosing a model: arrows or a click choose a row, Enter applies it.
+/// For the default model the first row clears the default. Thinking is a
+/// chooser of the levels the chosen model supports.
+pub(in crate::pages::manage) fn sheet(app: &App, dialog: &Dialog) -> Sheet<Action> {
let busy = app.management.pending.is_some();
- let dialog = app.management.dialog.as_mut().expect("models dialog");
- let models = dialog.models.as_mut().expect("model chooser");
- if area.width < 42 || area.height < 17 {
- dialog.visible = false;
- crate::view::clear_overlay(frame, area);
- frame.render_widget(
- Paragraph::new(app.i18n.text("terminal-small")).wrap(Wrap { trim: false }),
- area.inner(Margin::new(1, 1)),
- );
- return;
- }
- let width = area.width.saturating_sub(2).min(80);
- let height = area
- .height
- .saturating_sub(2)
- .min((models.catalog.rows.len().min(9) as u16 * 2 + 10).clamp(15, 28));
- let popup = Rect::new(
- area.x + (area.width - width) / 2,
- area.y + (area.height - height) / 2,
- width,
- height,
+ let models = dialog.models.as_ref().expect("model chooser");
+ let catalog = &models.catalog;
+ let enabled = !dialog.blocked && !busy;
+ // Rows arriving are a new step: focus moves into the list.
+ let step = if catalog.rows.is_empty() {
+ "empty"
+ } else {
+ "list"
+ };
+ let mut sheet = Sheet::new(
+ format!("model:{}:{step}", dialog.target.name),
+ app.i18n.text(dialog.kind.label(&dialog.target)),
);
- let block = Block::bordered()
- .border_type(if app.chrome.ascii {
- ratatui::widgets::BorderType::Plain
- } else {
- ratatui::widgets::BorderType::Rounded
- })
- .title(app.i18n.text(dialog.kind.label(&dialog.target)))
- .style(base)
- .border_style(Style::default().fg(app.theme.colors().subtle));
- let inner = block.inner(popup).inner(Margin::new(1, 0));
- app.modal_area = Some(popup);
- crate::view::clear_overlay(frame, popup);
- frame.render_widget(block, popup);
- dialog.visible = true;
+ if !models.for_default {
+ sheet = sheet.text("name", &safe(&dialog.target.name), Tone::Normal);
+ }
+ let marker = |selected: bool| match (selected, app.chrome.ascii) {
+ (true, false) => "›",
+ (true, true) => ">",
+ _ => " ",
+ };
+ let current = format!(" · {}", app.i18n.text("default-model-current"));
+ let choose = |node: Node<Action>, command: Command| {
+ node.on(On::Activate(Action::Manage(Manage::Models(command))))
+ .follow_focus()
+ .submit(Action::Manage(Manage::Save))
+ .enabled(enabled)
+ };
+ let mut rows = vec![];
+ let mut lines = 0;
if models.for_default {
- let command = Manage::Models(Command::ClearDefault);
- let marker = if models.clear_default {
- app.chrome.symbol("›", ">")
- } else {
- " "
- };
- let current = if models.catalog.revision().is_some() && !models.catalog.has_default {
- format!(" · {}", app.i18n.text("default-model-current"))
- } else {
- String::new()
- };
- let rect = Rect::new(inner.x, inner.y, inner.width, 1);
- frame.render_widget(
- Paragraph::new(format!(
- "{marker} {}{current}",
- app.i18n.text("default-model-none")
- ))
- .style(
- if models.clear_default || models.hovered.as_ref() == Some(&command) {
- tone::selection(app.theme.colors()).fg(tone::accent(app.theme.colors()))
- } else {
- Style::default()
- },
- ),
- rect,
- );
- if !dialog.blocked && !busy {
- app.hits.push(Hit {
- area: rect,
- action: Action::Manage(command),
- });
- }
- } else {
- frame.render_widget(
- Paragraph::new(safe(&dialog.target.name)),
- Rect::new(inner.x, inner.y, inner.width, 1),
+ let label = format!(
+ "{} {}{}",
+ marker(models.clear_default),
+ app.i18n.text("default-model-none"),
+ if catalog.revision().is_some() && !catalog.has_default {
+ current.as_str()
+ } else {
+ ""
+ }
);
+ rows.push(choose(
+ Node::text("none", vec![(label, Tone::Normal)]).clip(),
+ Command::ClearDefault,
+ ));
+ lines += 1;
}
- let list = Rect::new(
- inner.x,
- inner.y + 3,
- inner.width,
- inner.height.saturating_sub(9),
- );
- let visible = list.height as usize / 2;
- let selected = models
- .catalog
- .rows
- .iter()
- .position(|r| Some(&r.choice) == models.catalog.selected.as_ref());
- let offset = selected.map_or(0, |i| (i + 1).saturating_sub(visible));
- let enabled = !dialog.blocked && !busy;
- for (index, row) in models
- .catalog
- .rows
- .iter()
- .enumerate()
- .skip(offset)
- .take(visible)
- {
- let rect = Rect::new(
- list.x,
- list.y + ((index - offset) * 2) as u16,
- list.width,
- 2,
+ for row in &catalog.rows {
+ let selected = catalog.selected.as_ref() == Some(&row.choice);
+ let title = format!(
+ "{} {}{}",
+ marker(selected),
+ safe(&row.name),
+ if models.for_default && row.is_default {
+ current.as_str()
+ } else {
+ ""
+ }
);
- let command = Manage::Models(Command::Select(row.choice.clone()));
- let active = selected == Some(index) || models.hovered.as_ref() == Some(&command);
- let marker = if selected == Some(index) {
- if app.chrome.ascii { ">" } else { "›" }
- } else {
- " "
- };
- let subtitle = if row.name == row.choice.model {
+ let detail = if row.name == row.choice.model {
safe(&row.connection)
} else {
format!("{} · {}", safe(&row.connection), safe(&row.choice.model))
};
- frame.render_widget(
- Paragraph::new(format!(
- "{marker} {}{}",
- safe(&row.name),
- if models.for_default && row.is_default {
- format!(" · {}", app.i18n.text("default-model-current"))
- } else {
- String::new()
- }
- ))
- .style(if !enabled {
- Style::default().fg(app.theme.colors().subtle)
- } else if active {
- tone::selection(app.theme.colors()).fg(tone::accent(app.theme.colors()))
- } else {
- Style::default()
- }),
- Rect::new(rect.x, rect.y, rect.width, 1),
- );
- frame.render_widget(
- Paragraph::new(format!(" {subtitle}"))
- .style(Style::default().fg(app.theme.colors().subtle)),
- Rect::new(rect.x, rect.y + 1, rect.width, 1),
- );
- if enabled {
- app.hits.push(Hit {
- area: rect,
- action: Action::Manage(command),
- });
- }
+ rows.push(choose(
+ Node::column(
+ key(row),
+ vec![
+ Node::text("name", vec![(title, Tone::Normal)]).clip(),
+ Node::text("detail", vec![(format!(" {detail}"), Tone::Subtle)]).clip(),
+ ],
+ ),
+ Command::Select(row.choice.clone()),
+ ));
+ lines += 2;
}
- if models.catalog.rows.is_empty() && !models.catalog.error {
- frame.render_widget(
- Paragraph::new(app.i18n.text(if models.catalog.ready() {
- if models.catalog.can_previous() {
- "session-model-page-empty"
- } else {
- "session-model-empty"
- }
- } else {
- "session-model-loading"
- }))
- .wrap(Wrap { trim: false })
- .style(Style::default().fg(app.theme.colors().subtle)),
- list,
+ if !rows.is_empty() {
+ let height = app.frame_size.map_or(24, |(_, height)| height);
+ let visible = lines.min(height.saturating_sub(18).max(4));
+ sheet =
+ sheet.body(Node::scroll("list", Node::column("rows", rows)).size(Size::Fixed(visible)));
+ }
+ if catalog.rows.is_empty() && !catalog.error {
+ let key = match (catalog.ready(), catalog.can_previous()) {
+ (true, true) => "session-model-page-empty",
+ (true, false) => "session-model-empty",
+ _ => "session-model-loading",
+ };
+ sheet = sheet.text("empty", &app.i18n.text(key), Tone::Subtle);
+ }
+ if let Some(row) = models.selection().filter(|_| models.has_thinking()) {
+ let level = models.thinking_level();
+ let levels: Vec<_> = iter::once(None)
+ .chain(row.thinking_levels.iter().copied().map(Some))
+ .collect();
+ let choices = levels
+ .iter()
+ .map(|level| Choice {
+ label: app.i18n.text(thinking_key(*level)),
+ action: Action::Manage(Manage::Models(Command::Thinking(*level))),
+ })
+ .collect();
+ sheet = sheet.body(
+ Node::row(
+ "thinking",
+ vec![
+ Node::text(
+ "label",
+ vec![(app.i18n.text("session-thinking"), Tone::Normal)],
+ )
+ .size(Size::Fill),
+ Node::text(
+ "value",
+ vec![(
+ format!(
+ "{} {}",
+ app.i18n.text(thinking_key(level)),
+ app.chrome.symbol("▾", "v")
+ ),
+ Tone::Muted,
+ )],
+ ),
+ ],
+ )
+ .on(On::Choose {
+ choices,
+ current: levels.iter().position(|candidate| *candidate == level),
+ })
+ .enabled(enabled),
);
}
- let key = if busy {
- "session-saving"
+ let (note, tone) = if busy {
+ ("session-saving", Tone::Subtle)
} else if let Some(error) = dialog.error {
- error
- } else if models.catalog.error {
- "session-model-load-failed"
+ (error, Tone::Warning)
+ } else if catalog.error {
+ ("session-model-load-failed", Tone::Warning)
+ } else if models.for_default && models.clear_default {
+ ("default-model-clear-note", Tone::Subtle)
+ } else if models.for_default {
+ ("default-model-note", Tone::Subtle)
+ } else if models.selection().is_some()
+ && models.thinking.is_some()
+ && models.thinking_level().is_none()
+ {
+ ("session-thinking-fallback", Tone::Subtle)
} else {
- let command = models.hovered.clone().unwrap_or_else(|| focused(models));
- match command {
- Manage::Models(Command::Refresh | Command::Previous | Command::Next) => command.label(),
- _ if models.for_default && models.clear_default => "default-model-clear-note",
- _ if models.for_default => "default-model-note",
- _ if models.selection().is_some()
- && models.thinking.is_some()
- && models.thinking_level().is_none() =>
- {
- "session-thinking-fallback"
- }
- _ => "session-model-note",
- }
+ ("session-model-note", Tone::Subtle)
};
- frame.render_widget(
- Paragraph::new(super::super::view::note_lines(
- &app.i18n.text(key),
- inner.width,
- ))
- .style(
- Style::default().fg(if dialog.error.is_some() || models.catalog.error {
- app.theme.colors().warning
- } else {
- app.theme.colors().subtle
- }),
- ),
- Rect::new(inner.x, inner.bottom() - 5, inner.width, 3),
- );
- let focus = models.focus;
- let hovered = models.hovered.clone();
- let thinking = models.has_thinking().then(|| {
- format!(
- "{} {} {} {}",
- app.i18n.text("session-thinking"),
- app.chrome.symbol("‹", "<"),
- app.i18n.text(super::thinking_key(models.thinking_level())),
- app.chrome.symbol("›", ">")
- )
- });
- let save = app.i18n.text(if models.for_default {
- if models.clear_default {
- "default-model-clear"
- } else {
- "default-model-apply"
- }
- } else {
- "session-model-apply"
- });
- let cancel = app.i18n.text("session-cancel");
- let save_width = (save.width() as u16 + 2).min(inner.width / 2);
- let cancel_width = (cancel.width() as u16 + 2).min(inner.width / 2);
- let save_rect = Rect::new(
- inner.right() - save_width,
- inner.bottom() - 1,
- save_width,
- 1,
- );
- if let Some(text) = thinking {
- let command = Manage::Models(Command::Thinking(true));
- let previous = Manage::Models(Command::Thinking(false));
- let rect = Rect::new(
- inner.x,
- inner.bottom() - 6,
- (text.width() as u16).min(inner.width),
- 1,
- );
- crate::view::list_item(
- frame,
- app,
- rect,
- &text,
- Action::Manage(command.clone()),
- focus == 6 || hovered.as_ref() == Some(&command) || hovered.as_ref() == Some(&previous),
- );
- if app.enabled(&Action::Manage(previous.clone())) {
- // The left chevron reverses; the value/right chevron advances.
- app.hits.push(Hit {
- area: Rect::new(
- rect.x + app.i18n.text("session-thinking").width() as u16 + 1,
- rect.y,
- 3,
- 1,
+ sheet = sheet.text("note", &app.i18n.text(note), tone);
+ let command = |command: Command| {
+ let action = Action::Manage(Manage::Models(command));
+ let enabled = app.enabled(&action);
+ (action, enabled)
+ };
+ if catalog.can_previous() || catalog.can_next() {
+ let (previous, can_previous) = command(Command::Previous);
+ let (next, can_next) = command(Command::Next);
+ sheet = sheet
+ .aside(
+ "previous",
+ format!(
+ "{} {}",
+ app.chrome.symbol("‹", "<"),
+ app.i18n.text("sessions-previous")
+ ),
+ previous,
+ can_previous,
+ )
+ .aside(
+ "next",
+ format!(
+ "{} {}",
+ app.i18n.text("sessions-next"),
+ app.chrome.symbol("›", ">")
),
- action: Action::Manage(previous),
- });
- }
+ next,
+ can_next,
+ );
}
- for (rect, text, command, index) in [
- (
- Rect::new(save_rect.x - cancel_width - 1, save_rect.y, cancel_width, 1),
- cancel,
- Manage::Close,
- 4,
- ),
- (save_rect, save, Manage::Save, 5),
- ] {
- let active = focus == index || hovered.as_ref() == Some(&command);
- button(frame, app, rect, &text, Action::Manage(command), active);
+ if catalog.error {
+ let (refresh, can_refresh) = command(Command::Refresh);
+ sheet = sheet.aside("refresh", app.i18n.text("list-retry"), refresh, can_refresh);
}
- for (index, command, icon, ascii) in [
- (1, Command::Refresh, "⟳", "R"),
- (2, Command::Previous, "‹", "<"),
- (3, Command::Next, "›", ">"),
- ] {
- let command = Manage::Models(command);
- let active = focus == index || hovered.as_ref() == Some(&command);
- button(
- frame,
- app,
- Rect::new(inner.x + ((index - 1) * 4) as u16, inner.y + 1, 3, 1),
- if app.chrome.ascii { ascii } else { icon },
- Action::Manage(command),
- active,
+ let save = match (models.for_default, models.clear_default) {
+ (true, true) => "default-model-clear",
+ (true, false) => "default-model-apply",
+ _ => "session-model-apply",
+ };
+ let sheet = sheet
+ .button(
+ "cancel",
+ app.i18n.text("session-cancel"),
+ Role::Normal,
+ Action::Manage(Manage::Close),
+ true,
+ )
+ .button(
+ "save",
+ app.i18n.text(save),
+ Role::Primary,
+ Action::Manage(Manage::Save),
+ app.enabled(&Action::Manage(Manage::Save)),
);
+ if models.for_default && models.clear_default {
+ return sheet.focus_node("list/rows/none");
}
+ match catalog
+ .rows
+ .iter()
+ .find(|row| catalog.selected.as_ref() == Some(&row.choice))
+ {
+ Some(row) => sheet.focus_node(format!("list/rows/{}", key(row))),
+ None => sheet,
+ }
+}
+
+/// A model's identity across pages: its connection and model id.
+fn key(row: &super::catalog::Row) -> String {
+ format!("{}:{}", row.choice.connection_id, row.choice.model)
}
diff --git a/crates/tui/src/pages/manage/view.rs b/crates/tui/src/pages/manage/view.rs
index f4eee9e17b..4caa582048 100644
--- a/crates/tui/src/pages/manage/view.rs
+++ b/crates/tui/src/pages/manage/view.rs
@@ -107,6 +107,9 @@ pub(crate) fn sheet(app: &App) -> Option<Sheet<Action>> {
if dialog.chooser.is_some() {
return Some(super::choose_project::sheet(app, dialog));
}
+ if dialog.models.is_some() {
+ return Some(super::models::sheet(app, dialog));
+ }
let busy = app.management.pending.is_some();
let kind = dialog.kind;
let label = kind.label(&dialog.target);
@@ -331,8 +334,6 @@ pub fn draw(frame: &mut Frame<'_>, app: &mut App, area: Rect, base: Style) {
super::oauth::draw(frame, app, area, base);
} else if dialog.enabled_models.is_some() {
super::enabled_models::draw(frame, app, area, base);
- } else if dialog.models.is_some() {
- super::models::draw(frame, app, area, base);
} else if dialog.locations.is_some() {
super::locations::draw(frame, app, area, base);
} else if dialog.browser.is_some() {
diff --git a/crates/tui/src/ui/surface.rs b/crates/tui/src/ui/surface.rs
index db92c79048..85d4a5902e 100644
--- a/crates/tui/src/ui/surface.rs
+++ b/crates/tui/src/ui/surface.rs
@@ -732,7 +732,14 @@ impl<M: Clone> Surface<M> {
return Outcome::handled(false);
};
if Some(&item.id) == self.focus.as_ref() {
- return Outcome::handled(false);
+ // An arrow at a list's edge still chooses the focused row when
+ // it is not the choice yet (it lost its choice to a refresh).
+ return match &item.on {
+ On::Activate(message) if item.follow_focus && !item.current => {
+ Outcome::emit(message.clone())
+ }
+ _ => Outcome::handled(false),
+ };
}
let message = match &item.on {
On::Activate(message) if item.follow_focus => Some(message.clone()),
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org